hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e042012b909907e1101c92c464171a613973628
2,968
java
Java
back-end/src/main/java/House.java
hadisfr/khaneBeDoosh
f48b3b81a0b1275187cf5c4c02c98a70ff762aff
[ "MIT" ]
null
null
null
back-end/src/main/java/House.java
hadisfr/khaneBeDoosh
f48b3b81a0b1275187cf5c4c02c98a70ff762aff
[ "MIT" ]
2
2018-08-06T02:51:52.000Z
2018-08-06T02:53:02.000Z
back-end/src/main/java/House.java
hadisfr/khaneBeDoosh
f48b3b81a0b1275187cf5c4c02c98a70ff762aff
[ "MIT" ]
null
null
null
29.386139
130
0.641509
1,713
package main.java; import java.io.IOException; import java.sql.SQLException; public class House { protected HouseDetail detail; protected String ownerName; protected String imageUrl; protected String address; protected String id; protected int area; protected BuildingType buildingType; private Price price; public DealType getDealType() { if (price instanceof PriceRent) return DealType.RENT; else if (price instanceof PriceSell) return DealType.SELL; else return null; } public String getImageUrl() { return imageUrl; } public String getId() { return id; } public int getArea() { return area; } public BuildingType getBuildingType() { return buildingType; } protected HouseDetail getDetail() throws IOException, SQLException, ClassNotFoundException { if (this.detail != null) return this.detail; else { User owner = KhaneBeDoosh.getInstance().getUserById(this.ownerName); if (owner instanceof RealEstate) return ((RealEstate) (owner)).getHouse(this.id).detail; else return null; } } public String getPhone() throws IOException, SQLException, ClassNotFoundException { return this.getDetail().getPhone(); } public String getDescription() throws IOException, SQLException, ClassNotFoundException { return this.getDetail().getDescription(); } public String getAddress() { return this.address; } public String getOwnerName() { return ownerName; } public House(String id, int area, BuildingType buildingType, String imageUrl, String ownerName, String address, Price price) { this.id = id; this.area = area; this.buildingType = buildingType; this.imageUrl = imageUrl; this.ownerName = ownerName; this.price = price; this.address = address; detail = null; } public House(String id, int area, BuildingType buildingType, String imageUrl, String ownerName, String address, String phone, String description, Price price) { this(id, area, buildingType, imageUrl, ownerName, address, price); this.detail = new HouseDetail(phone, description); } public House(String id, int area, BuildingType buildingType, String imageUrl, User owner, String address, Price price) { this(id, area, buildingType, imageUrl, owner.getUsername(), address, price); } public House(String id, int area, BuildingType buildingType, String imageUrl, User owner, String address, String phone, String description, Price price) { this(id, area, buildingType, imageUrl, owner.getUsername(), address, phone, description, price); } public Price getPrice() { return price; } }
3e0420a1644cfe1aa20f2252b064ca166e0a526b
13,871
java
Java
src/main/java/com/stevekung/skyblockcatia/utils/skyblock/SBDungeons.java
SJKZ1-2565/SkyBlockcatia
a403a7b9f7ec7e268998536e7b90f58276d375af
[ "MIT" ]
33
2020-08-11T16:38:33.000Z
2021-11-15T00:41:59.000Z
src/main/java/com/stevekung/skyblockcatia/utils/skyblock/SBDungeons.java
SJKZ1-2565/SkyBlockcatia
a403a7b9f7ec7e268998536e7b90f58276d375af
[ "MIT" ]
95
2020-07-24T01:39:56.000Z
2021-11-10T20:57:01.000Z
src/main/java/com/stevekung/skyblockcatia/utils/skyblock/SBDungeons.java
SJKZ1-2565/SkyBlockcatia
a403a7b9f7ec7e268998536e7b90f58276d375af
[ "MIT" ]
14
2020-07-29T17:48:11.000Z
2021-09-25T06:13:32.000Z
28.482546
192
0.59974
1,714
package com.stevekung.skyblockcatia.utils.skyblock; import java.io.IOException; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import com.stevekung.skyblockcatia.utils.DataUtils; import com.stevekung.skyblockcatia.utils.skyblock.api.IBonusTemplate; import net.minecraft.entity.EntityList; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; public class SBDungeons { private static final Gson GSON = new Gson(); public static SBDungeons DUNGEONS; private final int[] leveling; private final Bonus bonus; @SerializedName("valid_dungeons") private final List<String> validDungeons; public SBDungeons(int[] leveling, Bonus bonus, List<String> validDungeons) { this.leveling = leveling; this.bonus = bonus; this.validDungeons = validDungeons; } public int[] getLeveling() { return this.leveling; } public Bonus getBonus() { return this.bonus; } public List<String> getValidDungeons() { return this.validDungeons; } public static void getDungeons() throws IOException { DUNGEONS = GSON.fromJson(DataUtils.getData("dungeons.json"), SBDungeons.class); } public static class Bonus { private final Catacombs[] catacombs; public Bonus(Catacombs[] catacombs) { this.catacombs = catacombs; } public Catacombs[] getCatacombs() { return this.catacombs; } } public static class Catacombs implements IBonusTemplate { private final int level; private final double health; public Catacombs(int level, double health) { this.level = level; this.health = health; } @Override public int getLevel() { return this.level; } @Override public double getHealth() { return this.health; } } public static class Dungeons { @SerializedName("dungeon_types") private final Map<String, TypeData> dungeonTypes; @SerializedName("selected_dungeon_class") private final String selectedClass; @SerializedName("player_classes") private final Map<String, Exp> playerClasses; public Dungeons(Map<String, TypeData> dungeonTypes, String selectedClass, Map<String, Exp> playerClasses) { this.dungeonTypes = dungeonTypes; this.selectedClass = selectedClass; this.playerClasses = playerClasses; } public Map<String, TypeData> getDungeonTypes() { return this.dungeonTypes; } public String getSelectedClass() { return this.selectedClass; } public Map<String, Exp> getPlayerClasses() { return this.playerClasses; } } public static class TypeData { private final double experience; @SerializedName("highest_tier_completed") private final int highestFloorCompleted; @SerializedName("times_played") private final Map<Integer, Integer> timesPlayed; @SerializedName("tier_completions") private final Map<Integer, Integer> floorCompletions; @SerializedName("fastest_time") private final Map<Integer, Integer> fastestTime; @SerializedName("best_runs") private final Map<Integer, List<Runs>> bestRuns; @SerializedName("best_score") private final Map<Integer, Integer> bestScores; @SerializedName("mobs_killed") private final Map<Integer, Integer> mobsKilled; @SerializedName("most_mobs_killed") private final Map<Integer, Integer> mostMobsKilled; @SerializedName("most_damage_berserk") private final Map<Integer, Float> mostBerserkDamage; @SerializedName("most_damage_mage") private final Map<Integer, Float> mostMageDamage; @SerializedName("most_healing") private final Map<Integer, Float> mostHealing; @SerializedName("watcher_kills") private final Map<Integer, Integer> watcherKills; @SerializedName("fastest_time_s") private final Map<Integer, Integer> sFastestTime; @SerializedName("fastest_time_s_plus") private final Map<Integer, Integer> sPlusFastestTime; @SerializedName("milestone_completions") private final Map<Integer, Integer> milestoneCompletions; public TypeData(double experience, int highestFloorCompleted, Map<Integer, Integer> timesPlayed, Map<Integer, Integer> floorCompletions, Map<Integer, Integer> fastestTime, Map<Integer, List<Runs>> bestRuns, Map<Integer, Integer> bestScores, Map<Integer, Integer> mobsKilled, Map<Integer, Integer> mostMobsKilled, Map<Integer, Float> mostBerserkDamage, Map<Integer, Float> mostMageDamage, Map<Integer, Float> mostHealing, Map<Integer, Integer> watcherKills, Map<Integer, Integer> sFastestTime, Map<Integer, Integer> sPlusFastestTime, Map<Integer, Integer> milestoneCompletions) { this.experience = experience; this.highestFloorCompleted = highestFloorCompleted; this.timesPlayed = timesPlayed; this.floorCompletions = floorCompletions; this.fastestTime = fastestTime; this.bestRuns = bestRuns; this.bestScores = bestScores; this.mobsKilled = mobsKilled; this.mostMobsKilled = mostMobsKilled; this.mostBerserkDamage = mostBerserkDamage; this.mostMageDamage = mostMageDamage; this.mostHealing = mostHealing; this.watcherKills = watcherKills; this.sFastestTime = sFastestTime; this.sPlusFastestTime = sPlusFastestTime; this.milestoneCompletions = milestoneCompletions; } public double getExperience() { return this.experience; } public int getHighestFloorCompleted() { return this.highestFloorCompleted; } public Map<Integer, Integer> getTimesPlayed() { return this.timesPlayed; } public Map<Integer, Integer> getFloorCompletions() { return this.floorCompletions; } public Map<Integer, Integer> getFastestTime() { return this.fastestTime; } public Map<Integer, List<Runs>> getBestRuns() { return this.bestRuns; } public Map<Integer, Integer> getBestScores() { return this.bestScores; } public Map<Integer, Integer> getMobsKilled() { return this.mobsKilled; } public Map<Integer, Integer> getMostMobsKilled() { return this.mostMobsKilled; } public Map<Integer, Float> getMostBerserkDamage() { return this.mostBerserkDamage; } public Map<Integer, Float> getMostMageDamage() { return this.mostMageDamage; } public Map<Integer, Float> getMostHealing() { return this.mostHealing; } public Map<Integer, Integer> getWatcherKills() { return this.watcherKills; } public Map<Integer, Integer> getsFastestTime() { return this.sFastestTime; } public Map<Integer, Integer> getsPlusFastestTime() { return this.sPlusFastestTime; } public Map<Integer, Integer> getMilestoneCompletions() { return this.milestoneCompletions; } } public static class Runs { private final long timestamp; @SerializedName("dungeon_class") private final String dungeonClass; @SerializedName("score_skill") private final int skillScore; @SerializedName("score_speed") private final int speedScore; @SerializedName("score_exploration") private final int explorationScore; @SerializedName("score_bonus") private final int bonusScore; private final List<String> teammates; @SerializedName("elapsed_time") private final int elapsedTime; @SerializedName("damage_dealt") private final double damageDealt; @SerializedName("damage_mitigated") private final double damageMitigated; private final int deaths; @SerializedName("mobs_killed") private final int mobsKilled; @SerializedName("secrets_found") private final int secretsFound; public Runs(long timestamp, String dungeonClass, int skillScore, int speedScore, int explorationScore, int bonusScore, List<String> teammates, int elapsedTime, double damageDealt, double damageMitigated, int deaths, int mobsKilled, int secretsFound) { this.timestamp = timestamp; this.dungeonClass = dungeonClass; this.skillScore = skillScore; this.speedScore = speedScore; this.explorationScore = explorationScore; this.bonusScore = bonusScore; this.teammates = teammates; this.elapsedTime = elapsedTime; this.damageDealt = damageDealt; this.damageMitigated = damageMitigated; this.deaths = deaths; this.mobsKilled = mobsKilled; this.secretsFound = secretsFound; } public long getTimestamp() { return this.timestamp; } public String getDungeonClass() { return this.dungeonClass; } public int getSkillScore() { return this.skillScore; } public int getSpeedScore() { return this.speedScore; } public int getExplorationScore() { return this.explorationScore; } public int getBonusScore() { return this.bonusScore; } public List<String> getTeammates() { return this.teammates; } public int getElapsedTime() { return this.elapsedTime; } public double getDamageDealt() { return this.damageDealt; } public double getDamageMitigated() { return this.damageMitigated; } public int getDeaths() { return this.deaths; } public int getMobsKilled() { return this.mobsKilled; } public int getSecretsFound() { return this.secretsFound; } } public static class PlayerClasses { private final Exp healer; private final Exp mage; private final Exp berserk; private final Exp archer; private final Exp tank; public PlayerClasses(Exp healer, Exp mage, Exp berserk, Exp archer, Exp tank) { this.healer = healer; this.mage = mage; this.berserk = berserk; this.archer = archer; this.tank = tank; } public Exp getHealer() { return this.healer; } public Exp getMage() { return this.mage; } public Exp getBerserk() { return this.berserk; } public Exp getArcher() { return this.archer; } public Exp getTank() { return this.tank; } } public static class Exp { private final double experience; public Exp(double experience) { this.experience = experience; } public double getExperience() { return this.experience; } } public enum Class { HEALER("Healer"), MAGE("Mage"), BERSERK("Berserk"), ARCHER("Archer"), TANK("Tank"); private final String name; Class(String name) { this.name = name; } public String getName() { return this.name; } } public enum Drops { SPIRIT_LEAP(EnumChatFormatting.RESET.toString() + EnumChatFormatting.BLUE + "Spirit Leap", new ItemStack(Items.ender_pearl), true), DUNGEON_DECOY(EnumChatFormatting.RESET.toString() + EnumChatFormatting.GREEN + "Decoy", new ItemStack(Items.spawn_egg), false), INFLATABLE_JERRY(EnumChatFormatting.RESET.toString() + EnumChatFormatting.WHITE + "Inflatable Jerry", new ItemStack(Items.spawn_egg, 0, EntityList.getIDFromString("Villager")), false), DUNGEON_TRAP(EnumChatFormatting.RESET.toString() + EnumChatFormatting.GREEN + "Dungeon Trap", new ItemStack(Blocks.heavy_weighted_pressure_plate), false); private final String displayName; private final ItemStack baseItem; private final boolean enchanted; Drops(String displayName, ItemStack baseItem, boolean enchanted) { this.displayName = displayName; this.baseItem = baseItem; this.enchanted = enchanted; } public String getDisplayName() { return this.displayName; } public ItemStack getBaseItem() { return this.baseItem; } public boolean isEnchanted() { return this.enchanted; } } }
3e0422a530858524b44b3cf0d2d83616a94d3da8
3,648
java
Java
dag/runtime/runtime/src/test/java/com/asakusafw/dag/runtime/table/HeapKeyBufferTest.java
asakusafw/asakusafw-compiler
f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e
[ "Apache-2.0" ]
2
2015-07-08T17:32:50.000Z
2020-06-14T02:26:14.000Z
dag/runtime/runtime/src/test/java/com/asakusafw/dag/runtime/table/HeapKeyBufferTest.java
asakusafw/asakusafw-compiler
f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e
[ "Apache-2.0" ]
212
2015-06-30T09:16:35.000Z
2022-02-09T22:31:09.000Z
dag/runtime/runtime/src/test/java/com/asakusafw/dag/runtime/table/HeapKeyBufferTest.java
asakusafw/asakusafw-compiler
f88ae71d9d9a3e8ab22f25069d2086a6d3bb810e
[ "Apache-2.0" ]
7
2015-06-25T02:37:40.000Z
2020-06-18T03:27:40.000Z
27.428571
75
0.578947
1,715
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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.asakusafw.dag.runtime.table; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.apache.hadoop.io.IntWritable; import org.junit.Test; import com.asakusafw.dag.runtime.adapter.KeyBuffer; /** * Test for {@link HeapKeyBuffer}. */ public class HeapKeyBufferTest { /** * simple case. */ @Test public void simple() { KeyBuffer a = newBuffer(); KeyBuffer b = newBuffer(); assertThat(a.getView(), is(a.getView())); assertThat(a.getView(), is(b.getView())); assertThat(a.getView().hashCode(), is(b.getView().hashCode())); append(a, 1); assertThat(a.getView(), is(not(b.getView()))); append(b, 1); assertThat(a.getView().hashCode(), is(b.getView().hashCode())); append(a, 2); append(b, 3); assertThat(a.getView(), is(not(b.getView()))); } /** * w/ frozen keys. */ @Test public void frozen() { KeyBuffer a = newBuffer(); KeyBuffer b = newBuffer(); assertThat(a.getFrozen(), is(a.getFrozen())); assertThat(a.getFrozen(), is(b.getFrozen())); assertThat(a.getFrozen().hashCode(), is(b.getFrozen().hashCode())); append(a, 1); assertThat(a.getFrozen(), is(not(b.getFrozen()))); append(b, 1); assertThat(a.getFrozen().hashCode(), is(b.getFrozen().hashCode())); append(a, 2); append(b, 3); assertThat(a.getFrozen(), is(not(b.getFrozen()))); } /** * clear. */ @Test public void clear() { KeyBuffer a = newBuffer(); KeyBuffer b = newBuffer(); append(a, 1, 2, 3); append(b, 1, 2, 3); assertThat(a.getView(), is(b.getView())); b.clear(); assertThat(a.getView(), is(not(b.getView()))); append(b, 1, 2, 3); assertThat(a.getView(), is(b.getView())); } /** * views. */ @Test public void views() { KeyBuffer a = newBuffer(); KeyBuffer b = newBuffer(); KeyBuffer.View a1 = append(a, 1).getFrozen(); KeyBuffer.View b1 = append(b, 1).getFrozen(); assertThat(a1, is(a1)); assertThat(a1, is(b1)); assertThat(a1, is(a.getView())); assertThat(a1, is(b.getView())); assertThat(a.getView(), is(b1)); assertThat(a.getView(), is(b1)); assertThat(a1.hashCode(), is(b1.hashCode())); KeyBuffer.View a12 = append(a, 2).getFrozen(); KeyBuffer.View b123 = append(b, 2, 3).getFrozen(); assertThat(a12, is(not(b123))); append(a, 3); KeyBuffer.View a123 = a.getFrozen(); assertThat(a12, is(not(a123))); assertThat(a123, is(b123)); } private KeyBuffer newBuffer() { return new HeapKeyBuffer(); } private KeyBuffer append(KeyBuffer buffer, int... values) { for (int value : values) { buffer.append(new IntWritable(value)); } return buffer; } }
3e0422ca07c31375c32424ac12bc177148932033
610
java
Java
src/test/java/com/adioss/security/AbstractBouncyCastleTest.java
adioss/cryptoMemo
1e8477072bf927860d841ecdf12bde40a7144a40
[ "Apache-2.0" ]
1
2017-07-11T01:34:20.000Z
2017-07-11T01:34:20.000Z
src/test/java/com/adioss/security/AbstractBouncyCastleTest.java
adioss/cryptoMemo
1e8477072bf927860d841ecdf12bde40a7144a40
[ "Apache-2.0" ]
null
null
null
src/test/java/com/adioss/security/AbstractBouncyCastleTest.java
adioss/cryptoMemo
1e8477072bf927860d841ecdf12bde40a7144a40
[ "Apache-2.0" ]
null
null
null
22.592593
67
0.713115
1,716
package com.adioss.security; import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.After; import org.junit.Before; /** * Add/remove bouncy castle provider before/after tests */ public class AbstractBouncyCastleTest { private String name; @Before public void setUp() throws Exception { BouncyCastleProvider provider = new BouncyCastleProvider(); name = provider.getName(); Security.addProvider(provider); } @After public void tearDown() throws Exception { Security.removeProvider(name); } }
3e04238aafed1b8045868d4c027373ba47aded15
12,571
java
Java
test/integration/src/test/java/io/pravega/test/integration/UnreadBytesTest.java
shshashwat/pravega
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
[ "Apache-2.0" ]
1,840
2017-05-10T16:29:14.000Z
2022-03-31T07:02:11.000Z
test/integration/src/test/java/io/pravega/test/integration/UnreadBytesTest.java
shshashwat/pravega
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
[ "Apache-2.0" ]
5,485
2017-05-10T16:56:17.000Z
2022-03-31T14:08:36.000Z
test/integration/src/test/java/io/pravega/test/integration/UnreadBytesTest.java
shshashwat/pravega
f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6
[ "Apache-2.0" ]
443
2017-05-10T21:34:50.000Z
2022-03-31T07:02:14.000Z
48.164751
173
0.697797
1,717
/** * Copyright Pravega Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pravega.test.integration; import com.google.common.collect.ImmutableMap; import io.pravega.client.ClientConfig; import io.pravega.client.EventStreamClientFactory; import io.pravega.client.admin.ReaderGroupManager; import io.pravega.client.control.impl.Controller; import io.pravega.client.segment.impl.Segment; import io.pravega.client.stream.Checkpoint; import io.pravega.client.stream.EventRead; import io.pravega.client.stream.EventStreamReader; import io.pravega.client.stream.EventStreamWriter; import io.pravega.client.stream.EventWriterConfig; import io.pravega.client.stream.ReaderConfig; import io.pravega.client.stream.ReaderGroup; import io.pravega.client.stream.ReaderGroupConfig; import io.pravega.client.stream.ScalingPolicy; import io.pravega.client.stream.Stream; import io.pravega.client.stream.StreamConfiguration; import io.pravega.client.stream.StreamCut; import io.pravega.client.stream.impl.JavaSerializer; import io.pravega.client.stream.impl.StreamCutImpl; import io.pravega.test.common.ThreadPooledTestSuite; import java.util.Arrays; import java.util.Map; import java.util.concurrent.CompletableFuture; import lombok.Cleanup; import org.junit.ClassRule; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class UnreadBytesTest extends ThreadPooledTestSuite { @ClassRule public static final PravegaResource PRAVEGA = new PravegaResource(); @Override protected int getThreadPoolSize() { return 1; } @Test(timeout = 50000) public void testUnreadBytes() throws Exception { StreamConfiguration config = StreamConfiguration.builder() .scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1)) .build(); String streamName = "testUnreadBytes"; Controller controller = PRAVEGA.getLocalController(); controller.createScope("unreadbytes").get(); controller.createStream("unreadbytes", streamName, config).get(); @Cleanup EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); @Cleanup EventStreamWriter<String> writer = clientFactory.createEventWriter(streamName, new JavaSerializer<>(), EventWriterConfig.builder().build()); String group = "testUnreadBytes-group"; @Cleanup ReaderGroupManager groupManager = ReaderGroupManager.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); groupManager.createReaderGroup(group, ReaderGroupConfig.builder().disableAutomaticCheckpoints().stream("unreadbytes/" + streamName).build()); @Cleanup ReaderGroup readerGroup = groupManager.getReaderGroup(group); @Cleanup EventStreamReader<String> reader = clientFactory.createReader("readerId", group, new JavaSerializer<>(), ReaderConfig.builder().build()); long unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 0); writer.writeEvent("0", "data of size 30").get(); writer.writeEvent("0", "data of size 30").get(); EventRead<String> firstEvent = reader.readNextEvent(15000); EventRead<String> secondEvent = reader.readNextEvent(15000); assertNotNull(firstEvent); assertEquals("data of size 30", firstEvent.getEvent()); assertNotNull(secondEvent); assertEquals("data of size 30", secondEvent.getEvent()); // trigger a checkpoint. CompletableFuture<Checkpoint> chkPointResult = readerGroup.initiateCheckpoint("test", executorService()); EventRead<String> chkpointEvent = reader.readNextEvent(15000); assertEquals("test", chkpointEvent.getCheckpointName()); EventRead<String> emptyEvent = reader.readNextEvent(100); assertEquals(false, emptyEvent.isCheckpoint()); assertEquals(null, emptyEvent.getEvent()); chkPointResult.join(); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 0); writer.writeEvent("0", "data of size 30").get(); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bytes: " + unreadBytes, unreadBytes == 30); } @Test(timeout = 50000) public void testUnreadBytesWithEndStreamCuts() throws Exception { StreamConfiguration config = StreamConfiguration.builder() .scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1)) .build(); String streamName = "testUnreadBytesWithEndStreamCuts"; Controller controller = PRAVEGA.getLocalController(); controller.createScope("unreadbytes").get(); controller.createStream("unreadbytes", streamName, config).get(); @Cleanup EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); @Cleanup EventStreamWriter<String> writer = clientFactory.createEventWriter(streamName, new JavaSerializer<>(), EventWriterConfig.builder().build()); //Write just 2 events to simplify simulating a checkpoint. writer.writeEvent("0", "data of size 30").get(); writer.writeEvent("0", "data of size 30").get(); String group = "testUnreadBytesWithEndStreamCuts-group"; @Cleanup ReaderGroupManager groupManager = ReaderGroupManager.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); //create a bounded reader group. groupManager.createReaderGroup(group, ReaderGroupConfig .builder().disableAutomaticCheckpoints().stream("unreadbytes/" + streamName, StreamCut.UNBOUNDED, getStreamCut(streamName, 90L, 0)).build()); ReaderGroup readerGroup = groupManager.getReaderGroup(group); @Cleanup EventStreamReader<String> reader = clientFactory.createReader("readerId", group, new JavaSerializer<>(), ReaderConfig.builder().build()); EventRead<String> firstEvent = reader.readNextEvent(15000); EventRead<String> secondEvent = reader.readNextEvent(15000); assertNotNull(firstEvent); assertEquals("data of size 30", firstEvent.getEvent()); assertNotNull(secondEvent); assertEquals("data of size 30", secondEvent.getEvent()); // trigger a checkpoint. CompletableFuture<Checkpoint> chkPointResult = readerGroup.initiateCheckpoint("test", executorService()); EventRead<String> chkpointEvent = reader.readNextEvent(15000); assertEquals("test", chkpointEvent.getCheckpointName()); EventRead<String> emptyEvent = reader.readNextEvent(100); assertEquals(false, emptyEvent.isCheckpoint()); assertEquals(null, emptyEvent.getEvent()); chkPointResult.join(); //Writer events, to ensure 120Bytes are written. writer.writeEvent("0", "data of size 30").get(); writer.writeEvent("0", "data of size 30").get(); long unreadBytes = readerGroup.getMetrics().unreadBytes(); //Ensure the endoffset of 90 Bytes is taken into consideration when computing unread assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 30); } @Test public void testUnreadBytesWithCheckpointsAndStreamCuts() throws Exception { StreamConfiguration config = StreamConfiguration.builder() .scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1)) .build(); String streamName = "testUnreadBytesWithCheckpointsAndStreamCuts"; Controller controller = PRAVEGA.getLocalController(); controller.createScope("unreadbytes").get(); controller.createStream("unreadbytes", streamName, config).get(); @Cleanup EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); @Cleanup EventStreamWriter<String> writer = clientFactory.createEventWriter(streamName, new JavaSerializer<>(), EventWriterConfig.builder().build()); String group = "testUnreadBytesWithCheckpointsAndStreamCuts-group"; @Cleanup ReaderGroupManager groupManager = ReaderGroupManager.withScope("unreadbytes", ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build()); groupManager.createReaderGroup(group, ReaderGroupConfig.builder().disableAutomaticCheckpoints().stream("unreadbytes/" + streamName).build()); @Cleanup ReaderGroup readerGroup = groupManager.getReaderGroup(group); @Cleanup EventStreamReader<String> reader = clientFactory.createReader("readerId", group, new JavaSerializer<>(), ReaderConfig.builder().build()); long unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 0); writer.writeEvent("0", "data of size 30").get(); writer.writeEvent("0", "data of size 30").get(); EventRead<String> firstEvent = reader.readNextEvent(15000); EventRead<String> secondEvent = reader.readNextEvent(15000); assertNotNull(firstEvent); assertEquals("data of size 30", firstEvent.getEvent()); assertNotNull(secondEvent); assertEquals("data of size 30", secondEvent.getEvent()); // trigger a checkpoint. CompletableFuture<Checkpoint> chkPointResult = readerGroup.initiateCheckpoint("test", executorService()); EventRead<String> chkpointEvent = reader.readNextEvent(15000); assertEquals("test", chkpointEvent.getCheckpointName()); EventRead<String> emptyEvent = reader.readNextEvent(100); assertEquals(false, emptyEvent.isCheckpoint()); assertEquals(null, emptyEvent.getEvent()); chkPointResult.join(); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 0); // starting from checkpoint "test", data of size 30 is read writer.writeEvent("0", "data of size 30").get(); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bytes: " + unreadBytes, unreadBytes == 30); // trigger a stream-cut CompletableFuture<Map<Stream, StreamCut>> scResult = readerGroup.generateStreamCuts(executorService()); EventRead<String> scEvent = reader.readNextEvent(15000); reader.readNextEvent(100); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bvtes: " + unreadBytes, unreadBytes == 30); // starting from checkpoint "test", data of size 60 is written => stream-cut does not change last checkpointed position writer.writeEvent("0", "data of size 30").get(); unreadBytes = readerGroup.getMetrics().unreadBytes(); assertTrue("Unread bytes: " + unreadBytes, unreadBytes == 60); } /* * Test method to create StreamCuts. In the real world StreamCuts are obtained via the Pravega client apis. */ private StreamCut getStreamCut(String streamName, long offset, int... segmentNumbers) { ImmutableMap.Builder<Segment, Long> builder = ImmutableMap.<Segment, Long>builder(); Arrays.stream(segmentNumbers).forEach(seg -> { builder.put(new Segment("unreadbytes", streamName, seg), offset); }); return new StreamCutImpl(Stream.of("unreadbytes", streamName), builder.build()); } }
3e042458dbbac773aa8c2c6b4e8ba625c6c9ecc8
1,067
java
Java
src/test/java/module/JavaScriptError.java
rajitha1406/take-home-webdriver-test
1ecf7965533f7eebb62c32ec64e15774dbf852d2
[ "MIT" ]
null
null
null
src/test/java/module/JavaScriptError.java
rajitha1406/take-home-webdriver-test
1ecf7965533f7eebb62c32ec64e15774dbf852d2
[ "MIT" ]
null
null
null
src/test/java/module/JavaScriptError.java
rajitha1406/take-home-webdriver-test
1ecf7965533f7eebb62c32ec64e15774dbf852d2
[ "MIT" ]
null
null
null
25.404762
70
0.759138
1,718
package module; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.logging.LogEntries; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import configuration.PageLoader; public class JavaScriptError { private WebDriver driver = null; public JavaScriptError(WebDriver driver) { this.driver = driver; this.loadPage(); } public List<String> getLogEntryMessages() { LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER); // Store a copy of only the messages, since that's interesting List<String> messages = new ArrayList<String>(); for( LogEntry entry : logEntries ) { messages.add(entry.getMessage()); } return messages; } public void loadPage() { PageLoader.loadPage(driver, "/javascript_error"); } }
3e0424f9ff735e100f3ddbdd8e2005945c867984
2,216
java
Java
src/main/java/info/skydark/maidpro/EventHookWolf.java
skydark/maidpro
3ab723a3a98b41e5d3a64a42574d92e2dcac970f
[ "MIT" ]
null
null
null
src/main/java/info/skydark/maidpro/EventHookWolf.java
skydark/maidpro
3ab723a3a98b41e5d3a64a42574d92e2dcac970f
[ "MIT" ]
null
null
null
src/main/java/info/skydark/maidpro/EventHookWolf.java
skydark/maidpro
3ab723a3a98b41e5d3a64a42574d92e2dcac970f
[ "MIT" ]
null
null
null
44.32
141
0.710289
1,719
package info.skydark.maidpro; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import info.skydark.maidpro.ai.EntityAIHurtByTargetPlus; import info.skydark.maidpro.ai.EntityAIOwnerHurtByTargetPlus; import info.skydark.maidpro.ai.EntityAIOwnerHurtTargetPlus; import littleMaidMobX.LMM_EntityLittleMaid; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.*; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent; /** * Created by skydark on 15-11-11. */ public class EventHookWolf { @SubscribeEvent public void onEntitySpawn(EntityJoinWorldEvent event) { if (event.entity instanceof EntityWolf) { EntityWolf entity = (EntityWolf) event.entity; for (Object entry : entity.targetTasks.taskEntries.toArray()) { EntityAIBase ai = ((EntityAITasks.EntityAITaskEntry) entry).action; if (ai instanceof EntityAIOwnerHurtByTarget || ai instanceof EntityAIOwnerHurtTarget || ai instanceof EntityAIHurtByTarget) { entity.targetTasks.removeTask(ai); } } entity.targetTasks.addTask(1, new EntityAIOwnerHurtByTargetPlus(entity)); entity.targetTasks.addTask(2, new EntityAIOwnerHurtTargetPlus(entity)); entity.targetTasks.addTask(3, new EntityAIHurtByTargetPlus(entity, true)); } } @SubscribeEvent public void onSetAttackTarget(LivingSetAttackTargetEvent event) { if (!(event.entity instanceof EntityWolf)) return; EntityWolf wolf = (EntityWolf) event.entity; EntityLivingBase target = wolf.getAttackTarget(); if (target == null || !(target instanceof LMM_EntityLittleMaid)) return; EntityLivingBase owner = wolf.getOwner(); if (owner instanceof EntityPlayer && ((LMM_EntityLittleMaid) target).isMaidContractOwner((EntityPlayer) owner)) { wolf.setAttackTarget(null); wolf.setTarget(null); wolf.setRevengeTarget(null); } } }
3e0425a1ef7370730fa889f3ac36c9414bb20a3e
446
java
Java
src/main/java/com/hubspot/jinjava/interpret/UnknownTokenException.java
ylacaute/jinjava
8fcfe6071bba48cb5eaa99b1937f3a39afc284dc
[ "Apache-2.0" ]
544
2015-01-06T02:18:44.000Z
2022-03-30T20:59:10.000Z
src/main/java/com/hubspot/jinjava/interpret/UnknownTokenException.java
ylacaute/jinjava
8fcfe6071bba48cb5eaa99b1937f3a39afc284dc
[ "Apache-2.0" ]
378
2015-02-13T20:49:15.000Z
2022-03-30T07:27:02.000Z
src/main/java/com/hubspot/jinjava/interpret/UnknownTokenException.java
ylacaute/jinjava
8fcfe6071bba48cb5eaa99b1937f3a39afc284dc
[ "Apache-2.0" ]
188
2015-02-13T21:00:49.000Z
2022-03-23T09:08:30.000Z
27.875
81
0.753363
1,720
package com.hubspot.jinjava.interpret; public class UnknownTokenException extends InterpretException { private static final long serialVersionUID = -388757722051666198L; private final String token; public UnknownTokenException(String token, int lineNumber, int startPosition) { super("Unknown token found: " + token.trim(), lineNumber, startPosition); this.token = token; } public String getToken() { return token; } }
3e0425e3cceb790205a9c517955ae144493087d8
2,084
java
Java
data7/src/main/java/data7/model/change/Commit.java
vuninja/VulnNet
ad6dd1f4df882f6f8e9ea9aa4ca4d9434a70aecd
[ "Apache-2.0" ]
33
2018-06-27T13:36:04.000Z
2021-12-03T10:15:07.000Z
data7/src/main/java/data7/model/change/Commit.java
vuninja/VulnNet
ad6dd1f4df882f6f8e9ea9aa4ca4d9434a70aecd
[ "Apache-2.0" ]
7
2018-12-11T13:41:03.000Z
2020-08-03T07:36:01.000Z
data7/src/main/java/data7/model/change/Commit.java
vuninja/VulnNet
ad6dd1f4df882f6f8e9ea9aa4ca4d9434a70aecd
[ "Apache-2.0" ]
15
2018-10-10T07:30:04.000Z
2021-04-21T09:03:15.000Z
23.954023
85
0.642994
1,721
package data7.model.change; /*- * #%L * Data7 * %% * Copyright (C) 2018 University of Luxembourg, Matthieu Jimenez * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.Serializable; import java.util.List; /** * Data class representing a commit */ public class Commit implements Serializable { private static final long serialVersionUID = 20180531L; //commit full message private final String message; //commit timestamp private final long timestamp; //list of all the file that were modified by the commit private final List<FileFix> fixes; //commit hash private final String hash; /** * Constructor of the commit class * @param hash * @param message * @param timestamp * @param fixes list of modified files */ public Commit(String hash, String message, long timestamp, List<FileFix> fixes) { this.hash = hash; this.message = message; this.timestamp = timestamp; this.fixes = fixes; } /** * @return the full message of the commit */ public String getMessage() { return message; } /** * @return the timestamp of the commit */ public long getTimestamp() { return timestamp; } /** * @return the list of the files that were modified by the commit * @see FileFix */ public List<FileFix> getFixes() { return fixes; } /** * @return the hash of the commit */ public String getHash() { return hash; } }
3e04263e3d4a07ba215f9ebb83fbdb8703351ce8
2,545
java
Java
modules/blockchain/src/test/java/com/ibm/cloud/blockchain/v3/model/ConfigPeerGossipElectionTest.java
IBM-Blockchain/ibp-java-sdk
3faabbb314eb41cf6e1c1fe5bb55b047b635ddc8
[ "Apache-2.0" ]
null
null
null
modules/blockchain/src/test/java/com/ibm/cloud/blockchain/v3/model/ConfigPeerGossipElectionTest.java
IBM-Blockchain/ibp-java-sdk
3faabbb314eb41cf6e1c1fe5bb55b047b635ddc8
[ "Apache-2.0" ]
1
2020-12-01T16:36:19.000Z
2020-12-09T10:36:14.000Z
modules/blockchain/src/test/java/com/ibm/cloud/blockchain/v3/model/ConfigPeerGossipElectionTest.java
IBM-Blockchain/ibp-java-sdk
3faabbb314eb41cf6e1c1fe5bb55b047b635ddc8
[ "Apache-2.0" ]
1
2020-12-01T16:33:14.000Z
2020-12-01T16:33:14.000Z
47.12963
128
0.794106
1,722
/* * (C) Copyright IBM Corp. 2020. * * 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.ibm.cloud.blockchain.v3.model; import com.ibm.cloud.blockchain.v3.model.ConfigPeerGossipElection; import com.ibm.cloud.blockchain.v3.utils.TestUtilities; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import java.io.InputStream; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Unit test class for the ConfigPeerGossipElection model. */ public class ConfigPeerGossipElectionTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testConfigPeerGossipElection() throws Throwable { ConfigPeerGossipElection configPeerGossipElectionModel = new ConfigPeerGossipElection.Builder() .startupGracePeriod("15s") .membershipSampleInterval("1s") .leaderAliveThreshold("10s") .leaderElectionDuration("5s") .build(); assertEquals(configPeerGossipElectionModel.startupGracePeriod(), "15s"); assertEquals(configPeerGossipElectionModel.membershipSampleInterval(), "1s"); assertEquals(configPeerGossipElectionModel.leaderAliveThreshold(), "10s"); assertEquals(configPeerGossipElectionModel.leaderElectionDuration(), "5s"); String json = TestUtilities.serialize(configPeerGossipElectionModel); ConfigPeerGossipElection configPeerGossipElectionModelNew = TestUtilities.deserialize(json, ConfigPeerGossipElection.class); assertTrue(configPeerGossipElectionModelNew instanceof ConfigPeerGossipElection); assertEquals(configPeerGossipElectionModelNew.startupGracePeriod(), "15s"); assertEquals(configPeerGossipElectionModelNew.membershipSampleInterval(), "1s"); assertEquals(configPeerGossipElectionModelNew.leaderAliveThreshold(), "10s"); assertEquals(configPeerGossipElectionModelNew.leaderElectionDuration(), "5s"); } }
3e042666c523136c3c002afe3489a540df3719d8
378
java
Java
gulimall-member/src/main/java/com/xunqi/gulimall/member/service/MemberLevelService.java
bolongxi/gulimall
ab31b128e700987b3f8d007baab2f8190f12d8e7
[ "Apache-2.0" ]
null
null
null
gulimall-member/src/main/java/com/xunqi/gulimall/member/service/MemberLevelService.java
bolongxi/gulimall
ab31b128e700987b3f8d007baab2f8190f12d8e7
[ "Apache-2.0" ]
null
null
null
gulimall-member/src/main/java/com/xunqi/gulimall/member/service/MemberLevelService.java
bolongxi/gulimall
ab31b128e700987b3f8d007baab2f8190f12d8e7
[ "Apache-2.0" ]
null
null
null
21
73
0.78836
1,723
package com.xunqi.gulimall.member.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xunqi.common.utils.PageUtils; import com.xunqi.gulimall.member.entity.MemberLevelEntity; import java.util.Map; /** * 会员等级 * */ public interface MemberLevelService extends IService<MemberLevelEntity> { PageUtils queryPage(Map<String, Object> params); }
3e0426b5b6a66394d48f510f93ca434bd4ff3852
9,065
java
Java
src/MQTTUtility/runtime/ssac/aadl/runtime/mqtt/MqttSession.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
src/MQTTUtility/runtime/ssac/aadl/runtime/mqtt/MqttSession.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
src/MQTTUtility/runtime/ssac/aadl/runtime/mqtt/MqttSession.java
degulab/FALCON-SEED
69c7ecd5c13dd75aa33371be086a3e77a068d8ca
[ "MIT" ]
null
null
null
33.698885
118
0.699724
1,724
/* * 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. * * Copyright 2007-2013 SSAC(Systems of Social Accounting Consortium) * <author> Yasunari Ishizuka (PieCake,Inc.) * <author> Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY) * <author> Yuji Onuki (Statistics Bureau) * <author> Shungo Sakaki (Tokyo University of Technology) * <author> Akira Sasaki (HOSEI UNIVERSITY) * <author> Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY) */ /* * @(#)MqttSession.java 0.3.0 2013/06/27 * - modified by Y.Ishizuka(PieCake.inc,) * @(#)MqttSession.java 0.2.0 2013/05/15 * - modified by Y.Ishizuka(PieCake.inc,) * @(#)MqttSession.java 0.1.0 2013/03/07 * - created by Y.Ishizuka(PieCake.inc,) */ package ssac.aadl.runtime.mqtt; /** * MQTT のセッションを管理するインタフェース。 * * @version 0.3.0 2013/06/27 * * @author Yasunari Ishizuka (PieCake,Inc.) * @author Hiroshi Deguchi (TOKYO INSTITUTE OF TECHNOLOGY) * @author Hideki Tanuma (TOKYO INSTITUTE OF TECHNOLOGY) */ public interface MqttSession { //------------------------------------------------------------ // Constants //------------------------------------------------------------ //------------------------------------------------------------ // Public interfaces //------------------------------------------------------------ /** * 接続先サーバーの URI を取得する。 * @return サーバー URI */ public String getServerURI(); /** * 現在設定されているクライアントIDを返す。 * @return クライアントID */ public String getClientID(); /** * 再接続時にセッションの状態をクリアするかどうかの設定を取得する。 * @return クリアする場合は <tt>true</tt>、それ以外の場合は <tt>false</tt> */ public boolean isCleanSession(); /** * 接続時のタイムアウト時間を返す。デフォルトは 30 秒。 * このタイムアウト時間は、サーバーへの接続、サブスクライブ、アンサブスクライブの * リクエスト完了までのタイムアウトを指定する。 * @return タイムアウト時間[秒] */ public int getConnectionTimeout(); /** * キープアライブ間隔を返す。デフォルトは 60 秒。 * この時間間隔は、送信もしくは受信したメッセージ間の最大時間間隔を定義する。 * @return キープアライブ間隔[秒] */ public int getKeepAliveInterval(); /** * このセッションがサーバーと接続されている場合に <tt>true</tt> を返す。 * @return 接続中なら <tt>true</tt>、それ以外の場合は <tt>false</tt> */ public boolean isConnected(); /** * このセッションが何らかの理由により切断された場合に <tt>true</tt> を返す。 * {@link #isConnected()} が <tt>true</tt> を返す場合、もしくは * {@link #disconnect()} によって正常に切断されている場合、このメソッドは <tt>false</tt> を返す。 * @return 何らかの理由により切断された場合は <tt>true</tt>、それ以外の場合は <tt>false</tt> */ public boolean isConnectionLost(); /** * このセッションが何らかの理由に切断されたときの、要因を示す例外オブジェクトを返す。 * {@link #isConnected()} が <tt>true</tt> を返す場合、もしくは * {@link #disconnect()} によって正常に切断されている場合、このメソッドは <tt>null</tt> を返す。 * @return 何らかの理由によりセッションが切断されたときの要因である例外オブジェクトを返す。 * 接続中もしくは正常に切断されている場合は <tt>null</tt> を返す。 */ public Throwable getConnectionLostCause(); // /** // * 現在の接続パラメータで、サーバーへ接続する。 // * @throws MqttRuntimeException 正常に接続できなかった場合、もしくはすでに接続されている場合 // */ // public void connect(); /** * このセッションを切断する。 * すでに切断されているセッションの場合、このメソッドは何もしない。 * @throws MqttRuntimeException 正常に切断できなかった場合 */ public void disconnect(); /** * 指定されたトピックに対してメッセージを投稿する。 * このメソッドは、投稿完了まで待たない。 * <p>投稿完了までの待機には、このメソッドが返す <code>MqDeliveryToken</code> オブジェクトの * <code>waitForCompletion()</code> もしくは <code>waitForCompletion(long timeout)</code> を実行する。 * 投稿が完了したかどうかの判定には <code>MqDeliveryToken</code> オブジェクトの <code>isComplete()</code> が * <tt>true</tt> を返せば、投稿完了となる。 * @param topic トピック * @param payload 投稿するメッセージのバイト配列 * @param qos メッセージ伝達品質(0, 1, 2) * @param retained サーバーにメッセージを残す場合は <tt>true</tt> * @return <code>MqDeliveryToken</code> オブジェクト * @throws IllegalArgumentException <em>qos</em> の値が 0、1、2 のどれかではない場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException publish に失敗した場合 */ public MqDeliveryToken asyncPublish(String topic, byte[] payload, int qos, boolean retained); /** * 指定されたトピックに対してメッセージを投稿する。 * このメソッドは、投稿完了まで待たない。 * <p>投稿完了までの待機には、このメソッドが返す <code>MqDeliveryToken</code> オブジェクトの * <code>waitForCompletion()</code> もしくは <code>waitForCompletion(long timeout)</code> を実行する。 * 投稿が完了したかどうかの判定には <code>MqDeliveryToken</code> オブジェクトの <code>isComplete()</code> が * <tt>true</tt> を返せば、投稿完了となる。 * @param topic トピック * @param payload 投稿するメッセージのバイト配列 * @param offset 投稿するバイト配列の開始位置 * @param length 投稿するバイト配列のオフセット位置からの有効データ長 * @param qos メッセージ伝達品質(0, 1, 2) * @param retained サーバーにメッセージを残す場合は <tt>true</tt> * @return <code>MqDeliveryToken</code> オブジェクト * @throws IndexOutOfBoundsException <em>offset</em> および <em>length</em> の値が適切ではない場合 * @throws IllegalArgumentException <em>qos</em> の値が 0、1、2 のどれかではない場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException publish に失敗した場合 * @since 0.3.0 */ public MqDeliveryToken asyncPublish(String topic, byte[] payload, int offset, int length, int qos, boolean retained); /** * 指定されたトピックに対してメッセージを投稿する。 * このメソッドは、投稿が完了するまで処理をブロックする。 * @param topic トピック * @param payload 投稿するメッセージのバイト配列 * @param qos メッセージ伝達品質(0, 1, 2) * @param retained サーバーにメッセージを残す場合は <tt>true</tt> * @throws IllegalArgumentException <em>qos</em> の値が 0、1、2 のどれかではない場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException publish に失敗した場合 */ public void publishAndWait(String topic, byte[] payload, int qos, boolean retained); /** * 指定されたトピックに対してメッセージを投稿する。 * このメソッドは、投稿が完了するまで処理をブロックする。 * @param topic トピック * @param payload 投稿するメッセージのバイト配列 * @param offset 投稿するバイト配列の開始位置 * @param length 投稿するバイト配列のオフセット位置からの有効データ長 * @param qos メッセージ伝達品質(0, 1, 2) * @param retained サーバーにメッセージを残す場合は <tt>true</tt> * @throws IndexOutOfBoundsException <em>offset</em> および <em>length</em> の値が適切ではない場合 * @throws IllegalArgumentException <em>qos</em> の値が 0、1、2 のどれかではない場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException publish に失敗した場合 * @since 0.3.0 */ public void publishAndWait(String topic, byte[] payload, int offset, int length, int qos, boolean retained); /** * 指定されたトピックに対して、<code>qos=1</code> でメッセージの購読を要求する。 * トピックにはワイルドカードが指定できる。 * @param topic トピック(ワイルドカード含む) * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException subscribe に失敗した場合 */ public void subscribe(String topic); /** * 指定されたトピックに対して、メッセージの購読を要求する。 * トピックにはワイルドカードが指定できる。 * @param topic トピック(ワイルドカード含む) * @param qos 購読時のメッセージ伝達品質(0, 1, 2) * @throws IllegalArgumentException <em>qos</em> の値が 0、1、2 のどれかではない場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException subscribe に失敗した場合 */ public void subscribe(String topic, int qos); /** * 指定されたトピックに対して、<code>qos=1</code> でメッセージの購読を要求する。 * トピックにはワイルドカードが指定できる。 * @param topicFilters トピック(ワイルドカード含む)の配列 * @throws NullPointerException 引数が <tt>null</tt> の場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException subscribe に失敗した場合 */ public void subscribe(String[] topicFilters); /** * 指定されたトピックに対して、メッセージの購読を要求する。 * トピックにはワイルドカードが指定できる。 * @param topicFilters トピック(ワイルドカード含む)の配列 * @param qos 購読時のメッセージ伝達品質(0, 1, 2)の配列 * @throws NullPointerException 引数が <tt>null</tt> の場合 * @throws IllegalArgumentException <em>topicFilters</code> の要素数より <em>qos</em> の要素数が少ない場合、 * もしくは <em>qos</em> の要素の値に 0、1、2 以外の値が含まれる場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException subscribe に失敗した場合 */ public void subscribe(String[] topicFilters, int[] qos); /** * 指定されたトピックに対するメッセージの購読を解除する。 * トピックにはワイルドカードが指定できる。 * @param topic トピック(ワイルドカード含む) * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException unsubscribe に失敗した場合 */ public void unsubscribe(String topic); /** * 指定されたトピックに対するメッセージの購読を解除する。 * トピックにはワイルドカードが指定できる。 * @param topicFilters トピック(ワイルドカード含む)の配列 * @throws NullPointerException 引数が <tt>null</tt> の場合 * @throws IllegalStateException サーバーに接続されていない場合 * @throws MqttRuntimeException unsubscribe に失敗した場合 */ public void unsubscribe(String[] topicFilters); // /** // * 現在設定されている MQTT イベントハンドラを取得する。 // * 設定されていない場合は <tt>null</tt> を返す。 // * @return 設定されている <code>MqttEventHandler</code> オブジェクト、設定されていない場合は <tt>null</tt> // * @see ssac.aadl.runtime.mqtt.event.MqttEventHandler // */ // public MqttEventHandler getEventHandler(); // // /** // * 新しい MQTT イベントハンドラを設定する。 // * イベントハンドラを無効にする場合は <tt>null</tt> を指定する。 // * @param newHandler <code>MqttEventHandler</code> オブジェクト、設定しない場合は <tt>null</tt> // * @see ssac.aadl.runtime.mqtt.event.MqttEventHandler // */ // public void setEventHandler(MqttEventHandler newHandler); }
3e04275e585ebd027db3f2e12b7ea2126cb33860
1,029
java
Java
src/main/java/hu/gamf/szakdolgozatbackend/service/WorktimeService.java
twead/szakdolgozat-backend
83b593d9af86c7cba2d01071eca1f62f456061da
[ "MIT" ]
null
null
null
src/main/java/hu/gamf/szakdolgozatbackend/service/WorktimeService.java
twead/szakdolgozat-backend
83b593d9af86c7cba2d01071eca1f62f456061da
[ "MIT" ]
null
null
null
src/main/java/hu/gamf/szakdolgozatbackend/service/WorktimeService.java
twead/szakdolgozat-backend
83b593d9af86c7cba2d01071eca1f62f456061da
[ "MIT" ]
null
null
null
26.384615
77
0.82896
1,725
package hu.gamf.szakdolgozatbackend.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import hu.gamf.szakdolgozatbackend.entity.Worktime; import hu.gamf.szakdolgozatbackend.repository.WorktimeRepository; @Service public class WorktimeService { private WorktimeRepository worktimeRepository; @Autowired public WorktimeService(WorktimeRepository worktimeRepository) { this.worktimeRepository = worktimeRepository; } public Optional<Worktime> findWorktimeById(Long id) { return worktimeRepository.findById(id); } public void saveWorktime(Worktime worktime) { worktimeRepository.save(worktime); } public List<Worktime> findAllWorktimeByPractitionerId(Long practitionerId) { return worktimeRepository.findAllByPractitionerId(practitionerId); } public void deleteAllWorktimeByPractitionerId(Long practitionerId) { worktimeRepository.deleteAllByPractitionerId(practitionerId); } }
3e0427804d94f0a219fe583c53e866bffc77b4cd
2,864
java
Java
diozero-sampleapps/src/main/java/com/diozero/sampleapps/JoystickTest.java
stbischof/diozero
2df77949772694513fc5acf027d3c5fbcfac1685
[ "MIT" ]
214
2016-05-26T21:01:53.000Z
2022-03-01T15:22:03.000Z
diozero-sampleapps/src/main/java/com/diozero/sampleapps/JoystickTest.java
stbischof/diozero
2df77949772694513fc5acf027d3c5fbcfac1685
[ "MIT" ]
81
2016-05-31T10:28:16.000Z
2022-03-11T17:52:43.000Z
diozero-sampleapps/src/main/java/com/diozero/sampleapps/JoystickTest.java
stbischof/diozero
2df77949772694513fc5acf027d3c5fbcfac1685
[ "MIT" ]
58
2016-06-11T20:15:19.000Z
2022-01-29T13:20:55.000Z
36.717949
81
0.718575
1,726
package com.diozero.sampleapps; /*- * #%L * Organisation: diozero * Project: diozero - Sample applications * Filename: JoystickTest.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2021 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import org.tinylog.Logger; import com.diozero.api.AnalogInputDevice; import com.diozero.devices.PCF8591; import com.diozero.devices.PwmLed; import com.diozero.util.Diozero; import com.diozero.util.SleepUtil; public class JoystickTest { public static void main(String[] args) { if (args.length < 4) { Logger.error("Usage: {} <adc1> <adc2> <pwm1> <pwm2>", JoystickTest.class); System.exit(1); } int adc_num1 = Integer.parseInt(args[0]); int adc_num2 = Integer.parseInt(args[1]); int pwm1 = Integer.parseInt(args[2]); int pwm2 = Integer.parseInt(args[3]); test(adc_num1, adc_num2, pwm1, pwm2); } private static void test(int adcNum1, int adcNum2, int pwm1, int pwm2) { try (PCF8591 adc = new PCF8591(1); AnalogInputDevice axis_1 = new AnalogInputDevice(adc, adcNum1); AnalogInputDevice axis_2 = new AnalogInputDevice(adc, adcNum2); PwmLed led1 = new PwmLed(pwm1); PwmLed led2 = new PwmLed(pwm2)) { axis_1.addListener(event -> led1.setValue(event.getUnscaledValue())); axis_2.addListener(event -> led2.setValue(event.getUnscaledValue())); for (int i = 0; i < 20; i++) { Logger.info("axis 1: {}, axis 2: {}", Float.valueOf(axis_1.getScaledValue()), Float.valueOf(axis_2.getScaledValue())); SleepUtil.sleepSeconds(1); } } finally { // Required if there are non-daemon threads that will prevent the // built-in clean-up routines from running Diozero.shutdown(); } } }
3e0427cc99f9c76b1aef61ed26f5f621c616bbd5
9,104
java
Java
integration/dataservice-hosting-tests/tests-integration/tests/src/test/java/org/wso2/ei/dataservice/integration/test/syntax/ReturnRequestStatusTest.java
sajithaliyanage/product-ei
7cc0ab117429967bc01d602a23805e9955924e6a
[ "Apache-2.0" ]
339
2017-03-29T20:40:34.000Z
2022-03-31T08:05:43.000Z
integration/dataservice-hosting-tests/tests-integration/tests/src/test/java/org/wso2/ei/dataservice/integration/test/syntax/ReturnRequestStatusTest.java
sajithaliyanage/product-ei
7cc0ab117429967bc01d602a23805e9955924e6a
[ "Apache-2.0" ]
3,938
2017-01-23T12:28:02.000Z
2022-03-28T14:20:20.000Z
integration/dataservice-hosting-tests/tests-integration/tests/src/test/java/org/wso2/ei/dataservice/integration/test/syntax/ReturnRequestStatusTest.java
sajithaliyanage/product-ei
7cc0ab117429967bc01d602a23805e9955924e6a
[ "Apache-2.0" ]
345
2016-12-21T11:59:07.000Z
2022-03-31T08:39:38.000Z
44.817734
129
0.656188
1,727
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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.ei.dataservice.integration.test.syntax; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axis2.AxisFault; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.test.utils.axis2client.AxisServiceClient; import org.wso2.carbon.automation.test.utils.concurrency.test.exception.ConcurrencyTestFailedError; import org.wso2.carbon.automation.test.utils.concurrency.test.exception.ExceptionHandler; import org.wso2.ei.dataservice.integration.common.utils.DSSTestCaseUtils; import org.wso2.ei.dataservice.integration.test.DSSIntegrationTest; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.assertTrue; //https://wso2.org/jira/browse/CARBON-12361 public class ReturnRequestStatusTest extends DSSIntegrationTest { private static final Log log = LogFactory.getLog(ReturnRequestStatusTest.class); private final OMFactory fac = OMAbstractFactory.getOMFactory(); private final OMNamespace omNs = fac.createOMNamespace("http://ws.wso2.org/dataservice/samples/" + "rdbms_sample", "ns1"); private static String serviceName = "ReturnRequestStatusTest"; private static String serviceEndPoint; private DSSTestCaseUtils dssTest; @BeforeClass(alwaysRun = true) public void initialize() throws Exception { super.init(); List<File> sqlFileLis = new ArrayList<File>(); dssTest = new DSSTestCaseUtils(); sqlFileLis.add(selectSqlFile("CreateTables.sql")); deployService(serviceName, createArtifact(getResourceLocation() + File.separator + "dbs" + File.separator + "rdbms" + File.separator + "MySql" + File.separator + "ReturnRequestStatusTest.dbs", sqlFileLis)); serviceEndPoint = getServiceUrlHttp(serviceName); } @Test(groups = "wso2.dss", description = "check whether the service is deployed") public void testServiceDeployment() throws Exception { assertTrue(dssTest.isServiceDeployed(dssContext.getContextUrls().getBackEndUrl(), sessionCookie, serviceName)); } @Test(groups = "wso2.dss", dependsOnMethods = {"testServiceDeployment"}, description = "add employees") public void requestStatusNameSpaceQualifiedForInsertOperation() throws AxisFault { addEmployee(serviceEndPoint, String.valueOf(180)); log.info("Insert Operation Success"); } @Test(groups = "wso2.dss", dependsOnMethods = {"requestStatusNameSpaceQualifiedForInsertOperation"}) public void requestStatusNameSpaceQualifiedForDeleteOperation() throws AxisFault { deleteEmployeeById(String.valueOf(180)); log.info("Delete operation success"); } @Test(groups = "wso2.dss", dependsOnMethods = {"requestStatusNameSpaceQualifiedForDeleteOperation"}, timeOut = 1000 * 60 * 2) public void inOperationConcurrencyTest() throws InterruptedException, ConcurrencyTestFailedError { final ExceptionHandler handler = new ExceptionHandler(); final int concurrencyNumber = 50; final int numberOfIterations = 1; Thread[] clientThread = new Thread[concurrencyNumber]; final AxisServiceClient serviceClient = new AxisServiceClient(); for (int i = 0; i < concurrencyNumber; i++) { final int empNo = i + 50; clientThread[i] = new Thread(new Runnable() { public void run() { for (int j = 0; j < numberOfIterations; j++) { try { OMElement response = serviceClient.sendReceive(getAddEmployeePayload(empNo + ""), serviceEndPoint, "addEmployee"); Assert.assertTrue(response.toString().contains("SUCCESSFUL"), "Response Not Successful"); OMNamespace nameSpace = response.getNamespace(); Assert.assertNotNull(nameSpace, "Response Message NameSpace not qualified"); } catch (AxisFault axisFault) { log.error(axisFault); handler.setException(axisFault); } } } }); clientThread[i].setUncaughtExceptionHandler(handler); } for (int i = 0; i < concurrencyNumber; i++) { clientThread[i].start(); } for (int i = 0; i < concurrencyNumber; i++) { try { clientThread[i].join(); } catch (InterruptedException e) { throw new InterruptedException("Exception Occurred while joining Thread"); } } if (!handler.isTestPass()) { throw new ConcurrencyTestFailedError(handler.getFailCount() + " service invocation/s failed out of " + concurrencyNumber * numberOfIterations + " service invocations.\n" + "Concurrency Test Failed for Thread Group=" + concurrencyNumber + " and loop count=" + numberOfIterations, handler.getException()); } } @AfterClass(alwaysRun = true) public void testCleanup() throws Exception { dssTest.deleteService(dssContext.getContextUrls().getBackEndUrl(),sessionCookie, serviceName); } private void addEmployee(String serviceEndPoint, String employeeNumber) throws AxisFault { OMElement result; result = new AxisServiceClient().sendReceive(getAddEmployeePayload(employeeNumber), serviceEndPoint, "addEmployee"); Assert.assertTrue(result.toString().contains("SUCCESSFUL"), "Response Not Successful"); OMNamespace nameSpace = result.getNamespace(); Assert.assertNotNull(nameSpace, "Response Message NameSpace not qualified"); Assert.assertNotNull(nameSpace.getPrefix(), "Invalid prefix. prefix value null"); Assert.assertNotSame(nameSpace.getPrefix(), "", "Invalid prefix"); Assert.assertEquals(nameSpace.getNamespaceURI(), "http://ws.wso2.org/dataservice", "Invalid NamespaceURI"); } private void deleteEmployeeById(String employeeNumber) throws AxisFault { OMElement result; OMElement payload = fac.createOMElement("deleteEmployeeById", omNs); OMElement empNo = fac.createOMElement("employeeNumber", omNs); empNo.setText(employeeNumber); payload.addChild(empNo); result = new AxisServiceClient().sendReceive(payload, serviceEndPoint, "deleteEmployeeById"); Assert.assertTrue(result.toString().contains("SUCCESSFUL"), "Response Not Successful"); OMNamespace nameSpace = result.getNamespace(); Assert.assertNotNull(nameSpace.getPrefix(), "Invalid prefix. prefix value null"); Assert.assertNotSame(nameSpace.getPrefix(), "", "Invalid prefix"); Assert.assertEquals(nameSpace.getNamespaceURI(), "http://ws.wso2.org/dataservice", "Invalid NamespaceURI"); } private OMElement getAddEmployeePayload(String employeeNumber) { OMElement payload = fac.createOMElement("addEmployee", omNs); OMElement empNo = fac.createOMElement("employeeNumber", omNs); empNo.setText(employeeNumber); payload.addChild(empNo); OMElement lastName = fac.createOMElement("lastName", omNs); lastName.setText("BBB"); payload.addChild(lastName); OMElement fName = fac.createOMElement("firstName", omNs); fName.setText("AAA"); payload.addChild(fName); OMElement email = fac.createOMElement("email", omNs); email.setText("[email protected]"); payload.addChild(email); OMElement salary = fac.createOMElement("salary", omNs); salary.setText("50000"); payload.addChild(salary); return payload; } }
3e0428b2ae3595e0e8adf3e60638b49087ceb15a
3,547
java
Java
src/softuni/spring_data/Exam-preparation/MVC-Project-Airline/src/main/java/softuni/exam/service/impl/PassengerServiceImpl.java
NikolayDobrinski/SoftUni
eda8d838db1aaa9e8119ffa2015fe6121c0ee49a
[ "Apache-2.0" ]
null
null
null
src/softuni/spring_data/Exam-preparation/MVC-Project-Airline/src/main/java/softuni/exam/service/impl/PassengerServiceImpl.java
NikolayDobrinski/SoftUni
eda8d838db1aaa9e8119ffa2015fe6121c0ee49a
[ "Apache-2.0" ]
null
null
null
src/softuni/spring_data/Exam-preparation/MVC-Project-Airline/src/main/java/softuni/exam/service/impl/PassengerServiceImpl.java
NikolayDobrinski/SoftUni
eda8d838db1aaa9e8119ffa2015fe6121c0ee49a
[ "Apache-2.0" ]
null
null
null
37.734043
141
0.634057
1,728
package softuni.exam.service.impl; import com.google.gson.Gson; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; import softuni.exam.models.dto.json.PassengersSeedDto; import softuni.exam.models.entity.Passenger; import softuni.exam.repository.PassengerRepository; import softuni.exam.service.PassengerService; import softuni.exam.util.ValidationUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Comparator; import java.util.List; @Service public class PassengerServiceImpl implements PassengerService { private static final String PASSENGERS_FILE_PATH = "src/main/resources/files/json/passengers.json"; private final PassengerRepository passengerRepository; private final Gson gson; private final ValidationUtil validationUtil; private final ModelMapper modelMapper; public PassengerServiceImpl(PassengerRepository passengerRepository, Gson gson, ValidationUtil validationUtil, ModelMapper modelMapper) { this.passengerRepository = passengerRepository; this.gson = gson; this.validationUtil = validationUtil; this.modelMapper = modelMapper; } @Override public boolean areImported() { return passengerRepository.count() > 0; } @Override public String readPassengersFileContent() throws IOException { return Files.readString(Path.of(PASSENGERS_FILE_PATH)); } @Override public String importPassengers() throws IOException { StringBuilder sb = new StringBuilder(); Arrays.stream(gson.fromJson(readPassengersFileContent(), PassengersSeedDto[].class)) .filter(passengersSeedDto -> { boolean isValid = validationUtil.isValid(passengersSeedDto); sb .append(isValid ? String.format("Successfully imported Passenger %s - %s", passengersSeedDto.getLastName(), passengersSeedDto.getEmail()) : "Invalid Passenger") .append(System.lineSeparator()); return isValid; }) .map(passengersSeedDto -> modelMapper.map(passengersSeedDto, Passenger.class)) .forEach(passengerRepository::save); return sb.toString(); } @Override public String getPassengersOrderByTicketsCountDescendingThenByEmail() { StringBuilder sb = new StringBuilder(); List<Passenger> allPassengers = passengerRepository.findAll(); allPassengers .stream() .sorted(Comparator.comparingInt((Passenger a) -> a.getTickets().size()).thenComparing(Passenger::getEmail)) .forEach(passenger -> { sb.append(String.format("Passenger %s %s\n" + "\tEmail - %s\n" + "Phone - %s\n" + "\tNumber of tickets - %d\n", passenger.getFirstName(), passenger.getLastName(), passenger.getEmail(), passenger.getPhoneNumber(), passenger.getTickets().size() )) .append(System.lineSeparator()); }); return sb.toString(); } @Override public Passenger findPassengerByEmail(String email) { return passengerRepository.findPassengerByEmail(email); } }
3e04293310262be26a1930483027af0f197aea7a
3,426
java
Java
src/test/java/trclib/TrcPathTest.java
DrDab/Frc2020InfiniteRecharge
2e13e450e5eabec9cccabbe40c4db73fc20de014
[ "MIT" ]
1
2020-02-19T05:27:30.000Z
2020-02-19T05:27:30.000Z
src/test/java/trclib/TrcPathTest.java
DrDab/Frc2020InfiniteRecharge
2e13e450e5eabec9cccabbe40c4db73fc20de014
[ "MIT" ]
null
null
null
src/test/java/trclib/TrcPathTest.java
DrDab/Frc2020InfiniteRecharge
2e13e450e5eabec9cccabbe40c4db73fc20de014
[ "MIT" ]
2
2019-12-31T23:47:43.000Z
2020-01-09T04:12:56.000Z
45.078947
113
0.646818
1,729
package trclib; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import java.util.Arrays; public class TrcPathTest { @Test public void trapezoidVelocityTest() { TrcPose2D[] poses = new TrcPose2D[] { new TrcPose2D(), new TrcPose2D(0, 0.5), new TrcPose2D(0, 5), new TrcPose2D(-5, 10) }; TrcPath path = new TrcPath( Arrays.stream(poses).map(pose -> new TrcWaypoint(pose, null)).toArray(TrcWaypoint[]::new)); testTrapezoid(path, 10, 50); testTrapezoid(path, 50, 10); } private void testTrapezoid(TrcPath path, double maxVel, double maxAccel) { TrcPath trapezoid = path.trapezoidVelocity(maxVel, maxAccel); // up to two points inserted assertTrue(TrcUtil.inRange(trapezoid.getSize(), path.getSize(), path.getSize() + 2, true)); for (int i = 0; i < trapezoid.getSize(); i++) { TrcWaypoint from = trapezoid.getWaypoint(0); TrcWaypoint to = trapezoid.getWaypoint(1); assertEquals(from.distanceTo(to), TrcUtil.average(from.velocity, to.velocity) * from.timeStep, 1e-3); assertEquals(from.acceleration, Math.abs(to.velocity - from.velocity) / from.timeStep, 1e-3); } // average velocity must be less than the maximum velocity assertTrue(trapezoid.getArcLength() / trapezoid.getPathDuration() < maxVel); // The first and last points must have zero velocity assertEquals(0, trapezoid.getWaypoint(0).velocity, 1e-6); assertEquals(0, trapezoid.getWaypoint(trapezoid.getSize() - 1).velocity, 1e-6); } @Test public void getSizeTest() { TrcWaypoint waypoint1 = new TrcWaypoint(1, 1, 1, 1, 1, 1, 1, 1); TrcWaypoint waypoint2 = new TrcWaypoint(2, 2, 2, 2, 2, 2, 2, 2); TrcPath path = new TrcPath(waypoint1, waypoint2); assertEquals(2, path.getSize()); } @Test public void toRadiansTest() { TrcWaypoint waypointDeg1 = new TrcWaypoint(1, 1, 1, 1, 1, 1, 1, 90); TrcWaypoint waypointDeg2 = new TrcWaypoint(2, 2, 2, 2, 2, 2, 2, 180); TrcPath pathDeg = new TrcPath(waypointDeg1, waypointDeg2); TrcWaypoint waypointRad1 = new TrcWaypoint(1, 1, 1, 1, 1, 1, 1, Math.PI / 2); TrcWaypoint waypointRad2 = new TrcWaypoint(2, 2, 2, 2, 2, 2, 2, Math.PI); TrcPath pathRad = new TrcPath(false, waypointRad1, waypointRad2); assertEquals(pathRad.getWaypoint(0).heading, pathDeg.toRadians().getWaypoint(0).heading, 1e-6); assertEquals(pathRad.getWaypoint(1).heading, pathDeg.toRadians().getWaypoint(1).heading, 1e-6); } @Test public void toDegreesTest() { TrcWaypoint waypointRad1 = new TrcWaypoint(1, 1, 1, 1, 1, 1, 1, Math.PI / 2); TrcWaypoint waypointRad2 = new TrcWaypoint(2, 2, 2, 2, 2, 2, 2, Math.PI); TrcPath pathRad = new TrcPath(false, waypointRad1, waypointRad2); TrcWaypoint waypointDeg1 = new TrcWaypoint(1, 1, 1, 1, 1, 1, 1, 90); TrcWaypoint waypointDeg2 = new TrcWaypoint(2, 2, 2, 2, 2, 2, 2, 180); TrcPath pathDeg = new TrcPath(waypointDeg1, waypointDeg2); assertEquals(pathDeg.getWaypoint(0).heading, pathRad.toDegrees().getWaypoint(0).heading, 1e-6); assertEquals(pathDeg.getWaypoint(1).heading, pathRad.toDegrees().getWaypoint(1).heading, 1e-6); } }
3e042991820694707f7519dc48a2f9dbee8644e8
5,082
java
Java
security-legacy/skeleton-key-idm/skeleton-key-idp/src/test/java/org/jboss/resteasy/test/skeleton/key/SkeletonTestBase.java
iBlocksLimited/Resteasy
61e8d4a806d28511b4f8fc7a3bba004852da02c2
[ "Apache-2.0" ]
null
null
null
security-legacy/skeleton-key-idm/skeleton-key-idp/src/test/java/org/jboss/resteasy/test/skeleton/key/SkeletonTestBase.java
iBlocksLimited/Resteasy
61e8d4a806d28511b4f8fc7a3bba004852da02c2
[ "Apache-2.0" ]
null
null
null
security-legacy/skeleton-key-idm/skeleton-key-idp/src/test/java/org/jboss/resteasy/test/skeleton/key/SkeletonTestBase.java
iBlocksLimited/Resteasy
61e8d4a806d28511b4f8fc7a3bba004852da02c2
[ "Apache-2.0" ]
null
null
null
34.835616
96
0.745773
1,730
package org.jboss.resteasy.test.skeleton.key; import static org.jboss.resteasy.test.TestPortProvider.generateURL; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.jboss.logging.Logger; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.jwt.JsonSerialization; import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer; import org.jboss.resteasy.skeleton.key.SkeletonKeyContextResolver; import org.jboss.resteasy.skeleton.key.idm.adapters.infinispan.InfinispanIDM; import org.jboss.resteasy.skeleton.key.idm.service.RealmFactory; import org.jboss.resteasy.skeleton.key.idm.service.TokenManagement; import org.jboss.resteasy.skeleton.key.representations.idm.PublishedRealmRepresentation; import org.jboss.resteasy.skeleton.key.representations.idm.RealmRepresentation; import org.jboss.resteasy.spi.Registry; import org.jboss.resteasy.spi.ResteasyDeployment; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.test.TestPortProvider; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class SkeletonTestBase { private static final Logger LOG = Logger.getLogger(SkeletonTestBase.class); protected static NettyJaxrsServer server; protected static ResteasyDeployment deployment; protected static InfinispanIDM idm; protected static WebTarget realm; protected static ResteasyClient client; protected static PublishedRealmRepresentation realmInfo; @BeforeClass public static void beforeClass() throws Exception { server = new NettyJaxrsServer(); server.setPort(TestPortProvider.getPort()); server.setRootResourcePath("/"); server.start(); deployment = server.getDeployment(); } @AfterClass public static void afterClass() throws Exception { server.stop(); server = null; deployment = null; client.close(); } public Registry getRegistry() { return deployment.getRegistry(); } public ResteasyProviderFactory getProviderFactory() { return deployment.getProviderFactory(); } /** * @param resource */ public static void addPerRequestResource(Class<?> resource) { deployment.getRegistry().addPerRequestResource(resource); } public static void setupIDM(String realmJson) throws Exception { idm = new InfinispanIDM(getDefaultCache()); RealmFactory factory = new RealmFactory(idm); deployment.getProviderFactory().register(new SkeletonKeyContextResolver(true)); deployment.getRegistry().addSingletonResource(factory); TokenManagement tokenManagement = new TokenManagement(idm); deployment.getRegistry().addSingletonResource(tokenManagement); RealmRepresentation r = loadJson(realmJson); client = new ResteasyClientBuilder().build(); WebTarget target = client.target(generateURL("/realms")); Response response = target.request().post(Entity.json(r)); Assert.assertEquals(201, response.getStatus()); Assert.assertNotNull(response.getLocation()); realm = client.target(response.getLocation()); realmInfo = response.readEntity(PublishedRealmRepresentation.class); response.close(); } public static Cache getDefaultCache() { GlobalConfiguration gconfig = new GlobalConfigurationBuilder() .globalJmxStatistics() .allowDuplicateDomains(true) .enable() .jmxDomain("custom-cache") .build(); Configuration configuration = new ConfigurationBuilder() .eviction() .strategy(EvictionStrategy.NONE) .maxEntries(5000) .jmxStatistics().enable() .build(); EmbeddedCacheManager manager = new DefaultCacheManager(gconfig, configuration); return manager.getCache("custom-cache"); } public static RealmRepresentation loadJson(String path) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); ByteArrayOutputStream os = new ByteArrayOutputStream(); int c; while ( (c = is.read()) != -1) { os.write(c); } byte[] bytes = os.toByteArray(); LOG.info(new String(bytes)); return JsonSerialization.fromBytes(RealmRepresentation.class, bytes); } }
3e042a080c8c35f7bdbfbad1cb46adb3fdea2780
1,662
java
Java
datavault-webapp/src/main/java/org/datavaultplatform/webapp/services/ForceLogoutService.java
DataVault/datavault
4e0cb6aa9f0920ca598b65b3986bd232a9ff7009
[ "MIT" ]
20
2015-10-30T22:54:03.000Z
2022-01-16T23:44:29.000Z
datavault-webapp/src/main/java/org/datavaultplatform/webapp/services/ForceLogoutService.java
DataVault/datavault
4e0cb6aa9f0920ca598b65b3986bd232a9ff7009
[ "MIT" ]
169
2015-06-02T12:44:02.000Z
2022-03-18T12:52:00.000Z
datavault-webapp/src/main/java/org/datavaultplatform/webapp/services/ForceLogoutService.java
digirati-co-uk/datavault
5ad40556bfbd9761d16060121328b039b14695e5
[ "MIT" ]
18
2015-06-01T09:17:48.000Z
2022-03-23T11:35:46.000Z
34.625
96
0.7142
1,731
package org.datavaultplatform.webapp.services; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionRegistry; import java.util.Set; import java.util.stream.Collectors; public class ForceLogoutService { private static final Logger logger = LoggerFactory.getLogger(ForceLogoutService.class); private SessionRegistry sessionRegistry; private RestService restService; public void setSessionRegistry(SessionRegistry sessionRegistry) { this.sessionRegistry = sessionRegistry; } public void setRestService(RestService restService) { this.restService = restService; } public void logoutUser(String userId) { logger.warn("Forcing a logout for user {}", userId); logoutUsers(Sets.newHashSet(userId)); } public void logoutRole(long roleId) { logger.warn("Forcing a logout for all users assigned to role {}", roleId); Set<String> userIds = restService.getRoleAssignmentsForRole(roleId).stream() .map(roleAssignment -> roleAssignment.getUserId()) .collect(Collectors.toSet()); logoutUsers(userIds); } private void logoutUsers(Set<String> userIds) { sessionRegistry.getAllPrincipals().stream() .filter(principal -> principal instanceof String && userIds.contains(principal)) .flatMap(principal -> sessionRegistry.getAllSessions(principal, false).stream()) .forEach(SessionInformation::expireNow); } }
3e042a2a46f2bc866990ee2528004cfbd1dfc64b
1,280
java
Java
Course Materials/chapter-2-main/Demo/app/src/main/java/com/example/demo/MainActivity.java
chshzhe/CS175-Repository
f1efd20364efae570d25eeb75b32f881600417fc
[ "MIT" ]
6
2021-03-04T16:31:57.000Z
2021-06-09T16:07:47.000Z
Course Materials/chapter-2-main/Demo/app/src/main/java/com/example/demo/MainActivity.java
chshzhe/CS175-Repository
f1efd20364efae570d25eeb75b32f881600417fc
[ "MIT" ]
null
null
null
Course Materials/chapter-2-main/Demo/app/src/main/java/com/example/demo/MainActivity.java
chshzhe/CS175-Repository
f1efd20364efae570d25eeb75b32f881600417fc
[ "MIT" ]
null
null
null
29.090909
82
0.608594
1,732
package com.example.demo; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Intent intent = new Intent(MainActivity.this, MyActivity.class); // intent.putExtra("extra", "from MainActivity"); // startActivity(intent); // Intent intent = new Intent("com.example.chapter2.ACTION_START"); // startActivity(intent); // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse("http://www.baidu.com")); // startActivity(intent); Intent intent = new Intent(MainActivity.this, MyActivity.class); intent.putExtra("userId",123456); startActivity(intent); // // getIntent() } }); } }
3e042a7fca2850fb7f0297fa2fa2471c82797220
3,509
java
Java
simba-core/src/main/java/org/simbasecurity/core/audit/AuditLogEvent.java
cegeka/simba-os
3bebb61d878b3cf9cd1d28436d497e22e44e5f21
[ "MIT" ]
1
2016-07-05T14:38:02.000Z
2016-07-05T14:38:02.000Z
simba-core/src/main/java/org/simbasecurity/core/audit/AuditLogEvent.java
cegeka/simba-os
3bebb61d878b3cf9cd1d28436d497e22e44e5f21
[ "MIT" ]
23
2017-07-18T18:34:52.000Z
2021-12-09T20:17:05.000Z
simba-core/src/main/java/org/simbasecurity/core/audit/AuditLogEvent.java
cegeka/simba-os
3bebb61d878b3cf9cd1d28436d497e22e44e5f21
[ "MIT" ]
4
2017-01-07T18:41:51.000Z
2019-04-02T09:01:11.000Z
26.583333
150
0.68481
1,733
/* * Copyright 2013-2017 Simba Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.simbasecurity.core.audit; import static org.simbasecurity.core.audit.AuditLogLevel.*; import org.apache.commons.lang.StringUtils; import org.simbasecurity.api.service.thrift.SSOToken; /** * @since 1.0 */ public class AuditLogEvent { private static final String NO_TOKEN = "No SSO Token"; private final AuditLogEventCategory category; private final String username; private final SSOToken ssoToken; private final String remoteIP; private final String message; private final long timestamp; private final String hostServerName; private final String name; private final String firstName; private final String userAgent; private final String requestURL; private final String chainId; private AuditLogLevel auditLogLevel; public AuditLogEvent(AuditLogEventCategory category, String username, SSOToken ssoToken, String remoteIP, String message, String userAgent, String hostServerName, String surname, String firstName,String requestURL,String chainId) { this.timestamp = System.currentTimeMillis(); this.category = category; this.username = truncate(username); this.ssoToken = ssoToken; this.remoteIP = remoteIP; this.message = truncate(message, 512); this.name = truncate(surname); this.firstName = truncate(firstName); this.hostServerName = truncate(hostServerName); this.userAgent = truncate(userAgent); this.requestURL = truncate(requestURL); this.chainId = chainId; this.auditLogLevel = TRACE; } private static String truncate(String input) { return StringUtils.abbreviate(input, 255); } private static String truncate(String input, int length) { return StringUtils.abbreviate(input, length); } public String getUsername() { return username; } public SSOToken getSSOToken() { return ssoToken; } public String getSSOTokenString() { return ssoToken != null ? ssoToken.getToken() : NO_TOKEN; } public String getRemoteIP() { return remoteIP; } public String getMessage() { return message; } public long getTimestamp() { return timestamp; } public String getHostServerName() { return hostServerName; } public String getName() { return name; } public String getFirstName() { return firstName; } public AuditLogEventCategory getCategory() { return category; } public String getUserAgent() { return userAgent; } public String getRequestURL() { return requestURL; } public String getChainId() { return chainId; } public AuditLogLevel getAuditLogLevel() { return auditLogLevel; } public void markAuditLogToBeArchived() { this.auditLogLevel = INFO; } }
3e042ac08cf75a245003d3da60c09cd432a8da27
4,717
java
Java
thrift/src/main/java/com/intellij/plugins/thrift/inspections/ThriftIDDuplicatesInspection.java
kasecato/intellij-thrift
54d80ac4ea6dbadf489f569b9734580f71396c6f
[ "Apache-2.0" ]
49
2015-05-28T17:15:59.000Z
2022-01-12T19:38:49.000Z
thrift/src/main/java/com/intellij/plugins/thrift/inspections/ThriftIDDuplicatesInspection.java
clatisus/intellij-thrift
317c3d9f31bf592ee172750705e2d158ca906fbb
[ "Apache-2.0" ]
83
2015-01-30T06:39:19.000Z
2022-03-08T08:26:49.000Z
thrift/src/main/java/com/intellij/plugins/thrift/inspections/ThriftIDDuplicatesInspection.java
clatisus/intellij-thrift
317c3d9f31bf592ee172750705e2d158ca906fbb
[ "Apache-2.0" ]
46
2015-04-08T14:18:48.000Z
2021-12-31T03:58:33.000Z
33.453901
131
0.635361
1,734
package com.intellij.plugins.thrift.inspections; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.plugins.thrift.ThriftBundle; import com.intellij.plugins.thrift.lang.psi.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ThriftIDDuplicatesInspection extends LocalInspectionTool { @NotNull public String getGroupDisplayName() { return ThriftBundle.message("inspections.group.name"); } @Nls @NotNull @Override public String getDisplayName() { return ThriftBundle.message("thrift.inspection.duplicates.id"); } @Override public boolean isEnabledByDefault() { return true; } @NotNull @Override public String getShortName() { return "ThriftIDDuplicates"; } @Nullable @Override public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) { final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>(); new ThriftVisitor() { @Override public void visitTopLevelDeclaration(@NotNull ThriftTopLevelDeclaration o) { Set<String> ids = new HashSet<String>(); if (o instanceof ThriftEnum) { ThriftEnumFields enumFields = ((ThriftEnum) o).getEnumFields(); if (enumFields == null) { return; } for (ThriftEnumField enumField : enumFields.getEnumFieldList()) { ThriftIntConstant id = enumField.getIntConstant(); if (id != null && !ids.add(id.getText())) { result.add(manager.createProblemDescriptor( enumField.getIntConstant(), String.format("multiple enum values with id %s", id.getText()), true, ProblemHighlightType.ERROR, isOnTheFly )); } } } else if (o instanceof ThriftService) { ThriftService service = (ThriftService) o; ThriftServiceBody body = service.getServiceBody(); if (body == null) { return; } for (ThriftFunction f : body.getFunctionList()) { result.addAll(checkFieldList(manager, isOnTheFly, f.getFieldList(), "args")); ThriftThrows t = f.getThrows(); if (t != null) { result.addAll(checkFieldList(manager, isOnTheFly, t.getFieldList(), "throws")); } } } else if (o instanceof ThriftStruct) { ThriftFields fields = ((ThriftStruct) o).getFields(); if (fields != null) { result.addAll(checkFieldList(manager, isOnTheFly, fields.getFieldList(), "fields")); } } else if (o instanceof ThriftUnion) { ThriftFields fields = ((ThriftUnion) o).getFields(); if (fields != null) { result.addAll(checkFieldList(manager, isOnTheFly, fields.getFieldList(), "union values")); } } else if (o instanceof ThriftException) { ThriftFields fields = ((ThriftException) o).getFields(); if (fields != null) { result.addAll(checkFieldList(manager, isOnTheFly, fields.getFieldList(), "fields")); } } } public void visitElement(@NotNull PsiElement element) { super.visitElement(element); element.acceptChildren(this); } }.visitFile(file); return ArrayUtil.toObjectArray(result, ProblemDescriptor.class); } private List<ProblemDescriptor> checkFieldList( @NotNull final InspectionManager manager, final boolean isOnTheFly, List<ThriftField> fields, String part ) { Set<String> ids = new HashSet<String>(); final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>(); for (ThriftField field : fields) { ThriftFieldID id = field.getFieldID(); if (id != null && !ids.add(id.getText())) { result.add(manager.createProblemDescriptor( id.getIntConstant(), String.format("multiple %s with id %s", part, id.getIntConstant().getText()), true, ProblemHighlightType.ERROR, isOnTheFly )); } } return result; } }
3e042c0163475757cbfc66fb9b59f3f2db785231
2,090
java
Java
subprojects/base-services/src/main/java/org/gradle/concurrent/ParallelismConfiguration.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
2
2020-04-01T18:40:33.000Z
2021-04-23T12:06:15.000Z
subprojects/base-services/src/main/java/org/gradle/concurrent/ParallelismConfiguration.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
12
2020-07-11T15:43:32.000Z
2020-10-13T23:39:44.000Z
subprojects/base-services/src/main/java/org/gradle/concurrent/ParallelismConfiguration.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
1
2019-06-26T20:28:16.000Z
2019-06-26T20:28:16.000Z
31.666667
96
0.683732
1,735
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.concurrent; /** * A {@code ParallelismConfiguration} defines the parallel settings for a Gradle build. * * @since 4.1 */ public interface ParallelismConfiguration { /** * Returns true if parallel project execution is enabled. * * @see #getMaxWorkerCount() */ boolean isParallelProjectExecutionEnabled(); /** * Enables/disables parallel project execution. * * @see #isParallelProjectExecutionEnabled() */ void setParallelProjectExecutionEnabled(boolean parallelProjectExecution); /** * Returns the maximum number of concurrent workers used for underlying build operations. * * Workers can be threads, processes or whatever Gradle considers a "worker". Some examples: * * <ul> * <li>A thread running a task</li> * <li>A test process</li> * <li>A language compiler in a forked process</li> * </ul> * * Defaults to the number of processors available to the Java virtual machine. * * @return maximum number of concurrent workers, always &gt;= 1. * @see java.lang.Runtime#availableProcessors() */ int getMaxWorkerCount(); /** * Specifies the maximum number of concurrent workers used for underlying build operations. * * @throws IllegalArgumentException if {@code maxWorkerCount} is &lt; 1 * @see #getMaxWorkerCount() */ void setMaxWorkerCount(int maxWorkerCount); }
3e042c38f68c8bdd0d800ae0235d94ce537531b7
5,158
java
Java
src/main/java/net/andreinc/mockneat/unit/user/Names.java
varzay-abbas/datagenerate
9e90cac69f6d68bafbaa63a7fab0439a659bd40a
[ "Apache-2.0" ]
1
2021-02-19T11:45:21.000Z
2021-02-19T11:45:21.000Z
src/main/java/net/andreinc/mockneat/unit/user/Names.java
varzay-abbas/datagenerate
9e90cac69f6d68bafbaa63a7fab0439a659bd40a
[ "Apache-2.0" ]
null
null
null
src/main/java/net/andreinc/mockneat/unit/user/Names.java
varzay-abbas/datagenerate
9e90cac69f6d68bafbaa63a7fab0439a659bd40a
[ "Apache-2.0" ]
null
null
null
38.781955
142
0.674098
1,736
package net.andreinc.mockneat.unit.user; /** * Copyright 2017, Andrei N. Ciobanu Permission is hereby granted, free of charge, to any user 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. PARAM NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER PARAM AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, FREE_TEXT OF OR PARAM CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS PARAM THE SOFTWARE. */ import net.andreinc.mockneat.MockNeat; import net.andreinc.mockneat.abstraction.MockUnitBase; import net.andreinc.mockneat.abstraction.MockUnitString; import net.andreinc.mockneat.types.enums.DictType; import net.andreinc.mockneat.types.enums.NameType; import java.util.function.Supplier; import static net.andreinc.mockneat.types.enums.NameType.*; import static net.andreinc.mockneat.utils.ValidationUtils.betweenClosed; import static net.andreinc.mockneat.utils.ValidationUtils.notEmptyOrNullValues; import static org.apache.commons.lang3.Validate.notNull; public class Names extends MockUnitBase implements MockUnitString { public static Names names() { return MockNeat.threadLocal().names(); } protected Names() { } public Names(MockNeat mockNeat) { super(mockNeat); } @Override public Supplier<String> supplier() { return full().supplier(); } /** * <p>Returns a new {@code MockUnitString} that can be used to generate arbitrary first names (both male and female).</p> * * @return A new {@code MockUnitString}. */ public MockUnitString first() { return type(FIRST_NAME); } /** * <p>Returns a new {@code MockUnitString} that can be used to generate first names (males only).</p> * * @return A new {@code MockUnitString}. */ public MockUnitString firstAndMale() { return type(FIRST_NAME_MALE); } /** * <p>Returns a new {@code MockUnitString} that can be used to generate first names (female only).</p> * * @return A new {@code MockUnitString}. */ public MockUnitString firstAndFemale() { return type(FIRST_NAME_FEMALE); } /** * <p>Returns a new {@code MockUnitstring} that can be used to generate last names.</p> * * @return A new {@code MockUnitString}. */ public MockUnitString last() { return type(LAST_NAME); } /** * <p>Returns a new {@code MockUnitString} that can be used to generate full names (First Name + Last Name).</p> * * @return A new {@code MockUnitString}. */ public MockUnitString full() { Supplier<String> supp = () -> first().val() + " " + last().val(); return () -> supp; } /** * <p>Returns a new {@code MockUnitString} that can be used to generate full names including a middle name (with a given probability).</p> * * @param middleInitialProbability A double value between [0.0, 100.0] denoting the probability of the middle name to appear. * * @return A new {@code MockUnitString} */ public MockUnitString full(double middleInitialProbability) { betweenClosed(middleInitialProbability, 0.0, 100.0); Supplier<String> supp = () -> { boolean middleName = mockNeat.bools().probability(middleInitialProbability).val(); String initial = (middleName) ? " " + mockNeat.chars().upperLetters().val() + "." : ""; return first().val() + initial + " " + last().val(); }; return () -> supp; } /** * <p>Returns a new {@code MockUnitString} that can be used to generate names in the given array of types.</p> * * @param types A var-arg array denoting the types of names that are generated. * * @return A new {@code MockUnitString}. */ public MockUnitString types(NameType... types) { notEmptyOrNullValues(types, "types"); return () -> { NameType nameType = mockNeat.from(types).val(); return type(nameType).supplier(); }; } /** * <p>Returns a new {@code MockUnitString} that can be used to generate names of the given type.</p> * * @param type The type of name we want to generate. * * @return A new {@code MockUnitString}. */ public MockUnitString type(NameType type) { notNull(type, "type"); DictType dictType = mockNeat.from(type.getDictionaries()).val(); return () -> mockNeat.dicts().type(dictType)::val; } }
3e042c3fc9ae4295f4c8d2714f883bfaf62d40ce
875
java
Java
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/crypto/UnencryptedServerSocket.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/crypto/UnencryptedServerSocket.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/crypto/UnencryptedServerSocket.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
28.225806
91
0.677714
1,737
package testcode.crypto; import javax.net.ssl.SSLServerSocketFactory; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; public class UnencryptedServerSocket { static void sslServerSocket() throws IOException { ServerSocket ssoc = SSLServerSocketFactory.getDefault().createServerSocket(1234); ssoc.close(); } static void plainServerSocket() throws IOException { ServerSocket ssoc = new ServerSocket(1234); ssoc.close(); } static void otherConstructors() throws IOException { ServerSocket ssoc1 = new ServerSocket(); ssoc1.close(); ServerSocket ssoc2 = new ServerSocket(1234, 10); ssoc2.close(); byte[] address = {127, 0, 0, 1}; ServerSocket ssoc3 = new ServerSocket(1234, 10, InetAddress.getByAddress(address)); ssoc3.close(); } }
3e042c75a1a80d5648ff6a2aa641ecb39d1f5e69
2,037
java
Java
YiBoLibrary/src/com/cattong/sns/impl/facebook/FacebookResponseHandler.java
cattong/YiBo
0a609365d87128808c3accceafbafaf416f93c47
[ "Apache-2.0" ]
30
2015-01-08T09:14:43.000Z
2022-02-04T07:11:36.000Z
YiBoLibrary/src/com/cattong/sns/impl/facebook/FacebookResponseHandler.java
shinyvince/YiBo
0a609365d87128808c3accceafbafaf416f93c47
[ "Apache-2.0" ]
null
null
null
YiBoLibrary/src/com/cattong/sns/impl/facebook/FacebookResponseHandler.java
shinyvince/YiBo
0a609365d87128808c3accceafbafaf416f93c47
[ "Apache-2.0" ]
9
2015-06-15T10:08:31.000Z
2022-02-04T07:11:48.000Z
32.854839
91
0.720668
1,738
package com.cattong.sns.impl.facebook; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import com.cattong.commons.LibResultCode; import com.cattong.commons.LibRuntimeException; import com.cattong.commons.Logger; import com.cattong.commons.ServiceProvider; import com.cattong.commons.util.ParseUtil; class FacebookResponseHandler implements ResponseHandler<String> { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); String responseString = (entity == null ? null : EntityUtils.toString(entity, "UTF-8")); Logger.debug("FacebookResponseHandler : {}", responseString); if (responseString != null) { responseString = responseString.trim(); try { JSONObject json = new JSONObject(responseString); if (json.has("data")) { responseString = ParseUtil.getRawString("data", json); } else if (json.has("error")) { json = json.getJSONObject("error"); String errorDesc = json.getString("message"); int errorCode = LibResultCode.E_UNKNOWN_ERROR; String errorType = ParseUtil.getRawString("type", json); if ("OAuthException".equals(errorType)) { errorCode = LibResultCode.OAUTH_EXCEPTION; } throw new LibRuntimeException(errorCode, "", errorDesc, ServiceProvider.Facebook); } } catch (JSONException e) { Logger.debug(e.getMessage(), e); } } int statusCode = statusLine.getStatusCode(); if (statusCode >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } return responseString; } }
3e042d9a6d70b5c0ee517c4b8dc47060fa1d7f77
5,070
java
Java
src/main/java/com/lots/lotswxxw/util/IntfaceEncryptUtils.java
456001715/cps
c8b78ee3813574843e2356df13317f10901c50c1
[ "MIT" ]
null
null
null
src/main/java/com/lots/lotswxxw/util/IntfaceEncryptUtils.java
456001715/cps
c8b78ee3813574843e2356df13317f10901c50c1
[ "MIT" ]
null
null
null
src/main/java/com/lots/lotswxxw/util/IntfaceEncryptUtils.java
456001715/cps
c8b78ee3813574843e2356df13317f10901c50c1
[ "MIT" ]
null
null
null
31.842424
632
0.642177
1,739
package com.lots.lotswxxw.util; import org.apache.commons.codec.binary.Base64; import org.springframework.util.StringUtils; import sun.misc.BASE64Decoder; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.SecretKeySpec; /** * * 用于接口加密。因为接口返回的数据长度可能超过普通加密的长度,所以用此方法加密 * * @author lots * @date 2012-4-26 * @version 1.0 */ public class IntfaceEncryptUtils { /**默认加密秘钥,必须16位*/ private static final String DEFAULT_KEY = "a2s1xsd12a@!xssf"; /*** 算法*/ private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding"; /** * aes解密 * @param encrypt 内容 * @return * @throws Exception */ public static String decryptByDefaultKey(String encrypt) throws Exception { return decrypt(encrypt, DEFAULT_KEY); } /** * aes加密 * @param content * @return * @throws Exception */ public static String encryptByDefaultKey(String content) throws Exception { return encrypt(content,DEFAULT_KEY); } /** * base 64 encode * @param bytes 待编码的byte[] * @return 编码后的base 64 code */ private static String base64Encode(byte[] bytes) { return Base64.encodeBase64String(bytes); } /** * base 64 decode * @param base64Code 待解码的base 64 code * @return 解码后的byte[] * @throws Exception */ private static byte[] base64Decode(String base64Code) throws Exception { return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code); } /** * AES加密 * @param content 待加密的内容 * @param encryptKey 加密密钥 * @return 加密后的byte[] * @throws Exception */ private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); Cipher cipher = Cipher.getInstance(ALGORITHMSTR); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES")); return cipher.doFinal(content.getBytes("utf-8")); } /** * AES加密为base 64 code * @param content 待加密的内容 * @param encryptKey 加密密钥 * @return 加密后的base 64 code * @throws Exception */ public static String encrypt(String content, String encryptKey) throws Exception { return base64Encode(aesEncryptToBytes(content, encryptKey)); } /** * AES解密 * * @param encryptBytes 待解密的byte[] * @param decryptKey 解密密钥 * @return 解密后的 String * @throws Exception */ private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); Cipher cipher = Cipher.getInstance(ALGORITHMSTR); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES")); byte[] decryptBytes = cipher.doFinal(encryptBytes); return new String(decryptBytes); } /** * 将base 64 code AES解密 * @param encryptStr 待解密的base 64 code * @param decryptKey 解密密钥 * @return 解密后的string * @throws Exception */ public static String decrypt(String encryptStr, String decryptKey) throws Exception { return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey); } public static void main(String[] args) { String b="{knxx={是否建档立卡=否, 是否农村低保户=否, 困难程度=不困难, 是否低收入家庭=否, 年级认定意见=null, 家庭是否遭受突发意外=否, 是否孤儿=否, 认定时间=2016-09-25 00:00:00.0, 其他=null, 认定原因=调查了解, 是否残疾人子女=否, 家庭是否遭受自然灾害=否, 是否父母失业或丧失劳动能力=否, 家中是否有大病患者=否, 是否烈士子女=否, 是否残疾=否, 是否扶贫低保户=否, 是否农村五保户=否, 是否农村特困供养=否, 是否单亲家庭子女=否, 是否扶贫户=否, 班级认定意见=null}, jtcyxx=null, jbxx={就读方式=走读, 入学年份=201609, 特长=null, OID=00e120411fcf4e0db5fc, 专业=null, 性别=女, 学校=德阳市旌阳区柏隆小学校, 姓名=陆钰婷, 民族=汉族, 班级=null, 身体状况=健康或良好, 家庭住址=安徽省蒙城县立仓镇陆瓦坊村陆胡庄18号, 学籍号=L510603201004250043, 联系电话=3661919, 出生日期=20100425, 学院=null, 政治面貌=群众, 户口所在地=蒙城县, 上下学距离=null, 身份证号=341622201004252143, 现住址=安徽省蒙城县立仓镇陆瓦坊村陆胡庄18号, 教育阶段=义务教育}, jtqkxx=null}"; //加密 try { String result= encryptByDefaultKey(b); System.out.println(result); //解密 System.out.println(decryptByDefaultKey("9jnerlff23u8ed01np9g6ysbhsh0dvcs")); }catch (Exception e) { e.printStackTrace(); } } // 前端解密 // $(function(){ // // $.ajax({ // // type:"post", // url:"http://localhost:8081/post", // data:{ // a:"你是谁啊??" // }, // success:function(res){ // var data = JSON.parse( Decrypt('a2s1xsd12a@!xssf',res.data)); // console.log(data); // } // }) // // //解密 // function Decrypt(keyStr,word){ // var key = CryptoJS.enc.Utf8.parse(keyStr); // var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7}); // return CryptoJS.enc.Utf8.stringify(decrypt).toString(); // } // }) }
3e042daedab3b674439f4f468df895234e001d6d
1,581
java
Java
src/xml/parser/SegregationXMLParser.java
vincentliu98/Cell-Society
e1c7ec77b3deb61e8dc185a0713f07d445626d9d
[ "MIT" ]
null
null
null
src/xml/parser/SegregationXMLParser.java
vincentliu98/Cell-Society
e1c7ec77b3deb61e8dc185a0713f07d445626d9d
[ "MIT" ]
null
null
null
src/xml/parser/SegregationXMLParser.java
vincentliu98/Cell-Society
e1c7ec77b3deb61e8dc185a0713f07d445626d9d
[ "MIT" ]
null
null
null
31
114
0.683112
1,740
package xml.parser; import org.w3c.dom.Element; import simulation.CellGraph; import simulation.Simulator; import simulation.models.SegregationModel; import java.io.File; import java.util.Map; /** * Returns a Simulator for a Segregation simulation based on the file being loaded * @author jgp17 */ public class SegregationXMLParser extends ParentXMLParser { public static final String THRESHOLD_TAG = "satisfactionThreshold"; public static final String TYPE_VALUE_TAG = "type"; public static final Map<String, Map<String, Object>> VAL_TAG_TO_RANGE_MAP = Map.ofEntries( Map.entry(THRESHOLD_TAG, Map.of(MIN_STRING, 0.0, MAX_STRING, 1.0, DEF_STRING, 0.5)), Map.entry(TYPE_VALUE_TAG, Map.of(MIN_STRING, SegregationModel.EMPTY, MAX_STRING, SegregationModel.RED, DEF_STRING, SegregationModel.EMPTY)) ); /** * Create a parser for XML files of given type. * * @param language */ public SegregationXMLParser(String language) { super(language); } /** * * @param datafile * @return */ public Simulator<Integer> getSimulator(File datafile) { Element root = getRootElement(datafile); SegregationModel model = new SegregationModel(getDoubleValue(root, THRESHOLD_TAG, 0.0, 1.0, 0.5)); CellGraph<Integer> graph = getCellGraph(root, model); return new Simulator<>(graph, model); } // @Override // public Integer getCellValue(Element e) { // return getIntValue(e, TYPE_VALUE_TAG, VAL_TAG_TO_RANGE_MAP); // } }
3e042e5070047b02e3ea7903b948c1cbb104f949
3,997
java
Java
winterwell.nlp/src/com/winterwell/nlp/corpus/wikipedia/CreateWikipediaStopwords.java
good-loop/open-code
3a5b9f49d22778db8b87eb6b59543fea6f7e61a9
[ "MIT" ]
2
2016-12-13T15:12:41.000Z
2017-05-04T08:00:23.000Z
winterwell.nlp/src/com/winterwell/nlp/corpus/wikipedia/CreateWikipediaStopwords.java
anitawoodruff/open-code
5d8f66ce318838fb4c305b20c187864b483ae6ec
[ "MIT" ]
11
2017-06-09T17:16:42.000Z
2021-03-10T13:59:57.000Z
winterwell.nlp/src/com/winterwell/nlp/corpus/wikipedia/CreateWikipediaStopwords.java
anitawoodruff/open-code
5d8f66ce318838fb4c305b20c187864b483ae6ec
[ "MIT" ]
5
2017-06-09T11:27:23.000Z
2022-02-25T22:47:57.000Z
26.470199
80
0.689767
1,741
package com.winterwell.nlp.corpus.wikipedia; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.util.List; import com.winterwell.maths.datastorage.HalfLifeIndex; import com.winterwell.nlp.NLPWorkshop; import com.winterwell.nlp.corpus.IDocument; import com.winterwell.nlp.io.Tkn; import com.winterwell.nlp.io.WordAndPunctuationTokeniser; import com.winterwell.utils.StrUtils; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.io.FileUtils; import com.winterwell.utils.log.Log; import com.winterwell.utils.threads.ATask; /** * FIXME the list created for English is pretty bad. Wikipedia perhaps isn't the * best corpus here! * * TODO use Google's n-grams?? * * @see WikipediaCorpus * @testedby CreateWikipediaStopwordsTest} * @author daniel * */ public class CreateWikipediaStopwords extends ATask<List<String>> { public static final String FILENAME = "stopwords.wikipedia.txt"; /** * Make some (but NOT English cos we like the list we have) * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // Depot.getDefault().setErrorPolicy(KErrorPolicy.ASK); for (String lang : new String[] { // "en" // "es" // "he", "tr" }) { NLPWorkshop ws = NLPWorkshop.get(lang); CreateWikipediaStopwords cwd = new CreateWikipediaStopwords(ws); cwd.run(); } } /** * documents processed */ int cnt; private WikipediaCorpus corpus; private HalfLifeIndex<String> index; /** * How many stopwords to find. */ private int size = 700; private final NLPWorkshop workshop; public CreateWikipediaStopwords(NLPWorkshop ws) { workshop = ws; // protect the English & Arabic stopwords list // (Arabic list from http://arabicstopwords.sourceforge.net/ via Dubai // School of Govt) // assert ! workshop.getLanguage().startsWith("en"); assert ! workshop.getLanguage().startsWith("ar"); assert ! workshop.getLanguage().startsWith("en"); } @Override public List<String> getIntermediateOutput() { List<String> words = index.getSortedEntries(); words = Containers.subList(words, 0, size); return words; } @Override public double[] getProgress() { return new double[] { cnt, corpus.size() }; } @Override public List<String> run() throws IOException { corpus = new WikipediaCorpus(workshop); if ( ! corpus.getDumpFile().exists()) { corpus.download(); } // collect frequency counts in a lossy/approximate manner index = new HalfLifeIndex<String>(size * 10); for (IDocument doc : corpus) { String contents = doc.getContents(); String _contents = contents.replaceAll("\\{\\{.+?\\}\\}", ""); // if ( ! contents.equals(_contents)) { // System.out.println(_contents); // } WordAndPunctuationTokeniser ts = new WordAndPunctuationTokeniser( _contents); ts.setLowerCase(true); ts.setSwallowPunctuation(false); ts.setSplitOnApostrophe(false); for (Tkn token : ts) { String txt = token.getText(); if (txt.matches(".*\\d.*")) continue; if (StrUtils.isPunctuation(txt)) { continue; } index.indexOfWithAdd(txt); } cnt++; if (cnt % 1000 == 0) { Log.i("corpus", " ..." + cnt + " documents"); } } // get the stopwords List<String> words = index.getSortedEntries(); words = Containers.subList(words, 0, size); // output stopwords, over-writing if it's there!! File out = new File("wtf-stopwords.txt"); out.getAbsoluteFile().getParentFile().mkdirs(); BufferedWriter writer = FileUtils.getWriter(out); for (String w : words) { writer.write(w); writer.write('\n'); } FileUtils.close(writer); Log.i("stopwords", "...Created temp file "+out); File properFile = workshop.getFilePointer(CreateWikipediaStopwords.FILENAME); FileUtils.move(out, properFile); Log.i("stopwords", "Created file "+properFile); // done // ...free the memory corpus = null; index = null; return words; } }
3e042e84b9bb3e3ce51a80382aab9e7473bc717f
830
java
Java
android/src/main/java/pro/brouwer/fluttermdnsplugin/handlers/DiscoveryRunningHandler.java
brouwer/flutter_mdns_plugin
d1cf315bae970f9819ad8dbd79ed53fc8f3a867a
[ "MIT" ]
null
null
null
android/src/main/java/pro/brouwer/fluttermdnsplugin/handlers/DiscoveryRunningHandler.java
brouwer/flutter_mdns_plugin
d1cf315bae970f9819ad8dbd79ed53fc8f3a867a
[ "MIT" ]
null
null
null
android/src/main/java/pro/brouwer/fluttermdnsplugin/handlers/DiscoveryRunningHandler.java
brouwer/flutter_mdns_plugin
d1cf315bae970f9819ad8dbd79ed53fc8f3a867a
[ "MIT" ]
null
null
null
21.842105
76
0.63494
1,742
package pro.brouwer.fluttermdnsplugin.handlers; import android.os.Handler; import io.flutter.plugin.common.EventChannel; public class DiscoveryRunningHandler implements EventChannel.StreamHandler { final private Handler mainHandler = new Handler(); EventChannel.EventSink sink; @Override public void onListen(Object o, EventChannel.EventSink eventSink) { sink = eventSink; } @Override public void onCancel(Object o) { } public void onDiscoveryStopped(){ mainHandler.post(new Runnable() { @Override public void run() { sink.success(false); } }); } public void onDiscoveryStarted(){ mainHandler.post(new Runnable() { @Override public void run() { sink.success(true); } }); } }
3e042fe8d54c1919828a0ddb341ee660c37473b2
1,321
java
Java
Lists/ArrayList/3 ArrayList Iterate Front to Back/GFG.java
Rani-dha/JAVA-COLLECTIONS
91e8dbe95646f14cad90911db3fecb698030658d
[ "MIT" ]
null
null
null
Lists/ArrayList/3 ArrayList Iterate Front to Back/GFG.java
Rani-dha/JAVA-COLLECTIONS
91e8dbe95646f14cad90911db3fecb698030658d
[ "MIT" ]
null
null
null
Lists/ArrayList/3 ArrayList Iterate Front to Back/GFG.java
Rani-dha/JAVA-COLLECTIONS
91e8dbe95646f14cad90911db3fecb698030658d
[ "MIT" ]
null
null
null
24.462963
127
0.647994
1,743
// ArrayList Iterate from front to back // https://practice.geeksforgeeks.org/problems/arraylist-iterate-front-to-back/1/?track=Java-Collections-ArrayList&batchId=318 //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG { public static void main (String[] args) { //Creating an object of class Scanner Scanner sc = new Scanner(System.in); int t = sc.nextInt();//taking all the testcases while(t-->0) { int n=sc.nextInt();//taking the total number of elements ArrayList<Integer>arr=new ArrayList<>();//Declaring and Intializing an ArrayList for(int i=0;i<n;i++) { int x=sc.nextInt();//taking in the element arr.add(x); } Iterator iterator=arr.iterator();//creating an iterator of ArrayList arr //calling the iterFTB method and passing the iteraror iterFTB(iterator); System.out.println(); } } // } Driver Code Ends //User function Template for Java public static void iterFTB(Iterator iterator) { //Your code here //Just print the elements, don't provide new line while( iterator.hasNext()){ System.out.print( iterator.next() + " "); } } // { Driver Code Starts. } // } Driver Code Ends
3e04306eada05b30b0c1aca42b4be4e50f1adb82
10,495
java
Java
java-client/src/main/java/com/couchbase/client/java/AsyncBucket.java
joshrotenberg/couchbase-jvm-clients
34a98b95bec1eed7a50a774f866c9dfebb0cd2ee
[ "Apache-2.0" ]
26
2019-04-15T08:51:51.000Z
2022-02-17T18:31:35.000Z
java-client/src/main/java/com/couchbase/client/java/AsyncBucket.java
joshrotenberg/couchbase-jvm-clients
34a98b95bec1eed7a50a774f866c9dfebb0cd2ee
[ "Apache-2.0" ]
14
2019-08-26T19:01:18.000Z
2022-03-31T05:51:08.000Z
java-client/src/main/java/com/couchbase/client/java/AsyncBucket.java
joshrotenberg/couchbase-jvm-clients
34a98b95bec1eed7a50a774f866c9dfebb0cd2ee
[ "Apache-2.0" ]
31
2019-03-31T05:45:58.000Z
2022-03-31T07:29:31.000Z
37.482143
124
0.74302
1,744
/* * Copyright (c) 2018 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.couchbase.client.java; import com.couchbase.client.core.Core; import com.couchbase.client.core.annotation.Stability; import com.couchbase.client.core.cnc.RequestSpan; import com.couchbase.client.core.cnc.TracingIdentifiers; import com.couchbase.client.core.diagnostics.ClusterState; import com.couchbase.client.core.diagnostics.HealthPinger; import com.couchbase.client.core.diagnostics.PingResult; import com.couchbase.client.core.diagnostics.WaitUntilReadyHelper; import com.couchbase.client.core.env.Authenticator; import com.couchbase.client.core.error.context.ReducedViewErrorContext; import com.couchbase.client.core.io.CollectionIdentifier; import com.couchbase.client.core.msg.view.ViewRequest; import com.couchbase.client.core.retry.RetryStrategy; import com.couchbase.client.java.codec.JsonSerializer; import com.couchbase.client.java.diagnostics.PingOptions; import com.couchbase.client.java.diagnostics.WaitUntilReadyOptions; import com.couchbase.client.java.env.ClusterEnvironment; import com.couchbase.client.java.manager.collection.AsyncCollectionManager; import com.couchbase.client.java.manager.view.AsyncViewIndexManager; import com.couchbase.client.java.view.ViewAccessor; import com.couchbase.client.java.view.ViewOptions; import com.couchbase.client.java.view.ViewResult; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import static com.couchbase.client.core.util.Validators.notNull; import static com.couchbase.client.core.util.Validators.notNullOrEmpty; import static com.couchbase.client.java.ReactiveBucket.DEFAULT_VIEW_OPTIONS; import static com.couchbase.client.java.ReactiveCluster.DEFAULT_PING_OPTIONS; import static com.couchbase.client.java.ReactiveCluster.DEFAULT_WAIT_UNTIL_READY_OPTIONS; /** * Provides access to a Couchbase bucket in an async fashion. */ public class AsyncBucket { /** * The name of the bucket. */ private final String name; /** * The underlying attached environment. */ private final ClusterEnvironment environment; /** * The core reference used. */ private final Core core; private final AsyncCollectionManager collectionManager; private final AsyncViewIndexManager viewManager; private final Authenticator authenticator; /** * Stores already opened scopes for reuse. */ private final Map<String, AsyncScope> scopeCache = new ConcurrentHashMap<>(); /** * Creates a new {@link AsyncBucket}. * * @param name the name of the bucket. * @param core the underlying core. * @param environment the attached environment. */ AsyncBucket(final String name, final Core core, final ClusterEnvironment environment) { this.core = core; this.environment = environment; this.name = name; this.collectionManager = new AsyncCollectionManager(core, name); this.viewManager = new AsyncViewIndexManager(core, name); this.authenticator = core.context().authenticator(); } /** * Returns the name of the {@link AsyncBucket}. */ public String name() { return name; } /** * Returns the attached {@link ClusterEnvironment}. */ public ClusterEnvironment environment() { return environment; } /** * Provides access to the underlying {@link Core}. * * <p>This is advanced API, use with care!</p> */ @Stability.Volatile public Core core() { return core; } public AsyncCollectionManager collections() { return collectionManager; } public AsyncViewIndexManager viewIndexes() { return viewManager; } /** * Opens the {@link AsyncScope} with the given name. * * @param name the name of the scope. * @return the {@link AsyncScope} once opened. */ public AsyncScope scope(final String name) { return maybeCreateAsyncScope(name); } /** * Opens the default {@link AsyncScope}. * * @return the {@link AsyncScope} once opened. */ public AsyncScope defaultScope() { return maybeCreateAsyncScope(CollectionIdentifier.DEFAULT_SCOPE); } /** * Helper method to create the scope or load it from the cache if present. * * @param scopeName the name of the scope. * @return the created or cached scope. */ private AsyncScope maybeCreateAsyncScope(final String scopeName) { return scopeCache.computeIfAbsent(scopeName, ignored -> new AsyncScope(scopeName, name, core, environment)); } /** * Opens the default collection for this {@link AsyncBucket} using the default scope. * <p> * This method does not block and the client will try to establish all needed resources in the background. If you * need to eagerly await until all resources are established before performing an operation, use the * {@link #waitUntilReady(Duration)} method on the {@link AsyncBucket}. * * @return the opened default {@link AsyncCollection}. */ public AsyncCollection defaultCollection() { return defaultScope().defaultCollection(); } /** * Provides access to the collection with the given name for this {@link AsyncBucket} using the default scope. * <p> * This method does not block and the client will try to establish all needed resources in the background. If you * need to eagerly await until all resources are established before performing an operation, use the * {@link #waitUntilReady(Duration)} method on the {@link AsyncBucket}. * * @return the opened named {@link AsyncCollection}. */ public AsyncCollection collection(final String collectionName) { return defaultScope().collection(collectionName); } public CompletableFuture<ViewResult> viewQuery(final String designDoc, final String viewName) { return viewQuery(designDoc, viewName, DEFAULT_VIEW_OPTIONS); } public CompletableFuture<ViewResult> viewQuery(final String designDoc, final String viewName, final ViewOptions options) { notNull(options, "ViewOptions", () -> new ReducedViewErrorContext(designDoc, viewName, name)); ViewOptions.Built opts = options.build(); JsonSerializer serializer = opts.serializer() == null ? environment.jsonSerializer() : opts.serializer(); return ViewAccessor.viewQueryAsync(core, viewRequest(designDoc, viewName, opts), serializer); } ViewRequest viewRequest(final String designDoc, final String viewName, final ViewOptions.Built opts) { notNullOrEmpty(designDoc, "DesignDoc", () -> new ReducedViewErrorContext(designDoc, viewName, name)); notNullOrEmpty(viewName, "ViewName", () -> new ReducedViewErrorContext(designDoc, viewName, name)); String query = opts.query(); Optional<byte[]> keysJson = Optional.ofNullable(opts.keys()).map(s -> s.getBytes(StandardCharsets.UTF_8)); boolean development = opts.development(); Duration timeout = opts.timeout().orElse(environment.timeoutConfig().viewTimeout()); RetryStrategy retryStrategy = opts.retryStrategy().orElse(environment.retryStrategy()); final RequestSpan span = environment() .requestTracer() .requestSpan(TracingIdentifiers.SPAN_REQUEST_VIEWS, opts.parentSpan().orElse(null)); ViewRequest request = new ViewRequest(timeout, core.context(), retryStrategy, authenticator, name, designDoc, viewName, query, keysJson, development, span); request.context().clientContext(opts.clientContext()); return request; } /** * Performs application-level ping requests against services in the couchbase cluster. * * @return the {@link PingResult} once complete. */ public CompletableFuture<PingResult> ping() { return ping(DEFAULT_PING_OPTIONS); } /** * Performs application-level ping requests with custom options against services in the couchbase cluster. * * @return the {@link PingResult} once complete. */ public CompletableFuture<PingResult> ping(final PingOptions options) { notNull(options, "PingOptions"); final PingOptions.Built opts = options.build(); return HealthPinger.ping( core, opts.timeout(), opts.retryStrategy().orElse(environment.retryStrategy()), opts.serviceTypes(), opts.reportId(), Optional.of(name) ).toFuture(); } /** * Waits until the desired {@link ClusterState} is reached. * <p> * This method will wait until either the cluster state is "online", or the timeout is reached. Since the SDK is * bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online * and usable before moving on. * * @param timeout the maximum time to wait until readiness. * @return a completable future that completes either once ready or timeout. */ public CompletableFuture<Void> waitUntilReady(final Duration timeout) { return waitUntilReady(timeout, DEFAULT_WAIT_UNTIL_READY_OPTIONS); } /** * Waits until the desired {@link ClusterState} is reached. * <p> * This method will wait until either the cluster state is "online" by default, or the timeout is reached. Since the * SDK is bootstrapping lazily, this method allows to eagerly check during bootstrap if all of the services are online * and usable before moving on. You can tune the properties through {@link WaitUntilReadyOptions}. * * @param timeout the maximum time to wait until readiness. * @param options the options to customize the readiness waiting. * @return a completable future that completes either once ready or timeout. */ public CompletableFuture<Void> waitUntilReady(final Duration timeout, final WaitUntilReadyOptions options) { notNull(options, "WaitUntilReadyOptions"); final WaitUntilReadyOptions.Built opts = options.build(); return WaitUntilReadyHelper.waitUntilReady(core, opts.serviceTypes(), timeout, opts.desiredState(), Optional.of(name)); } }
3e0431039e96c11ad626b019ec2bf4b1ae63c8f1
3,558
java
Java
server/src/test-integration/java/com/thoughtworks/go/server/service/builders/BuilderFactoryIntegrationTest.java
ralcini/gocd
eb7c461e22d4707b169ae110ada517bc610838d4
[ "Apache-2.0" ]
null
null
null
server/src/test-integration/java/com/thoughtworks/go/server/service/builders/BuilderFactoryIntegrationTest.java
ralcini/gocd
eb7c461e22d4707b169ae110ada517bc610838d4
[ "Apache-2.0" ]
null
null
null
server/src/test-integration/java/com/thoughtworks/go/server/service/builders/BuilderFactoryIntegrationTest.java
ralcini/gocd
eb7c461e22d4707b169ae110ada517bc610838d4
[ "Apache-2.0" ]
null
null
null
43.390244
117
0.758291
1,745
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.service.builders; import com.thoughtworks.go.config.*; import com.thoughtworks.go.domain.Pipeline; import com.thoughtworks.go.domain.buildcause.BuildCause; import com.thoughtworks.go.domain.builder.Builder; import com.thoughtworks.go.domain.builder.FetchArtifactBuilder; import com.thoughtworks.go.domain.builder.FetchPluggableArtifactBuilder; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.server.service.PipelineService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:WEB-INF/applicationContext-global.xml", "classpath:WEB-INF/applicationContext-dataLocalAccess.xml", "classpath:WEB-INF/applicationContext-acegi-security.xml", "classpath:testPropertyConfigurer.xml" }) public class BuilderFactoryIntegrationTest { @Autowired private BuilderFactory builderFactory; @Autowired private PipelineService upstreamResolver; @Autowired private GoConfigService goConfigService; @Test public void shouldCreateBuilderForFetchTask() { final FetchTask fetchTask = new FetchTask(new CaseInsensitiveString("up42"), new CaseInsensitiveString("up42_stage"), new CaseInsensitiveString("up42_job"), "installers.zip", "dist"); final Pipeline pipeline = new Pipeline("up42", BuildCause.createExternal()); final Builder builder = builderFactory.builderFor(fetchTask, pipeline, upstreamResolver); assertThat(builder, instanceOf(FetchArtifactBuilder.class)); } @Test public void shouldCreateBuilderForFetchPluggableArtifactTask() { final PipelineConfig pipelineConfig = goConfigService.pipelineConfigNamed(new CaseInsensitiveString("up42")); goConfigService.artifactStores().add(new ArtifactStore("storeId", "PluginId")); pipelineConfig.getStage("up42_stage").jobConfigByConfigName("up42_job").artifactConfigs() .add(new PluggableArtifactConfig("artifactId", "storeId")); final FetchPluggableArtifactTask pluggableArtifactTask = new FetchPluggableArtifactTask( new CaseInsensitiveString("up42"), new CaseInsensitiveString("up42_stage"), new CaseInsensitiveString("up42_job"), "artifactId"); final Pipeline pipeline = new Pipeline("up42", BuildCause.createExternal()); final Builder builder = builderFactory.builderFor(pluggableArtifactTask, pipeline, upstreamResolver); assertThat(builder, instanceOf(FetchPluggableArtifactBuilder.class)); } }
3e0431bc89640a2dbf36fcb532979bdb845cc813
4,445
java
Java
Coding-Android/common-coding/src/main/java/net/coding/program/common/model/Subject.java
zhangqi-ak47/codingnet-android
1b6c6739957bceecada731b0f758e68840abc908
[ "MIT" ]
282
2015-09-09T10:39:10.000Z
2022-02-28T16:25:26.000Z
Coding-Android/common-coding/src/main/java/net/coding/program/common/model/Subject.java
zhangqi-ak47/codingnet-android
1b6c6739957bceecada731b0f758e68840abc908
[ "MIT" ]
null
null
null
Coding-Android/common-coding/src/main/java/net/coding/program/common/model/Subject.java
zhangqi-ak47/codingnet-android
1b6c6739957bceecada731b0f758e68840abc908
[ "MIT" ]
95
2015-09-11T04:50:08.000Z
2021-11-28T18:29:39.000Z
31.083916
96
0.574128
1,746
package net.coding.program.common.model; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by david on 15-7-21. */ public class Subject { public static class SubjectDescObject implements Serializable, ISubjectRecommendObject { private static final long serialVersionUID = -8890594453428648661L; public int id; public String name; public Integer speackers; public int watchers; public Integer count; public String image_url; public String description; public boolean watched; public long created_at; public HotTweetDescObject hot_tweet; public List<UserObject> user_list; private int type = 1; // 自定义属性 1 表示热门话题 2 表示 public SubjectDescObject(JSONObject json) throws JSONException { created_at = json.optLong("created_at"); id = json.optInt("id"); watched = json.optBoolean("watched"); speackers = json.optInt("speackers"); if (speackers == 0) speackers = json.optInt("speakers"); watchers = json.optInt("watchers"); count = json.optInt("count"); image_url = json.optString("image_url"); description = json.optString("description"); name = json.optString("name"); if (json.has("hot_tweet")) hot_tweet = new HotTweetDescObject(json.optJSONObject("hot_tweet")); JSONArray arr = json.optJSONArray("user_list"); if (arr != null && arr.length() > 0) { user_list = new ArrayList<UserObject>(); for (int i = 0; i < arr.length(); i++) { user_list.add(new UserObject(arr.optJSONObject(i))); } } } @Override public String getName() { return this.name; } @Override public int getType() { return type; } public void setType(int type) { this.type = type; } } public static class HotTweetDescObject implements Serializable { private static final long serialVersionUID = 6695978729344184433L; public int id; public int owner_id; public UserObject owner; public long created_at; public int likes; public int comments; public List<BaseComment> comment_list; public String device; public String location; public String coord; public String address; public String content; public String path; public int acitivity_id; public boolean liked; public List<UserObject> like_users; public HotTweetDescObject(JSONObject json) { id = json.optInt("id"); owner_id = json.optInt("owner_id"); owner = new UserObject(json.optJSONObject("owner")); created_at = json.optLong("created_at"); likes = json.optInt("likes"); comments = json.optInt("comments"); device = json.optString("device"); location = json.optString("location"); device = json.optString("device"); coord = json.optString("coord"); device = json.optString("device"); address = json.optString("address"); content = json.optString("content"); acitivity_id = json.optInt("acitivity_id"); liked = json.optBoolean("liked"); JSONArray arr = json.optJSONArray("like_users"); if (arr != null && arr.length() > 0) { like_users = new ArrayList<UserObject>(); for (int i = 0; i < arr.length(); i++) { like_users.add(new UserObject(arr.optJSONObject(i))); } } } } public static class SubjectLastUsedObject implements Serializable, ISubjectRecommendObject { private static final long serialVersionUID = 587704153402125828L; public String name; public SubjectLastUsedObject(String name) { this.name = name; } @Override public String getName() { return name; } @Override public int getType() { return 0; } } }
3e043262b793bdb4a9106546b08dfcd23925eaea
22,083
java
Java
aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/ApplicationConfigurationDescription.java
maxsjohn/aws-sdk-java
6f4f520e7ed9ae3b997f893ef65864fb0f562412
[ "Apache-2.0" ]
1
2020-10-14T16:15:38.000Z
2020-10-14T16:15:38.000Z
aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/ApplicationConfigurationDescription.java
maxsjohn/aws-sdk-java
6f4f520e7ed9ae3b997f893ef65864fb0f562412
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/ApplicationConfigurationDescription.java
maxsjohn/aws-sdk-java
6f4f520e7ed9ae3b997f893ef65864fb0f562412
[ "Apache-2.0" ]
1
2020-10-10T15:59:17.000Z
2020-10-10T15:59:17.000Z
44.166
161
0.715709
1,747
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisanalyticsv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes details about the application code and starting parameters for a Kinesis Data Analytics application. * </p> * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/ApplicationConfigurationDescription" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ApplicationConfigurationDescription implements Serializable, Cloneable, StructuredPojo { /** * <p> * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics application. * </p> */ private SqlApplicationConfigurationDescription sqlApplicationConfigurationDescription; /** * <p> * The details about the application code for a Flink-based Kinesis Data Analytics application. * </p> */ private ApplicationCodeConfigurationDescription applicationCodeConfigurationDescription; /** * <p> * The details about the starting properties for a Kinesis Data Analytics application. * </p> */ private RunConfigurationDescription runConfigurationDescription; /** * <p> * The details about a Flink-based Kinesis Data Analytics application. * </p> */ private FlinkApplicationConfigurationDescription flinkApplicationConfigurationDescription; /** * <p> * Describes execution properties for a Flink-based Kinesis Data Analytics application. * </p> */ private EnvironmentPropertyDescriptions environmentPropertyDescriptions; /** * <p> * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. * </p> */ private ApplicationSnapshotConfigurationDescription applicationSnapshotConfigurationDescription; /** * <p> * The array of descriptions of VPC configurations available to the application. * </p> */ private java.util.List<VpcConfigurationDescription> vpcConfigurationDescriptions; /** * <p> * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics application. * </p> * * @param sqlApplicationConfigurationDescription * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics * application. */ public void setSqlApplicationConfigurationDescription(SqlApplicationConfigurationDescription sqlApplicationConfigurationDescription) { this.sqlApplicationConfigurationDescription = sqlApplicationConfigurationDescription; } /** * <p> * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics application. * </p> * * @return The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics * application. */ public SqlApplicationConfigurationDescription getSqlApplicationConfigurationDescription() { return this.sqlApplicationConfigurationDescription; } /** * <p> * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics application. * </p> * * @param sqlApplicationConfigurationDescription * The details about inputs, outputs, and reference data sources for a SQL-based Kinesis Data Analytics * application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withSqlApplicationConfigurationDescription( SqlApplicationConfigurationDescription sqlApplicationConfigurationDescription) { setSqlApplicationConfigurationDescription(sqlApplicationConfigurationDescription); return this; } /** * <p> * The details about the application code for a Flink-based Kinesis Data Analytics application. * </p> * * @param applicationCodeConfigurationDescription * The details about the application code for a Flink-based Kinesis Data Analytics application. */ public void setApplicationCodeConfigurationDescription(ApplicationCodeConfigurationDescription applicationCodeConfigurationDescription) { this.applicationCodeConfigurationDescription = applicationCodeConfigurationDescription; } /** * <p> * The details about the application code for a Flink-based Kinesis Data Analytics application. * </p> * * @return The details about the application code for a Flink-based Kinesis Data Analytics application. */ public ApplicationCodeConfigurationDescription getApplicationCodeConfigurationDescription() { return this.applicationCodeConfigurationDescription; } /** * <p> * The details about the application code for a Flink-based Kinesis Data Analytics application. * </p> * * @param applicationCodeConfigurationDescription * The details about the application code for a Flink-based Kinesis Data Analytics application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withApplicationCodeConfigurationDescription( ApplicationCodeConfigurationDescription applicationCodeConfigurationDescription) { setApplicationCodeConfigurationDescription(applicationCodeConfigurationDescription); return this; } /** * <p> * The details about the starting properties for a Kinesis Data Analytics application. * </p> * * @param runConfigurationDescription * The details about the starting properties for a Kinesis Data Analytics application. */ public void setRunConfigurationDescription(RunConfigurationDescription runConfigurationDescription) { this.runConfigurationDescription = runConfigurationDescription; } /** * <p> * The details about the starting properties for a Kinesis Data Analytics application. * </p> * * @return The details about the starting properties for a Kinesis Data Analytics application. */ public RunConfigurationDescription getRunConfigurationDescription() { return this.runConfigurationDescription; } /** * <p> * The details about the starting properties for a Kinesis Data Analytics application. * </p> * * @param runConfigurationDescription * The details about the starting properties for a Kinesis Data Analytics application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withRunConfigurationDescription(RunConfigurationDescription runConfigurationDescription) { setRunConfigurationDescription(runConfigurationDescription); return this; } /** * <p> * The details about a Flink-based Kinesis Data Analytics application. * </p> * * @param flinkApplicationConfigurationDescription * The details about a Flink-based Kinesis Data Analytics application. */ public void setFlinkApplicationConfigurationDescription(FlinkApplicationConfigurationDescription flinkApplicationConfigurationDescription) { this.flinkApplicationConfigurationDescription = flinkApplicationConfigurationDescription; } /** * <p> * The details about a Flink-based Kinesis Data Analytics application. * </p> * * @return The details about a Flink-based Kinesis Data Analytics application. */ public FlinkApplicationConfigurationDescription getFlinkApplicationConfigurationDescription() { return this.flinkApplicationConfigurationDescription; } /** * <p> * The details about a Flink-based Kinesis Data Analytics application. * </p> * * @param flinkApplicationConfigurationDescription * The details about a Flink-based Kinesis Data Analytics application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withFlinkApplicationConfigurationDescription( FlinkApplicationConfigurationDescription flinkApplicationConfigurationDescription) { setFlinkApplicationConfigurationDescription(flinkApplicationConfigurationDescription); return this; } /** * <p> * Describes execution properties for a Flink-based Kinesis Data Analytics application. * </p> * * @param environmentPropertyDescriptions * Describes execution properties for a Flink-based Kinesis Data Analytics application. */ public void setEnvironmentPropertyDescriptions(EnvironmentPropertyDescriptions environmentPropertyDescriptions) { this.environmentPropertyDescriptions = environmentPropertyDescriptions; } /** * <p> * Describes execution properties for a Flink-based Kinesis Data Analytics application. * </p> * * @return Describes execution properties for a Flink-based Kinesis Data Analytics application. */ public EnvironmentPropertyDescriptions getEnvironmentPropertyDescriptions() { return this.environmentPropertyDescriptions; } /** * <p> * Describes execution properties for a Flink-based Kinesis Data Analytics application. * </p> * * @param environmentPropertyDescriptions * Describes execution properties for a Flink-based Kinesis Data Analytics application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withEnvironmentPropertyDescriptions(EnvironmentPropertyDescriptions environmentPropertyDescriptions) { setEnvironmentPropertyDescriptions(environmentPropertyDescriptions); return this; } /** * <p> * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. * </p> * * @param applicationSnapshotConfigurationDescription * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. */ public void setApplicationSnapshotConfigurationDescription(ApplicationSnapshotConfigurationDescription applicationSnapshotConfigurationDescription) { this.applicationSnapshotConfigurationDescription = applicationSnapshotConfigurationDescription; } /** * <p> * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. * </p> * * @return Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. */ public ApplicationSnapshotConfigurationDescription getApplicationSnapshotConfigurationDescription() { return this.applicationSnapshotConfigurationDescription; } /** * <p> * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. * </p> * * @param applicationSnapshotConfigurationDescription * Describes whether snapshots are enabled for a Flink-based Kinesis Data Analytics application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withApplicationSnapshotConfigurationDescription( ApplicationSnapshotConfigurationDescription applicationSnapshotConfigurationDescription) { setApplicationSnapshotConfigurationDescription(applicationSnapshotConfigurationDescription); return this; } /** * <p> * The array of descriptions of VPC configurations available to the application. * </p> * * @return The array of descriptions of VPC configurations available to the application. */ public java.util.List<VpcConfigurationDescription> getVpcConfigurationDescriptions() { return vpcConfigurationDescriptions; } /** * <p> * The array of descriptions of VPC configurations available to the application. * </p> * * @param vpcConfigurationDescriptions * The array of descriptions of VPC configurations available to the application. */ public void setVpcConfigurationDescriptions(java.util.Collection<VpcConfigurationDescription> vpcConfigurationDescriptions) { if (vpcConfigurationDescriptions == null) { this.vpcConfigurationDescriptions = null; return; } this.vpcConfigurationDescriptions = new java.util.ArrayList<VpcConfigurationDescription>(vpcConfigurationDescriptions); } /** * <p> * The array of descriptions of VPC configurations available to the application. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setVpcConfigurationDescriptions(java.util.Collection)} or * {@link #withVpcConfigurationDescriptions(java.util.Collection)} if you want to override the existing values. * </p> * * @param vpcConfigurationDescriptions * The array of descriptions of VPC configurations available to the application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withVpcConfigurationDescriptions(VpcConfigurationDescription... vpcConfigurationDescriptions) { if (this.vpcConfigurationDescriptions == null) { setVpcConfigurationDescriptions(new java.util.ArrayList<VpcConfigurationDescription>(vpcConfigurationDescriptions.length)); } for (VpcConfigurationDescription ele : vpcConfigurationDescriptions) { this.vpcConfigurationDescriptions.add(ele); } return this; } /** * <p> * The array of descriptions of VPC configurations available to the application. * </p> * * @param vpcConfigurationDescriptions * The array of descriptions of VPC configurations available to the application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationConfigurationDescription withVpcConfigurationDescriptions(java.util.Collection<VpcConfigurationDescription> vpcConfigurationDescriptions) { setVpcConfigurationDescriptions(vpcConfigurationDescriptions); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSqlApplicationConfigurationDescription() != null) sb.append("SqlApplicationConfigurationDescription: ").append(getSqlApplicationConfigurationDescription()).append(","); if (getApplicationCodeConfigurationDescription() != null) sb.append("ApplicationCodeConfigurationDescription: ").append(getApplicationCodeConfigurationDescription()).append(","); if (getRunConfigurationDescription() != null) sb.append("RunConfigurationDescription: ").append(getRunConfigurationDescription()).append(","); if (getFlinkApplicationConfigurationDescription() != null) sb.append("FlinkApplicationConfigurationDescription: ").append(getFlinkApplicationConfigurationDescription()).append(","); if (getEnvironmentPropertyDescriptions() != null) sb.append("EnvironmentPropertyDescriptions: ").append(getEnvironmentPropertyDescriptions()).append(","); if (getApplicationSnapshotConfigurationDescription() != null) sb.append("ApplicationSnapshotConfigurationDescription: ").append(getApplicationSnapshotConfigurationDescription()).append(","); if (getVpcConfigurationDescriptions() != null) sb.append("VpcConfigurationDescriptions: ").append(getVpcConfigurationDescriptions()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ApplicationConfigurationDescription == false) return false; ApplicationConfigurationDescription other = (ApplicationConfigurationDescription) obj; if (other.getSqlApplicationConfigurationDescription() == null ^ this.getSqlApplicationConfigurationDescription() == null) return false; if (other.getSqlApplicationConfigurationDescription() != null && other.getSqlApplicationConfigurationDescription().equals(this.getSqlApplicationConfigurationDescription()) == false) return false; if (other.getApplicationCodeConfigurationDescription() == null ^ this.getApplicationCodeConfigurationDescription() == null) return false; if (other.getApplicationCodeConfigurationDescription() != null && other.getApplicationCodeConfigurationDescription().equals(this.getApplicationCodeConfigurationDescription()) == false) return false; if (other.getRunConfigurationDescription() == null ^ this.getRunConfigurationDescription() == null) return false; if (other.getRunConfigurationDescription() != null && other.getRunConfigurationDescription().equals(this.getRunConfigurationDescription()) == false) return false; if (other.getFlinkApplicationConfigurationDescription() == null ^ this.getFlinkApplicationConfigurationDescription() == null) return false; if (other.getFlinkApplicationConfigurationDescription() != null && other.getFlinkApplicationConfigurationDescription().equals(this.getFlinkApplicationConfigurationDescription()) == false) return false; if (other.getEnvironmentPropertyDescriptions() == null ^ this.getEnvironmentPropertyDescriptions() == null) return false; if (other.getEnvironmentPropertyDescriptions() != null && other.getEnvironmentPropertyDescriptions().equals(this.getEnvironmentPropertyDescriptions()) == false) return false; if (other.getApplicationSnapshotConfigurationDescription() == null ^ this.getApplicationSnapshotConfigurationDescription() == null) return false; if (other.getApplicationSnapshotConfigurationDescription() != null && other.getApplicationSnapshotConfigurationDescription().equals(this.getApplicationSnapshotConfigurationDescription()) == false) return false; if (other.getVpcConfigurationDescriptions() == null ^ this.getVpcConfigurationDescriptions() == null) return false; if (other.getVpcConfigurationDescriptions() != null && other.getVpcConfigurationDescriptions().equals(this.getVpcConfigurationDescriptions()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSqlApplicationConfigurationDescription() == null) ? 0 : getSqlApplicationConfigurationDescription().hashCode()); hashCode = prime * hashCode + ((getApplicationCodeConfigurationDescription() == null) ? 0 : getApplicationCodeConfigurationDescription().hashCode()); hashCode = prime * hashCode + ((getRunConfigurationDescription() == null) ? 0 : getRunConfigurationDescription().hashCode()); hashCode = prime * hashCode + ((getFlinkApplicationConfigurationDescription() == null) ? 0 : getFlinkApplicationConfigurationDescription().hashCode()); hashCode = prime * hashCode + ((getEnvironmentPropertyDescriptions() == null) ? 0 : getEnvironmentPropertyDescriptions().hashCode()); hashCode = prime * hashCode + ((getApplicationSnapshotConfigurationDescription() == null) ? 0 : getApplicationSnapshotConfigurationDescription().hashCode()); hashCode = prime * hashCode + ((getVpcConfigurationDescriptions() == null) ? 0 : getVpcConfigurationDescriptions().hashCode()); return hashCode; } @Override public ApplicationConfigurationDescription clone() { try { return (ApplicationConfigurationDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisanalyticsv2.model.transform.ApplicationConfigurationDescriptionMarshaller.getInstance() .marshall(this, protocolMarshaller); } }
3e04328e1e50d4f167564e8853d04fff46dd7618
11,725
java
Java
Lab8/BubbleGameSkeleton/app/src/main/java/course/labs/graphicslab/BubbleActivity.java
hpowell20/cs2063-winter-2021-labs
70c592c2fc10101c21270c3506ef4c8f82710115
[ "Apache-2.0" ]
2
2021-01-28T04:54:17.000Z
2021-03-25T00:13:02.000Z
Lab8/BubbleGameSkeleton/app/src/main/java/course/labs/graphicslab/BubbleActivity.java
hpowell20/cs2063-winter-2021-labs
70c592c2fc10101c21270c3506ef4c8f82710115
[ "Apache-2.0" ]
null
null
null
Lab8/BubbleGameSkeleton/app/src/main/java/course/labs/graphicslab/BubbleActivity.java
hpowell20/cs2063-winter-2021-labs
70c592c2fc10101c21270c3506ef4c8f82710115
[ "Apache-2.0" ]
8
2021-01-26T18:49:22.000Z
2021-04-26T01:28:07.000Z
33.595989
114
0.58209
1,748
package course.labs.graphicslab; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class BubbleActivity extends Activity { private static final int STREAM_TYPE = AudioManager.STREAM_MUSIC; // The Main view private RelativeLayout mFrame; // Bubble image's bitmap private Bitmap bitmap; // Display dimensions private int displayWidth, displayHeight; // Gesture Detector private GestureDetector gestureDetector; // A TextView to hold the current number of bubbles private TextView bubbleCountTextView; // Sound variables // SoundPool private SoundPool soundPool; // ID for the bubble popping sound private int soundID; // Audio volume private float streamVolume; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Set up user interface mFrame = findViewById(R.id.frame); bubbleCountTextView = findViewById(R.id.count); // Initialize the number of bubbles bubbleCountTextView.setText(0); // Load basic bubble Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.b64); } @Override protected void onResume() { super.onResume(); setStreamVolume(); // TODO // Make a new SoundPool, allowing up to 10 streams // Store this as soundPool // TODO // Set a SoundPool OnLoadCompletedListener that calls setupGestureDetector() // TODO // Load the sound from res/raw/bubble_pop.wav // Store this as soundID } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { // Get the size of the display so this View knows where borders are displayWidth = mFrame.getWidth(); displayHeight = mFrame.getHeight(); } } // Setup the stream volume private void setStreamVolume() { // Manage bubble popping sound // Use AudioManager.STREAM_MUSIC as stream type // AudioManager audio settings for adjusting the volume AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); // Current volume Index of particular stream type float currentVolumeIndex = (float) audioManager.getStreamVolume(STREAM_TYPE); // Get the maximum volume index for a particular stream type float maxVolumeIndex = (float) audioManager.getStreamMaxVolume(STREAM_TYPE); // Set the volume between 0 --> 1 streamVolume = currentVolumeIndex / maxVolumeIndex; setVolumeControlStream(STREAM_TYPE); } // Set up GestureDetector private void setupGestureDetector() { gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent motionEvent) { return true; } // If a fling gesture starts on a BubbleView then change the // BubbleView's velocity based on x and y velocity from // this gesture @Override public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { // TODO // Implement onFling actions (See comment above for expected behaviour) // You can get all Views in mmFrame one at a time using the ViewGroup.getChildAt() method return true; } // If a single tap intersects a BubbleView, then pop the BubbleView // Otherwise, create a new BubbleView at the tap's location and add // it to mmFrame. Hint: Don't forget to start the movement of the // BubbleView. // Also update the number of bubbles displayed in the appropriate TextView @Override public boolean onSingleTapConfirmed(MotionEvent event) { // TODO - Implement onSingleTapConfirmed actions. // (See comment above for expected behaviour.) // You can get all Views in mmFrame using the // ViewGroup.getChildCount() method return true; } }); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO // Delegate the touch to the gestureDetector // Remove this when you're done the above todo return true || false; } @Override protected void onPause() { super.onPause(); // TODO // Release all SoundPool resources } // BubbleView is a View that displays a bubble. // This class handles animating, drawing, and popping amongst other actions. // A new BubbleView is created for each bubble on the display public class BubbleView extends View { private static final int BITMAP_SIZE = 64; private static final int REFRESH_RATE = 40; private final Paint mPainter = new Paint(); private ScheduledFuture<?> mMoverFuture; private int scaledBitmapSize; private Bitmap scaledBitmap; // location and direction of the bubble private float xPos, yPos, radius; // Speed of bubble private float dx, dy; // Rotation and speed of rotation of the bubble private long mRotate, mDRotate; BubbleView(Context context, float x, float y) { super(context); // Create a new random number generator to // randomize size, rotation, speed and direction Random r = new Random(); // Creates the bubble bitmap for this BubbleView createScaledBitmap(r); // Radius of the Bitmap radius = scaledBitmapSize / 2; // Adjust position to center the bubble under user's finger xPos = x - radius; yPos = y - radius; // Set the BubbleView's speed and direction setSpeedAndDirection(r); // Set the BubbleView's rotation setRotation(r); mPainter.setAntiAlias(true); } private void setRotation(Random r) { // TODO // Set rotation in range [1..5] } private void setSpeedAndDirection(Random r) { // TODO // Set dx and dy to indicate movement direction and speed // Limit speed in the x and y direction to [-3..3] pixels per movement } private void createScaledBitmap(Random r) { // TODO // Set scaled bitmap size (scaledBitmapSize) in range [2..4] * BITMAP_SIZE // TODO // Create the scaled bitmap (scaledBitmap) using size set above } // Start moving the BubbleView & updating the display private void startMovement() { // Creates a WorkerThread ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // Execute the run() in Worker Thread every REFRESH_RATE // milliseconds // Save reference to this job in mMoverFuture mMoverFuture = executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { // TODO // Implement movement logic. // Each time this method is run the BubbleView should // move one step. (Use moveWhileOnScreen() to do this.) // If the BubbleView exits the display, stop the BubbleView's // Worker Thread. (Use stopMovement() to do this.) Otherwise, // request that the BubbleView be redrawn. } }, 0, REFRESH_RATE, TimeUnit.MILLISECONDS); } // Returns true if the BubbleView intersects position (x,y) private synchronized boolean intersects(float x, float y) { float centerX = xPos + radius; float centerY = yPos + radius; // TODO // Return true if the BubbleView intersects position (x,y) // Remove this when you're done the above todo return false; } // Cancel the Bubble's movement // Remove Bubble from mmFrame // Play pop sound if the BubbleView was popped private void stopMovement(final boolean wasPopped) { if (null != mMoverFuture) { if (!mMoverFuture.isDone()) { mMoverFuture.cancel(true); } // This work will be performed on the UI Thread mFrame.post(new Runnable() { @Override public void run() { // TODO // Remove the BubbleView from mmFrame // TODO // Update the TextView displaying the number of bubbles // TODO // If the bubble was popped by user play the popping sound // HINT: Use the streamVolume for left and right volume parameters } }); } } // Change the Bubble's speed and direction private synchronized void deflect(float velocityX, float velocityY) { dx = velocityX / REFRESH_RATE; dy = velocityY / REFRESH_RATE; } // Draw the Bubble at its current location @Override protected synchronized void onDraw(Canvas canvas) { // TODO // Save the canvas // TODO // Increase the rotation of the original image by mDRotate // TODO // Rotate the canvas by current rotation // Hint - Rotate around the bubble's center, not its position // TODO // Draw the bitmap at it's new location // TODO // Restore the canvas } // Returns true if the BubbleView is still on the screen after the move // operation private synchronized boolean moveWhileOnScreen() { // TODO // Move the BubbleView return isInView(); } // Return true if the BubbleView is still on the screen after the move // operation private boolean isInView() { // TODO // Return true if the BubbleView is still on the screen after // the move operation // Remove this when you're done the above TODO return false; } } }
3e0432cb92aa4e92d9f429338a5dcd5f5db187f0
937
java
Java
amazon-kinesis-client/src/main/java/software/amazon/kinesis/coordinator/NoOpWorkerStateChangeListener.java
Unacademy/amazon-kinesis-client
d5cac0785188a1d081adcb0512d314d544e9bcd8
[ "Apache-2.0" ]
570
2015-01-14T12:49:22.000Z
2022-03-11T19:45:54.000Z
amazon-kinesis-client/src/main/java/software/amazon/kinesis/coordinator/NoOpWorkerStateChangeListener.java
Unacademy/amazon-kinesis-client
d5cac0785188a1d081adcb0512d314d544e9bcd8
[ "Apache-2.0" ]
520
2015-01-06T17:31:28.000Z
2022-03-31T09:39:05.000Z
amazon-kinesis-client/src/main/java/software/amazon/kinesis/coordinator/NoOpWorkerStateChangeListener.java
zengyu714/amazon-kinesis-client
cd737adf76b2918f8377fb49d9e0478de33a4140
[ "Apache-2.0" ]
474
2015-01-06T18:22:54.000Z
2022-03-30T17:40:03.000Z
30.225806
81
0.75667
1,749
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package software.amazon.kinesis.coordinator; public class NoOpWorkerStateChangeListener implements WorkerStateChangeListener { /** * Empty constructor for NoOp Worker State Change Listener */ public NoOpWorkerStateChangeListener() { } @Override public void onWorkerStateChange(WorkerState newState) { } }
3e0432f313a1089e2bf75865c1580fd5cea17a8d
2,488
java
Java
Search Engine/src/Indexer.java
Ahmedmma72/Search-Engine
04d2e6ac7d26a27323468d245f785032c43693b6
[ "MIT" ]
1
2021-06-08T16:48:03.000Z
2021-06-08T16:48:03.000Z
Search Engine/src/Indexer.java
PeterAyad/SearchEngine
6fd51fb3dc5c4a6d16631c3c342d0564a1b2d7bd
[ "MIT" ]
null
null
null
Search Engine/src/Indexer.java
PeterAyad/SearchEngine
6fd51fb3dc5c4a6d16631c3c342d0564a1b2d7bd
[ "MIT" ]
null
null
null
37.134328
107
0.626206
1,750
import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Scanner; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Indexer { private static ArrayList<String> listOfWords; private static ArrayList<String> listOfWordsP; private static int countOfWords; private static String content; private static int tCountOfWords; public static void main(String[] args) throws SQLException, IOException { tCountOfWords=0; IndexerDB.open(); Scanner s = new Scanner(System.in); System.out.println("Start over indexing ? enter y if yes"); String startOver=s.nextLine(); if(startOver.equals("y")){ IndexerDB.startOver(); } s.close(); System.out.println("Started Indexing"); String URL; int count=0; long startTime = System.currentTimeMillis(); while ((URL = IndexerDB.getNonIndexedURL()) != null) { System.out.println("Started Parsing "+URL); parsePAGE(URL); System.out.println("Finished Parsing "+URL); if (countOfWords > 0) { System.out.printf("started indexing page %d%n",++count); LinkedHashMap<String, Double> TF = IndexerDB.calcTF(listOfWords,listOfWordsP,countOfWords); IndexerDB.indexWords(TF, URL); } IndexerDB.updateURL(URL); System.out.printf("finished indexing page %d%n", count); } IndexerDB.clean(); long endTime = System.currentTimeMillis(); System.out.printf("Finished Indexing %d words at %d %n",tCountOfWords,endTime-startTime); IndexerDB.close(); } private static void parsePAGE(String url) throws IOException { try { countOfWords = 0; content = Extract.escapeMetaCharacters(IndexerDB.getDocument(url)); if(content.isEmpty()){ return; } listOfWords = Extract.splitSentence(content); listOfWordsP=listOfWords; listOfWords = Extract.removeStoppingWords(listOfWords); countOfWords += listOfWords.size(); tCountOfWords += countOfWords; }catch(Exception e){ System.out.println("error occurred in parse page"); } } }
3e04331484efaf44e9a2011c7ce4879d373b14b6
6,462
java
Java
app/src/main/java/myapp/lenovo/viewpager/bmob/MyBmob.java
wn1137162270/MyOcr
45b7eca529e9e4d62c55b5080d6175c30e00e4a4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/myapp/lenovo/viewpager/bmob/MyBmob.java
wn1137162270/MyOcr
45b7eca529e9e4d62c55b5080d6175c30e00e4a4
[ "Apache-2.0" ]
null
null
null
app/src/main/java/myapp/lenovo/viewpager/bmob/MyBmob.java
wn1137162270/MyOcr
45b7eca529e9e4d62c55b5080d6175c30e00e4a4
[ "Apache-2.0" ]
null
null
null
37.789474
133
0.594089
1,751
package myapp.lenovo.viewpager.bmob; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.tencent.connect.common.Constants; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import org.json.JSONException; import org.json.JSONObject; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobConfig; import cn.bmob.v3.BmobSMS; import cn.bmob.v3.BmobUser; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.LogInListener; import cn.bmob.v3.listener.QueryListener; import cn.bmob.v3.listener.SaveListener; import myapp.lenovo.viewpager.entity.MyUser; /** * Created by wn on 2019/5/18. */ public class MyBmob { private static final String TAG ="MyBmob"; private static final String qqAppId ="1105782685"; public static final int REGISTER = 0; public static final int LOGIN_BY_ACCOUNT = 1; public static final int LOGIN_BY_QQ = 2; public static final int REQUEST_LOGIN_PHONESMS = 3; public static final int LOGIN_BY_PHONESMS = 4; private static IUiListener iUiListener; private static Tencent tencent; public static void initBmob(Context context){ Bmob.initialize(context,"167be2b330d3485eaad70348455b3853"); BmobConfig bmobConfig=new BmobConfig.Builder(context) .setApplicationId("167be2b330d3485eaad70348455b3853") .build(); Bmob.initialize(bmobConfig); } public static void registerBmobUserWithEmail(String username, String email, String password, final OperateDoneListener listener){ MyUser bmobUser=new MyUser(); bmobUser.setUsername(username); bmobUser.setPassword(password); if(email != null && !TextUtils.isEmpty(email)){ bmobUser.setEmail(email); } bmobUser.signUp(new SaveListener<MyUser>() { @Override public void done(MyUser myUser, BmobException e) { int errorCode; if(e == null){ errorCode = -1; } else{ errorCode = e.getErrorCode(); } listener.onOperateDone(errorCode, REGISTER); } }); } public static void loginBmobUserByAccount(String account, String password, final OperateDoneListener listener){ final boolean[] isSucceed = new boolean[1]; BmobUser.loginByAccount(account, password, new LogInListener<MyUser>() { @Override public void done(MyUser o, BmobException e) { isSucceed[0] = (e == null); listener.onOperateDone(isSucceed[0] ? 1 : 0, LOGIN_BY_ACCOUNT); } }); } public static void requestPhoneSMS(String phone, final OperateDoneListener listener){ BmobSMS.requestSMSCode(phone, "验证码", new QueryListener<Integer>() { @Override public void done(Integer integer, BmobException e) { boolean isSucceed = (e == null); listener.onOperateDone(isSucceed ? 1 : 0, REQUEST_LOGIN_PHONESMS); } }); } public static void LoginBmobUserByPhone(String phone, String phoneSMS, final OperateDoneListener listener){ BmobUser.loginBySMSCode(phone, phoneSMS, new LogInListener<MyUser>() { @Override public void done(MyUser bmobUser, BmobException e) { boolean isSucceed = (e == null); listener.onOperateDone(isSucceed ? 1 : 0, LOGIN_BY_PHONESMS); } }); } public static void bmobThirdLoginByQQ(final Activity activity, final OperateDoneListener listener){ iUiListener=new IUiListener() { @Override public void onComplete(Object o) { if (o != null) { JSONObject jsonObject = (JSONObject) o; try { String accessToken = jsonObject.getString(com.tencent. connect.common.Constants.PARAM_ACCESS_TOKEN); String expires = jsonObject.getString(com.tencent. connect.common.Constants.PARAM_EXPIRES_IN); String openId = jsonObject.getString(com.tencent. connect.common.Constants.PARAM_OPEN_ID); Log.d("accessToken", accessToken); Log.d("expires", expires); Log.d("openId", openId); BmobUser.BmobThirdUserAuth authInfo = new BmobUser.BmobThirdUserAuth(BmobUser. BmobThirdUserAuth.SNS_TYPE_QQ, accessToken, expires, openId); BmobUser.loginWithAuthData(authInfo, new LogInListener<JSONObject>() { @Override public void done(JSONObject jsonObject, BmobException e) { boolean isSucceed = (e == null); listener.onOperateDone(isSucceed ? 1 : 0, LOGIN_BY_QQ); } }); } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onError(UiError uiError) { Toast.makeText(activity,"QQ登录出错"+uiError.errorCode+uiError.errorDetail, Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(activity,"取消QQ绑定",Toast.LENGTH_SHORT).show(); } }; if(tencent==null){ tencent= Tencent.createInstance(qqAppId,activity); } tencent.logout(activity); tencent.login(activity,"all", iUiListener); } public static void handleActivityResult(int requestCode, int resultCode, Intent data){ Tencent.onActivityResultData(requestCode, resultCode, data, iUiListener); if (requestCode == Constants.REQUEST_API) { if (resultCode == 65) { tencent.handleLoginData(data, iUiListener); } } } public interface OperateDoneListener{ void onOperateDone(int errorCode, int which); } }
3e04335af5922b94c2086d54963634fc0cd412e9
918
java
Java
jdi-light-angular-tests/src/test/java/io/github/epam/angular/tests/elements/complex/tabgroup/TestsTabGroupBase.java
Valbod-I-am-a-Swiftie/jdi-light
d2932747b62438bd0313887356bee4b0d33b5f9a
[ "MIT" ]
92
2018-08-28T12:39:33.000Z
2022-03-22T16:30:59.000Z
jdi-light-angular-tests/src/test/java/io/github/epam/angular/tests/elements/complex/tabgroup/TestsTabGroupBase.java
Valbod-I-am-a-Swiftie/jdi-light
d2932747b62438bd0313887356bee4b0d33b5f9a
[ "MIT" ]
2,299
2018-10-05T11:32:28.000Z
2022-03-31T09:55:59.000Z
jdi-light-angular-tests/src/test/java/io/github/epam/angular/tests/elements/complex/tabgroup/TestsTabGroupBase.java
Valbod-I-am-a-Swiftie/jdi-light
d2932747b62438bd0313887356bee4b0d33b5f9a
[ "MIT" ]
51
2018-06-21T16:10:54.000Z
2022-03-30T19:18:47.000Z
34
101
0.751634
1,752
package io.github.epam.angular.tests.elements.complex.tabgroup; import io.github.epam.TestsInit; import org.testng.annotations.BeforeTest; import java.util.Arrays; import java.util.List; import static io.github.com.StaticSite.angularPage; import static io.github.epam.site.steps.States.shouldBeLoggedIn; public class TestsTabGroupBase extends TestsInit { public static final String CLASS_ATTR = "class"; public static final String ACCENT = "accent"; public static final String PRIMARY = "primary"; public static final String DYNAMIC_CONTENT = "Content %s"; public static final String TAB_GROUP_DEFAULT_CLASS = "mat-tab-group mat-primary"; public static final List<String> TITLES_DEFAULT_LIST = Arrays.asList("First", "Second", "Third"); @BeforeTest(alwaysRun = true) public static void beforeStartTest() { shouldBeLoggedIn(); angularPage.shouldBeOpened(); } }
3e0434783b0b830f7749099fd52b2f996467041e
2,052
java
Java
Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/format/dwarf4/MockDWARFCompilationUnit.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/format/dwarf4/MockDWARFCompilationUnit.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Features/Base/src/test/java/ghidra/app/util/bin/format/dwarf4/MockDWARFCompilationUnit.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
1
2022-03-07T13:22:05.000Z
2022-03-07T13:22:05.000Z
33.096774
93
0.764133
1,753
/* ### * IP: GHIDRA * * 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 ghidra.app.util.bin.format.dwarf4; import java.util.ArrayList; import java.util.List; import ghidra.app.util.bin.format.dwarf4.encoding.*; import ghidra.app.util.bin.format.dwarf4.next.DWARFProgram; import ghidra.util.task.TaskMonitor; public class MockDWARFCompilationUnit extends DWARFCompilationUnit { private List<DebugInfoEntry> mockEntries = new ArrayList<>(); private DebugInfoEntry compUnitDIE; public MockDWARFCompilationUnit(DWARFProgram dwarfProgram, long startOffset, long endOffset, long length, int format, short version, long abbreviationOffset, byte pointerSize, int compUnitNumber, int language) { super(dwarfProgram, startOffset, endOffset, length, format, version, abbreviationOffset, pointerSize, compUnitNumber, startOffset, null); setCompileUnit( new DWARFCompileUnit("Mock Comp Unit", "Mock Comp Unit Producer", "Mock Comp Unit Dir", 0, 0, language, DWARFIdentifierCase.DW_ID_case_insensitive, false, null)); compUnitDIE = new DIECreator(DWARFTag.DW_TAG_compile_unit) .addString(DWARFAttribute.DW_AT_name, "MockCompUnit" + compUnitNumber) .create(this); } @Override public void readDIEs(List<DebugInfoEntry> dies, TaskMonitor unused_monitor) { dies.addAll(mockEntries); } public DebugInfoEntry getCompileUnitDIE() { return compUnitDIE; } public void addMockEntry(DebugInfoEntry die) { mockEntries.add(die); } public int getMockEntryCount() { return mockEntries.size(); } }
3e04354c295b3d258bfe3bd793ee8cd398d1d4e6
2,827
java
Java
java-client/uri/src/main/java/io/deephaven/uri/UriHelper.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
55
2021-05-11T16:01:59.000Z
2022-03-30T14:30:33.000Z
java-client/uri/src/main/java/io/deephaven/uri/UriHelper.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
943
2021-05-10T14:00:02.000Z
2022-03-31T21:28:15.000Z
java-client/uri/src/main/java/io/deephaven/uri/UriHelper.java
mattrunyon/deephaven-core
80e3567e4647ab76a81e483d0a8ab542f9aadace
[ "MIT" ]
29
2021-05-10T11:33:16.000Z
2022-03-30T21:01:54.000Z
34.47561
120
0.52989
1,754
package io.deephaven.uri; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; public class UriHelper { public static boolean isUriSafe(String part) { final String encoded; try { encoded = URLEncoder.encode(part, "UTF-8"); } catch (UnsupportedEncodingException e) { return false; } return part.equals(encoded); } /** * A URI is a "local path" when the only components are {@link URI#getScheme() scheme} and {@link URI#getPath() * path}; and path starts with {@code "/"}. * * @param uri the URI * @return true if {@code uri} is a "local path" */ public static boolean isLocalPath(URI uri) { return uri.getHost() == null && !uri.isOpaque() && uri.getPath().startsWith("/") && uri.getQuery() == null && uri.getUserInfo() == null && uri.getFragment() == null; } /** * A URI is a "remote path" when the only components are {@link URI#getScheme() scheme}, {@link URI#getHost() host}, * and {@link URI#getPath() path}; and path starts with {@code "/"}. * * @param uri the URI * @return true if {@code uri} is a "remote path" */ public static boolean isRemotePath(URI uri) { return uri.getHost() != null && !uri.isOpaque() && uri.getPath().startsWith("/") && uri.getQuery() == null && uri.getUserInfo() == null && uri.getFragment() == null; } /** * A URI is a "remote target" when the only components are {@link URI#getScheme() scheme}, {@link URI#getHost() * host}, and {@link URI#getPath() path}; and path is empty. * * @param uri the URI * @return true if {@code uri} is a "remote target" */ public static boolean isRemoteTarget(URI uri) { return uri.getHost() != null && !uri.isOpaque() && uri.getPath().isEmpty() && uri.getQuery() == null && uri.getUserInfo() == null && uri.getFragment() == null; } /** * A URI is a "remote query" when the only components are {@link URI#getScheme() scheme}, {@link URI#getHost() * host}, {@link URI#getQuery() query}, and {@link URI#getPath() path}; and path is empty. * * @param uri the URI * @return true if {@code uri} is a "remote query" */ public static boolean isRemoteQuery(URI uri) { return uri.getHost() != null && !uri.isOpaque() && uri.getPath().isEmpty() && uri.getQuery() != null && uri.getUserInfo() == null && uri.getFragment() == null; } }
3e0435ac39d7bc0a4d062f70b3bad0160824cbf9
651
java
Java
lichkin-projects-pss-entities/src/main/java/com/lichkin/framework/db/beans/SysPssStoreR.java
LichKinContributor/lichkin-projects-pss
ce4e540dba03741964d59d7588bfa90d05277520
[ "MIT" ]
null
null
null
lichkin-projects-pss-entities/src/main/java/com/lichkin/framework/db/beans/SysPssStoreR.java
LichKinContributor/lichkin-projects-pss
ce4e540dba03741964d59d7588bfa90d05277520
[ "MIT" ]
null
null
null
lichkin-projects-pss-entities/src/main/java/com/lichkin/framework/db/beans/SysPssStoreR.java
LichKinContributor/lichkin-projects-pss
ce4e540dba03741964d59d7588bfa90d05277520
[ "MIT" ]
null
null
null
22.448276
58
0.768049
1,755
package com.lichkin.framework.db.beans; /** * 数据库资源定义类 * @author SuZhou LichKin Information Technology Co., Ltd. */ public interface SysPssStoreR { public static final int id = 0x50004000; public static final int usingStatus = 0x50004001; public static final int insertTime = 0x50004002; public static final int compId = 0x50004003; public static final int storeCode = 0x50004004; public static final int storeName = 0x50004005; public static final int storageId = 0x50004006; public static final int address = 0x50004007; public static final int responsiblePerson = 0x50004008; public static final int remarks = 0x50004009; }
3e0435d1aa6cb709fa6444b4ae5aad71adcb758a
4,138
java
Java
src/main/java/org/praisenter/data/json/PraisenterFormat.java
wnbittle/praisenter
98a72542193c1a5df9646a3afd14ab8bf8455b60
[ "BSD-3-Clause" ]
8
2015-03-14T04:09:49.000Z
2022-03-30T03:34:45.000Z
src/main/java/org/praisenter/data/json/PraisenterFormat.java
wnbittle/praisenter
98a72542193c1a5df9646a3afd14ab8bf8455b60
[ "BSD-3-Clause" ]
29
2015-03-14T01:42:00.000Z
2021-10-20T01:02:11.000Z
src/main/java/org/praisenter/data/json/PraisenterFormat.java
wnbittle/praisenter
98a72542193c1a5df9646a3afd14ab8bf8455b60
[ "BSD-3-Clause" ]
2
2018-10-18T15:55:33.000Z
2020-08-10T06:34:39.000Z
34.198347
106
0.696472
1,756
/* * Copyright (c) 2015-2016 William Bittle http://www.praisenter.org/ * 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 Praisenter nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.praisenter.data.json; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import org.praisenter.Constants; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Class used to store format information for the Praisenter JSON format. * @author William Bittle * @version 3.0.0 */ public final class PraisenterFormat { /** The class type specified by JsonSubTypes and Type Jackson annotations */ private final String type; /** The format; should always be {@link Constants#FORMAT_NAME} */ private final String format; /** The version; could be null */ private final String version; /** * Full constructor. * @param type the type * @param format the format * @param version the version */ public PraisenterFormat(String type, String format, String version) { this.type = type; this.format = format; this.version = version; } /** * Returns true if this format detail matches the given class. * @param clazz the class * @return boolean */ public boolean is(Class<?> clazz) { Annotation[] annotations = clazz.getAnnotations(); List<String> typeNames = new ArrayList<String>(); if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof JsonSubTypes) { Type[] types = ((JsonSubTypes)annotation).value(); if (types != null) { for (Type type : types) { if (clazz.isAssignableFrom(type.value())) { typeNames.add(type.name()); } } } } else if (annotation instanceof JsonTypeName) { typeNames.add(((JsonTypeName)annotation).value()); } } } if (typeNames.isEmpty()) { typeNames.add(clazz.getSimpleName()); } return typeNames.contains(this.type) && this.format.equalsIgnoreCase(Constants.FORMAT_NAME); } /** * Returns the type as specified by JsonSubTypes and Type Jackson annotations. * @return String */ public String getType() { return this.type; } /** * Returns the format, which should always be {@link Constants#FORMAT_NAME}. * @return String */ public String getFormat() { return this.format; } /** * Returns the version. Can be null or empty. * @return String */ public String getVersion() { return this.version; } }
3e0435f773c08794b99383789abe1542e3ac23f1
4,491
java
Java
java/src/com/google/gdata/data/PlainTextConstruct.java
athibanraj/gdata-java-client
ed1958f80d7dc3d37f29f4c48cab2319796827a5
[ "Apache-2.0" ]
149
2015-04-13T12:19:37.000Z
2021-10-24T01:07:52.000Z
java/src/com/google/gdata/data/PlainTextConstruct.java
athibanraj/gdata-java-client
ed1958f80d7dc3d37f29f4c48cab2319796827a5
[ "Apache-2.0" ]
33
2015-04-10T08:23:33.000Z
2019-03-18T17:58:01.000Z
java/src/com/google/gdata/data/PlainTextConstruct.java
athibanraj/gdata-java-client
ed1958f80d7dc3d37f29f4c48cab2319796827a5
[ "Apache-2.0" ]
140
2015-04-09T03:09:10.000Z
2022-02-21T22:41:12.000Z
26.417647
79
0.635716
1,757
/* Copyright (c) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gdata.data; import com.google.gdata.util.common.xml.XmlWriter; import com.google.gdata.client.Service; import com.google.gdata.util.Namespaces; import com.google.gdata.util.ParseException; import com.google.gdata.util.XmlParser; import java.io.IOException; import java.util.ArrayList; /** * Plain text variant of {@link TextConstruct}. * * */ public class PlainTextConstruct extends TextConstruct { /** Class constructor. */ public PlainTextConstruct() {} /** * Class constructor specifying the plain text content for this * text construct to contain. */ public PlainTextConstruct(String text) { this.text = text; } /** * Class constructor specifying the plain text content for this * text construct to contain, plus the human language that * the text is written in. */ public PlainTextConstruct(String text, String lang) { this.text = text; this.lang = lang; } /** @return the type (TEXT) of this text construct */ @Override public int getType() { return Type.TEXT; } @Override /** @return {@code true} if this text construct has no contents */ public boolean isEmpty() { return getText() == null; } /** Plain text contents. */ protected String text; /** @return the plain text contents of this text construct */ public String getText() { return text; } /** Specifies the plain text contents of this text construct. */ public void setText(String v) { text = v; } /** * @return a plain-text representation of this text construct or {@code null} * if there is no text content. */ @Override public String getPlainText() { return text != null ? new String(text) : null; } /** * Generates XML in the Atom format. * * @param w * output writer * * @param elementName * Atom element name * * @throws IOException */ @Override public void generateAtom(XmlWriter w, String elementName) throws IOException { ArrayList<XmlWriter.Attribute> attrs = new ArrayList<XmlWriter.Attribute>(); // For v2 and later, optimize out the text attribute since it is implied. if (Service.getVersion().isCompatible(Service.Versions.V1)) { attrs.add(new XmlWriter.Attribute("type", "text")); } if (lang != null) { attrs.add(new XmlWriter.Attribute("xml:lang", lang)); } w.simpleElement(Namespaces.atomNs, elementName, attrs, text); } /** * Generates XML in the RSS format. * * @param w * output writer * * @param elementName * RSS element name * * @param rssFormat * the restrictions on what HTML tags are allowed * * @throws IOException */ @Override public void generateRss(XmlWriter w, String elementName, RssFormat rssFormat) throws IOException { w.simpleElement(Namespaces.rssNs, elementName, null, text); } /** Parses XML in the Atom format. */ public class AtomHandler extends XmlParser.ElementHandler { /** * Processes attributes. * * @throws ParseException */ @Override public void processAttribute(String namespace, String localName, String value) throws ParseException { if (!namespace.equals("") || !localName.equals("type")) { // Don't understand other attributes. super.processAttribute(namespace, localName, value); } } /** * Processes this element; overrides inherited method. * * @throws ParseException from subclasses. */ @Override public void processEndElement() throws ParseException { if (value == null) { value = ""; } text = value; lang = xmlLang; } } }
3e0436142d93ecb311cc77ec68c185be7e8b07a8
4,157
java
Java
fsdevtools-cli/src/main/java/com/espirit/moddev/cli/api/parsing/parser/ProjectPropertiesParser.java
e-Spirit/FSDevTools
01835b7cf7a3ef291e36771b7b1b809739904a69
[ "ECL-2.0", "Apache-2.0" ]
31
2016-04-06T16:01:24.000Z
2021-12-17T07:58:23.000Z
fsdevtools-cli/src/main/java/com/espirit/moddev/cli/api/parsing/parser/ProjectPropertiesParser.java
e-Spirit/FSDevTools
01835b7cf7a3ef291e36771b7b1b809739904a69
[ "ECL-2.0", "Apache-2.0" ]
46
2017-04-07T20:14:40.000Z
2021-08-09T11:58:42.000Z
fsdevtools-cli/src/main/java/com/espirit/moddev/cli/api/parsing/parser/ProjectPropertiesParser.java
e-Spirit/FSDevTools
01835b7cf7a3ef291e36771b7b1b809739904a69
[ "ECL-2.0", "Apache-2.0" ]
29
2016-09-09T11:17:07.000Z
2022-03-12T18:46:31.000Z
38.490741
146
0.631465
1,758
/* * * ********************************************************************* * fsdevtools * %% * Copyright (C) 2021 e-Spirit AG * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************* * */ package com.espirit.moddev.cli.api.parsing.parser; import java.util.*; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.espirit.moddev.cli.api.parsing.identifier.ProjectPropertiesIdentifier; import de.espirit.firstspirit.transport.PropertiesTransportOptions; /** * * @author kohlbrecher */ public class ProjectPropertiesParser implements Parser<ProjectPropertiesIdentifier> { protected static final Logger LOGGER = LoggerFactory.getLogger(ProjectPropertiesParser.class); private static final Pattern DELIMITER = Pattern.compile("\\s*:\\s*"); public static final String CUSTOM_PREFIX_PROJECT_PROPERTIES = "projectproperty"; /** * Special keyword to identify all project properties (projectproperty:ALL) */ public static final String ALL = "ALL"; @Override public List<ProjectPropertiesIdentifier> parse(List<String> input) { if (input == null) { throw new IllegalArgumentException("input is null!"); } if (input.isEmpty()) { return Collections.emptyList(); } EnumSet<PropertiesTransportOptions.ProjectPropertyType> tempEnum = EnumSet.noneOf(PropertiesTransportOptions.ProjectPropertyType.class); final List<ProjectPropertiesIdentifier> list = new ArrayList<>(input.size()); for (final String identifier : input) { try(Scanner uidScanner = new Scanner(identifier)) { uidScanner.useDelimiter(DELIMITER); if (uidScanner.hasNext()) { uidScanner.next(); if (uidScanner.hasNext()) { final String secondPart = uidScanner.next(); if (ALL.equalsIgnoreCase(secondPart)) { // user wants to export all project properties --> ignore already collected properties and skip further collecting tempEnum = EnumSet.allOf(PropertiesTransportOptions.ProjectPropertyType.class); break; } else { tempEnum.add(PropertiesTransportOptions.ProjectPropertyType.valueOf(secondPart.toUpperCase(Locale.UK))); } } else { throw new IllegalArgumentException("Wrong input format for input string " + identifier); } } } } final ProjectPropertiesIdentifier fqUid = new ProjectPropertiesIdentifier(tempEnum); list.add(fqUid); return list; } /** * @return Returns a set of all possible values for the related keyword {@link #CUSTOM_PREFIX_PROJECT_PROPERTIES} */ public static Collection<String> getAllPossibleValues() { final List<String> result = new ArrayList<>(); result.add(ALL); for (final PropertiesTransportOptions.ProjectPropertyType projectPropertyType : PropertiesTransportOptions.ProjectPropertyType.values()) { result.add(projectPropertyType.name()); } return result; } @Override public boolean appliesTo(String input) { final String[] splitted = input.split(DELIMITER.pattern()); return splitted.length == 2 && splitted[0].toLowerCase(Locale.UK).trim().equals(CUSTOM_PREFIX_PROJECT_PROPERTIES); } }
3e04361622a94ef9ee87113d04c78167ea063dc4
338
java
Java
config/config-client-refresh-bus/src/main/java/net/yeah/cloud/ConfigClientRefreshBusApplication.java
lolog/spring-cloud
3a4370f7f8dc2a1ae53c2d0853176941ffac3e58
[ "Apache-2.0" ]
1
2017-06-23T16:19:36.000Z
2017-06-23T16:19:36.000Z
config/config-client-refresh-bus/src/main/java/net/yeah/cloud/ConfigClientRefreshBusApplication.java
lolog/spring-cloud
3a4370f7f8dc2a1ae53c2d0853176941ffac3e58
[ "Apache-2.0" ]
null
null
null
config/config-client-refresh-bus/src/main/java/net/yeah/cloud/ConfigClientRefreshBusApplication.java
lolog/spring-cloud
3a4370f7f8dc2a1ae53c2d0853176941ffac3e58
[ "Apache-2.0" ]
null
null
null
26
71
0.837278
1,759
package net.yeah.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ConfigClientRefreshBusApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientRefreshBusApplication.class, args); } }
3e04365bad00fa621f390799a41ba26fd59605dc
1,989
java
Java
platform/core-api/src/com/intellij/util/ArrayQuery.java
liveqmock/platform-tools-idea
1c4b76108add6110898a7e3f8f70b970e352d3d4
[ "Apache-2.0" ]
2
2015-05-08T15:07:10.000Z
2022-03-09T05:47:53.000Z
platform/core-api/src/com/intellij/util/ArrayQuery.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
null
null
null
platform/core-api/src/com/intellij/util/ArrayQuery.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
25.177215
105
0.719457
1,760
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util; import com.intellij.concurrency.AsyncFuture; import com.intellij.concurrency.AsyncFutureFactory; import com.intellij.concurrency.AsyncFutureResult; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** * @author max */ public class ArrayQuery<T> implements Query<T> { private final T[] myArray; public ArrayQuery(@NotNull T... array) { myArray = array; } @Override @NotNull public Collection<T> findAll() { return Arrays.asList(myArray); } @Override public T findFirst() { return myArray.length > 0 ? myArray[0] : null; } @Override public boolean forEach(@NotNull final Processor<T> consumer) { return ContainerUtil.process(myArray, consumer); } @NotNull @Override public AsyncFuture<Boolean> forEachAsync(@NotNull final Processor<T> consumer) { final AsyncFutureResult<Boolean> result = AsyncFutureFactory.getInstance().createAsyncFutureResult(); try { result.set(forEach(consumer)); } catch (Throwable t){ result.setException(t); } return result; } @NotNull @Override public T[] toArray(@NotNull final T[] a) { return myArray; } @Override public Iterator<T> iterator() { return Arrays.asList(myArray).iterator(); } }
3e0436ee7ea2bd42794e96e633149dab4fa40714
3,922
java
Java
snailjava/snailjava-vm/src/main/java/snail/vm/io/SnailWriter.java
skissane/snail
215c2b5f637a534c8b454be5b621ae4c3bfbf7ce
[ "Unlicense" ]
null
null
null
snailjava/snailjava-vm/src/main/java/snail/vm/io/SnailWriter.java
skissane/snail
215c2b5f637a534c8b454be5b621ae4c3bfbf7ce
[ "Unlicense" ]
null
null
null
snailjava/snailjava-vm/src/main/java/snail/vm/io/SnailWriter.java
skissane/snail
215c2b5f637a534c8b454be5b621ae4c3bfbf7ce
[ "Unlicense" ]
null
null
null
29.488722
100
0.558134
1,761
package snail.vm.io; import snail.vm.util.GeneralException; import snail.vm.values.*; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.NavigableSet; import java.util.Objects; import static snail.vm.util.CheckedException.handle; public final class SnailWriter { private final DataOutputStream out; public SnailWriter(@Nonnull OutputStream out) { this(toDataOutputStream(out)); } private static DataOutputStream toDataOutputStream(@Nonnull OutputStream out) { return out instanceof DataOutputStream ? (DataOutputStream) out : new DataOutputStream(out); } private SnailWriter(@Nonnull DataOutputStream out) { this.out = Objects.requireNonNull(out); } public static byte[] toBytes(@Nullable SnailValue value) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final SnailWriter writer = new SnailWriter(out); writer.write(value); return out.toByteArray(); } private void write(@Nullable SnailValue value) { if (value == null) writeTag(SnailValueType.T_null); else if (value instanceof SnailHandle) { write(((SnailHandle) value).deref()); } else { final SnailValueType valueType = value.valueType(); writeTag(valueType); switch (valueType) { case T_ref: writeRef((SnailRef) value); break; case T_int: writeInt((SnailInt) value); break; case T_string: writeString((SnailString) value); break; case T_object: writeObject((SnailObject) value); break; case T_list: writeList((SnailList) value); break; default: throw new GeneralException("Cannot write value of type %s", valueType.ref() ); } } } private void writeObject(@Nonnull SnailObject object) { try { writeRef(object.ofClass()); final NavigableSet<SnailRef> attrs = object.attrs(); out.writeInt(attrs.size()); attrs.forEach(attr -> { writeRef(attr); write(object.get(attr)); }); } catch (IOException e) { throw handle(e); } } private void writeList(@Nonnull SnailList list) { try { final int size = list.size(); out.writeInt(size); for (int i = 0; i < size; i++) write(list.get(i)); } catch (IOException e) { throw handle(e); } } private void writeInt(@Nonnull SnailInt integer) { try { out.writeLong(integer.value()); } catch (IOException e) { throw handle(e); } } private void writeString(@Nonnull SnailString str) { writeString(str.value()); } private void writeRef(@Nonnull SnailRef ref) { final String name = ref.asPrintable(); writeString(name); } private void writeString(@Nonnull String str) { try { final byte[] bytes = str.getBytes(StandardCharsets.UTF_8); out.writeInt(bytes.length); out.write(bytes); } catch (IOException e) { throw handle(e); } } private void writeTag(@Nonnull SnailValueType valueType) { try { out.write(valueType.ordinal()); } catch (IOException e) { throw handle(e); } } }
3e0437a60fca2fe3c08057615476e4da4b55ca3a
204
java
Java
src/main/java/com/idus/market/dto/AuthDto.java
small-dogg/small-dogg-market
8561e06cf6f4327afec84b05ae4f761e94f333f8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/idus/market/dto/AuthDto.java
small-dogg/small-dogg-market
8561e06cf6f4327afec84b05ae4f761e94f333f8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/idus/market/dto/AuthDto.java
small-dogg/small-dogg-market
8561e06cf6f4327afec84b05ae4f761e94f333f8
[ "Apache-2.0" ]
null
null
null
14.571429
45
0.764706
1,762
package com.idus.market.dto; import javax.validation.constraints.NotBlank; import lombok.Data; @Data public class AuthDto { @NotBlank private String email; @NotBlank private String password; }
3e0438393236535bdcaf744872520edeab4d6e7b
3,227
java
Java
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/crashlytics/android/core/CompositeCreateReportSpiCall.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
4
2019-10-07T05:17:21.000Z
2020-11-02T08:29:13.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/crashlytics/android/core/CompositeCreateReportSpiCall.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
38
2019-10-07T02:40:35.000Z
2019-12-12T09:15:24.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/com/crashlytics/android/core/CompositeCreateReportSpiCall.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
5
2019-10-07T02:41:15.000Z
2020-10-30T01:36:08.000Z
52.901639
169
0.626588
1,763
package com.crashlytics.android.core; import com.crashlytics.android.core.Report.Type; class CompositeCreateReportSpiCall implements CreateReportSpiCall { private final DefaultCreateReportSpiCall javaReportSpiCall; private final NativeCreateReportSpiCall nativeReportSpiCall; /* renamed from: com.crashlytics.android.core.CompositeCreateReportSpiCall$1 reason: invalid class name */ static /* synthetic */ class AnonymousClass1 { static final /* synthetic */ int[] $SwitchMap$com$crashlytics$android$core$Report$Type = new int[Type.values().length]; /* JADX WARNING: Can't wrap try/catch for region: R(6:0|1|2|3|4|6) */ /* JADX WARNING: Code restructure failed: missing block: B:7:?, code lost: return; */ /* JADX WARNING: Failed to process nested try/catch */ /* JADX WARNING: Missing exception handler attribute for start block: B:3:0x0014 */ static { /* com.crashlytics.android.core.Report$Type[] r0 = com.crashlytics.android.core.Report.Type.values() int r0 = r0.length int[] r0 = new int[r0] $SwitchMap$com$crashlytics$android$core$Report$Type = r0 int[] r0 = $SwitchMap$com$crashlytics$android$core$Report$Type // Catch:{ NoSuchFieldError -> 0x0014 } com.crashlytics.android.core.Report$Type r1 = com.crashlytics.android.core.Report.Type.JAVA // Catch:{ NoSuchFieldError -> 0x0014 } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x0014 } r2 = 1 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x0014 } L_0x0014: int[] r0 = $SwitchMap$com$crashlytics$android$core$Report$Type // Catch:{ NoSuchFieldError -> 0x001f } com.crashlytics.android.core.Report$Type r1 = com.crashlytics.android.core.Report.Type.NATIVE // Catch:{ NoSuchFieldError -> 0x001f } int r1 = r1.ordinal() // Catch:{ NoSuchFieldError -> 0x001f } r2 = 2 r0[r1] = r2 // Catch:{ NoSuchFieldError -> 0x001f } L_0x001f: return */ throw new UnsupportedOperationException("Method not decompiled: com.crashlytics.android.core.CompositeCreateReportSpiCall.AnonymousClass1.<clinit>():void"); } } public CompositeCreateReportSpiCall(DefaultCreateReportSpiCall defaultCreateReportSpiCall, NativeCreateReportSpiCall nativeCreateReportSpiCall) { this.javaReportSpiCall = defaultCreateReportSpiCall; this.nativeReportSpiCall = nativeCreateReportSpiCall; } public boolean invoke(CreateReportRequest createReportRequest) { int i = AnonymousClass1.$SwitchMap$com$crashlytics$android$core$Report$Type[createReportRequest.report.getType().ordinal()]; if (i == 1) { this.javaReportSpiCall.invoke(createReportRequest); return true; } else if (i != 2) { return false; } else { this.nativeReportSpiCall.invoke(createReportRequest); return true; } } }
3e04385cf1d59db70e04eff5ee260d055cb4d9f7
1,127
java
Java
hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
1
2021-11-11T01:36:23.000Z
2021-11-11T01:36:23.000Z
hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
18.47541
94
0.699201
1,764
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.annotations.embedded.one2many; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.Entity; /** * TODO : javadoc * * @author Steve Ebersole */ @Entity public class Alias { private Long id; private Name name; private String source; public Alias() { } public Alias(String firstName, String lastName, String source) { this( new PersonName( firstName, lastName ), source ); } public Alias(Name name, String source) { this.name = name; this.source = source; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } }
3e0438c043aea7dd140a61d3d72e36fa246a379c
602
java
Java
mycms-main/src/main/java/pl/codecity/main/model/NavigationItemPage.java
stamich/myCmsEngine2
6a51e5fa7448041d34a7bda5977291da568f11ba
[ "Apache-2.0" ]
1
2019-08-05T03:19:08.000Z
2019-08-05T03:19:08.000Z
mycms-main/src/main/java/pl/codecity/main/model/NavigationItemPage.java
stamich/myCmsEngine2
6a51e5fa7448041d34a7bda5977291da568f11ba
[ "Apache-2.0" ]
null
null
null
mycms-main/src/main/java/pl/codecity/main/model/NavigationItemPage.java
stamich/myCmsEngine2
6a51e5fa7448041d34a7bda5977291da568f11ba
[ "Apache-2.0" ]
1
2021-05-16T18:03:02.000Z
2021-05-16T18:03:02.000Z
18.242424
56
0.775748
1,765
package pl.codecity.main.model; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.OneToOne; @Entity @DiscriminatorValue("page") @DynamicInsert @DynamicUpdate @SuppressWarnings("serial") public class NavigationItemPage extends NavigationItem { @OneToOne private Page page; public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } @Override public String print() { return getPage().getTitle(); } }
3e043979936e9922a9780c90d33713ce47eb87cb
3,271
java
Java
src/main/java/frc/robot/core/Globals.java
teamkomodo/Robot-2021
93fa704c435ecdef6a9a56f3bc1c2059bd3a13ed
[ "BSD-3-Clause" ]
1
2021-09-01T13:43:10.000Z
2021-09-01T13:43:10.000Z
src/main/java/frc/robot/core/Globals.java
teamkomodo/Robot-2021
93fa704c435ecdef6a9a56f3bc1c2059bd3a13ed
[ "BSD-3-Clause" ]
2
2021-08-30T22:40:15.000Z
2021-09-02T14:40:47.000Z
src/main/java/frc/robot/core/Globals.java
teamkomodo/Robot-2021
93fa704c435ecdef6a9a56f3bc1c2059bd3a13ed
[ "BSD-3-Clause" ]
2
2021-05-12T15:15:11.000Z
2021-08-28T22:31:19.000Z
31.152381
52
0.65882
1,766
package frc.robot.core; public final class Globals { public static boolean driveDirection; public static int ball_counter; public static double LEDoffset=-.06; public static int LEDmode = 22; public static boolean[] lineloopflag ={ false, false }; public static boolean Seetarget; public static boolean SwitchFlag; public static boolean VisionFlag; public static boolean UserControl; public static boolean[] buttonDone = { false, false, false }; public static boolean vision; public static boolean driveType; public static double revolverintakevarible; public static boolean angle; public static boolean check_flag; public static boolean angle_turn; public static boolean angle_flag; public static double speed; public static boolean tA_flag; public static double tA; public static boolean reverse; public static boolean Shootflag; public static double linecounter; public static boolean turn2angle; public static double turn1angle; public static int autonomous_stage; public static int stage_counter; public static double automode; public static boolean intake_flag; public static boolean intaketimer_flag; public static boolean anticlog_flag; public static boolean anticlogtimer_flag; public static boolean shooter_lineup; public static boolean RPM_good; public static boolean flip_flag; public static boolean ball_pickedup; public static double origonal_ball; public static int ball_stage_count; public static boolean ball_reset; public static double Vilocity1; public static boolean target_covered; public static boolean ball_intheintake; public static boolean revolver_delay_flag; public static boolean reset_ball_cycle; public static boolean Ball_down; public static boolean Ball_up; public static boolean antianti_flag; public static double distance_to_target; public Globals (){ distance_to_target = 0; antianti_flag = false; reset_ball_cycle = false; revolver_delay_flag = false; ball_intheintake = false; target_covered = false; Vilocity1 = 0; ball_reset = false; origonal_ball = 0; ball_stage_count = 0; RPM_good = false; driveDirection = false; shooter_lineup= false; anticlogtimer_flag = false; anticlog_flag = false; revolverintakevarible = 0; intaketimer_flag = false; intake_flag = false; check_flag = false; Shootflag = false; angle = false; speed = 0.0; tA = 0.0; tA_flag = false; angle_turn = false; turn2angle = false; turn1angle = (0.0); Seetarget = false; SwitchFlag = false; VisionFlag = false; UserControl = true; vision = false; driveType = false; reverse = false; angle_flag = false; automode = 0; flip_flag = false; Ball_down = false; Ball_up = false; ball_counter = 3; autonomous_stage = 0; //use slider to change stage_counter = 0; } }
3e043a245aeacd22f3d197ba70a63d135b1f8b4a
1,125
java
Java
src/main/java/ca/gc/aafc/seqdb/api/repository/ChainStepTemplateRepository.java
chalkert/seqdb-api
47cdf782461577d982c03d93d608e2d39b3a426b
[ "MIT" ]
null
null
null
src/main/java/ca/gc/aafc/seqdb/api/repository/ChainStepTemplateRepository.java
chalkert/seqdb-api
47cdf782461577d982c03d93d608e2d39b3a426b
[ "MIT" ]
null
null
null
src/main/java/ca/gc/aafc/seqdb/api/repository/ChainStepTemplateRepository.java
chalkert/seqdb-api
47cdf782461577d982c03d93d608e2d39b3a426b
[ "MIT" ]
null
null
null
40.178571
109
0.836444
1,767
package ca.gc.aafc.seqdb.api.repository; import java.util.Arrays; import org.springframework.stereotype.Component; import ca.gc.aafc.seqdb.api.dto.ChainStepTemplateDto; import ca.gc.aafc.seqdb.api.repository.filter.RsqlFilterHandler; import ca.gc.aafc.seqdb.api.repository.filter.SimpleFilterHandler; import ca.gc.aafc.seqdb.api.repository.jpa.JpaDtoRepository; import ca.gc.aafc.seqdb.api.repository.jpa.JpaResourceRepository; import ca.gc.aafc.seqdb.api.repository.meta.JpaMetaInformationProvider; import ca.gc.aafc.seqdb.api.security.authorization.ReadableGroupFilterHandlerFactory; @Component public class ChainStepTemplateRepository extends JpaResourceRepository<ChainStepTemplateDto> { public ChainStepTemplateRepository(JpaDtoRepository dtoRepository, SimpleFilterHandler simpleFilterHandler, RsqlFilterHandler rsqlFilterHandler, ReadableGroupFilterHandlerFactory groupFilterFactory, JpaMetaInformationProvider metaInformationProvider) { super(ChainStepTemplateDto.class, dtoRepository, Arrays.asList(simpleFilterHandler, rsqlFilterHandler), metaInformationProvider); } }
3e043ab534dd5425d6db735a25807687781514e9
405
java
Java
Java-SpringMVC/tasks - workshop/src/main/java/softuni/areas/tasks/models/view/CheckerViewModel.java
VasilPanovski/Java
4ae145680522424d8aaf7e7d41eb31a350d5e94e
[ "MIT" ]
null
null
null
Java-SpringMVC/tasks - workshop/src/main/java/softuni/areas/tasks/models/view/CheckerViewModel.java
VasilPanovski/Java
4ae145680522424d8aaf7e7d41eb31a350d5e94e
[ "MIT" ]
null
null
null
Java-SpringMVC/tasks - workshop/src/main/java/softuni/areas/tasks/models/view/CheckerViewModel.java
VasilPanovski/Java
4ae145680522424d8aaf7e7d41eb31a350d5e94e
[ "MIT" ]
null
null
null
16.2
42
0.602469
1,768
package softuni.areas.tasks.models.view; import java.util.Date; public class CheckerViewModel { private Long id; private Date endDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } }
3e043b4fc704d73b43f38024ee1cf346888aedf6
556
java
Java
Java_Lang_Package/src/lang/practice/ToString_Hashcode.java
Jayvardhan-Reddy/Core_Java_Concepts
49aff08a89095b21255eddab18d2f1004c368022
[ "MIT" ]
2
2020-05-21T10:32:46.000Z
2021-06-01T08:00:06.000Z
Java_Lang_Package/src/lang/practice/ToString_Hashcode.java
Jayvardhan-Reddy/Core_Java_Concepts
49aff08a89095b21255eddab18d2f1004c368022
[ "MIT" ]
null
null
null
Java_Lang_Package/src/lang/practice/ToString_Hashcode.java
Jayvardhan-Reddy/Core_Java_Concepts
49aff08a89095b21255eddab18d2f1004c368022
[ "MIT" ]
2
2018-10-02T05:29:45.000Z
2018-12-17T14:03:11.000Z
17.375
61
0.638489
1,769
package lang.practice; public class ToString_Hashcode { private int i; private String name; ToString_Hashcode(int i, String name){ this.i = i; this.name = name; } @Override public String toString() { return i +" is " + name ; } @Override public int hashCode() { return i; } public static void main(String[] args) { ToString_Hashcode sh = new ToString_Hashcode(10, "rock"); ToString_Hashcode sh1 = new ToString_Hashcode(11, "kane"); System.out.println(sh); System.out.println(sh1); } }
3e043bc1626ae7d5a9ab608e51f02d86d37cddd5
2,633
java
Java
app/src/main/java/com/example/bearapp/utils/request/BaseRequest.java
zhengwanshi/BearApp
6508281d67b5df0e1ae2530b450545c8e7e4c329
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/bearapp/utils/request/BaseRequest.java
zhengwanshi/BearApp
6508281d67b5df0e1ae2530b450545c8e7e4c329
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/bearapp/utils/request/BaseRequest.java
zhengwanshi/BearApp
6508281d67b5df0e1ae2530b450545c8e7e4c329
[ "Apache-2.0" ]
null
null
null
28.010638
85
0.586783
1,770
package com.example.bearapp.utils.request; import android.os.Handler; import android.os.Looper; import android.os.Message; import com.google.gson.Gson; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by zhengyg on 2018/3/13. */ public abstract class BaseRequest { protected final int WHAT_FAIL = 0; protected final int WHAT_SUCC = 1; private final static OkHttpClient okClient = new OkHttpClient(); protected final static Gson gson = new Gson(); public interface OnResultListener<T>{ void onFail(int code,String msg); void onSuccess(T object); } private OnResultListener listener; private Handler uiHandler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { int what = msg.what; if (what == WHAT_FAIL){ if (listener != null){ listener.onFail(msg.arg1, (String) msg.obj); } }else if (what ==WHAT_SUCC){ if (listener != null){ listener.onSuccess(msg.obj); } } } }; protected void sendFailMsg(int code, String reason){ Message msg = uiHandler.obtainMessage(WHAT_FAIL); msg.arg1 = code; msg.obj = reason; uiHandler.sendMessage(msg); } protected <T> void sendSuccMsg(T data){ Message msg = uiHandler.obtainMessage(WHAT_SUCC); msg.obj = data; uiHandler.sendMessage(msg); } public void setOnResultListener(OnResultListener l){ listener = l; } /** * OKHttp 请求 * @param url */ public void request(String url){ final Request request = new Request.Builder().url(url) .build(); okClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { onFail(e); } @Override public void onResponse(Call call, Response response) throws IOException { //不是UI线程 if (response.isSuccessful()){ onResponseSuccess(response.body().string()); }else{ onResponseFail(response.code()); } } }); } protected abstract void onFail(IOException e); protected abstract void onResponseFail(int code); protected abstract void onResponseSuccess(String bady); }
3e043be2e4e81ee89668ac9b4b2e05d1aca3459e
4,333
java
Java
src/main/java/org/openapitools/model/AnnotationsV2.java
thomasyu888/synapse-java-server
ab39b545261b7f55024db462f36062d6dbe6ea62
[ "Apache-2.0" ]
1
2021-03-11T12:22:59.000Z
2021-03-11T12:22:59.000Z
src/main/java/org/openapitools/model/AnnotationsV2.java
thomasyu888/synapse-java-server
ab39b545261b7f55024db462f36062d6dbe6ea62
[ "Apache-2.0" ]
null
null
null
src/main/java/org/openapitools/model/AnnotationsV2.java
thomasyu888/synapse-java-server
ab39b545261b7f55024db462f36062d6dbe6ea62
[ "Apache-2.0" ]
null
null
null
29.882759
291
0.7039
1,771
package org.openapitools.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openapitools.model.AnnotationsValue; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; /** * Annotations are additional key-value pair metadata that are associated with an object. */ @ApiModel(description = "Annotations are additional key-value pair metadata that are associated with an object.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2021-03-11T20:51:24.548366+08:00[Asia/Taipei]") public class AnnotationsV2 { @JsonProperty("annotations") @Valid private Map<String, AnnotationsValue> annotations = null; @JsonProperty("etag") private String etag; @JsonProperty("id") private String id; public AnnotationsV2 annotations(Map<String, AnnotationsValue> annotations) { this.annotations = annotations; return this; } public AnnotationsV2 putAnnotationsItem(String key, AnnotationsValue annotationsItem) { if (this.annotations == null) { this.annotations = new HashMap<>(); } this.annotations.put(key, annotationsItem); return this; } /** * Additional metadata associated with the object. The key is the name of your desired annotations. The value is an object containing a list of string values (use empty list to represent no values for key) and the value type associated with all values in the list * @return annotations */ @ApiModelProperty(value = "Additional metadata associated with the object. The key is the name of your desired annotations. The value is an object containing a list of string values (use empty list to represent no values for key) and the value type associated with all values in the list") @Valid public Map<String, AnnotationsValue> getAnnotations() { return annotations; } public void setAnnotations(Map<String, AnnotationsValue> annotations) { this.annotations = annotations; } public AnnotationsV2 etag(String etag) { this.etag = etag; return this; } /** * Etag of the object to which this annotation belongs. To update an AnnotationV2, this field must match the current etag on the object. * @return etag */ @ApiModelProperty(value = "Etag of the object to which this annotation belongs. To update an AnnotationV2, this field must match the current etag on the object.") public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public AnnotationsV2 id(String id) { this.id = id; return this; } /** * ID of the object to which this annotation belongs * @return id */ @ApiModelProperty(value = "ID of the object to which this annotation belongs") public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AnnotationsV2 annotationsV2 = (AnnotationsV2) o; return Objects.equals(this.annotations, annotationsV2.annotations) && Objects.equals(this.etag, annotationsV2.etag) && Objects.equals(this.id, annotationsV2.id); } @Override public int hashCode() { return Objects.hash(annotations, etag, id); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AnnotationsV2 {\n"); sb.append(" annotations: ").append(toIndentedString(annotations)).append("\n"); sb.append(" etag: ").append(toIndentedString(etag)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e043d41b45cda067a81512e8a137d4eeeed0df6
1,158
java
Java
src/Sentence.java
EHENJOOM/BagOfWords
ff139affb79171c44d229ea5412dea5401e2bc53
[ "Apache-2.0" ]
null
null
null
src/Sentence.java
EHENJOOM/BagOfWords
ff139affb79171c44d229ea5412dea5401e2bc53
[ "Apache-2.0" ]
null
null
null
src/Sentence.java
EHENJOOM/BagOfWords
ff139affb79171c44d229ea5412dea5401e2bc53
[ "Apache-2.0" ]
null
null
null
22.705882
88
0.53886
1,772
import java.util.*; /** * @author 赵洪苛 * @date 2020/3/10 17:36 * @description 句子 */ public class Sentence { // 句子原句 private String sentence; // 针对该句的总体词袋 private WordBag wordBag = new WordBag(); // 该句分解后的词 private List<String> allWords = new ArrayList<>(); public void analyze() { // 把一个句子分解成单词 allWords.addAll(new ArrayList<>(Arrays.asList(sentence.split(" ")))); Map<String, Integer> map = new HashMap<>(); // 计算单词出现的次数 allWords.forEach(temp -> { int n = 1; if (map.get(temp) != null) { n = map.get(temp) + 1; } map.put(temp, n); }); // 填入单词的权重信息 allWords.stream() .distinct() .forEach(temp -> wordBag.findWordByName(temp).setWeight(map.get(temp))); } public void setWordBag(WordBag wordBag) { this.wordBag = wordBag; } public WordBag getWordBag() { return wordBag; } public String getSentence() { return sentence; } public void setSentence(String sentence) { this.sentence = sentence; } }
3e043d6ebdcd38993fefd7f6a2d96180e386a9fd
291
java
Java
src/main/java/org/xmlet/htmlapifaster/SelectAll0.java
xmlet/HtmlApiFaster
9eb9c4e941e196aba47336b3fe6b9e52b206e6ce
[ "MIT" ]
6
2018-08-28T17:14:13.000Z
2021-11-30T14:01:09.000Z
src/main/java/org/xmlet/htmlapifaster/SelectAll0.java
xmlet/HtmlApiFaster
9eb9c4e941e196aba47336b3fe6b9e52b206e6ce
[ "MIT" ]
null
null
null
src/main/java/org/xmlet/htmlapifaster/SelectAll0.java
xmlet/HtmlApiFaster
9eb9c4e941e196aba47336b3fe6b9e52b206e6ce
[ "MIT" ]
null
null
null
24.25
97
0.670103
1,773
package org.xmlet.htmlapifaster; public interface SelectAll0<T extends Element<T, Z>, Z extends Element> extends TextGroup<T, Z> { default Option<T> option() { return new Option(this.self()); } default Optgroup<T> optgroup() { return new Optgroup(this.self()); } }
3e043dc046ae8e18ec2204c76dee5a39ef4df47c
9,792
java
Java
hearth-core/src/main/java/cn/eiden/hsm/game/card/CardFactory.java
EidenRitto/hearthstone
a5192ac07c9b69c5dbce08447f74b8b0f5db27df
[ "MIT" ]
25
2018-09-19T08:44:43.000Z
2021-08-01T09:55:41.000Z
hearth-core/src/main/java/cn/eiden/hsm/game/card/CardFactory.java
EidenRitto/hearthstone
a5192ac07c9b69c5dbce08447f74b8b0f5db27df
[ "MIT" ]
null
null
null
hearth-core/src/main/java/cn/eiden/hsm/game/card/CardFactory.java
EidenRitto/hearthstone
a5192ac07c9b69c5dbce08447f74b8b0f5db27df
[ "MIT" ]
null
null
null
33.765517
92
0.552288
1,774
package cn.eiden.hsm.game.card; import cn.eiden.hsm.annotation.Id; import cn.eiden.hsm.annotation.Tags; import cn.eiden.hsm.enums.*; import cn.eiden.hsm.util.EnumUtils; import lombok.extern.slf4j.Slf4j; import org.reflections.Reflections; import java.lang.reflect.Field; import java.util.*; /** * @author Eiden J.P Zhou * @date 2020/4/3 14:56 */ @Slf4j public class CardFactory { private static final String BASE_PACKAGE_PATH = "cn.eiden.hsm.game.card"; /** * 随机数种子 */ private Random random; /** * 自身单例对象 */ private static CardFactory cardFactory; private Map<Integer, Set<Integer>> cardCostPool = new HashMap<>(16); private Map<CardSet, Set<Integer>> cardSetPool = new HashMap<>(32); private Map<CardClass, Set<Integer>> cardClassPool = new HashMap<>(16); private Map<CardType, Set<Integer>> cardTypePool = new HashMap<>(8); private Map<Race, Set<Integer>> cardRacePool = new HashMap<>(32); private Map<GameTag, Set<Integer>> cardGameTagPool = new HashMap<>(32); /** * id卡牌池 */ private Map<Integer, Class<? extends Card>> cardPool; public static CardFactory getInstance() { if (cardFactory == null) { cardFactory = new CardFactory(); } return cardFactory; } private CardFactory() { random = new Random(); cardPool = new HashMap<>(7000); this.initCache(); } private void initCache() { //获取某个包中所有版本的卡牌类 Reflections reflections = new Reflections(BASE_PACKAGE_PATH); Set<Class<? extends Card>> subTypesOfCard = reflections.getSubTypesOf(Card.class); for (Class<? extends Card> cardClass : subTypesOfCard) { Id id = cardClass.getAnnotation(Id.class); if (id != null) { if (cardPool.containsKey(id.value())) { Class<? extends Card> aClass = cardPool.get(id.value()); //如果缓存池中存在父类则用子类覆盖,否则跳过(什么也不做) if (aClass.isAssignableFrom(cardClass)) { cardPool.put(id.value(), cardClass); } } else { cardPool.put(id.value(), cardClass); } this.initDifferentKindsPool(id.value(), cardClass); } } } private void initDifferentKindsPool(int id, Class<? extends Card> cardClass) { try { Field costField = cardClass.getDeclaredField("COST"); costField.setAccessible(true); int cost = costField.getInt(cardClass); this.addInPool(cardCostPool, cost, id); Field setField = cardClass.getDeclaredField("CARD_SET"); setField.setAccessible(true); CardSet cardSet = (CardSet) setField.get(cardClass); this.addInPool(cardSetPool, cardSet, id); Field classField = cardClass.getDeclaredField("CARD_CLASS"); classField.setAccessible(true); CardClass cardClass1 = (CardClass) classField.get(cardClass); this.addInPool(cardClassPool, cardClass1, id); Field typeField = cardClass.getDeclaredField("CARD_TYPE"); typeField.setAccessible(true); CardType cardType = (CardType) typeField.get(cardClass); this.addInPool(cardTypePool, cardType, id); if (cardType == CardType.MINION) { Field raceField = cardClass.getDeclaredField("RACE"); raceField.setAccessible(true); Race race = (Race) raceField.get(cardClass); this.addInPool(cardRacePool, race, id); } //创建对应的标签缓存池 Tags tags = cardClass.getAnnotation(Tags.class); int[] value = tags.value(); if (value.length ==0 ){ return; } Arrays.stream(value) .boxed() .map(e -> EnumUtils.getEnumObject(GameTag.class, f -> f.getCode() == e)) .filter(Objects::nonNull) .filter(Optional::isPresent) .map(Optional::get) .forEach(e->addInPool(cardGameTagPool, e, id)); } catch (NoSuchFieldException | IllegalAccessException e) { log.warn(String.format("%s已实现卡牌跳过属性", cardClass.getSimpleName())); } } private <T> void addInPool(Map<T, Set<Integer>> pool, T val, Integer id) { if (pool.containsKey(val)) { pool.get(val).add(id); } else { pool.put(val, new HashSet<Integer>() {{ add(id); }}); } } public Card buildCardById(Integer id) throws Exception { Class<? extends Card> aClass = cardPool.get(id); if (aClass == null) { String format = String.format("找不到id为%s的卡牌", id); throw new NullPointerException(format); } return aClass.newInstance(); } public static Card getCardById(int id) { try { return getInstance().buildCardById(id); } catch (Exception e) { e.printStackTrace(); return null; } } public static CardFactory.CardBuilder buildCard() { return new CardFactory.CardBuilder(); } /** * 使用建造者对象进行条件查询<br/> * retainAll set集合取交集 * * @param builder 建造者对象 * @return 条件查询结果集合 */ private static Set<Integer> condition(CardBuilder builder) { Set<Integer> result = new HashSet<>(getInstance().cardPool.keySet()); if (builder.cost.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (Integer cardCost : builder.cost) { idSet.addAll(getInstance().cardCostPool.get(cardCost)); } result.retainAll(idSet); } if (builder.cardSet.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (CardSet cardSet : builder.cardSet) { idSet.addAll(getInstance().cardSetPool.get(cardSet)); } result.retainAll(idSet); } if (builder.cardClass.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (CardClass cardClass : builder.cardClass) { idSet.addAll(getInstance().cardClassPool.get(cardClass)); } result.retainAll(idSet); } if (builder.cardType.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (CardType cardType : builder.cardType) { idSet.addAll(getInstance().cardTypePool.get(cardType)); } result.retainAll(idSet); } if (builder.race.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (Race race : builder.race) { idSet.addAll(getInstance().cardRacePool.get(race)); } result.retainAll(idSet); } if (builder.gameTags.size() > 0) { Set<Integer> idSet = new HashSet<>(); for (GameTag gameTag : builder.gameTags) { idSet.addAll(getInstance().cardGameTagPool.get(gameTag)); } result.retainAll(idSet); } return result; } public static class CardBuilder { private Set<Integer> cost; private Set<CardSet> cardSet; private Set<CardClass> cardClass; private Set<CardType> cardType; private Set<Race> race; private Set<GameTag> gameTags; private Random random; public CardBuilder() { random = new Random(); cost = new HashSet<>(16); cardSet = new HashSet<>(16); cardClass = new HashSet<>(16); cardType = new HashSet<>(16); race = new HashSet<>(16); gameTags = new HashSet<>(16); } public CardFactory.CardBuilder cost(Integer cost) { this.cost.add(cost); return this; } public CardFactory.CardBuilder cardSet(CardSet cardSet) { this.cardSet.add(cardSet); return this; } public CardFactory.CardBuilder cardClass(CardClass cardClass) { this.cardClass.add(cardClass); return this; } public CardFactory.CardBuilder cardType(CardType cardType) { this.cardType.add(cardType); return this; } public CardFactory.CardBuilder race(Race race) { this.race.add(race); return this; } public CardFactory.CardBuilder gameTags(GameTag gameTag){ this.gameTags.add(gameTag); return this; } public Card randomBuild() { Set<Integer> condition = condition(this); Integer randomCardId = getRandomCardId(condition); return getCardById(randomCardId); } private Integer getRandomCardId(Set<Integer> condition) { Iterator<Integer> iterator = condition.iterator(); int target = random.nextInt(condition.size()); Integer index = null; for (int i = 0; i < target; i++) { index = iterator.next(); } return index; } public List<Card> discover(){ List<Card> result = new ArrayList<>(); Set<Integer> condition = condition(this); for (int i = 0; i < 3; i++) { if (condition.size() == 0){ break; } Integer randomCardId = getRandomCardId(condition); condition.remove(randomCardId); result.add(getCardById(randomCardId)); } return result; } } }
3e043ddf978c7c94deae97d391d12ded1842a320
1,535
java
Java
h2o-core/src/main/java/water/rapids/transforms/H2OScaler.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
6,098
2015-05-22T02:46:12.000Z
2022-03-31T16:54:51.000Z
h2o-core/src/main/java/water/rapids/transforms/H2OScaler.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
2,517
2015-05-23T02:10:54.000Z
2022-03-30T17:03:39.000Z
h2o-core/src/main/java/water/rapids/transforms/H2OScaler.java
jbentleyEG/h2o-3
93f1084b5e244beca517b0a1fc8b0c02061d597f
[ "Apache-2.0" ]
2,199
2015-05-22T04:09:55.000Z
2022-03-28T22:20:45.000Z
29.519231
110
0.635831
1,775
package water.rapids.transforms; import hex.genmodel.GenMunger; import water.H2O; import water.MRTask; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.util.ArrayUtils; public class H2OScaler extends Transform<H2OScaler> { double[] means; double[] sdevs; H2OScaler(String name, String ast, boolean inplace, String[] newNames) { super(name,ast,inplace,newNames); } @Override public Transform<H2OScaler> fit(Frame f) { means = new double[f.numCols()]; sdevs = new double[f.numCols()]; for(int i=0;i<f.numCols();++i) { means[i] = f.vec(i).mean(); sdevs[i] = f.vec(i).sigma(); } return this; } // TODO: handle Categorical, String, NA @Override protected Frame transformImpl(Frame f) { final double[] fmeans = means; final double[] fmults = ArrayUtils.invert(sdevs); return new MRTask() { @Override public void map(Chunk[] cs, NewChunk[] ncs) { double[] in = new double[cs.length]; for(int row=0; row<cs[0]._len; row++) { for(int col=0; col<cs.length; col++) in[col] = cs[col].atd(row); GenMunger.scaleInPlace(fmeans, fmults, in); for(int col=0; col<ncs.length; col++) ncs[col].addNum(in[col]); } } }.doAll(f.numCols(), Vec.T_NUM, f).outputFrame(f.names(), f.domains()); } @Override Frame inverseTransform(Frame f) { throw H2O.unimpl(); } @Override public String genClassImpl() { throw H2O.unimpl(); } }
3e043e1e6200f39bfec6cd136d5281ea8d4286cc
769
java
Java
src/test/java/com/javafortesters/junit/ChromeTest.java
Kristofvdw/BeehiveTest
9a55c980bc09c3e09b6568e1eed8af4a85a0d9ee
[ "MIT" ]
null
null
null
src/test/java/com/javafortesters/junit/ChromeTest.java
Kristofvdw/BeehiveTest
9a55c980bc09c3e09b6568e1eed8af4a85a0d9ee
[ "MIT" ]
null
null
null
src/test/java/com/javafortesters/junit/ChromeTest.java
Kristofvdw/BeehiveTest
9a55c980bc09c3e09b6568e1eed8af4a85a0d9ee
[ "MIT" ]
null
null
null
20.236842
62
0.639792
1,776
package com.javafortesters.junit; import io.github.bonigarcia.wdm.ChromeDriverManager; import org.junit.*; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import static junit.framework.Assert.assertTrue; public class ChromeTest { private WebDriver driver; @BeforeClass public static void setupClass() { ChromeDriverManager.getInstance().setup(); } @Before public void setupTest() { driver = new ChromeDriver(); } @After public void teardown() { if (driver != null) { driver.quit(); } } @Test public void test() { driver.get("http://172.16.62.26/#/"); assertTrue(driver.getTitle().startsWith("B-Central")); } }
3e043f79c81bb778daedde2f7c403826258c8234
1,623
java
Java
flexible/helloworld-springboot/src/main/java/com/example/java/controller/TransactionServiceImpl.java
karanpurswani0723/java-docs-samples
a98589fea5710174b8cd2b634639ad767ced4108
[ "Apache-2.0" ]
null
null
null
flexible/helloworld-springboot/src/main/java/com/example/java/controller/TransactionServiceImpl.java
karanpurswani0723/java-docs-samples
a98589fea5710174b8cd2b634639ad767ced4108
[ "Apache-2.0" ]
null
null
null
flexible/helloworld-springboot/src/main/java/com/example/java/controller/TransactionServiceImpl.java
karanpurswani0723/java-docs-samples
a98589fea5710174b8cd2b634639ad767ced4108
[ "Apache-2.0" ]
null
null
null
23.867647
76
0.683919
1,777
package com.example.java.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service("transactionService") public class TransactionServiceImpl implements TransactionService { @Autowired TransactionRepository transactionRepository; @Override public void create(Transaction transaction) { Transaction transaction1=transactionRepository.save(transaction); System.out.println("transaction created---"); } @Override public void update(Transaction transaction) { Transaction transaction1 = transactionRepository.save(transaction); System.out.println("Updated:- " ); } @Override public void delete(Transaction transaction) { transactionRepository.delete(transaction); //System.out.println("Deleted:- " + transaction.getAccountNumber()); } @Override public void deleteAll() { transactionRepository.deleteAll(); } @Override public Transaction find(Transaction transaction) { return null; } @Override public List<Transaction> findByAccountNumber(String accountNumber) { return // new ArrayList<>(); transactionRepository.findByAccountNumber(accountNumber); } @Override public List<Transaction> findAll() { List<Transaction> result = new ArrayList<Transaction>(); transactionRepository.findAll().forEach(result::add); //new ArrayList<>(); return result; } }
3e043f7ead8ba5eef7bfe451bd379419e9320821
628
java
Java
resources/src/main/java/org/cdshooks/Action.java
kumarerubandi/CRD
efd24b9ab38052d93654286ace3fb7d12c046e94
[ "Apache-2.0" ]
null
null
null
resources/src/main/java/org/cdshooks/Action.java
kumarerubandi/CRD
efd24b9ab38052d93654286ace3fb7d12c046e94
[ "Apache-2.0" ]
13
2020-03-04T23:29:57.000Z
2022-02-26T17:24:01.000Z
resources/src/main/java/org/cdshooks/Action.java
kumarerubandi/CRD
efd24b9ab38052d93654286ace3fb7d12c046e94
[ "Apache-2.0" ]
1
2020-01-21T05:38:35.000Z
2020-01-21T05:38:35.000Z
16.102564
50
0.670382
1,778
package org.cdshooks; public class Action { private TypeEnum type = null; private String description = null; private Object resource = null; public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Object getResource() { return resource; } public void setResource(Object resource) { this.resource = resource; } public enum TypeEnum { create, update, delete } }
3e04401e89fb42bb8207770e6b1ab95f6e1dbcfd
3,199
java
Java
src/com/interview/sort/CarFleet.java
mukeshkumargupta/data-structure-java-tutorials
133a2d2cf83424aafb24111766001f00d707421d
[ "Apache-2.0" ]
null
null
null
src/com/interview/sort/CarFleet.java
mukeshkumargupta/data-structure-java-tutorials
133a2d2cf83424aafb24111766001f00d707421d
[ "Apache-2.0" ]
null
null
null
src/com/interview/sort/CarFleet.java
mukeshkumargupta/data-structure-java-tutorials
133a2d2cf83424aafb24111766001f00d707421d
[ "Apache-2.0" ]
null
null
null
30.759615
180
0.597687
1,779
package com.interview.sort; import java.util.*; /* * https://leetcode.com/problems/car-fleet/ * https://www.youtube.com/watch?v=P99yS9jLr6o&list=PLIA-9QRQ0RqGP4zrm09iyiVSXU-3e6CfP&index=65 * Category: Medium, Tricky * https://leetcode.com/problems/car-fleet-ii/ Hard * here are n cars going to the same destination along a one-lane road. The destination is target miles away. You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. Example 1: Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] Output: 3 Explanation: The cars starting at 10 and 8 become a fleet, meeting each other at 12. The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself. The cars starting at 5 and 3 become a fleet, meeting each other at 6. Note that no other cars meet these fleets before the destination, so the answer is 3. Example 2: Input: target = 10, position = [3], speed = [3] Output: 1 Constraints: n == position.length == speed.length 1 <= n <= 105 0 < target <= 106 0 <= position[i] < target All the values of position are unique. 0 < speed[i] <= 106 Accepted 60,407 Submissions 130,175 */ public class CarFleet { public int carFleet(int target, int[] position, int[] speed) { /* * Runtime: 159 ms, faster than 19.08% of Java online submissions for Car Fleet. */ class Details { int pos; double time; Details(int pos, double time) { this.pos = pos; this.time = time; } } PriorityQueue<Details> pq = new PriorityQueue<>((d1, d2) -> { return d2.pos - d1.pos; }); for (int i = 0; i < position.length; i++) { double t = (double)(target - position[i])/(double)(speed[i]); Details d = new Details(position[i], t); pq.add(d); } int fleet = 0; if (pq.size() == 0) { return fleet; } while (true) { if (pq.size() == 1) { fleet++; break; } Details ahead = pq.remove(); Details behind = pq.remove(); if (ahead.time < behind.time) {//behind will never catch fleet++; pq.add(behind); } else { pq.add(ahead); } } return fleet; } public static void main(String[] args) { // TODO Auto-generated method stub } }
3e04410f521b21ea8b2a9ea884a50b47cacbca20
5,258
java
Java
src/main/java/cn/vlabs/duckling/vwb/service/emailnotifier/task/ChangeList.java
ducklingcloud/dct
31e4ab2ea6983ee0416933494b3e86cae3ab843d
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/vlabs/duckling/vwb/service/emailnotifier/task/ChangeList.java
ducklingcloud/dct
31e4ab2ea6983ee0416933494b3e86cae3ab843d
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/vlabs/duckling/vwb/service/emailnotifier/task/ChangeList.java
ducklingcloud/dct
31e4ab2ea6983ee0416933494b3e86cae3ab843d
[ "Apache-2.0" ]
1
2020-06-08T03:55:51.000Z
2020-06-08T03:55:51.000Z
32.658385
108
0.698935
1,780
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cn.vlabs.duckling.vwb.service.emailnotifier.task; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import cn.vlabs.duckling.vwb.VWBContext; import cn.vlabs.duckling.vwb.service.dpage.data.LightDPage; import cn.vlabs.duckling.vwb.service.url.UrlService; import cn.vlabs.duckling.vwb.service.viewport.ViewPortService; /** * @date 2013-5-28 * @author xiejj */ public class ChangeList { private static final String EMAIL_SUBSCRIBER_LIST = "<table border=1 width=600 bgcolor=#ffe4e4>" + "<tr><th width='50%'>页面名(标题)</th><th width='35%'>更新人</th><th width='15%'>版本变化</th></tr>" + "CHANGED_PAGE_LIST</table>"; private static final String m_pageListItemTemplate = "<tr><td><a href='CHANGED_PAGE_URL' target='_blank'>" + "<font size=2>CHANGED_PAGE_TITLE</font></a></td>" + "<td width=100><font size=2>CHANGED_PAGE_AUTHORS</font></a></td>" + "<td width=200><a href='PAGE_DIFF_URL' target='_blank'>" + "<font size=2>查看版本变化</font></a></td></tr>"; private static final String MARKER_CHANGED_PAGE_AUTHOR = "CHANGED_PAGE_AUTHORS"; private static final String MARKER_CHANGED_PAGE_LIST = "CHANGED_PAGE_LIST"; private static final String MARKER_CHANGED_PAGE_NAME = "CHANGED_PAGE_NAME"; private static final String MARKER_CHANGED_PAGE_NAME_TITLE = "CHANGED_PAGE_TITLE"; private static final String MARKER_CHANGED_PAGE_URL = "CHANGED_PAGE_URL"; private static final String MARKER_PAGE_DIFF_URL = "PAGE_DIFF_URL"; private int m_pageId; private List<LightDPage> m_versionList; private UrlService urlConstructor; private ViewPortService viewport; String m_subscribedPagesList = null; public ChangeList() { m_subscribedPagesList = ""; } private String buildChangeInfo(List<LightDPage> pageVersions) { StringBuffer buffer = new StringBuffer(); HashMap<String, String> authors = new HashMap<String, String>(); for (Iterator<LightDPage> iter = pageVersions.iterator(); iter .hasNext();) { LightDPage page = iter.next(); String author = page.getAuthor(); if (author == null) // ignore null authors... continue; if (authors.get(author) == null) authors.put(author, author); } for (String value : authors.values()) { if (buffer.length() > 0) buffer.append(", "); buffer.append(value); } return buffer.toString(); } private String buildDiffURL(List<Integer> vlist, int siteId, int pageid) { Integer max = (Integer) vlist.get(0); Integer min = (Integer) vlist.get(0); for (int i = 0; i < vlist.size(); i++) { if (max < (Integer) vlist.get(i)) max = (Integer) vlist.get(i); if (min > (Integer) vlist.get(i)) min = (Integer) vlist.get(i); } String baseurl = urlConstructor.getBaseURL(); if (!baseurl.endsWith("/")) { baseurl = baseurl + "/"; } return urlConstructor.getURL(VWBContext.DIFF, Integer.toString(pageid), "r1=" + max + "&r2=" + (min == 1 ? min : min - 1)); } public void buildChangeList(int siteId) { String pageTitle = viewport.getViewPort(siteId, m_pageId).getTitle(); String listItem = ""; List<Integer> vlist = new ArrayList<Integer>(); for (Iterator<LightDPage> iter = m_versionList.iterator(); iter .hasNext();) { LightDPage page = iter.next(); vlist.add(page.getVersion()); } if ((vlist == null) || (vlist.size() == 0)) return; listItem = m_pageListItemTemplate.replaceAll( MARKER_CHANGED_PAGE_NAME_TITLE, pageTitle + "(" + pageTitle + ")"); listItem = listItem.replaceAll(MARKER_CHANGED_PAGE_NAME, Integer.toString(m_pageId)); listItem = listItem.replaceAll(MARKER_CHANGED_PAGE_URL, urlConstructor.getViewURL(m_pageId)); listItem = listItem.replaceAll(MARKER_CHANGED_PAGE_AUTHOR, buildChangeInfo(m_versionList)); listItem = listItem.replaceAll(MARKER_PAGE_DIFF_URL, buildDiffURL(vlist, siteId, m_pageId)); m_subscribedPagesList += listItem; } public void currentChangeList(int pageId, List<LightDPage> versionList) { this.m_pageId = pageId; this.m_versionList = versionList; } public String getHTML() { String changePageList = EMAIL_SUBSCRIBER_LIST.replace( MARKER_CHANGED_PAGE_LIST, m_subscribedPagesList); return changePageList; } public void setUrlService(UrlService urlService) { this.urlConstructor = urlService; } public void setViewportService(ViewPortService viewport) { this.viewport = viewport; } }
3e044270bbadf1fb0be4e600e842e9e8f471db6e
300
java
Java
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/Meldingskoe.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
null
null
null
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/Meldingskoe.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
37
2020-09-23T14:00:49.000Z
2021-11-17T12:19:57.000Z
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/Meldingskoe.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
1
2022-02-16T13:52:48.000Z
2022-02-16T13:52:48.000Z
16.666667
41
0.813333
1,781
package no.nav.tps.forvalteren.domain.rs; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class Meldingskoe { private String koenavn; }
3e0442cad5e3ab318ec684eaa9106361f7e9c9fd
2,146
java
Java
src/main/java/ball/util/ant/taskdefs/PropertySetterAntTask.java
allen-ball/ball-util
28811694cca09368e045b732d8ecba1afca44261
[ "Apache-2.0" ]
null
null
null
src/main/java/ball/util/ant/taskdefs/PropertySetterAntTask.java
allen-ball/ball-util
28811694cca09368e045b732d8ecba1afca44261
[ "Apache-2.0" ]
null
null
null
src/main/java/ball/util/ant/taskdefs/PropertySetterAntTask.java
allen-ball/ball-util
28811694cca09368e045b732d8ecba1afca44261
[ "Apache-2.0" ]
null
null
null
32.830769
77
0.582943
1,782
package ball.util.ant.taskdefs; /*- * ########################################################################## * Utilities * %% * Copyright (C) 2008 - 2022 Allen D. Ball * %% * 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. * ########################################################################## */ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * Interface to provide common default methods for {@link Task}s that may * assign property values. * * @author [email protected] mailto:[email protected] Allen D. Ball} */ public interface PropertySetterAntTask extends AntTaskMixIn { String getProperty(); void setProperty(String property); /** * Method to get the value to assign to the property. * * @return The property value. * * @throws Exception As specified by implementing subclass. */ Object getPropertyValue() throws Exception; default void execute() throws BuildException { try { Task task = (Task) this; String key = getProperty(); Object value = getPropertyValue(); if (key != null) { if (value != null) { task.getProject().setNewProperty(key, value.toString()); } } else { task.log(String.valueOf(value)); } } catch (BuildException exception) { throw exception; } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new BuildException(exception); } } }
3e044341bf905906baeb04bce4a7e7ce0d0f1153
1,012
java
Java
Project/src/main/java/com/example/cmpe313/Department.java
ZeroToHero2/Human-Resource-Management-System-with-JFoenix
ba03fb48b57674310fb8c12f2f11f64e26107f2e
[ "MIT" ]
1
2022-01-22T16:50:50.000Z
2022-01-22T16:50:50.000Z
Project/src/main/java/com/example/cmpe313/Department.java
ZeroToHero2/Human-Resource-Management-System-with-JFoenix
ba03fb48b57674310fb8c12f2f11f64e26107f2e
[ "MIT" ]
null
null
null
Project/src/main/java/com/example/cmpe313/Department.java
ZeroToHero2/Human-Resource-Management-System-with-JFoenix
ba03fb48b57674310fb8c12f2f11f64e26107f2e
[ "MIT" ]
null
null
null
23.534884
88
0.641304
1,783
package com.example.cmpe313; public class Department { String name; String budgetOfDeparment; String numberOfEmployee; public Department(String name, String budgetOfDeparment, String numberOfEmployee) { this.name = name; this.budgetOfDeparment = budgetOfDeparment; this.numberOfEmployee = numberOfEmployee; } @Override public String toString() { return name; } public String getName() { return name; } public String getBudgetOfDeparment() { return budgetOfDeparment; } public String getNumberOfEmployee() { return numberOfEmployee; } public void setName(String name) { this.name = name; } public void setBudgetOfDeparment(String budgetOfDeparment) { this.budgetOfDeparment = budgetOfDeparment; } public void setNumberOfEmployee(String numberOfEmployee) { this.numberOfEmployee = numberOfEmployee; } }
3e04434dd2dea99401be0c64c9a7c8a35a4778e1
318
java
Java
wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/mapper/GenerateMapper.java
lvpv/wemirr-platform
33a23b4d74a2a8e6acf1d838efc8acec437d7d97
[ "Apache-2.0" ]
22
2021-08-18T10:27:39.000Z
2022-03-23T09:39:57.000Z
wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/mapper/GenerateMapper.java
lvpv/wemirr-platform
33a23b4d74a2a8e6acf1d838efc8acec437d7d97
[ "Apache-2.0" ]
null
null
null
wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/mapper/GenerateMapper.java
lvpv/wemirr-platform
33a23b4d74a2a8e6acf1d838efc8acec437d7d97
[ "Apache-2.0" ]
4
2021-09-27T06:47:56.000Z
2022-02-23T14:04:59.000Z
24.461538
69
0.814465
1,784
package com.wemirr.platform.tools.mapper; import com.wemirr.framework.db.mybatis.SuperMapper; import com.wemirr.platform.tools.domain.entity.GenerateEntity; import org.springframework.stereotype.Repository; /** * @author Levin */ @Repository public interface GenerateMapper extends SuperMapper<GenerateEntity> { }
3e044378ef767793a6b14100c8629487527ae2d6
1,374
java
Java
learn-baselib-service/src/main/java/com/donkeycode/data/entity/ResourceAuthority.java
walker-xue/learn-cloud
e87c036aab897e4689bc43b78fddcda87c6d4e65
[ "Apache-2.0" ]
1
2021-02-02T02:59:40.000Z
2021-02-02T02:59:40.000Z
learn-baselib-service/src/main/java/com/donkeycode/data/entity/ResourceAuthority.java
walker-xue/learn-cloud
e87c036aab897e4689bc43b78fddcda87c6d4e65
[ "Apache-2.0" ]
null
null
null
learn-baselib-service/src/main/java/com/donkeycode/data/entity/ResourceAuthority.java
walker-xue/learn-cloud
e87c036aab897e4689bc43b78fddcda87c6d4e65
[ "Apache-2.0" ]
null
null
null
19.083333
73
0.691412
1,785
package com.donkeycode.data.entity; import java.util.Date; import javax.persistence.*; import com.donkeycode.core.BaseEntity; import lombok.Getter; import lombok.Setter; @Getter @Setter @Table(name = "base_resource_authority") public class ResourceAuthority extends BaseEntity { @Id private Integer id; @Column(name = "authority_id") private String authorityId; @Column(name = "authority_type") private String authorityType; @Column(name = "resource_id") private String resourceId; @Column(name = "resource_type") private String resourceType; @Column(name = "parent_id") private String parentId; private String path; private String description; @Column(name = "crt_time") private Date crtTime; @Column(name = "crt_user") private String crtUser; @Column(name = "crt_name") private String crtName; @Column(name = "crt_host") private String crtHost; private String attr1; private String attr2; private String attr3; private String attr4; private String attr5; private String attr6; private String attr7; private String attr8; public ResourceAuthority() { } public ResourceAuthority(String authorityType, String resourceType) { this.authorityType = authorityType; this.resourceType = resourceType; } }
3e0443ef760553408d8f01f574077db90e7b50ef
976
java
Java
src/main/java/uk/co/bigsoft/greenmail/http/commands/Utils.java
MitulKapoor/greenmail-http
5466f90f42f0c0580ab9a92740c51f6f7a08fa80
[ "MIT" ]
null
null
null
src/main/java/uk/co/bigsoft/greenmail/http/commands/Utils.java
MitulKapoor/greenmail-http
5466f90f42f0c0580ab9a92740c51f6f7a08fa80
[ "MIT" ]
null
null
null
src/main/java/uk/co/bigsoft/greenmail/http/commands/Utils.java
MitulKapoor/greenmail-http
5466f90f42f0c0580ab9a92740c51f6f7a08fa80
[ "MIT" ]
null
null
null
25.025641
64
0.73873
1,786
package uk.co.bigsoft.greenmail.http.commands; import com.icegreen.greenmail.imap.ImapHostManager; import com.icegreen.greenmail.store.MailFolder; import com.icegreen.greenmail.user.GreenMailUser; import com.icegreen.greenmail.user.UserManager; import io.javalin.http.Context; public class Utils { public GreenMailUser getUser(Context ctx, UserManager um) { String user = ctx.pathParam("email"); return um.getUserByEmail(user); } public String getEmail(Context ctx) { String email = ctx.pathParam("email"); return email; } public String getDomain(Context ctx) { String domain = ctx.pathParam("domain"); return domain; } public MailFolder getMailbox(Context ctx, ImapHostManager im) { String mailbox = ctx.pathParam("mailbox").replace("%23", "#"); MailFolder m = im.getStore().getMailbox(mailbox); return m; } public long getUid(Context ctx) { String sUid = ctx.pathParam("uid"); Long uid = new Long(sUid); return uid.longValue(); } }
3e0444b6eaba846c03e76d52de2799d7326ba363
1,922
java
Java
len-core/src/main/java/com/len/redis/RedisConfig.java
dongjinlong123/lenosp
ca74b0f95f30dd6a45169fd38f43e1be50cb628a
[ "Apache-2.0" ]
null
null
null
len-core/src/main/java/com/len/redis/RedisConfig.java
dongjinlong123/lenosp
ca74b0f95f30dd6a45169fd38f43e1be50cb628a
[ "Apache-2.0" ]
7
2020-12-21T16:56:12.000Z
2022-02-09T22:16:53.000Z
len-core/src/main/java/com/len/redis/RedisConfig.java
dongjinlong123/lenosp
ca74b0f95f30dd6a45169fd38f43e1be50cb628a
[ "Apache-2.0" ]
null
null
null
43.681818
103
0.801249
1,787
package com.len.redis; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * 默认的redis 是采用jdk中的序列化方式,在redis工具上现实的不是明文 * 因为redis在注入redisTemplate时,使用了注解@ConditionalOnMissingBean(name = "redisTemplate") * 可以自行注入,并设置序列化方法 */ @Configuration public class RedisConfig { @Bean @ConditionalOnClass(RedisOperations.class) //如果存在RedisOperations.class这个类,表示引入了redis public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setDefaultSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class)); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(24)); // 设置缓存有效期24小时 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } }
3e0444bacad57b564098369c000b0da168a35ca8
417
java
Java
src/main/java/cn/mgl/tally/dao/mapper/UserInfoMapper.java
MongieLee/tally-service
f718cd6c0c57f1c74905a3a8f55713b88054cae9
[ "MIT" ]
null
null
null
src/main/java/cn/mgl/tally/dao/mapper/UserInfoMapper.java
MongieLee/tally-service
f718cd6c0c57f1c74905a3a8f55713b88054cae9
[ "MIT" ]
null
null
null
src/main/java/cn/mgl/tally/dao/mapper/UserInfoMapper.java
MongieLee/tally-service
f718cd6c0c57f1c74905a3a8f55713b88054cae9
[ "MIT" ]
null
null
null
32.076923
103
0.788969
1,788
package cn.mgl.tally.dao.mapper; import cn.mgl.tally.model.persistence.UserInfo; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper public interface UserInfoMapper { @Select("select id,username,password,create_time,update_time from tally_userinfo where id = #{id}") UserInfo getUserInfoById(@Param("id") long id); }
3e0445556771ed0398152043d289c68cda48207e
904
java
Java
cineast-core/src/main/java/org/vitrivr/cineast/core/db/PersistentOperator.java
simonpeterhans/cineast
d7c1d16accf29a63da98d9a4cc7bbc552ee9f7ac
[ "MIT" ]
43
2017-04-25T14:48:51.000Z
2022-02-11T16:45:01.000Z
cineast-core/src/main/java/org/vitrivr/cineast/core/db/PersistentOperator.java
simonpeterhans/cineast
d7c1d16accf29a63da98d9a4cc7bbc552ee9f7ac
[ "MIT" ]
158
2017-04-25T08:53:29.000Z
2022-03-21T16:29:17.000Z
cineast-core/src/main/java/org/vitrivr/cineast/core/db/PersistentOperator.java
simonpeterhans/cineast
d7c1d16accf29a63da98d9a4cc7bbc552ee9f7ac
[ "MIT" ]
48
2017-03-27T09:39:38.000Z
2022-02-03T16:47:29.000Z
30.133333
170
0.74115
1,789
package org.vitrivr.cineast.core.db; import java.util.ArrayList; import java.util.List; import org.vitrivr.cineast.core.db.setup.EntityCreator; import java.util.function.Supplier; public interface PersistentOperator { /** * Initializes the underlying layers in which the data is stored. Commonly, the entities which are used are created */ void initalizePersistentLayer(Supplier<EntityCreator> supply); /** * Drops all underlying layers in which data is stored. */ void dropPersistentLayer(Supplier<EntityCreator> supply); /** * Returns the table/entity names which this {@link PersistentOperator} uses to store/access its data. Defaults to an empty list, in which case no table/entity is used. * * @return Tables which this {@link PersistentOperator} uses to store/access its data. */ default List<String> getTableNames() { return new ArrayList<>(0); } }
3e0446abf2c58818b223a623679dc77cd8b9c251
750
java
Java
app/src/main/java/me/aidengaripoli/dhapexample/DiscoveringDevicesFragment.java
decentralised-home-automation-protocol/DHAP-Android
c66f867d1743def6af41935e72c7d5f5412b87a1
[ "MIT" ]
null
null
null
app/src/main/java/me/aidengaripoli/dhapexample/DiscoveringDevicesFragment.java
decentralised-home-automation-protocol/DHAP-Android
c66f867d1743def6af41935e72c7d5f5412b87a1
[ "MIT" ]
10
2019-09-05T02:36:57.000Z
2019-10-15T01:36:37.000Z
app/src/main/java/me/aidengaripoli/dhapexample/DiscoveringDevicesFragment.java
decentralised-home-automation-protocol/DHAP-Android
c66f867d1743def6af41935e72c7d5f5412b87a1
[ "MIT" ]
null
null
null
27.777778
132
0.78
1,790
package me.aidengaripoli.dhapexample; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class DiscoveringDevicesFragment extends Fragment { public DiscoveringDevicesFragment() { } static DiscoveringDevicesFragment newInstance() { return new DiscoveringDevicesFragment(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_discovering_devices, container, false); } }
3e04477c40644d45fd8f0004f553c199ed656a14
398
java
Java
src/main/java/com/starfish/model/PageResult.java
sunlin901203/starfish
4b5903cb2f04505b8a096d96dcbd278bde1d1171
[ "Apache-2.0" ]
1
2020-09-13T04:49:19.000Z
2020-09-13T04:49:19.000Z
src/main/java/com/starfish/model/PageResult.java
sunlin901203/starfish
4b5903cb2f04505b8a096d96dcbd278bde1d1171
[ "Apache-2.0" ]
1
2021-02-12T00:36:07.000Z
2021-02-12T00:36:07.000Z
src/main/java/com/starfish/model/PageResult.java
sunlin901203/starfish
4b5903cb2f04505b8a096d96dcbd278bde1d1171
[ "Apache-2.0" ]
null
null
null
13.266667
52
0.625628
1,791
package com.starfish.model; import lombok.Data; import java.io.Serializable; import java.util.List; /** * 分页结果 * * @author neacle * @version 1.0.0 * @since 2015-04-13 */ @Data @SuppressWarnings("unused") public class PageResult<T> implements Serializable { /** * total count,optional */ private Long totalCount; /** * list */ private List<T> list; }
3e044848c322397cfb03c8842d05c90451619d7d
1,195
java
Java
webx/dev/src/main/java/com/alibaba/citrus/dev/handler/util/ClassValue.java
guafei/citrus
51fdd768621fe75f666b989e81ee42498f715534
[ "Apache-2.0" ]
1
2016-07-21T10:08:28.000Z
2016-07-21T10:08:28.000Z
webx/dev/src/main/java/com/alibaba/citrus/dev/handler/util/ClassValue.java
guafei/citrus
51fdd768621fe75f666b989e81ee42498f715534
[ "Apache-2.0" ]
null
null
null
webx/dev/src/main/java/com/alibaba/citrus/dev/handler/util/ClassValue.java
guafei/citrus
51fdd768621fe75f666b989e81ee42498f715534
[ "Apache-2.0" ]
null
null
null
28.452381
75
0.712971
1,792
/* * Copyright 2010 Alibaba Group Holding Limited. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.citrus.dev.handler.util; import com.alibaba.citrus.util.ClassUtil; public class ClassValue extends StyledValue { private final String className; public ClassValue(String className) { super(className); this.className = className; } public String getPackageName() { return ClassUtil.getPackageName(className); } public String getSimpleName() { return ClassUtil.getSimpleClassName(className, false); } public String getClassName() { return className; } }
3e0448b8f75960a1581322ea63d409eb0ee1a9ce
1,012
java
Java
src/main/java/com/github/tomakehurst/wiremock/matching/AdvancedPathPattern.java
Mahoney/wiremock
1d52af3286f13eb387740beef5da750e728c7860
[ "Apache-2.0" ]
4,473
2015-01-01T01:00:16.000Z
2021-09-20T09:02:58.000Z
src/main/java/com/github/tomakehurst/wiremock/matching/AdvancedPathPattern.java
Mahoney/wiremock
1d52af3286f13eb387740beef5da750e728c7860
[ "Apache-2.0" ]
1,259
2015-01-01T21:07:01.000Z
2021-09-16T22:22:13.000Z
src/main/java/com/github/tomakehurst/wiremock/matching/AdvancedPathPattern.java
mih-kopylov/wiremock
3b3e3b2de3664166a922992ee317f92f557c0927
[ "Apache-2.0" ]
1,217
2015-01-06T01:42:33.000Z
2021-09-20T12:27:01.000Z
31.625
81
0.744071
1,793
/* * Copyright (C) 2011 Thomas Akehurst * * 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.github.tomakehurst.wiremock.matching; import com.fasterxml.jackson.annotation.JsonUnwrapped; public class AdvancedPathPattern { public final String expression; @JsonUnwrapped public final ContentPattern<?> submatcher; public AdvancedPathPattern(String expression, ContentPattern<?> submatcher) { this.expression = expression; this.submatcher = submatcher; } }
3e044a39649a167c645bd1c5199e4d69106d39b9
12,693
java
Java
netty/src/main/java/io/grpc/netty/NettyClientStream.java
huangqiangxiong/grpc-java
821ec65f2ede1adaa54400e0a093597ec7958485
[ "Apache-2.0" ]
10,245
2015-02-26T17:30:44.000Z
2022-03-31T01:35:00.000Z
netty/src/main/java/io/grpc/netty/NettyClientStream.java
huangqiangxiong/grpc-java
821ec65f2ede1adaa54400e0a093597ec7958485
[ "Apache-2.0" ]
6,095
2015-02-26T18:09:35.000Z
2022-03-31T23:55:18.000Z
netty/src/main/java/io/grpc/netty/NettyClientStream.java
huangqiangxiong/grpc-java
821ec65f2ede1adaa54400e0a093597ec7958485
[ "Apache-2.0" ]
3,853
2015-02-26T17:19:14.000Z
2022-03-31T14:04:40.000Z
36.265714
100
0.691326
1,794
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.netty; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.netty.buffer.Unpooled.EMPTY_BUFFER; import com.google.common.base.Preconditions; import com.google.common.io.BaseEncoding; import io.grpc.Attributes; import io.grpc.CallOptions; import io.grpc.InternalKnownTransport; import io.grpc.InternalMethodDescriptor; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.internal.AbstractClientStream; import io.grpc.internal.Http2ClientStreamTransportState; import io.grpc.internal.StatsTraceContext; import io.grpc.internal.TransportTracer; import io.grpc.internal.WritableBuffer; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.EventLoop; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2Stream; import io.netty.util.AsciiString; import io.perfmark.PerfMark; import io.perfmark.Tag; import javax.annotation.Nullable; /** * Client stream for a Netty transport. Must only be called from the sending application * thread. */ class NettyClientStream extends AbstractClientStream { private static final InternalMethodDescriptor methodDescriptorAccessor = new InternalMethodDescriptor( NettyClientTransport.class.getName().contains("grpc.netty.shaded") ? InternalKnownTransport.NETTY_SHADED : InternalKnownTransport.NETTY); private final Sink sink = new Sink(); private final TransportState state; private final WriteQueue writeQueue; private final MethodDescriptor<?, ?> method; private AsciiString authority; private final AsciiString scheme; private final AsciiString userAgent; NettyClientStream( TransportState state, MethodDescriptor<?, ?> method, Metadata headers, Channel channel, AsciiString authority, AsciiString scheme, AsciiString userAgent, StatsTraceContext statsTraceCtx, TransportTracer transportTracer, CallOptions callOptions, boolean useGetForSafeMethods) { super( new NettyWritableBufferAllocator(channel.alloc()), statsTraceCtx, transportTracer, headers, callOptions, useGetForSafeMethods && method.isSafe()); this.state = checkNotNull(state, "transportState"); this.writeQueue = state.handler.getWriteQueue(); this.method = checkNotNull(method, "method"); this.authority = checkNotNull(authority, "authority"); this.scheme = checkNotNull(scheme, "scheme"); this.userAgent = userAgent; } @Override protected TransportState transportState() { return state; } @Override protected Sink abstractClientStreamSink() { return sink; } @Override public void setAuthority(String authority) { this.authority = AsciiString.of(checkNotNull(authority, "authority")); } @Override public Attributes getAttributes() { return state.handler.getAttributes(); } private class Sink implements AbstractClientStream.Sink { @Override public void writeHeaders(Metadata headers, byte[] requestPayload) { PerfMark.startTask("NettyClientStream$Sink.writeHeaders"); try { writeHeadersInternal(headers, requestPayload); } finally { PerfMark.stopTask("NettyClientStream$Sink.writeHeaders"); } } private void writeHeadersInternal(Metadata headers, byte[] requestPayload) { // Convert the headers into Netty HTTP/2 headers. AsciiString defaultPath = (AsciiString) methodDescriptorAccessor.geRawMethodName(method); if (defaultPath == null) { defaultPath = new AsciiString("/" + method.getFullMethodName()); methodDescriptorAccessor.setRawMethodName(method, defaultPath); } boolean get = (requestPayload != null); AsciiString httpMethod; if (get) { // Forge the query string // TODO(ericgribkoff) Add the key back to the query string defaultPath = new AsciiString(defaultPath + "?" + BaseEncoding.base64().encode(requestPayload)); httpMethod = Utils.HTTP_GET_METHOD; } else { httpMethod = Utils.HTTP_METHOD; } Http2Headers http2Headers = Utils.convertClientHeaders(headers, scheme, defaultPath, authority, httpMethod, userAgent); ChannelFutureListener failureListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { // Stream creation failed. Close the stream if not already closed. // When the channel is shutdown, the lifecycle manager has a better view of the failure, // especially before negotiation completes (because the negotiator commonly doesn't // receive the execeptionCaught because NettyClientHandler does not propagate it). Status s = transportState().handler.getLifecycleManager().getShutdownStatus(); if (s == null) { s = transportState().statusFromFailedFuture(future); } transportState().transportReportStatus(s, true, new Metadata()); } } }; // Write the command requesting the creation of the stream. writeQueue.enqueue( new CreateStreamCommand(http2Headers, transportState(), shouldBeCountedForInUse(), get), !method.getType().clientSendsOneMessage() || get).addListener(failureListener); } private void writeFrameInternal( WritableBuffer frame, boolean endOfStream, boolean flush, final int numMessages) { Preconditions.checkArgument(numMessages >= 0); ByteBuf bytebuf = frame == null ? EMPTY_BUFFER : ((NettyWritableBuffer) frame).bytebuf().touch(); final int numBytes = bytebuf.readableBytes(); if (numBytes > 0) { // Add the bytes to outbound flow control. onSendingBytes(numBytes); writeQueue.enqueue(new SendGrpcFrameCommand(transportState(), bytebuf, endOfStream), flush) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // If the future succeeds when http2stream is null, the stream has been cancelled // before it began and Netty is purging pending writes from the flow-controller. if (future.isSuccess() && transportState().http2Stream() != null) { // Remove the bytes from outbound flow control, optionally notifying // the client that they can send more bytes. transportState().onSentBytes(numBytes); NettyClientStream.this.getTransportTracer().reportMessageSent(numMessages); } } }); } else { // The frame is empty and will not impact outbound flow control. Just send it. writeQueue.enqueue( new SendGrpcFrameCommand(transportState(), bytebuf, endOfStream), flush); } } @Override public void writeFrame( WritableBuffer frame, boolean endOfStream, boolean flush, int numMessages) { PerfMark.startTask("NettyClientStream$Sink.writeFrame"); try { writeFrameInternal(frame, endOfStream, flush, numMessages); } finally { PerfMark.stopTask("NettyClientStream$Sink.writeFrame"); } } @Override public void cancel(Status status) { PerfMark.startTask("NettyClientStream$Sink.cancel"); try { writeQueue.enqueue(new CancelClientStreamCommand(transportState(), status), true); } finally { PerfMark.stopTask("NettyClientStream$Sink.cancel"); } } } /** This should only called from the transport thread. */ public abstract static class TransportState extends Http2ClientStreamTransportState implements StreamIdHolder { private static final int NON_EXISTENT_ID = -1; private final String methodName; private final NettyClientHandler handler; private final EventLoop eventLoop; private int id; private Http2Stream http2Stream; private Tag tag; protected TransportState( NettyClientHandler handler, EventLoop eventLoop, int maxMessageSize, StatsTraceContext statsTraceCtx, TransportTracer transportTracer, String methodName) { super(maxMessageSize, statsTraceCtx, transportTracer); this.methodName = checkNotNull(methodName, "methodName"); this.handler = checkNotNull(handler, "handler"); this.eventLoop = checkNotNull(eventLoop, "eventLoop"); tag = PerfMark.createTag(methodName); } @Override public int id() { // id should be positive return id; } public void setId(int id) { checkArgument(id > 0, "id must be positive %s", id); checkState(this.id == 0, "id has been previously set: %s", this.id); this.id = id; this.tag = PerfMark.createTag(methodName, id); } /** * Marks the stream state as if it had never existed. This can happen if the stream is * cancelled after it is created, but before it has been started. */ void setNonExistent() { checkState(this.id == 0, "Id has been previously set: %s", this.id); this.id = NON_EXISTENT_ID; } boolean isNonExistent() { return this.id == NON_EXISTENT_ID; } /** * Sets the underlying Netty {@link Http2Stream} for this stream. This must be called in the * context of the transport thread. */ public void setHttp2Stream(Http2Stream http2Stream) { checkNotNull(http2Stream, "http2Stream"); checkState(this.http2Stream == null, "Can only set http2Stream once"); this.http2Stream = http2Stream; // Now that the stream has actually been initialized, call the listener's onReady callback if // appropriate. onStreamAllocated(); getTransportTracer().reportLocalStreamStarted(); } /** * Gets the underlying Netty {@link Http2Stream} for this stream. */ @Nullable public Http2Stream http2Stream() { return http2Stream; } /** * Intended to be overridden by NettyClientTransport, which has more information about failures. * May only be called from event loop. */ protected abstract Status statusFromFailedFuture(ChannelFuture f); @Override protected void http2ProcessingFailed(Status status, boolean stopDelivery, Metadata trailers) { transportReportStatus(status, stopDelivery, trailers); handler.getWriteQueue().enqueue(new CancelClientStreamCommand(this, status), true); } @Override public void runOnTransportThread(final Runnable r) { if (eventLoop.inEventLoop()) { r.run(); } else { eventLoop.execute(r); } } @Override public void bytesRead(int processedBytes) { handler.returnProcessedBytes(http2Stream, processedBytes); handler.getWriteQueue().scheduleFlush(); } @Override public void deframeFailed(Throwable cause) { http2ProcessingFailed(Status.fromThrowable(cause), true, new Metadata()); } void transportHeadersReceived(Http2Headers headers, boolean endOfStream) { if (endOfStream) { if (!isOutboundClosed()) { handler.getWriteQueue().enqueue(new CancelClientStreamCommand(this, null), true); } transportTrailersReceived(Utils.convertTrailers(headers)); } else { transportHeadersReceived(Utils.convertHeaders(headers)); } } void transportDataReceived(ByteBuf frame, boolean endOfStream) { transportDataReceived(new NettyReadableBuffer(frame.retain()), endOfStream); } @Override public final Tag tag() { return tag; } } }
3e044a8d03dca14f9bc9d6d69960041143a1dcae
399
java
Java
java/src/main/java/com/ciaoshen/leetcode/new_21_game/Solution.java
helloShen/leetcode
5bba26f0612d785800c990947db8dae3af4bad81
[ "MIT" ]
1
2019-03-06T22:03:56.000Z
2019-03-06T22:03:56.000Z
java/src/main/java/com/ciaoshen/leetcode/new_21_game/Solution.java
helloShen/leetcode
5bba26f0612d785800c990947db8dae3af4bad81
[ "MIT" ]
1
2019-03-07T00:58:26.000Z
2019-03-19T01:43:05.000Z
java/src/main/java/com/ciaoshen/leetcode/new_21_game/Solution.java
helloShen/leetcode
5bba26f0612d785800c990947db8dae3af4bad81
[ "MIT" ]
null
null
null
21
64
0.729323
1,795
/** * Leetcode - new_21_game */ package com.ciaoshen.leetcode.new_21_game; import java.util.*; import com.ciaoshen.leetcode.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; interface Solution { // use this Object to print the log (call from slf4j facade) static Logger log = LoggerFactory.getLogger(Solution.class); public double new21Game(int N, int K, int W); }
3e044cbb0bcd6c7172a002b098214bf8c520dc9a
20,728
java
Java
app/src/main/java/org/wikipedia/readinglist/database/ReadingListDbHelper.java
amawai/android-wikipedia-390
814834fa23fcd0327a00a91d0694ce2b9fbd7921
[ "Apache-2.0" ]
3
2019-01-09T18:42:09.000Z
2019-04-21T12:25:47.000Z
app/src/main/java/org/wikipedia/readinglist/database/ReadingListDbHelper.java
amawai/android-wikipedia-390
814834fa23fcd0327a00a91d0694ce2b9fbd7921
[ "Apache-2.0" ]
23
2018-04-08T18:00:48.000Z
2018-04-15T01:37:08.000Z
app/src/main/java/org/wikipedia/readinglist/database/ReadingListDbHelper.java
amawai/android-wikipedia-390
814834fa23fcd0327a00a91d0694ce2b9fbd7921
[ "Apache-2.0" ]
7
2018-04-08T17:59:57.000Z
2019-09-16T16:51:28.000Z
40.484375
125
0.588335
1,796
package org.wikipedia.readinglist.database; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.wikipedia.WikipediaApp; import org.wikipedia.database.contract.ReadingListContract; import org.wikipedia.database.contract.ReadingListPageContract; import org.wikipedia.page.PageTitle; import org.wikipedia.savedpages.SavedPageSyncService; import org.wikipedia.util.log.L; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; public class ReadingListDbHelper { private static ReadingListDbHelper INSTANCE; public static ReadingListDbHelper instance() { if (INSTANCE == null) { INSTANCE = new ReadingListDbHelper(); } return INSTANCE; } public List<ReadingList> getAllLists() { List<ReadingList> lists = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListContract.TABLE, null, null, null, null, null, null)) { while (cursor.moveToNext()) { ReadingList list = ReadingList.DATABASE_TABLE.fromCursor(cursor); lists.add(list); } } for (ReadingList list : lists) { populateListPages(db, list); } return lists; } public List<ReadingList> getAllListsWithoutContents() { List<ReadingList> lists = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListContract.TABLE, null, null, null, null, null, null)) { while (cursor.moveToNext()) { ReadingList list = ReadingList.DATABASE_TABLE.fromCursor(cursor); lists.add(list); } } return lists; } @NonNull public ReadingList createList(@NonNull String title, @Nullable String description) { SQLiteDatabase db = getWritableDatabase(); return createList(db, title, description); } @NonNull public ReadingList createList(@NonNull SQLiteDatabase db, @NonNull String title, @Nullable String description) { db.beginTransaction(); try { ReadingList protoList = new ReadingList(title, description); long id = db.insertOrThrow(ReadingListContract.TABLE, null, ReadingList.DATABASE_TABLE.toContentValues(protoList)); db.setTransactionSuccessful(); protoList.id(id); return protoList; } finally { db.endTransaction(); } } public void updateList(@NonNull ReadingList list) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { // implicitly update the last-access time of the list list.touch(); int result = db.update(ReadingListContract.TABLE, ReadingList.DATABASE_TABLE.toContentValues(list), ReadingListContract.Col.ID.getName() + " = ?", new String[]{Long.toString(list.id())}); if (result != 1) { L.w("Failed to update db entry for list " + list.title()); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void deleteList(@NonNull ReadingList list) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { int result = db.delete(ReadingListContract.TABLE, ReadingListContract.Col.ID.getName() + " = ?", new String[]{Long.toString(list.id())}); if (result != 1) { L.w("Failed to delete db entry for list " + list.title()); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void addPageToList(@NonNull ReadingList list, @NonNull PageTitle title) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { addPageToList(db, list, title); db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public void addPagesToList(@NonNull ReadingList list, @NonNull List<ReadingListPage> pages) { SQLiteDatabase db = getWritableDatabase(); addPagesToList(db, list, pages); } public void addPagesToList(@NonNull SQLiteDatabase db, @NonNull ReadingList list, @NonNull List<ReadingListPage> pages) { db.beginTransaction(); try { for (ReadingListPage page : pages) { insertPageInDb(db, list, page); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public int addPagesToListIfNotExist(@NonNull ReadingList list, @NonNull List<PageTitle> titles) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); int numAdded = 0; try { for (PageTitle title : titles) { if (pageExistsInList(db, list, title)) { continue; } addPageToList(db, list, title); numAdded++; } db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); return numAdded; } public void markPageForDeletion(@NonNull ReadingListPage page) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { page.status(ReadingListPage.STATUS_QUEUE_FOR_DELETE); updatePageInDb(db, page); db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public void markPagesForDeletion(@NonNull List<ReadingListPage> pages) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { for (ReadingListPage page : pages) { page.status(ReadingListPage.STATUS_QUEUE_FOR_DELETE); updatePageInDb(db, page); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public void markPageForOffline(@NonNull ReadingListPage page, boolean offline) { if (page.offline() == offline) { return; } SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { page.offline(offline); updatePageInDb(db, page); db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public void markPagesForOffline(@NonNull List<ReadingListPage> pages, boolean offline) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { for (ReadingListPage page : pages) { if (page.offline() == offline) { continue; } page.offline(offline); updatePageInDb(db, page); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } SavedPageSyncService.enqueue(); } public void updatePage(@NonNull ReadingListPage page) { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { updatePageInDb(db, page); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private void insertPageInDb(SQLiteDatabase db, @NonNull ReadingList list, @NonNull ReadingListPage page) { page.listId(list.id()); long id = db.insertOrThrow(ReadingListPageContract.TABLE, null, ReadingListPage.DATABASE_TABLE.toContentValues(page)); page.id(id); } private void updatePageInDb(SQLiteDatabase db, @NonNull ReadingListPage page) { int result = db.update(ReadingListPageContract.TABLE, ReadingListPage.DATABASE_TABLE.toContentValues(page), ReadingListPageContract.Col.ID.getName() + " = ?", new String[]{Long.toString(page.id())}); if (result != 1) { L.w("Failed to update db entry for page " + page.title()); } } private void deletePageFromDb(SQLiteDatabase db, @NonNull ReadingListPage page) { int result = db.delete(ReadingListPageContract.TABLE, ReadingListPageContract.Col.ID.getName() + " = ?", new String[]{Long.toString(page.id())}); if (result != 1) { L.w("Failed to delete db entry for page " + page.title()); } } @Nullable public ReadingListPage getRandomPage() { SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.STATUS.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_SAVED)}, null, null, null)) { if (cursor.moveToFirst()) { cursor.move(new Random().nextInt(cursor.getCount())); return ReadingListPage.DATABASE_TABLE.fromCursor(cursor); } } return null; } @Nullable public ReadingListPage findPageInAnyList(@NonNull PageTitle title) { SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.SITE.getName() + " = ? AND " + ReadingListPageContract.Col.LANG.getName() + " = ? AND " + ReadingListPageContract.Col.NAMESPACE.getName() + " = ? AND " + ReadingListPageContract.Col.TITLE.getName() + " = ? AND " + ReadingListPageContract.Col.STATUS.getName() + " != ?", new String[]{title.getWikiSite().authority(), title.getWikiSite().languageCode(), Integer.toString(title.namespace().code()), title.getDisplayText(), Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { if (cursor.moveToFirst()) { return ReadingListPage.DATABASE_TABLE.fromCursor(cursor); } } return null; } public boolean pageExistsInList(@NonNull ReadingList list, @NonNull PageTitle title) { SQLiteDatabase db = getReadableDatabase(); return pageExistsInList(db, list, title); } @NonNull public List<ReadingListPage> getAllPageOccurrences(@NonNull PageTitle title) { List<ReadingListPage> pages = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.SITE.getName() + " = ? AND " + ReadingListPageContract.Col.LANG.getName() + " = ? AND " + ReadingListPageContract.Col.NAMESPACE.getName() + " = ? AND " + ReadingListPageContract.Col.TITLE.getName() + " = ? AND " + ReadingListPageContract.Col.STATUS.getName() + " != ?", new String[]{title.getWikiSite().authority(), title.getWikiSite().languageCode(), Integer.toString(title.namespace().code()), title.getDisplayText(), Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { while (cursor.moveToNext()) { pages.add(ReadingListPage.DATABASE_TABLE.fromCursor(cursor)); } } return pages; } @NonNull public List<ReadingList> getListsFromPageOccurrences(@NonNull List<ReadingListPage> pages) { List<ReadingList> lists = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); List<Long> listIds = new ArrayList<>(); for (ReadingListPage page : pages) { if (!listIds.contains(page.listId())) { listIds.add(page.listId()); } } for (long listId : listIds) { try (Cursor cursor = db.query(ReadingListContract.TABLE, null, ReadingListContract.Col.ID.getName() + " = ?", new String[]{Long.toString(listId)}, null, null, null)) { if (cursor.moveToFirst()) { lists.add(ReadingList.DATABASE_TABLE.fromCursor(cursor)); } } } for (ReadingList list : lists) { for (ReadingListPage page : pages) { if (list.id() == page.listId()) { list.pages().add(page); } } } return lists; } @NonNull public List<ReadingListPage> getAllPagesToBeSaved() { List<ReadingListPage> pages = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.STATUS.getName() + " = ? AND " + ReadingListPageContract.Col.OFFLINE.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_SAVE), Integer.toString(1)}, null, null, null)) { while (cursor.moveToNext()) { pages.add(ReadingListPage.DATABASE_TABLE.fromCursor(cursor)); } } return pages; } public List<ReadingListPage> getAllPagesToBeUnsaved() { List<ReadingListPage> pages = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.STATUS.getName() + " = ? AND " + ReadingListPageContract.Col.OFFLINE.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_SAVED), Integer.toString(0)}, null, null, null)) { while (cursor.moveToNext()) { pages.add(ReadingListPage.DATABASE_TABLE.fromCursor(cursor)); } } return pages; } @NonNull public List<ReadingListPage> getAllPagesToBeDeleted() { List<ReadingListPage> pages = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.STATUS.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { while (cursor.moveToNext()) { pages.add(ReadingListPage.DATABASE_TABLE.fromCursor(cursor)); } } return pages; } public void resetUnsavedPageStatus() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { ContentValues contentValues = new ContentValues(); contentValues.put(ReadingListPageContract.Col.STATUS.getName(), ReadingListPage.STATUS_QUEUE_FOR_SAVE); int result = db.update(ReadingListPageContract.TABLE, contentValues, ReadingListPageContract.Col.STATUS.getName() + " = ? AND " + ReadingListPageContract.Col.OFFLINE.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_SAVED), Integer.toString(0)}); L.d("Updated " + result + " pages in db."); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void purgeDeletedPages() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { int result = db.delete(ReadingListPageContract.TABLE, ReadingListPageContract.Col.STATUS.getName() + " = ?", new String[]{Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}); L.d("Deleted " + result + " pages from db."); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Nullable public ReadingList getFullListById(long id) { SQLiteDatabase db = getReadableDatabase(); ReadingList list = null; try (Cursor cursor = db.query(ReadingListContract.TABLE, null, ReadingListContract.Col.ID.getName() + " = ?", new String[]{Long.toString(id)}, null, null, null)) { if (cursor.moveToFirst()) { list = ReadingList.DATABASE_TABLE.fromCursor(cursor); } } if (list == null) { return null; } populateListPages(db, list); return list; } private void populateListPages(SQLiteDatabase db, @NonNull ReadingList list) { try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.LISTID.getName() + " = ? AND " + ReadingListPageContract.Col.STATUS.getName() + " != ?", new String[]{Long.toString(list.id()), Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { while (cursor.moveToNext()) { list.pages().add(ReadingListPage.DATABASE_TABLE.fromCursor(cursor)); } } } public HashMap<String, String> getLinks(@NonNull ReadingList list) { SQLiteDatabase db = getReadableDatabase(); return getLinks(list, db); } //Takes in a reading list and returns hashmap with the key being the title of the article and value, the link public HashMap<String, String> getLinks(@NonNull ReadingList list, SQLiteDatabase db) { HashMap<String, String> linkMap = new HashMap(); ReadingListPage savedLink; String link; try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.LISTID.getName() + " = ? AND " + ReadingListPageContract.Col.STATUS.getName() + " != ?", new String[]{Long.toString(list.id()), Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { while (cursor.moveToNext()) { savedLink = ReadingListPage.DATABASE_TABLE.fromCursor(cursor); link = savedLink.wiki().url() + "/wiki/" + savedLink.title().toString(); linkMap.put(savedLink.title(), link.replace(" ", "_")); } } return linkMap; } private boolean pageExistsInList(SQLiteDatabase db, @NonNull ReadingList list, @NonNull PageTitle title) { try (Cursor cursor = db.query(ReadingListPageContract.TABLE, null, ReadingListPageContract.Col.SITE.getName() + " = ? AND " + ReadingListPageContract.Col.LANG.getName() + " = ? AND " + ReadingListPageContract.Col.NAMESPACE.getName() + " = ? AND " + ReadingListPageContract.Col.TITLE.getName() + " = ? AND " + ReadingListPageContract.Col.LISTID.getName() + " = ? AND " + ReadingListPageContract.Col.STATUS.getName() + " != ?", new String[]{title.getWikiSite().authority(), title.getWikiSite().languageCode(), Integer.toString(title.namespace().code()), title.getDisplayText(), Long.toString(list.id()), Integer.toString(ReadingListPage.STATUS_QUEUE_FOR_DELETE)}, null, null, null)) { if (cursor.getCount() > 0) { return true; } } return false; } private void addPageToList(SQLiteDatabase db, @NonNull ReadingList list, @NonNull PageTitle title) { ReadingListPage protoPage = new ReadingListPage(title); insertPageInDb(db, list, protoPage); } private SQLiteDatabase getReadableDatabase() { return WikipediaApp.getInstance().getDatabase().getReadableDatabase(); } private SQLiteDatabase getWritableDatabase() { return WikipediaApp.getInstance().getDatabase().getWritableDatabase(); } }
3e044cc5348d3415f48c9faff08602f62bef5bbe
4,056
java
Java
src/main/java/com/kshrd/derphsar_api/repository/dto/UserDto.java
Vesal-IT/der-phsar-api
6012b0f33a4706a3cefab0846b6f31ab06ff2df4
[ "IJG" ]
null
null
null
src/main/java/com/kshrd/derphsar_api/repository/dto/UserDto.java
Vesal-IT/der-phsar-api
6012b0f33a4706a3cefab0846b6f31ab06ff2df4
[ "IJG" ]
null
null
null
src/main/java/com/kshrd/derphsar_api/repository/dto/UserDto.java
Vesal-IT/der-phsar-api
6012b0f33a4706a3cefab0846b6f31ab06ff2df4
[ "IJG" ]
null
null
null
21.347368
187
0.551036
1,797
package com.kshrd.derphsar_api.repository.dto; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class UserDto implements UserDetails { private int id; private String userId; private String name; private String gender; private int age; private String phone; private String email; private String password; private boolean status; private String profile; private RoleDto role; private OrderDto order; public UserDto(){} public UserDto(int id, String userId, String name, String gender, int age, String phone, String email, String password, boolean status, String profile, RoleDto role, OrderDto order) { this.id = id; this.userId = userId; this.name = name; this.gender = gender; this.age = age; this.phone = phone; this.email = email; this.password = password; this.status = status; this.profile = profile; this.role = role; this.order = order; } @Override public String toString() { return "UserDto{" + "id=" + id + ", userId='" + userId + '\'' + ", name='" + name + '\'' + ", gender='" + gender + '\'' + ", age=" + age + ", phone='" + phone + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + ", status=" + status + ", profile='" + profile + '\'' + ", role=" + role + ", order=" + order + '}'; } public OrderDto getOrder() { return order; } public void setOrder(OrderDto order) { this.order = order; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> list=new ArrayList<GrantedAuthority>(); list.add(()->role.getName()); return list; } @Override public String getPassword() { return password; } @Override public String getUsername() { return getEmail(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } public void setPassword(String password) { this.password = password; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public RoleDto getRole() { return role; } public void setRole(RoleDto role) { this.role = role; } }
3e044d2eb4d11d0529453d6aebb05a3d2bfc1c59
2,292
java
Java
src/main/java/poisondog/util/EqualsChecker.java
poisondog/poisondog.commons
255f42082a29231280e4c899c1720608b222704d
[ "Apache-2.0" ]
null
null
null
src/main/java/poisondog/util/EqualsChecker.java
poisondog/poisondog.commons
255f42082a29231280e4c899c1720608b222704d
[ "Apache-2.0" ]
null
null
null
src/main/java/poisondog/util/EqualsChecker.java
poisondog/poisondog.commons
255f42082a29231280e4c899c1720608b222704d
[ "Apache-2.0" ]
null
null
null
20.666667
75
0.652136
1,798
/* * Copyright (C) 2010 Adam Huang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package poisondog.util; /** * @author Adam Huang */ public class EqualsChecker { public boolean equivalence(Object o1, Object o2, Object o3) { if(!reflexive(o1)) return false; if(!reflexive(o2)) return false; if(!reflexive(o3)) return false; if(!symmetric(o1, o2)) return false; if(!symmetric(o2, o3)) return false; if(!symmetric(o3, o1)) return false; if(!transitive(o1, o2, o3)) return false; if (o1.equals(null)) return false; if (o2.equals(null)) return false; if (o3.equals(null)) return false; return true; } public boolean hashCode(Object o1, Object o2, Object o3) { if(!reflexive(o1.hashCode())) return false; if(!reflexive(o2.hashCode())) return false; if(!reflexive(o3.hashCode())) return false; if(!symmetric(o1.hashCode(), o2.hashCode())) return false; if(!symmetric(o2.hashCode(), o3.hashCode())) return false; if(!symmetric(o3.hashCode(), o1.hashCode())) return false; if(!transitive(o1.hashCode(), o2.hashCode(), o3.hashCode())) return false; return true; } /** * @param o * @return */ public boolean reflexive(Object o) { if (!o.equals(o)) return false; return true; } /** * @param o1 * @param o2 * @return */ public boolean symmetric(Object o1, Object o2) { if (!o1.equals(o2)) return false; if (!o2.equals(o1)) return false; return true; } /** * @param o1 * @param o2 * @param o3 * @return */ public boolean transitive(Object o1, Object o2, Object o3) { if (!o1.equals(o2)) return false; if (!o2.equals(o3)) return false; if (!o3.equals(o1)) return false; return true; } }
3e044ddc0b4bee3f9a8aa5a96d76cc33d5d49caf
7,820
java
Java
core/src/main/java/feign/Util.java
mhurne/feign
362f5e670ffbc7dffa7dcb712cfb10419409e592
[ "Apache-2.0" ]
null
null
null
core/src/main/java/feign/Util.java
mhurne/feign
362f5e670ffbc7dffa7dcb712cfb10419409e592
[ "Apache-2.0" ]
null
null
null
core/src/main/java/feign/Util.java
mhurne/feign
362f5e670ffbc7dffa7dcb712cfb10419409e592
[ "Apache-2.0" ]
null
null
null
31.28
100
0.650639
1,799
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package feign; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import static java.lang.String.format; /** * Utilities, typically copied in from guava, so as to avoid dependency conflicts. */ public class Util { /** * The HTTP Content-Length header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** * The HTTP Content-Encoding header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** * The HTTP Retry-After header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** * Value for the Content-Encoding header that indicates that GZIP encoding is in use. */ public static final String ENCODING_GZIP = "gzip"; /** * UTF-8: eight-bit UCS Transformation Format. */ public static final Charset UTF_8 = Charset.forName("UTF-8"); // com.google.common.base.Charsets /** * ISO-8859-1: ISO Latin Alphabet Number 1 (ISO-LATIN-1). */ public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes) private Util() { // no instances } /** * Copy of {@code com.google.common.base.Preconditions#checkArgument}. */ public static void checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException( format(errorMessageTemplate, errorMessageArgs)); } } /** * Copy of {@code com.google.common.base.Preconditions#checkNotNull}. */ public static <T> T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException( format(errorMessageTemplate, errorMessageArgs)); } return reference; } /** * Copy of {@code com.google.common.base.Preconditions#checkState}. */ public static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException( format(errorMessageTemplate, errorMessageArgs)); } } /** * Adapted from {@code com.google.common.base.Strings#emptyToNull}. */ public static String emptyToNull(String string) { return string == null || string.isEmpty() ? null : string; } /** * Adapted from {@code com.google.common.base.Strings#emptyToNull}. */ @SuppressWarnings("unchecked") public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { Collection<T> collection; if (iterable instanceof Collection) { collection = (Collection<T>) iterable; } else { collection = new ArrayList<T>(); for (T element : iterable) { collection.add(element); } } T[] array = (T[]) Array.newInstance(type, collection.size()); return collection.toArray(array); } /** * Returns an unmodifiable collection which may be empty, but is never null. */ public static <T> Collection<T> valuesOrEmpty(Map<String, Collection<T>> map, String key) { return map.containsKey(key) && map.get(key) != null ? map.get(key) : Collections.<T>emptyList(); } public static void ensureClosed(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ignored) { // NOPMD } } } /** * Resolves the last type parameter of the parameterized {@code supertype}, based on the {@code * genericContext}, into its upper bounds. <p/> Implementation copied from {@code * retrofit.RestMethodInfo}. * * @param genericContext Ex. {@link java.lang.reflect.Field#getGenericType()} * @param supertype Ex. {@code Decoder.class} * @return in the example above, the type parameter of {@code Decoder}. * @throws IllegalStateException if {@code supertype} cannot be resolved into a parameterized type * using {@code context}. */ public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException { Type resolvedSuperType = Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype); checkState(resolvedSuperType instanceof ParameterizedType, "could not resolve %s into a parameterized type %s", genericContext, supertype); Type[] types = ParameterizedType.class.cast(resolvedSuperType).getActualTypeArguments(); for (int i = 0; i < types.length; i++) { Type type = types[i]; if (type instanceof WildcardType) { types[i] = ((WildcardType) type).getUpperBounds()[0]; } } return types[types.length - 1]; } /** * Adapted from {@code com.google.common.io.CharStreams.toString()}. */ public static String toString(Reader reader) throws IOException { if (reader == null) { return null; } try { StringBuilder to = new StringBuilder(); CharBuffer buf = CharBuffer.allocate(BUF_SIZE); while (reader.read(buf) != -1) { buf.flip(); to.append(buf); buf.clear(); } return to.toString(); } finally { ensureClosed(reader); } } /** * Adapted from {@code com.google.common.io.ByteStreams.toByteArray()}. */ public static byte[] toByteArray(InputStream in) throws IOException { checkNotNull(in, "in"); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toByteArray(); } finally { ensureClosed(in); } } /** * Adapted from {@code com.google.common.io.ByteStreams.copy()}. */ private static long copy(InputStream from, OutputStream to) throws IOException { checkNotNull(from, "from"); checkNotNull(to, "to"); byte[] buf = new byte[BUF_SIZE]; long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } static String decodeOrDefault(byte[] data, Charset charset, String defaultValue) { if (data == null) { return defaultValue; } checkNotNull(charset, "charset"); try { return charset.newDecoder().decode(ByteBuffer.wrap(data)).toString(); } catch (CharacterCodingException ex) { return defaultValue; } } }
3e044e93458869998e739c8de5c11f7ebb6504cd
580
java
Java
src/StockIT-v1-release_source_from_JADX/sources/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylist.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-11-23T10:12:35.000Z
2021-11-23T10:12:35.000Z
src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylist.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
null
null
null
src/StockIT-v2-release_source_from_JADX/sources/com/google/android/exoplayer2/source/hls/playlist/HlsPlaylist.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-10-01T13:14:19.000Z
2021-10-01T13:14:19.000Z
32.222222
78
0.756897
1,800
package com.google.android.exoplayer2.source.hls.playlist; import com.google.android.exoplayer2.offline.FilterableManifest; import java.util.Collections; import java.util.List; public abstract class HlsPlaylist implements FilterableManifest<HlsPlaylist> { public final String baseUri; public final boolean hasIndependentSegments; public final List<String> tags; protected HlsPlaylist(String str, List<String> list, boolean z) { this.baseUri = str; this.tags = Collections.unmodifiableList(list); this.hasIndependentSegments = z; } }
3e044e9e97eae883e6e7075d948f912f0656b86e
1,813
java
Java
_src/Chapter08/Chapter08/Recipe03/src/rmqexample/ReliableClient.java
paullewallencom/rabbitmq-978-1-8495-1650-1
cbec48e514c2f3937c106ff4f4cba188629516c6
[ "Apache-2.0" ]
null
null
null
_src/Chapter08/Chapter08/Recipe03/src/rmqexample/ReliableClient.java
paullewallencom/rabbitmq-978-1-8495-1650-1
cbec48e514c2f3937c106ff4f4cba188629516c6
[ "Apache-2.0" ]
null
null
null
_src/Chapter08/Chapter08/Recipe03/src/rmqexample/ReliableClient.java
paullewallencom/rabbitmq-978-1-8495-1650-1
cbec48e514c2f3937c106ff4f4cba188629516c6
[ "Apache-2.0" ]
null
null
null
26.661765
125
0.691671
1,801
package rmqexample; import java.io.IOException; import java.util.Random; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class ReliableClient { protected Random rnd; protected Connection connection; protected Channel channel; public ReliableClient() { rnd = new Random(); } protected void waitForConnection() throws InterruptedException { while (true) { ConnectionFactory factory = new ConnectionFactory(); int delta = rnd.nextInt(Constants.hosts.length); Address[] addrArr = new Address[Constants.hosts.length]; for (int i = 0; i < Constants.hosts.length; ++i) { // let the hosts be tried in random order. int j = (i + delta) % Constants.hosts.length; addrArr[i] = new Address(Constants.hosts[j], Constants.port); } try { connection = factory.newConnection(addrArr); channel = connection.createChannel(); channel.queueDeclare(Constants.queue, Constants.durableQueue, Constants.exclusiveQueue, Constants.autodeleteQueue, null); return; } catch (Exception e) { e.printStackTrace(); // ignore errors. In a production case, it is important to // handle different kind of errors and give the application // some hint on what to do in case it is not possible to // connect after some timeouts, properly notifying persistent // errors disconnect(); Thread.sleep(1000); } } } protected void disconnect() { try { if (channel != null && channel.isOpen()) { channel.close(); channel = null; } if (connection != null && connection.isOpen()) { connection.close(); connection = null; } } catch (IOException e) { // just ignore e.printStackTrace(); } } }
3e044eb624a521e428e870ddbddbb51dcd5a83fc
1,835
java
Java
web/src/main/java/uk/ac/ebi/phenotype/comparator/GeneRowForHeatMap3IComparator.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
1
2018-04-03T06:44:47.000Z
2018-04-03T06:44:47.000Z
web/src/main/java/uk/ac/ebi/phenotype/comparator/GeneRowForHeatMap3IComparator.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
655
2016-05-16T13:04:02.000Z
2022-03-25T14:06:36.000Z
web/src/main/java/uk/ac/ebi/phenotype/comparator/GeneRowForHeatMap3IComparator.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
6
2017-06-16T13:43:37.000Z
2020-02-27T12:57:07.000Z
34.622642
98
0.693188
1,802
/******************************************************************************* * Copyright 2015 EMBL - European Bioinformatics Institute * * 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.ac.ebi.phenotype.comparator; import java.util.Comparator; import java.util.Map; import org.mousephenotype.cda.solr.web.dto.GeneRowForHeatMap; import org.mousephenotype.cda.solr.web.dto.HeatMapCell; public class GeneRowForHeatMap3IComparator implements Comparator<GeneRowForHeatMap> { @Override public int compare(GeneRowForHeatMap row1, GeneRowForHeatMap row2) { int score1 = scoreGeneRowForHeatMap(row1); int score2 = scoreGeneRowForHeatMap(row2); return Integer.compare(score2, score1); } private int scoreGeneRowForHeatMap(GeneRowForHeatMap row){ Map<String, HeatMapCell> cells = row.getXAxisToCellMap(); int score = 0; for (HeatMapCell cell : cells.values()){ if (cell.getStatus().equalsIgnoreCase(HeatMapCell.THREE_I_COULD_NOT_ANALYSE)){ score += 1; } else if (cell.getStatus().equalsIgnoreCase(HeatMapCell.THREE_I_DATA_ANALYSED_NOT_SIGNIFICANT)){ score += 2; } else if (cell.getStatus().equalsIgnoreCase(HeatMapCell.THREE_I_DEVIANCE_SIGNIFICANT)){ score += 20; } } return score; } }
3e044eb8aeafe9d542ed8e3dff0336bd926a5b75
246
java
Java
lab7/sentence-service/src/main/java/com/github/vlsidlyarevich/spring_cloud_starter/lab7/sentence_service/service/VerbService.java
vlsidlyarevich/spring-cloud-starter
439ae424c24b0be630f23d81ff89cf8f6070fe61
[ "MIT" ]
1
2018-02-23T17:34:52.000Z
2018-02-23T17:34:52.000Z
lab7/sentence-service/src/main/java/com/github/vlsidlyarevich/spring_cloud_starter/lab7/sentence_service/service/VerbService.java
vlsidlyarevich/spring-cloud-starter
439ae424c24b0be630f23d81ff89cf8f6070fe61
[ "MIT" ]
null
null
null
lab7/sentence-service/src/main/java/com/github/vlsidlyarevich/spring_cloud_starter/lab7/sentence_service/service/VerbService.java
vlsidlyarevich/spring-cloud-starter
439ae424c24b0be630f23d81ff89cf8f6070fe61
[ "MIT" ]
1
2021-01-09T13:34:18.000Z
2021-01-09T13:34:18.000Z
27.333333
95
0.845528
1,803
package com.github.vlsidlyarevich.spring_cloud_starter.lab7.sentence_service.service; import com.github.vlsidlyarevich.spring_cloud_starter.lab7.sentence_service.model.WordResponse; public interface VerbService { WordResponse getVerb(); }
3e044f59f2732644deee6f5ea1723cf8fc2c3563
480
java
Java
app/src/main/java/androidsamples/java/tictactoe/Player.java
dpungaliya/tic-tac-toe
80b7cf4507d0887528b4726c61de8c6e7804189a
[ "MIT" ]
null
null
null
app/src/main/java/androidsamples/java/tictactoe/Player.java
dpungaliya/tic-tac-toe
80b7cf4507d0887528b4726c61de8c6e7804189a
[ "MIT" ]
null
null
null
app/src/main/java/androidsamples/java/tictactoe/Player.java
dpungaliya/tic-tac-toe
80b7cf4507d0887528b4726c61de8c6e7804189a
[ "MIT" ]
null
null
null
24
82
0.791667
1,804
package androidsamples.java.tictactoe; import java.util.List; public interface Player { void setOnMoveListener(OnMoveListener listener); void setOnPresenceStatusChangeListener(OnPresenceStatusChangeListener listener); void notifyNextTurn(List<List<Integer>> locations); interface OnMoveListener { void onMove(int x, int y); } interface OnPresenceStatusChangeListener { void onPresenceStatusChange(PresenceStatus presenceStatus); } void onCleared(); }
3e04504118ed18e810c9746710172f268204d856
2,859
java
Java
testah-junit/src/main/java/org/testah/runner/performance/AbstractLongRunningTest.java
grpatil27/Testah
c48aaba5c2835f1078b706419d0680e2fb5f8568
[ "MIT" ]
null
null
null
testah-junit/src/main/java/org/testah/runner/performance/AbstractLongRunningTest.java
grpatil27/Testah
c48aaba5c2835f1078b706419d0680e2fb5f8568
[ "MIT" ]
null
null
null
testah-junit/src/main/java/org/testah/runner/performance/AbstractLongRunningTest.java
grpatil27/Testah
c48aaba5c2835f1078b706419d0680e2fb5f8568
[ "MIT" ]
null
null
null
43.318182
133
0.56978
1,805
package org.testah.runner.performance; import org.testah.TS; import org.testah.driver.http.requests.AbstractRequestDto; import org.testah.driver.http.response.ResponseDto; import org.testah.runner.HttpAkkaRunner; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; public abstract class AbstractLongRunningTest { /** * Execute the HTTP requests, gather and publish the statistics. * * @param loadTestDataGenerator the class that generates the requests * @param runProps properties that describe the test execution * @param publishers 0 or more ExecutionStatsPublisher, e.g. to push the statistics to Elasticsearch * @throws Exception when HTTP request generation fails */ public void executeTest(TestDataGenerator loadTestDataGenerator, TestRunProperties runProps, ExecutionStatsPublisher... publishers) throws Exception { List<ResponseDto> responses; runProps.setDomain(loadTestDataGenerator.getDomain()); TS.log().info(runProps.toString()); final HttpAkkaRunner akkaRunner = HttpAkkaRunner.getInstance(); long timeleft = runProps.getStopTime() - System.currentTimeMillis(); try { while (timeleft > 0) { List<ConcurrentLinkedQueue<AbstractRequestDto<?>>> concurrentLinkedQueues = loadTestDataGenerator.generateRequests(); for (ConcurrentLinkedQueue<AbstractRequestDto<?>> concurrentLinkedQueue : concurrentLinkedQueues) { try { responses = akkaRunner.runAndReport(runProps.getNumberOfAkkaThreads(), concurrentLinkedQueue, runProps.isVerbose()); if (publishers != null && publishers.length > 0) { for (ExecutionStatsPublisher publisher : publishers) { publisher.push(responses); } } // Take care of open sockets System.gc(); Thread.sleep(runProps.getMillisBetweenChunks()); timeleft = runProps.getStopTime() - System.currentTimeMillis(); TS.log().info("Time left (ms): " + timeleft); if (timeleft <= 0) { return; } } catch (Throwable t) { TS.log().warn("Exception while running tests!", t); } } } } finally { if (publishers != null && publishers.length > 0) { for (ExecutionStatsPublisher publisher : publishers) { publisher.cleanup(); } } } } }
3e0450af992a55a2f90f5612e58d302734e31cde
330
java
Java
src/main/java/structure/component/better_type/Leaf.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
src/main/java/structure/component/better_type/Leaf.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
src/main/java/structure/component/better_type/Leaf.java
yanan-zhu/design-pattern
5ffab8297212a4f938f985519b6000bbae96ad16
[ "Apache-2.0" ]
null
null
null
17.368421
48
0.627273
1,806
package structure.component.better_type; /** * Created by zhuyanan on 17/7/26. */ public class Leaf extends Component { private String name; public Leaf(String name) { this.name = name; } @Override public void printStruct(String preStr) { System.out.println(preStr + "-" + name); } }
3e045147674a6d6edbf2e9a5f0de042a386cc4ae
1,697
java
Java
src/openpaths/Vector3.java
FintanKelly/OpenPathsAnalyzer
cbf9c69d948116c77ddfb1b25392713b424f03a9
[ "MIT" ]
1
2016-01-24T01:56:53.000Z
2016-01-24T01:56:53.000Z
src/openpaths/Vector3.java
FintanKelly/OpenPathsAnalyzer
cbf9c69d948116c77ddfb1b25392713b424f03a9
[ "MIT" ]
null
null
null
src/openpaths/Vector3.java
FintanKelly/OpenPathsAnalyzer
cbf9c69d948116c77ddfb1b25392713b424f03a9
[ "MIT" ]
null
null
null
25.328358
211
0.621096
1,807
package openpaths; /** * Class that will handle the longitude, latitude, and altitude data * * @author Fintan Kelly */ public class Vector3 { /* Variables: - Floats that represent the location data */ private float longitude, latitude, altitude; /* Main Constructor: - Takes a new set of floats for the longitude, latitude, and altitude */ public Vector3(float newLongitude, float newLatitude, float newAltitude) { longitude = newLongitude; latitude = newLatitude; altitude = newAltitude; } /* Find Distance: - Finds the distance between two sets of location data */ public float findDistance(Vector3 secondVector) { return (float) Math.abs((Math.pow((Math.pow(latitude - secondVector.getLatitude(), 2) + Math.pow(longitude - secondVector.getLongitude(), 2) + Math.pow(altitude - secondVector.getAltitude(), 2)), 0.5))); } /* Return Longitude: - Returns the float that represents the longitude */ public float getLongitude() { return longitude; } /* Return Latitude: - Returns the float that represents the latitude */ public float getLatitude() { return latitude; } /* Return Altitude: - Returns the float that represents the altitude */ public float getAltitude() { return altitude; } /* String Representation: - Returns a String that shows the longitude, latitude, and altitude */ @Override public String toString() { return "Longitude: " + longitude + "\n" + "Latitude: " + latitude + "\n" + "Altitude: " + altitude + "\n"; } }
3e04514a107057c194071ae467f392a02cc44da3
4,431
java
Java
presto-main/src/main/java/com/facebook/presto/operator/scalar/ArraySortFunction.java
andytinycat/presto
48b632cb8c411461198869bd210a5649a27cefe8
[ "Apache-2.0" ]
456
2015-04-23T09:24:25.000Z
2022-01-11T08:49:25.000Z
presto-main/src/main/java/com/facebook/presto/operator/scalar/ArraySortFunction.java
andytinycat/presto
48b632cb8c411461198869bd210a5649a27cefe8
[ "Apache-2.0" ]
10
2015-08-02T15:37:23.000Z
2020-11-18T07:33:46.000Z
presto-main/src/main/java/com/facebook/presto/operator/scalar/ArraySortFunction.java
Myrthan/presto
deb1cd73fe05e04e10f653fa02d54fb804380de2
[ "Apache-2.0" ]
123
2015-04-30T04:04:40.000Z
2021-04-08T09:57:34.000Z
38.198276
179
0.722636
1,808
/* * 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.facebook.presto.operator.scalar; import com.facebook.presto.metadata.FunctionInfo; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.ParametricScalar; import com.facebook.presto.metadata.Signature; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.block.VariableWidthBlockBuilder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import io.airlift.slice.Slice; import java.lang.invoke.MethodHandle; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import static com.facebook.presto.metadata.Signature.orderableTypeParameter; import static com.facebook.presto.type.TypeUtils.readStructuralBlock; import static com.facebook.presto.type.TypeUtils.buildStructuralSlice; import static com.facebook.presto.type.TypeUtils.parameterizedTypeName; import static com.facebook.presto.util.Reflection.methodHandle; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; public final class ArraySortFunction extends ParametricScalar { public static final ArraySortFunction ARRAY_SORT_FUNCTION = new ArraySortFunction(); private static final String FUNCTION_NAME = "array_sort"; private static final Signature SIGNATURE = new Signature(FUNCTION_NAME, ImmutableList.of(orderableTypeParameter("E")), "array<E>", ImmutableList.of("array<E>"), false, false); private static final MethodHandle METHOD_HANDLE = methodHandle(ArraySortFunction.class, "sort", Type.class, Slice.class); @Override public Signature getSignature() { return SIGNATURE; } @Override public boolean isHidden() { return false; } @Override public boolean isDeterministic() { return true; } @Override public String getDescription() { return "Sorts the given array in ascending order according to the natural ordering of its elements."; } @Override public FunctionInfo specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { checkArgument(types.size() == 1, format("%s expects only one argument", FUNCTION_NAME)); Type type = types.get("E"); MethodHandle methodHandle = METHOD_HANDLE.bindTo(type); Signature signature = new Signature(FUNCTION_NAME, parameterizedTypeName("array", type.getTypeSignature()), parameterizedTypeName("array", type.getTypeSignature())); return new FunctionInfo(signature, getDescription(), isHidden(), methodHandle, isDeterministic(), false, ImmutableList.of(false)); } public static Slice sort(Type type, Slice encodedArray) { Block block = readStructuralBlock(encodedArray); List<Integer> positions = Ints.asList(new int[block.getPositionCount()]); for (int i = 0; i < block.getPositionCount(); i++) { positions.set(i, i); } Collections.sort(positions, new Comparator<Integer>() { @Override public int compare(Integer p1, Integer p2) { //TODO: This could be quite slow, it should use parametric equals return type.compareTo(block, p1, block, p2); } }); BlockBuilder blockBuilder = new VariableWidthBlockBuilder(new BlockBuilderStatus(), block.getSizeInBytes()); for (int position : positions) { type.appendTo(block, position, blockBuilder); } return buildStructuralSlice(blockBuilder); } }
3e0451fac0115dc76a5456f54ee286e3f69244e7
972
java
Java
Mage.Sets/src/mage/cards/s/SuChi.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/s/SuChi.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/s/SuChi.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
24.3
107
0.6893
1,809
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.Mana; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.effects.mana.BasicManaEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; /** * * @author LoneFox * */ public final class SuChi extends CardImpl { public SuChi(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT,CardType.CREATURE},"{4}"); this.subtype.add(SubType.CONSTRUCT); this.power = new MageInt(4); this.toughness = new MageInt(4); // When Su-Chi dies, add {C}{C}{C}{C}. this.addAbility(new DiesSourceTriggeredAbility(new BasicManaEffect(Mana.ColorlessMana(4)), false)); } private SuChi(final SuChi card) { super(card); } @Override public SuChi copy() { return new SuChi(this); } }
3e045215d149f0d6f7cff519940a72fec7232590
1,720
java
Java
src/main/java/org/segrada/model/prototype/IUserGroup.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
67
2015-09-14T08:45:42.000Z
2022-03-30T10:15:47.000Z
src/main/java/org/segrada/model/prototype/IUserGroup.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
59
2015-12-07T15:58:12.000Z
2022-02-27T20:53:45.000Z
src/main/java/org/segrada/model/prototype/IUserGroup.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
18
2015-11-28T03:58:02.000Z
2020-08-14T23:28:49.000Z
23.243243
119
0.693605
1,810
package org.segrada.model.prototype; import java.util.Map; /** * Copyright 2016 Maximilian Kalus [[email protected]] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * User Group model interface */ public interface IUserGroup extends SegradaEntity { //String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); /** * define user role * @param role to set * @param value to set the role to, 0 = unset/not active, 1 = active, other values may be set in certain circumstances */ void setRole(String role, int value); /** * set role to 1 * @param role to set */ void setRole(String role); /** * set role to 0 * @param role to unset */ void unsetRole(String role); /** * check whether role is not set 0 * @param role to check * @return true, if role not 0 */ boolean hasRole(String role); /** * get role value * @param role to check * @return value or 0 if role does not exist */ int getRole(String role); /** * get all roles * @return */ Map<String, Integer> getRoles(); /** * special types of groups have this property set */ String getSpecial(); void setSpecial(String special); }
3e045222cf7932d31abaafcf2df92f7d7979d6e7
3,908
java
Java
1-algorithm/13-leetcode/java/src/fundamentals/string/search/lc028_implementstrstr/Solution.java
cdai/interview
d2dfffb707eb32ee83ed9caecce5a4dce976ccb7
[ "MIT" ]
1
2020-01-06T08:40:36.000Z
2020-01-06T08:40:36.000Z
1-algorithm/13-leetcode/java/src/fundamentals/string/search/lc028_implementstrstr/Solution.java
cdai/interview
d2dfffb707eb32ee83ed9caecce5a4dce976ccb7
[ "MIT" ]
null
null
null
1-algorithm/13-leetcode/java/src/fundamentals/string/search/lc028_implementstrstr/Solution.java
cdai/interview
d2dfffb707eb32ee83ed9caecce5a4dce976ccb7
[ "MIT" ]
null
null
null
35.853211
162
0.486694
1,811
package fundamentals.string.search.lc028_implementstrstr; import java.util.Arrays; /** * Returns the index of the first occurrence of needle in haystack, * or -1 if needle is not part of haystack. */ public class Solution { public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.strStr("abcababdababaff", "ababa")); } public int strStr(String s, String t) { int[] f = computePrefixFunc(t); System.out.println(Arrays.toString(f)); int i, j; for (i = 0, j = 0; i < s.length() && j < t.length(); i++) { // never back up i while (j > 0 && s.charAt(i) != t.charAt(j)) j = f[j - 1]; // back up j recursively until next char matched if (s.charAt(i) == t.charAt(j)) j++; // if matched move j, otherwise give up current i and move onto next } return j == t.length() ? i - j : -1; } // Similar to strStr except compare t against itself private int[] computePrefixFunc(String t) { int[] f = new int[t.length()]; for (int i = 1, j = 0; i < t.length(); i++) { // now i = #matched while (j > 0 && t.charAt(i) != t.charAt(j)) j = f[j - 1]; if (t.charAt(i) == t.charAt(j)) j++; f[i] = j; } return f; } // 4AC. Brute force from <Algorithm,4e>. Prepare for KMP. public int strStr4(String s, String t) { if (s == null || t == null) return -1; int i, j; for (i = 0, j = 0; i < s.length() && j < t.length(); i++) { if (s.charAt(i) == t.charAt(j)) j++; else { // backup i and j i -= j; j = 0; } } return j == t.length() ? i - j : -1; } // My 3AC: O(MN) time public int strStr3(String s, String t) { if (t.isEmpty()) return 0; // error1: "",""=>0 "a",""=>0 for (int i = 0; i <= s.length() - t.length(); i++) { // error2: <= for (int j = 0; j < t.length(); j++) { if (s.charAt(i + j) != t.charAt(j)) break; if (j == t.length() - 1) return i; } } return -1; } public int strStr_shorter(String s, String t) { if (t.isEmpty()) return 0; for (int i = 0; i <= s.length() - t.length(); i++) for (int j = 0; j < t.length() && s.charAt(i + j) == t.charAt(j); j++) if (j == t.length() - 1) return i; return -1; } // Elegant brute force solution from leetcode discuss // JDK String.indexOf() is also brute force. O(MN) time. public int strStr2(String haystack, String needle) { for (int i = 0; ; i++) { for (int j = 0; ; j++) { if (j == needle.length()) return i; // Nice! Or j=len needs to be checked outside loop which is a mess if (i + j == haystack.length()) // These two if are guard condition for the following check return -1; // == is okay, since i + j starts from 0 if (haystack.charAt(i + j) != needle.charAt(j)) break; } } } // My 1AC public int strStr1(String haystack, String needle) { if (haystack == null || needle == null || haystack.length() < needle.length()) { // assert: both haystack and needle isn't NULL return -1; } for (int i = 0; i <= haystack.length() - needle.length(); i++) { // assert: haystack is longer than needle // Deal with smaller problem int j = 0; for ( ; j < needle.length() && (haystack.charAt(i+j) == needle.charAt(j)); j++) // assert: i+j < haystack.length (h.len-n.len+n.len-1=h.len-1 at most) ; if (j == needle.length()) { return i; } } return -1; } }
3e04525f65515a5a32c060b424cd011434f56bd1
1,109
java
Java
engine/src/main/java/org/teiid/security/Credentials.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
249
2015-01-04T12:32:56.000Z
2022-03-22T07:00:46.000Z
engine/src/main/java/org/teiid/security/Credentials.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
312
2015-01-06T19:01:51.000Z
2022-03-10T17:49:37.000Z
engine/src/main/java/org/teiid/security/Credentials.java
GavinRay97/teiid
f7ae9acdc372718e15aa9f5827b267dfd68db5a5
[ "Apache-2.0" ]
256
2015-01-06T18:14:39.000Z
2022-03-23T17:55:42.000Z
29.972973
75
0.738503
1,812
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.security; import java.io.Serializable; public class Credentials implements Serializable { private static final long serialVersionUID = 7453114713211221240L; private Object credentials; public Credentials(Object credentials) { this.credentials = credentials; } public Object getCredentials() { return credentials; } }