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
923dc5fecdd4e559c97962f1c1722140f39a3685
3,179
java
Java
jmix-ui/ui/src/main/java/io/jmix/ui/component/impl/ClipboardTriggerImpl.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
30
2019-02-26T07:42:11.000Z
2022-03-31T16:46:03.000Z
jmix-ui/ui/src/main/java/io/jmix/ui/component/impl/ClipboardTriggerImpl.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
909
2019-02-26T08:29:19.000Z
2022-03-31T16:56:18.000Z
jmix-ui/ui/src/main/java/io/jmix/ui/component/impl/ClipboardTriggerImpl.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
15
2019-05-08T19:17:03.000Z
2022-03-31T06:24:22.000Z
30.567308
96
0.664674
1,000,469
/* * Copyright 2019 Haulmont. * * 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.jmix.ui.component.impl; import io.jmix.core.common.event.Subscription; import io.jmix.ui.component.Button; import io.jmix.ui.component.ClipboardTrigger; import io.jmix.ui.component.TextInputField; import io.jmix.ui.widget.JmixCopyButtonExtension; import javax.annotation.Nullable; import java.util.function.Consumer; import static io.jmix.ui.widget.JmixCopyButtonExtension.browserSupportsCopy; import static io.jmix.ui.widget.JmixCopyButtonExtension.copyWith; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; public class ClipboardTriggerImpl extends AbstractFacet implements ClipboardTrigger { protected TextInputField<?> input; protected Button button; @Override public void setInput(@Nullable TextInputField<?> input) { this.input = input; checkInitialized(); } @Nullable @Override public TextInputField<?> getInput() { return input; } @Override public void setButton(@Nullable Button button) { if (this.button != null) { disableExtension(this.button); } this.button = button; checkInitialized(); } @Nullable @Override public Button getButton() { return button; } @Override public boolean isSupportedByWebBrowser() { return browserSupportsCopy(); } @Override public Subscription addCopyListener(Consumer<CopyEvent> listener) { return getEventHub().subscribe(CopyEvent.class, listener); } protected void disableExtension(Button button) { button.withUnwrapped(com.vaadin.ui.Button.class, vButton -> vButton.getExtensions().stream() .filter(e -> e instanceof JmixCopyButtonExtension) .findFirst() .ifPresent(vButton::removeExtension)); } protected void checkInitialized() { if (this.button != null && this.input != null) { // setup field CSS class for selector String generatedClassName = "copy-text-" + randomAlphanumeric(6); this.input.addStyleName(generatedClassName); button.withUnwrapped(com.vaadin.ui.Button.class, vButton -> { disableExtension(this.button); JmixCopyButtonExtension extension = copyWith(vButton, "." + generatedClassName); extension.addCopyListener(event -> publish(CopyEvent.class, new CopyEvent(this, event.isSuccess())) ); }); } } }
923dc62f7c44b7e76d9de5898d659ad0f37a55f4
549
java
Java
src/main/java/com/github/gingjing/plugin/generator/code/entity/GlobalConfig.java
GingJing/CodeFlutter
bdc4c58946ef5bce9babbe578da464b4e756ddb4
[ "Apache-2.0" ]
1
2020-07-30T05:45:34.000Z
2020-07-30T05:45:34.000Z
src/main/java/com/github/gingjing/plugin/generator/code/entity/GlobalConfig.java
GingJing/CodeFlutter
bdc4c58946ef5bce9babbe578da464b4e756ddb4
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/gingjing/plugin/generator/code/entity/GlobalConfig.java
GingJing/CodeFlutter
bdc4c58946ef5bce9babbe578da464b4e756ddb4
[ "Apache-2.0" ]
null
null
null
17.15625
62
0.701275
1,000,470
package com.github.gingjing.plugin.generator.code.entity; import com.github.gingjing.plugin.generator.code.ui.base.Item; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Objects; import java.util.StringJoiner; /** * 全局配置实体类 * * @author makejava * @version 1.0.0 * @since 2018/07/27 13:07 */ @Data @NoArgsConstructor @AllArgsConstructor public class GlobalConfig implements Item { /** * 名称 */ private String name; /** * 值 */ private String value; }
923dc65726312542c6faed3981c711c5fb7acc45
5,939
java
Java
src/main/java/ch/agent/crnickl/jdbc/ReadMethodsForValueType.java
jpvetterli/crnickl-jdbc
47dedda2b8abbf859c87c70b4df50db7cdbcadac
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/agent/crnickl/jdbc/ReadMethodsForValueType.java
jpvetterli/crnickl-jdbc
47dedda2b8abbf859c87c70b4df50db7cdbcadac
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/agent/crnickl/jdbc/ReadMethodsForValueType.java
jpvetterli/crnickl-jdbc
47dedda2b8abbf859c87c70b4df50db7cdbcadac
[ "Apache-2.0" ]
null
null
null
36.660494
158
0.742549
1,000,471
/* * Copyright 2012-2013 Hauser Olsson GmbH * * 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 ch.agent.crnickl.jdbc; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import ch.agent.crnickl.T2DBException; import ch.agent.crnickl.T2DBMsg; import ch.agent.crnickl.T2DBMsg.E; import ch.agent.crnickl.api.DBObjectType; import ch.agent.crnickl.api.Database; import ch.agent.crnickl.api.Surrogate; import ch.agent.crnickl.api.ValueType; import ch.agent.crnickl.impl.ValueTypeImpl; /** * A stateless object with methods providing read access to value types. * * @author Jean-Paul Vetterli */ public class ReadMethodsForValueType extends JDBCDatabaseMethods { public ReadMethodsForValueType() { } private PreparedStatement select_valuetype_by_name; private static final String SELECT_VALUETYPE_BY_NAME = "select id, restricted, scanner, lastmod " + "from " + DB.VALUE_TYPE + " where label = ?"; /** * Find a value type with a given name. * * @param database a database * @param name a string * @return a value type or null * @throws T2DBException */ public <T>ValueType<T> getValueType(Database database, String name) throws T2DBException { try { select_valuetype_by_name = open(SELECT_VALUETYPE_BY_NAME, database, select_valuetype_by_name); select_valuetype_by_name.setString(1, name); ResultSet rs = select_valuetype_by_name.executeQuery(); if (rs.next()) { Surrogate surrogate = makeSurrogate(database, DBObjectType.VALUE_TYPE, rs.getInt(1)); return getValueType(surrogate, name, rs.getBoolean(2), rs.getString(3)); } else return null; } catch (Exception e) { throw T2DBMsg.exception(e, E.E10104, name); } finally { select_valuetype_by_name = close(select_valuetype_by_name); } } private PreparedStatement select_valuetype_by_pattern; private static final String SELECT_VALUETYPE_BY_PATTERN = "select id, label, restricted, scanner, lastmod " + "from " + DB.VALUE_TYPE + " where label like ? order by label"; /** * Find a collection of value types with names matching a pattern. * * @param database a database * @param pattern a simple pattern where "*" stands for zero or more characters * @return a collection of value types, possibly empty, never null * @throws T2DBException */ public Collection<ValueType<?>> getValueTypes(Database database, String pattern) throws T2DBException { if (pattern == null) pattern = "*"; pattern = pattern.replace('*', '%'); Collection<ValueType<?>> result = new ArrayList<ValueType<?>>(); try { select_valuetype_by_pattern = open(SELECT_VALUETYPE_BY_PATTERN, database, select_valuetype_by_pattern); select_valuetype_by_pattern.setString(1, pattern); ResultSet rs = select_valuetype_by_pattern.executeQuery(); while(rs.next()) { Surrogate surrogate = makeSurrogate(database, DBObjectType.VALUE_TYPE, rs.getInt(1)); result.add(getValueType(surrogate, rs.getString(2), rs.getBoolean(3), rs.getString(4))); } return result; } catch (Exception e) { throw T2DBMsg.exception(e, E.E10106, pattern); } finally { select_valuetype_by_pattern = close(select_valuetype_by_pattern); } } private PreparedStatement select_valuetype_by_id; private static final String SELECT_VALUETYPE_BY_ID = "select label, restricted, scanner, lastmod " + "from " + DB.VALUE_TYPE + " where id = ?"; /** * Find a value type corresponding to a surrogate. * * @param surrogate a surrogate * @return a value type or null * @throws T2DBException */ public <T>ValueType<T> getValueType(Surrogate surrogate) throws T2DBException { try { select_valuetype_by_id = open(SELECT_VALUETYPE_BY_ID, surrogate, select_valuetype_by_id); select_valuetype_by_id.setInt(1, getId(surrogate)); ResultSet rs = select_valuetype_by_id.executeQuery(); if (rs.next()) return getValueType(surrogate, rs.getString(1), rs.getBoolean(2), rs.getString(3)); else return null; } catch (Exception e) { throw T2DBMsg.exception(e, E.E10105, surrogate.toString()); } finally { select_valuetype_by_id = close(select_valuetype_by_id); } } private PreparedStatement select_valuelist_by_id; private static final String SELECT_VALUELIST_BY_ID = "select value, descrip from " + DB.VALUE_TYPE_VALUE + " where type = ? order by value"; private Map<String, String> getValues(Surrogate surrogate) throws T2DBException, SQLException { Map<String, String> values = new LinkedHashMap<String, String>(); try { select_valuelist_by_id = open(SELECT_VALUELIST_BY_ID, surrogate, select_valuelist_by_id); select_valuelist_by_id.setInt(1, getId(surrogate)); ResultSet rs = select_valuelist_by_id.executeQuery(); while (rs.next()) { values.put(rs.getString(1), rs.getString(2)); } } finally { select_valuelist_by_id = close(select_valuelist_by_id); } return values; } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T>ValueType<T> getValueType(Surrogate surrogate, String name, boolean restricted, String scannerClassOrKeyword) throws T2DBException, SQLException { Map<String, String> values = null; if (restricted) values = getValues(surrogate); return new ValueTypeImpl(name, restricted, scannerClassOrKeyword, values, surrogate); } }
923dc6592f3cd458c13306b7d9bc56c0ba70a47d
4,090
java
Java
sharding-influxdb/src/main/java/com/eeeffff/hasentinel/influxdb/service/impl/SortedMetricSentinelDataService.java
fenglibin/HASentinel
5c2a887ac26be68f689a8c73ee51b01574ceea22
[ "Apache-2.0" ]
8
2021-07-01T09:47:05.000Z
2022-03-02T13:50:18.000Z
sharding-influxdb/src/main/java/com/eeeffff/hasentinel/influxdb/service/impl/SortedMetricSentinelDataService.java
fenglibin/HASentinel
5c2a887ac26be68f689a8c73ee51b01574ceea22
[ "Apache-2.0" ]
null
null
null
sharding-influxdb/src/main/java/com/eeeffff/hasentinel/influxdb/service/impl/SortedMetricSentinelDataService.java
fenglibin/HASentinel
5c2a887ac26be68f689a8c73ee51b01574ceea22
[ "Apache-2.0" ]
1
2022-03-02T13:50:16.000Z
2022-03-02T13:50:16.000Z
32.460317
109
0.711002
1,000,472
package com.eeeffff.hasentinel.influxdb.service.impl; import java.lang.reflect.Field; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.eeeffff.hasentinel.common.config.HASentineConfigProperties; import com.eeeffff.hasentinel.common.entity.MetricEntity; import com.eeeffff.hasentinel.influxdb.constant.HttpConstant; import com.eeeffff.hasentinel.influxdb.entity.Metric; import com.eeeffff.hasentinel.influxdb.service.SentinelDataService; import com.eeeffff.hasentinel.influxdb.util.HttpClientUtil; import com.eeeffff.hasentinel.influxdb.util.sqlparser.SqlMeta; import com.eeeffff.hasentinel.influxdb.vo.Result; import lombok.extern.slf4j.Slf4j; @Service(value = "sortedMetricSentinelDataService") @Slf4j public class SortedMetricSentinelDataService implements SentinelDataService { @Autowired private HASentineConfigProperties sentineConfigProperties; @Override public String getServiceName() { return "T"; } @Override public Metric queryMetricFromSentinelServer(Integer page, Integer size, SqlMeta sqlMeta) { // 获取组装好字段的Metric对象 Metric metric = Metric.getEmptyMetricWithColumns( sqlMeta.getFiledNames().toArray(new String[sqlMeta.getFiledNames().size()])); // 获取资源类型 // 查询Reousrce的类型,type默认为空表示全部类型的资源,WEB表示只查询WEB类型的资源,DUBBO表示只查询DUBBO类型的资源,OTHER表示查询除WEB及DUBBO以外类型的资源 String type = (String) sqlMeta.getWhereKeyValues().get("type"); // 获取是否需要超期的数据 boolean noExpire = (Boolean) Optional.ofNullable(sqlMeta.getWhereKeyValues().get("noExpire")).orElse(true); // 获取Sentinel Server的地址 String sentinelServer = sentineConfigProperties.getSentinelServer(); // 获取分页数据 page = page == null ? 1 : page; size = size == null ? 100 : size; // 如果在SQL中指定了limit数据,则取sql中的指定的数据 size = sqlMeta.getLimit() > 0 ? sqlMeta.getLimit() : size; // 拼装访问的URL StringBuilder url = new StringBuilder(); if (!sentinelServer.startsWith(HttpConstant.HTTP_PREFIX)) { url.append(HttpConstant.HTTP_PREFIX); } url.append(sentinelServer).append("/metric/getLastResourceSortedMetricAll.json?page=").append(page) .append("&size=").append(size).append("&type=").append(type).append("&withExpireData=") .append(!noExpire); log.info("Query url:" + url); String result = HttpClientUtil.doGet(url.toString()); Result<List<MetricEntity>> httpResult = JSON.parseObject(result, new TypeReference<Result<List<MetricEntity>>>() { }); if (httpResult == null || CollectionUtils.isEmpty(httpResult.getData())) { return metric; } httpResult.getData().stream().filter(new Predicate<MetricEntity>() { // 过滤掉结果为空的记录 @Override public boolean test(MetricEntity t) { if (t == null) { return false; } return true; } }).sorted(new Comparator<MetricEntity>() { // 按平均响应时间由高到低排序 @Override public int compare(MetricEntity o1, MetricEntity o2) { if (o1 == null && o2 != null) { return 1; } if (o1 != null && o2 == null) { return -1; } if (o1 == null && o2 == null) { return 0; } if (o1.getAvgRt() < o2.getAvgRt()) { return 1; } else if (o1.getAvgRt() > o2.getAvgRt()) { return -1; } return 0; } }).forEach(v -> { // 组装结果响应数据 String[] columns = metric.getResults().get(0).getSeries().get(0).getColumns(); Object[] objs = new Object[columns.length]; for (int index = 0; index < objs.length; index++) { try { if ("time".equals(columns[index])) { objs[index] = v.getTimestamp().getTime(); } else { Field field = v.getClass().getDeclaredField(columns[index]); field.setAccessible(true); objs[index] = field.get(v); } } catch (Exception e) { log.error(e.toString(), e); } } metric.getResults().get(0).getSeries().get(0).getValues().add(objs); }); return metric; } }
923dc67011d57f4f530b10cb88dd5531ce8c4cc1
619
java
Java
src/main/java/joshie/enchiridion/gui/book/buttons/ButtonInsertItem.java
TeamHarvest/Enchiridion
5693983ad572c6a994601f6c2bd5a35630759934
[ "MIT" ]
7
2016-11-06T23:16:32.000Z
2020-02-17T00:42:23.000Z
src/main/java/joshie/enchiridion/gui/book/buttons/ButtonInsertItem.java
TeamHarvest/Enchiridion
5693983ad572c6a994601f6c2bd5a35630759934
[ "MIT" ]
47
2016-08-10T17:56:01.000Z
2021-02-01T13:57:22.000Z
src/main/java/joshie/enchiridion/gui/book/buttons/ButtonInsertItem.java
TeamHarvest/Enchiridion
5693983ad572c6a994601f6c2bd5a35630759934
[ "MIT" ]
7
2016-09-26T00:55:26.000Z
2020-04-28T22:07:56.000Z
32.578947
91
0.733441
1,000,473
package joshie.enchiridion.gui.book.buttons; import joshie.enchiridion.EConfig; import joshie.enchiridion.api.EnchiridionAPI; import joshie.enchiridion.api.book.IPage; import joshie.enchiridion.gui.book.features.FeatureItem; public class ButtonInsertItem extends ButtonAbstract { public ButtonInsertItem() { super("item"); } @Override public void performAction() { IPage current = EnchiridionAPI.book.getPage(); FeatureItem feature = new FeatureItem(EConfig.getDefaultItem()); current.addFeature(feature, 0, current.getScroll(), 16D, 16D, false, false, false); } }
923dc6964823904a170e6301bd617f81f7673de4
310
java
Java
core/src/com/levien/synthesizer/core/model/rawaudio/PcmSeamlessMixerL2Cache.java
eeshvardasikcm/music-synthesizer-for-android-old
0c5d69114d4b4d5347cdba30f91b04e21f8afc3c
[ "Apache-2.0" ]
1
2022-02-22T08:14:35.000Z
2022-02-22T08:14:35.000Z
core/src/com/levien/synthesizer/core/model/rawaudio/PcmSeamlessMixerL2Cache.java
eeshvardasikcm/music-synthesizer-for-android-old
0c5d69114d4b4d5347cdba30f91b04e21f8afc3c
[ "Apache-2.0" ]
null
null
null
core/src/com/levien/synthesizer/core/model/rawaudio/PcmSeamlessMixerL2Cache.java
eeshvardasikcm/music-synthesizer-for-android-old
0c5d69114d4b4d5347cdba30f91b04e21f8afc3c
[ "Apache-2.0" ]
null
null
null
28.181818
65
0.787097
1,000,474
package com.levien.synthesizer.core.model.rawaudio; /** * PcmSeamlessMixerL2Cache mixes cached audio in together so that * when synthesizer settings are not being modified, a constant * seamless pcm audio stream loop can be outputed * from raw audio cache */ public interface PcmSeamlessMixerL2Cache { }
923dc6a4f80e5a2069aec5e61f7af3d6c25c7503
5,879
java
Java
src/main/java/com/kanomiya/mcmod/seikacreativemod/block/BlockPreparation.java
kanomiya/SeikaCreativeMod
25f7a3fe6fa0e42a2576ca0ddfd95d0d88969030
[ "MIT" ]
null
null
null
src/main/java/com/kanomiya/mcmod/seikacreativemod/block/BlockPreparation.java
kanomiya/SeikaCreativeMod
25f7a3fe6fa0e42a2576ca0ddfd95d0d88969030
[ "MIT" ]
null
null
null
src/main/java/com/kanomiya/mcmod/seikacreativemod/block/BlockPreparation.java
kanomiya/SeikaCreativeMod
25f7a3fe6fa0e42a2576ca0ddfd95d0d88969030
[ "MIT" ]
null
null
null
27.731132
193
0.692465
1,000,475
package com.kanomiya.mcmod.seikacreativemod.block; import com.kanomiya.mcmod.seikacreativemod.SeikaCreativeMod; import com.kanomiya.mcmod.seikacreativemod.tileentity.TileEntityPreparation; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; public class BlockPreparation extends BlockContainer { public BlockPreparation() { super(Material.GROUND); setCreativeTab(SeikaCreativeMod.tabSeika); setUnlocalizedName("blockPreparation"); setHardness(0.5f); setResistance(1.0f); setSoundType(SoundType.STONE); } // RS切断 @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { if (worldIn.isRemote) return false; if (hand == EnumHand.OFF_HAND) return false; TileEntityPreparation te = (TileEntityPreparation) worldIn.getTileEntity(pos); if (te == null) return false; if (heldItem != null) { if (heldItem.getItem() instanceof ItemBlock) { Block block = Block.getBlockFromItem(heldItem.getItem()); if (te.setmode) { te.setTgtState(block.getStateFromMeta(heldItem.getMetadata())); playerIn.addChatMessage(new TextComponentString( "Set the target as " + block.getLocalizedName())); } else { te.setPutState(Block.getStateById(heldItem.getMetadata())); playerIn.addChatMessage(new TextComponentString( "Set new block as " + te.getPutState().getBlock().getLocalizedName())); } te.setmode = ! te.setmode; } else if (heldItem.getItem() == Items.GUNPOWDER) { if (te.sidelength < 96) { EntityPlayerMP emp = (EntityPlayerMP) playerIn; if (!emp.interactionManager.getGameType() .isCreative()) { heldItem = heldItem.splitStack(heldItem.stackSize - 1); } te.sidelength += 4; playerIn.addChatMessage(new TextComponentString( "Set the power as " + te.sidelength)); } else { playerIn.addChatMessage(new TextComponentString( "The power is maximum(96).")); } } else if (heldItem.getItem() == Items.WATER_BUCKET) { Block block = Blocks.WATER; if (te.setmode) { te.setTgtState(block.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set the target as " + block.getLocalizedName())); } else { te.setPutState(block.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set new block as " + block.getLocalizedName())); } te.setmode = ! te.setmode; } else if (heldItem.getItem() == Items.LAVA_BUCKET) { Block block = Blocks.LAVA; if (te.setmode) { te.setTgtState(block.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set the target as " + block.getLocalizedName())); } else { te.setPutState(block.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set new block as " + block.getLocalizedName())); } } else { return false; } } else { if (te.setmode) { te.setTgtState(Blocks.AIR.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set the target as All")); } else { te.setPutState(Blocks.AIR.getDefaultState()); playerIn.addChatMessage(new TextComponentString( "Set new block as Air")); } te.setmode = ! te.setmode; } return true; } @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { onBlockAdded(worldIn, pos, state); } @Override public void onBlockAdded(World world, BlockPos pos, IBlockState state) { if (world.isRemote) { return ; } TileEntityPreparation te = (TileEntityPreparation) world.getTileEntity(pos); if (world.isBlockPowered(pos)) { if (te == null) { return ; } int r = te.sidelength; IBlockState putBlock = te.getPutState(); IBlockState delBlock = te.getTgtState(); if ((delBlock.getBlock() == Blocks.AIR && putBlock.getBlock() != Blocks.AIR) || (r == 0)) { SoundType soundtype = putBlock.getBlock().getSoundType(); world.playSound(pos.getX(), pos.getY(), pos.getZ(), soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, true); return ; } for (int i= -r; i<=r; i++) { for (int ii= 0; ii<255 -pos.getY(); ii++) { for (int iii= -r; iii<=r; iii++) { BlockPos newPos = pos.add(i,ii,iii); if (! world.isAirBlock(newPos)) { if (delBlock.getBlock() == Blocks.AIR || world.getBlockState(newPos) == delBlock) { world.setBlockState(newPos, putBlock); } } } } } world.setBlockToAir(pos); te.setPrevRSState(true); } else { te.setPrevRSState(false); } } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileEntityPreparation(); } @Override public EnumBlockRenderType getRenderType(IBlockState state) { return EnumBlockRenderType.MODEL; } }
923dc6bf8a2487b19f4aed6ef0605181ad3a2487
5,446
java
Java
code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java
opengauss-mirror/DataStudio
d240050ffb29fa96cbc8ae69e6d6a2e20525a277
[ "CC-BY-4.0" ]
null
null
null
code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java
opengauss-mirror/DataStudio
d240050ffb29fa96cbc8ae69e6d6a2e20525a277
[ "CC-BY-4.0" ]
null
null
null
code/datastudio/src/org.opengauss.mppdbide.presentation/src-test/org/opengauss/mppdbide/test/presentation/table/ERDiagramPresentationTest.java
opengauss-mirror/DataStudio
d240050ffb29fa96cbc8ae69e6d6a2e20525a277
[ "CC-BY-4.0" ]
null
null
null
44.639344
104
0.754131
1,000,476
package org.opengauss.mppdbide.test.presentation.table; import static org.junit.Assert.assertTrue; import java.sql.SQLException; import java.util.Arrays; import java.util.Iterator; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.opengauss.mppdbide.adapter.gauss.DBConnection; import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager; import org.opengauss.mppdbide.bl.preferences.IBLPreference; import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileId; import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl; import org.opengauss.mppdbide.bl.serverdatacache.DBConnProfCache; import org.opengauss.mppdbide.bl.serverdatacache.Database; import org.opengauss.mppdbide.bl.serverdatacache.JobCancelStatus; import org.opengauss.mppdbide.bl.serverdatacache.Server; import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo; import org.opengauss.mppdbide.bl.serverdatacache.groups.TableObjectGroup; import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions; import org.opengauss.mppdbide.mock.presentation.CommonLLTUtils; import org.opengauss.mppdbide.presentation.erd.ERDiagramPresentation; import org.opengauss.mppdbide.presentation.userrole.GrantRevokeCore; import org.opengauss.mppdbide.utils.exceptions.DatabaseCriticalException; import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException; import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility; import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter; import com.mockrunner.jdbc.PreparedStatementResultSetHandler; import com.mockrunner.jdbc.StatementResultSetHandler; import com.mockrunner.mock.jdbc.MockConnection; public class ERDiagramPresentationTest extends BasicJDBCTestCaseAdapter { MockConnection connection = null; PreparedStatementResultSetHandler preparedstatementHandler = null; StatementResultSetHandler statementHandler = null; PreparedStatementResultSetHandler epreparedstatementHandler = null; StatementResultSetHandler estatementHandler = null; DBConnProfCache connProfCache = null; ConnectionProfileId profileId = null; Database database; DBConnection dbconn; GrantRevokeCore grantRevokeCore; @Before public void setUp() throws Exception { super.setUp(); CommonLLTUtils.runLinuxFilePermissionInstance(); IBLPreference sysPref = new MockPresentationBLPreferenceImpl(); BLPreferenceManager.getInstance().setBLPreference(sysPref); MockPresentationBLPreferenceImpl.setDsEncoding("UTF-8"); connection = new MockConnection(); MPPDBIDELoggerUtility.setArgs(new String[] {"-logfolder=.", "-detailLogging=true"}); getJDBCMockObjectFactory().getMockDriver().setupConnection(connection); CommonLLTUtils.mockConnection(getJDBCMockObjectFactory().getMockDriver()); preparedstatementHandler = connection.getPreparedStatementResultSetHandler(); statementHandler = connection.getStatementResultSetHandler(); CommonLLTUtils.prepareProxyInfo(preparedstatementHandler); connProfCache = DBConnProfCache.getInstance(); ServerConnectionInfo serverInfo = new ServerConnectionInfo(); serverInfo.setConectionName("TestConnectionName"); serverInfo.setServerIp(""); serverInfo.setServerPort(5432); serverInfo.setDriverName("FusionInsight LibrA"); serverInfo.setDatabaseName("Gauss"); serverInfo.setUsername("myusername"); serverInfo.setPrd("mypassword".toCharArray()); serverInfo.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE); serverInfo.setPrivilegeBasedObAccess(true); ConnectionProfileManagerImpl.getInstance().getDiskUtility().setOsCurrentUserFolderPath("."); ConnectionProfileManagerImpl.getInstance().generateSecurityFolderInsideProfile(serverInfo); CommonLLTUtils.createTableSpaceRS(preparedstatementHandler); JobCancelStatus status = new JobCancelStatus(); status.setCancel(false); profileId = connProfCache.initConnectionProfile(serverInfo, status); database = connProfCache.getDbForProfileId(profileId); dbconn = CommonLLTUtils.getDBConnection(); } @After public void tearDown() throws Exception { super.tearDown(); Database database = connProfCache.getDbForProfileId(profileId); database.getServer().close(); preparedstatementHandler.clearPreparedStatements(); preparedstatementHandler.clearResultSets(); statementHandler.clearStatements(); connProfCache.closeAllNodes(); Iterator<Server> itr = connProfCache.getServers().iterator(); while (itr.hasNext()) { connProfCache.removeServer(itr.next().getId()); } connProfCache.closeAllNodes(); } @Test public void init_test() throws DatabaseCriticalException, DatabaseOperationException, SQLException { TableObjectGroup tablesGroup = database.getAllNameSpaces().get(0).getTablesGroup(); ERDiagramPresentation presentation = new ERDiagramPresentation(tablesGroup, dbconn); presentation.initERPresentation(); assertTrue(presentation.getWindowTitle() != null); } }
923dc75afbd071a906994998f6f4e676027e08c1
7,404
java
Java
src/com/misacfd/meshconverter/FvMsh.java
truongd8593/MisaCFDJava
694068dc3a6c64bc48c09329b99f8ff36da4c76c
[ "MIT" ]
1
2021-11-18T03:42:18.000Z
2021-11-18T03:42:18.000Z
src/com/misacfd/meshconverter/FvMsh.java
truongd8593/CFDJava
694068dc3a6c64bc48c09329b99f8ff36da4c76c
[ "MIT" ]
null
null
null
src/com/misacfd/meshconverter/FvMsh.java
truongd8593/CFDJava
694068dc3a6c64bc48c09329b99f8ff36da4c76c
[ "MIT" ]
null
null
null
33.502262
86
0.491086
1,000,477
package com.misacfd.meshconverter; import sun.security.x509.OtherName; import java.io.*; import java.util.ArrayList; import java.util.List; public class FvMsh { GmshReader mshReader; List<FvCell> cells; public FvMsh(GmshReader mshReader, List<FvCell> cells) { this.mshReader = mshReader; this.cells = cells; } public FvMsh(GmshReader mshReader) { this.mshReader = mshReader; this.cells = new ArrayList<>(); } public GmshReader getMshReader() { return mshReader; } public void setMshReader(GmshReader mshReader) { this.mshReader = mshReader; } public List<FvCell> getCells() { return cells; } public void setCells(List<FvCell> cells) { this.cells = cells; } public void assignVertex() { List<Point> coordNodes = mshReader.getCoordNodes(); for (int i = 0; i < mshReader.getNbElm(); i++) { FvCell aCell = new FvCell(); List<Point> vertex = new ArrayList<>(); aCell.setIdent(i); NodeIdent nodeIdent = mshReader.getIdNodes().get(i); for (int j = 5; j < 9; j++) { long idNode = nodeIdent.getIdNode().get(j); for (Point node : coordNodes) { if (idNode == node.getIdent()) { vertex.add(node); break; } } } aCell.setVertex(vertex); this.cells.add(aCell); } } public void assignFaces() { for (FvCell currentCell : cells) { List<Face> faces = new ArrayList<>(); List<Point> vertex = currentCell.getVertex(); Point p1 = vertex.get(0); Point p2 = vertex.get(1); Face face = new Face(); face.setP1(p1).setP2(p2); faces.add(face); p1 = vertex.get(1); p2 = vertex.get(2); face.setP1(p1).setP2(p2); faces.add(face); p1 = vertex.get(2); p2 = vertex.get(3); face.setP1(p1).setP2(p2); faces.add(face); p1 = vertex.get(3); p2 = vertex.get(0); face.setP1(p1).setP2(p2); faces.add(face); currentCell.setFaces(faces); } } public void assignBoundaryCondition() { } public void detectNearestNeighbor() { for (FvCell currentCell : cells) { long idNode1 = currentCell.getVertex().get(0).getIdent(); long idNode2 = currentCell.getVertex().get(1).getIdent(); for (FvCell anotherCell : cells) { if (anotherCell == currentCell) { // do nothing } else { int count = 0; if (idNode1 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(3).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(3).getIdent()) count++; if (count == 2) { currentCell.setNeighbor(anotherCell); } } } } for (FvCell currentCell : cells) { long idNode1 = currentCell.getVertex().get(1).getIdent(); long idNode2 = currentCell.getVertex().get(2).getIdent(); for (FvCell anotherCell : cells) { if (anotherCell == currentCell) { // do nothing } else { int count = 0; if (idNode1 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(3).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(3).getIdent()) count++; if (count == 2) { currentCell.setNeighbor(anotherCell); } } } } for (FvCell currentCell : cells) { long idNode1 = currentCell.getVertex().get(2).getIdent(); long idNode2 = currentCell.getVertex().get(3).getIdent(); for (FvCell anotherCell : cells) { if (anotherCell == currentCell) { // do nothing } else { int count = 0; if (idNode1 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(3).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(3).getIdent()) count++; if (count == 2) { currentCell.setNeighbor(anotherCell); } } } } for (FvCell currentCell : cells) { long idNode1 = currentCell.getVertex().get(3).getIdent(); long idNode2 = currentCell.getVertex().get(0).getIdent(); for (FvCell anotherCell : cells) { if (anotherCell == currentCell) { // do nothing } else { int count = 0; if (idNode1 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(0).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(1).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(2).getIdent()) count++; if (idNode1 == anotherCell.getVertex().get(3).getIdent()) count++; if (idNode2 == anotherCell.getVertex().get(3).getIdent()) count++; if (count == 2) { currentCell.setNeighbor(anotherCell); } } } } } }
923dc7eef208cd974ae15e1af455b739766b248c
804
java
Java
bpel-api/src/main/java/org/apache/ode/bpel/rapi/OdeRuntime.java
matthieu/apache-ode
5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6
[ "Apache-2.0" ]
1
2016-05-08T23:34:14.000Z
2016-05-08T23:34:14.000Z
bpel-api/src/main/java/org/apache/ode/bpel/rapi/OdeRuntime.java
matthieu/apache-ode
5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6
[ "Apache-2.0" ]
null
null
null
bpel-api/src/main/java/org/apache/ode/bpel/rapi/OdeRuntime.java
matthieu/apache-ode
5f8c77a7f4a13f800f79ab2ad79cc6abcf67afc6
[ "Apache-2.0" ]
1
2019-05-02T22:11:31.000Z
2019-05-02T22:11:31.000Z
27.724138
107
0.791045
1,000,478
package org.apache.ode.bpel.rapi; import org.apache.ode.bpel.iapi.ProcessConf; import org.apache.ode.bpel.common.FaultException; import org.apache.ode.bpel.extension.ExtensionBundleRuntime; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.util.Map; public interface OdeRuntime { void init(ProcessConf pconf, ProcessModel pmodel); OdeRTInstance newInstance(Object state); Object getReplacementMap(QName processName); ProcessModel getModel(); void clear(); String extractProperty(Element msgData, PropertyAliasModel alias, String target) throws FaultException; String extractMatch(Element msgData, PropertyExtractor extractor) throws FaultException; void setExtensionRegistry(Map<String, ExtensionBundleRuntime> extensionRegistry); }
923dc8354c6acee6d0f648fefb22f9db27ec6128
550
java
Java
src/test/java/lesson/reflection/ParentGeneric.java
tyrantqiao/algorithms
f21191608139ebaa2201169820b46c4400c690cf
[ "Apache-2.0" ]
null
null
null
src/test/java/lesson/reflection/ParentGeneric.java
tyrantqiao/algorithms
f21191608139ebaa2201169820b46c4400c690cf
[ "Apache-2.0" ]
1
2021-04-01T00:15:42.000Z
2021-04-01T00:15:42.000Z
src/test/java/lesson/reflection/ParentGeneric.java
tyrantqiao/Java-Algorithms
758c0a0d6a8e7fa87834b3bf9a529af8ff285429
[ "Apache-2.0" ]
null
null
null
21.269231
61
0.59132
1,000,479
package lesson.reflection; /** * @author tyrantqiao * @date 2020/8/20 * email: hzdkv@example.com */ public class ParentGeneric<T> { StringBuilder stringBuilder = new StringBuilder(); private T msg; public void setMsg(T msg) { System.out.println("parent try to set msg"); this.msg = msg; stringBuilder.append(",parent talked.\n"); } @Override public String toString() { return "ParentGeneric{" + "stringBuilder=" + stringBuilder.toString() + '}'; } }
923dc865d320cdeb1d4aecc97fa35f5a41824f4b
41,504
java
Java
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/editor/cmd/NodesMoveCommond.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/editor/cmd/NodesMoveCommond.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/editor/cmd/NodesMoveCommond.java
coheigea/tdi-studio-se
c4cd4df0fc841c497b51718e623145d29d0bf030
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
47.650976
142
0.558573
1,000,480
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.designer.core.ui.editor.cmd; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.EditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.commands.Command; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.ui.PlatformUI; import org.talend.commons.ui.runtime.exception.ExceptionHandler; import org.talend.core.CorePlugin; import org.talend.core.GlobalServiceRegister; import org.talend.core.model.components.IComponent; import org.talend.core.model.metadata.IMetadataColumn; import org.talend.core.model.metadata.IMetadataTable; import org.talend.core.model.process.EConnectionType; import org.talend.core.model.process.EParameterFieldType; import org.talend.core.model.process.IConnection; import org.talend.core.model.process.IConnectionCategory; import org.talend.core.model.process.IElementParameter; import org.talend.core.model.process.IExternalNode; import org.talend.core.model.process.INode; import org.talend.core.model.process.INodeConnector; import org.talend.core.model.process.IProcess; import org.talend.core.model.process.IProcess2; import org.talend.core.ui.IJobletProviderService; import org.talend.core.ui.component.ComponentsFactoryProvider; import org.talend.core.ui.process.IGraphicalNode; import org.talend.designer.core.i18n.Messages; import org.talend.designer.core.model.components.EParameterName; import org.talend.designer.core.model.components.ElementParameter; import org.talend.designer.core.ui.AbstractMultiPageTalendEditor; import org.talend.designer.core.ui.editor.TalendEditor; import org.talend.designer.core.ui.editor.connections.Connection; import org.talend.designer.core.ui.editor.jobletcontainer.JobletContainer; import org.talend.designer.core.ui.editor.nodecontainer.NodeContainer; import org.talend.designer.core.ui.editor.nodecontainer.NodeContainerPart; import org.talend.designer.core.ui.editor.nodes.Node; import org.talend.designer.core.ui.editor.nodes.NodePart; import org.talend.designer.core.ui.editor.process.Process; import org.talend.designer.core.ui.editor.process.ProcessPart; import org.talend.designer.core.ui.editor.subjobcontainer.SubjobContainer; import org.talend.designer.core.ui.editor.subjobcontainer.SubjobContainerPart; import org.talend.designer.core.utils.UpgradeElementHelper; /** * Command used to move all the components. $Id: NodesPasteCommand.java hwang class global comment. Detailled comment * */ public class NodesMoveCommond extends Command { private IProcess2 process; private List<NodeContainer> nodeContainerList; private List<EditPart> oldSelection; private INode node; private List<INode> nodes; private List<IConnection> connections; private List<String> createdNames; private boolean multipleCommand; Point cursorLocation = null; private List<SubjobContainerPart> subjobParts; /* * if true, all of properties will keep originally. feature 6131 */ private boolean isJobletRefactor = false; /** * Getter for cursorLocation. * * @return the cursorLocation */ public Point getCursorLocation() { return this.cursorLocation; } /** * Sets the cursorLocation. * * @param cursorLocation the cursorLocation to set */ public void setCursorLocation(Point cursorLocation) { this.cursorLocation = cursorLocation; } /** * * cLi Comment method "setJobletRefactor". * * feature 6131, refactor nodes to joblet. */ public void setJobletRefactor(boolean isJobletRefactor) { this.isJobletRefactor = isJobletRefactor; } public boolean isJobletRefactor() { return this.isJobletRefactor; } public NodesMoveCommond(List<INode> nodes, IProcess2 process, Point cursorLocation) { this.process = process; node = nodes.get(0); setCursorLocation(cursorLocation); orderNodes(nodes); setLabel(Messages.getString("NodesPasteCommand.label")); //$NON-NLS-1$ } @SuppressWarnings("unchecked") private String createNewConnectionName(String oldName, String baseName) { String newName = null; if (baseName != null) { for (String uniqueConnectionName : createdNames) { if (process.checkValidConnectionName(uniqueConnectionName, true)) { process.addUniqueConnectionName(uniqueConnectionName); } } newName = process.generateUniqueConnectionName(baseName); for (String uniqueConnectionName : createdNames) { if (!process.checkValidConnectionName(uniqueConnectionName, true)) { process.removeUniqueConnectionName(uniqueConnectionName); } } } else { if (process.checkValidConnectionName(oldName, true)) { newName = oldName; } else { newName = checkExistingNames("copyOf" + oldName); //$NON-NLS-1$ } newName = checkNewNames(newName, baseName); } createdNames.add(newName); return newName; } /* * (non-Javadoc) * * @see org.eclipse.gef.commands.Command#canExecute() */ @Override public boolean canExecute() { return true; } private void orderNodes(List<INode> nodes) { this.nodes = new ArrayList<INode>(); Point curLocation; INode toAdd = null; List<INode> restToOrder = new ArrayList<INode>(); restToOrder.addAll(nodes); for (INode copiedNode : nodes) { curLocation = null; for (INode nodeToOrder : restToOrder) { // IGraphicalNode copiedNode = (IGraphicalNode) nodeToOrder; if (curLocation == null) { curLocation = (Point) ((Node) copiedNode).getLocation(); toAdd = nodeToOrder; } else { if (curLocation.y >= ((Point) ((Node) copiedNode).getLocation()).y) { if (curLocation.x >= ((Point) ((Node) copiedNode).getLocation()).x) { curLocation = (Point) ((Node) copiedNode).getLocation(); toAdd = nodeToOrder; } } } } if (toAdd != null) { this.nodes.add(toAdd); restToOrder.remove(toAdd); } } } private String checkExistingNames(final String oldName) { String tmpName = oldName + "_"; //$NON-NLS-1$ String newName = oldName; int index = 0; while (!process.checkValidConnectionName(newName, true)) { newName = tmpName + (index++); } return newName; } private String checkNewNames(final String oldName, String baseName) { String tmpName = oldName + "_"; //$NON-NLS-1$ if (baseName != null) { tmpName = baseName; } String newName = oldName; int index = 0; while (createdNames.contains(newName)) { newName = tmpName + index++; } // check the name again in process. while (!process.checkValidConnectionName(newName, true)) { newName = tmpName + (index++); } return newName; } /** * * Will return a empty location for a component from a given point. * * @param location * @return */ private Point findLocationForNode(final Point location, final Dimension size, int index, int firstIndex, Node copiedNode) { Point newLocation = findLocationForNodeInProcess(location, size); newLocation = findLocationForNodeInContainerList(newLocation, size, index, firstIndex, copiedNode); return newLocation; } @SuppressWarnings("unchecked") private Point findLocationForNodeInProcess(final Point location, Dimension size) { Rectangle copiedRect = new Rectangle(location, size); Point newLocation = new Point(location); for (IGraphicalNode node : (List<IGraphicalNode>) process.getGraphicalNodes()) { Rectangle currentRect = new Rectangle((Point) node.getLocation(), (Dimension) node.getSize()); if (currentRect.intersects(copiedRect)) { newLocation.x += size.width; newLocation.y += size.height; return findLocationForNodeInProcess(newLocation, size); } } return newLocation; } private Point findLocationForNodeInContainerList(final Point location, Dimension size, int index, int firstIndex, Node copiedNode) { Rectangle copiedRect = new Rectangle(location, size); Point newLocation = new Point(location); if (getCursorLocation() == null) { for (NodeContainer nodeContainer : nodeContainerList) { IGraphicalNode node = nodeContainer.getNode(); Rectangle currentRect = new Rectangle((Point) node.getLocation(), (Dimension) node.getSize()); if (currentRect.intersects(copiedRect)) { newLocation.x += size.width; newLocation.y += size.height; // newLocation = computeTheDistance(index, firstIndex, newLocation); Point tmpPoint = findLocationForNodeInProcess(newLocation, size); return findLocationForNodeInContainerList(tmpPoint, size, index, firstIndex, copiedNode); } } return newLocation; } if (!node.equals(copiedNode)) { newLocation = computeTheDistance(index, firstIndex, newLocation); } return newLocation; } private Point computeTheDistance(int index, int firstIndex, Point location) { Point firstNodeLocation = ((IGraphicalNode) node).getLocation(); Point currentNodeLocation = ((IGraphicalNode) nodes.get(index)).getLocation(); int distanceX = firstNodeLocation.x - currentNodeLocation.x; int distanceY = firstNodeLocation.y - currentNodeLocation.y; location.x = location.x - distanceX; location.y = location.y - distanceY; return location; } private boolean containNodeInProcess(INode copiedNode) { if (copiedNode == null) { return false; } IProcess curNodeProcess = copiedNode.getProcess(); if (curNodeProcess != null) { List<? extends INode> graphicalNodes = curNodeProcess.getGraphicalNodes(); if (graphicalNodes != null) { for (INode node : graphicalNodes) { if (node == copiedNode) { return true; } } } } return false; } @SuppressWarnings("unchecked") private void createNodeContainerList() { int firstIndex = 0; int index = 0; nodeContainerList = new ArrayList<NodeContainer>(); connections = new ArrayList<IConnection>(); createdNames = new ArrayList<String>(); Map<String, String> oldNameTonewNameMap = new HashMap<String, String>(); Map<String, String> oldMetaToNewMeta = new HashMap<String, String>(); // see bug 0004882: Subjob title is not copied when copying/pasting subjobs from one job to another Map<INode, SubjobContainer> mapping = new HashMap<INode, SubjobContainer>(); IJobletProviderService service = (IJobletProviderService) GlobalServiceRegister.getDefault().getService( IJobletProviderService.class); // create the nodes for (INode copiedNode : nodes) { // IGraphicalNode copiedNode = (IGraphicalNode) copiedNodePart.getModel(); if (!containNodeInProcess(copiedNode)) { continue; } IComponent component = ComponentsFactoryProvider.getInstance().get(copiedNode.getComponent().getName(), copiedNode.getProcess().getComponentsType()); if (component == null) { component = copiedNode.getComponent(); } IGraphicalNode pastedNode = new Node(component, process); if (isJobletRefactor()) { // keep original for joblet refactor. process.removeUniqueNodeName(pastedNode.getUniqueName()); pastedNode.setPropertyValue(EParameterName.UNIQUE_NAME.getName(), copiedNode.getUniqueName()); process.addUniqueNodeName(copiedNode.getUniqueName()); } if (service != null) { if (service.isJobletInOutComponent(pastedNode)) { process.removeUniqueNodeName(pastedNode.getUniqueName()); pastedNode.setPropertyValue(EParameterName.UNIQUE_NAME.getName(), copiedNode.getUniqueName()); process.addUniqueNodeName(copiedNode.getUniqueName()); } } // for bug 0004882: Subjob title is not copied when copying/pasting subjobs from one job to another makeCopyNodeAndSubjobMapping(copiedNode, pastedNode, mapping); Point location = null; if (getCursorLocation() == null) { location = (Point) ((Node) copiedNode).getLocation(); } else { location = getCursorLocation(); index = nodes.indexOf(copiedNode); } if (process.isGridEnabled()) { // replace the component to set it on the grid if it's enabled int tempVar = location.x / TalendEditor.GRID_SIZE; location.x = tempVar * TalendEditor.GRID_SIZE; tempVar = location.y / TalendEditor.GRID_SIZE; location.y = tempVar * TalendEditor.GRID_SIZE; } pastedNode.setLocation(findLocationForNode(location, (Dimension) ((Node) copiedNode).getSize(), index, firstIndex, ((Node) copiedNode))); pastedNode.setSize(((Node) copiedNode).getSize()); INodeConnector mainConnector; if (pastedNode.isELTComponent()) { mainConnector = pastedNode.getConnectorFromType(EConnectionType.TABLE); } else { mainConnector = pastedNode.getConnectorFromType(EConnectionType.FLOW_MAIN); } if (!mainConnector.isMultiSchema()) { if (copiedNode.getMetadataList().size() != 0) { pastedNode.getMetadataList().clear(); for (IMetadataTable metaTable : copiedNode.getMetadataList()) { IMetadataTable newMetaTable = metaTable.clone(); if (metaTable.getTableName().equals(copiedNode.getUniqueName())) { newMetaTable.setTableName(pastedNode.getUniqueName()); } for (IMetadataColumn column : metaTable.getListColumns()) { if (column.isCustom()) { IMetadataColumn newColumn = newMetaTable.getColumn(column.getLabel()); newColumn.setReadOnly(column.isReadOnly()); newColumn.setCustom(column.isCustom()); } } pastedNode.getMetadataList().add(newMetaTable); } } } else { List<IMetadataTable> copyOfMetadataList = new ArrayList<IMetadataTable>(); for (IMetadataTable metaTable : copiedNode.getMetadataList()) { IMetadataTable newTable = metaTable.clone(); if (copiedNode.isELTComponent()) { newTable.setTableName(createNewConnectionName(metaTable.getTableName(), IProcess.DEFAULT_TABLE_CONNECTION_NAME)); } else { newTable.setTableName(createNewConnectionName(metaTable.getTableName(), null)); } oldMetaToNewMeta.put(pastedNode.getUniqueName() + ":" + metaTable.getTableName(), newTable.getTableName()); //$NON-NLS-1$ for (IMetadataColumn column : metaTable.getListColumns()) { if (column.isCustom()) { IMetadataColumn newColumn = newTable.getColumn(column.getLabel()); newColumn.setReadOnly(column.isReadOnly()); newColumn.setCustom(column.isCustom()); } } newTable.sortCustomColumns(); copyOfMetadataList.add(newTable); } pastedNode.setMetadataList(copyOfMetadataList); IExternalNode externalNode = pastedNode.getExternalNode(); if (externalNode != null) { if (copiedNode.getExternalData() != null) { try { externalNode.setExternalData(copiedNode.getExternalData().clone()); } catch (CloneNotSupportedException e) { ExceptionHandler.process(e); } ((Node) pastedNode).setExternalData(externalNode.getExternalData()); } for (IMetadataTable metaTable : copiedNode.getMetadataList()) { String oldName = metaTable.getTableName(); String newName = oldMetaToNewMeta.get(pastedNode.getUniqueName() + ":" + metaTable.getTableName()); //$NON-NLS-1$ externalNode.renameOutputConnection(oldName, newName); CorePlugin.getDefault().getMapperService() .renameJoinTable(process, externalNode.getExternalData(), createdNames); } // when copy a external node, should also copy screeshot if (copiedNode.getExternalNode() != null) { ImageDescriptor screenshot = copiedNode.getExternalNode().getScreenshot(); if (screenshot != null) { externalNode.setScreenshot(screenshot); } } } } ((Node) pastedNode).getNodeLabel().setOffset(new Point(((Node) copiedNode).getNodeLabel().getOffset())); oldNameTonewNameMap.put(copiedNode.getUniqueName(), pastedNode.getUniqueName()); if (copiedNode.getElementParametersWithChildrens() != null) { for (ElementParameter param : (List<ElementParameter>) copiedNode.getElementParametersWithChildrens()) { if (!EParameterName.UNIQUE_NAME.getName().equals(param.getName())) { IElementParameter elementParameter = pastedNode.getElementParameter(param.getName()); if (param.getFieldType() == EParameterFieldType.TABLE) { List<Map<String, Object>> tableValues = (List<Map<String, Object>>) param.getValue(); ArrayList newValues = new ArrayList(); for (Map<String, Object> map : tableValues) { Map<String, Object> newMap = new HashMap<String, Object>(); newMap.putAll(map); // rename schemas if (EParameterName.SCHEMAS.name().equals(param.getName()) && !oldMetaToNewMeta.isEmpty()) { String newSchemaName = oldMetaToNewMeta.get(pastedNode.getUniqueName() + ":" + map.get(EParameterName.SCHEMA.getName())); if (newSchemaName != null) { newMap.put(EParameterName.SCHEMA.getName(), newSchemaName); } } newValues.add(newMap); } elementParameter.setValue(newValues); } else { if (param.getParentParameter() != null) { String parentName = param.getParentParameter().getName(); pastedNode.setPropertyValue(parentName + ":" + param.getName(), param.getValue()); //$NON-NLS-1$ } else { pastedNode.setPropertyValue(param.getName(), param.getValue()); // See Bug 0005722: the pasted component don't keep the same read-only mode and didn;t // hide // the password. elementParameter.setReadOnly(param.getOriginalityReadOnly()); elementParameter.setRepositoryValueUsed(param.isRepositoryValueUsed()); } } } } } NodeContainer nc = ((Process)pastedNode.getProcess()).loadNodeContainer((Node)pastedNode, false);; nodeContainerList.add(nc); } ((Process) process).setCopyPasteSubjobMappings(mapping); Map<String, String> oldToNewConnVarMap = new HashMap<String, String>(); // add the connections for (INode copiedNode : nodes) { // INode copiedNode = (INode) copiedNodePart.getModel(); for (IConnection connection : (List<IConnection>) copiedNode.getOutgoingConnections()) { INode pastedTargetNode = null, pastedSourceNode = null; String nodeSource = oldNameTonewNameMap.get(copiedNode.getUniqueName()); for (NodeContainer nodeContainer : nodeContainerList) { INode node = nodeContainer.getNode(); if (node.getUniqueName().equals(nodeSource)) { pastedSourceNode = node; } } INode targetNode = connection.getTarget(); // test if the target is in the nodes to paste to add the // connection // if the targeted node is not in the nodes to paste, then the // string will be null String nodeToConnect = oldNameTonewNameMap.get(targetNode.getUniqueName()); if (nodeToConnect != null) { for (NodeContainer nodeContainer : nodeContainerList) { INode node = nodeContainer.getNode(); if (node.getUniqueName().equals(nodeToConnect)) { pastedTargetNode = node; } } } if ((pastedSourceNode != null) && (pastedTargetNode != null)) { String newConnectionName; String metaTableName; if (connection.getLineStyle().hasConnectionCategory(IConnectionCategory.UNIQUE_NAME) && connection.getLineStyle().hasConnectionCategory(IConnectionCategory.FLOW)) { String newNameBuiltIn = oldMetaToNewMeta.get(pastedSourceNode.getUniqueName() + ":" //$NON-NLS-1$ + connection.getMetaName()); if (newNameBuiltIn == null) { IElementParameter formatParam = pastedSourceNode.getElementParameter(EParameterName.CONNECTION_FORMAT .getName()); String baseName = IProcess.DEFAULT_ROW_CONNECTION_NAME; if (formatParam != null) { String value = (String) formatParam.getValue(); if (value != null && !"".equals(value)) { //$NON-NLS-1$ baseName = value; } } if (process.checkValidConnectionName(connection.getName(), true)) { baseName = null; // keep the name, bug 5086 } newConnectionName = createNewConnectionName(connection.getName(), baseName); } else { newConnectionName = newNameBuiltIn; } } else { newConnectionName = connection.getName(); } String meta = oldMetaToNewMeta.get(pastedSourceNode.getUniqueName() + ":" + connection.getMetaName()); //$NON-NLS-1$ if (meta != null) { if (pastedSourceNode.getConnectorFromType(connection.getLineStyle()).isMultiSchema() && !connection.getLineStyle().equals(EConnectionType.TABLE)) { newConnectionName = meta; } metaTableName = meta; } else { if (pastedSourceNode.getConnectorFromType(connection.getLineStyle()).isMultiSchema()) { metaTableName = pastedSourceNode.getMetadataList().get(0).getTableName(); } else { metaTableName = pastedSourceNode.getUniqueName(); // connection.getMetaName(); } } IConnection pastedConnection; if (!pastedTargetNode.isELTComponent()) { pastedConnection = new Connection(pastedSourceNode, pastedTargetNode, connection.getLineStyle(), connection.getConnectorName(), metaTableName, newConnectionName, connection.isMonitorConnection()); } else { pastedConnection = new Connection(pastedSourceNode, pastedTargetNode, connection.getLineStyle(), connection.getConnectorName(), metaTableName, newConnectionName, metaTableName, connection.isMonitorConnection()); } connections.add(pastedConnection); oldNameTonewNameMap.put(connection.getUniqueName(), pastedConnection.getUniqueName()); // pastedConnection.setActivate(pastedSourceNode.isActivate()); for (ElementParameter param : (List<ElementParameter>) connection.getElementParameters()) { // pastedConnection.getElementParameter(param.getName()) // .setValue(param.getValue()); pastedConnection.setPropertyValue(param.getName(), param.getValue()); } // reset unique name param IElementParameter uniqueNameParam = pastedConnection .getElementParameter(EParameterName.UNIQUE_NAME.getName()); String newName = oldNameTonewNameMap.get(connection.getUniqueName()); if (uniqueNameParam != null && newName != null) { if (!newName.equals(uniqueNameParam.getValue())) { pastedConnection.setPropertyValue(EParameterName.UNIQUE_NAME.getName(), newName); } } // // keep the label (bug 3778) // if (pastedConnection != null) { // if (pastedConnection.getSourceNodeConnector().isBuiltIn() // && pastedConnection.getLineStyle().hasConnectionCategory(EConnectionType.FLOW)) { // pastedConnection.setPropertyValue(EParameterName.LABEL.getName(), connection.getName()); // } else { // pastedConnection.setPropertyValue(EParameterName.LABEL.getName(), newConnectionName); // } // } ((Connection) pastedConnection).getConnectionLabel().setOffset( new Point(((Connection) connection).getConnectionLabel().getOffset())); INodeConnector connector = pastedConnection.getSourceNodeConnector(); connector.setCurLinkNbOutput(connector.getCurLinkNbOutput() + 1); connector = pastedConnection.getTargetNodeConnector(); connector.setCurLinkNbInput(connector.getCurLinkNbInput() + 1); IExternalNode externalNode = pastedTargetNode.getExternalNode(); if (externalNode != null) { externalNode.renameInputConnection(connection.getName(), newConnectionName); } // (feature 2962) if (pastedConnection.getMetadataTable() == null) { continue; } for (IMetadataColumn column : pastedConnection.getMetadataTable().getListColumns()) { String oldConnVar = connection.getName() + "." + column.getLabel(); //$NON-NLS-1$ String newConnVar = newConnectionName + "." + column.getLabel(); //$NON-NLS-1$ // String oldConnVar = connection.getName(); // String newConnVar = newConnectionName; if (!oldToNewConnVarMap.containsKey(oldConnVar)) { oldToNewConnVarMap.put(oldConnVar, newConnVar); } } } } } // rename the connection data for node parameters. (feature 2962) for (NodeContainer nodeContainer : nodeContainerList) { Node node = nodeContainer.getNode(); for (String oldConnVar : oldToNewConnVarMap.keySet()) { String newConnVar = oldToNewConnVarMap.get(oldConnVar); if (newConnVar != null) { node.renameData(oldConnVar, newConnVar); } } } // check if the new components use the old components name. Map<String, Set<String>> usedDataMap = new HashMap<String, Set<String>>(); for (NodeContainer nodeContainer : nodeContainerList) { Node currentNode = nodeContainer.getNode(); String uniqueName = currentNode.getUniqueName(); for (String oldName : oldNameTonewNameMap.keySet()) { if (!oldName.equals(oldNameTonewNameMap.get(oldName)) && currentNode.useData(oldName)) { Set<String> oldNameSet = usedDataMap.get(uniqueName); if (oldNameSet == null) { oldNameSet = new HashSet<String>(); usedDataMap.put(uniqueName, oldNameSet); } oldNameSet.add(oldName); } } } // check if the new connections use the old components name. Map<String, Set<String>> usedDataMapForConnections = new HashMap<String, Set<String>>(); for (IConnection connection : connections) { String uniqueName = connection.getUniqueName(); for (String oldName : oldNameTonewNameMap.keySet()) { if (oldName != null && !oldName.equals(oldNameTonewNameMap.get(oldName)) && UpgradeElementHelper.isUseData(connection, oldName)) { Set<String> oldNameSet = usedDataMapForConnections.get(uniqueName); if (oldNameSet == null) { oldNameSet = new HashSet<String>(); usedDataMapForConnections.put(uniqueName, oldNameSet); } oldNameSet.add(oldName); } } } if (!usedDataMap.isEmpty() || !usedDataMapForConnections.isEmpty()) { MessageBox msgBox = new MessageBox(PlatformUI.getWorkbench().getDisplay().getActiveShell(), SWT.YES | SWT.NO | SWT.ICON_WARNING); msgBox.setMessage(Messages.getString("NodesPasteCommand.renameMessages")); //$NON-NLS-1$ if (msgBox.open() == SWT.YES) { for (NodeContainer nodeContainer : nodeContainerList) { Node currentNode = nodeContainer.getNode(); Set<String> oldNameSet = usedDataMap.get(currentNode.getUniqueName()); if (oldNameSet != null && !oldNameSet.isEmpty()) { for (String oldName : oldNameSet) { currentNode.renameData(oldName, oldNameTonewNameMap.get(oldName)); } } } // Rename connections for (IConnection connection : connections) { Set<String> oldNameSet = usedDataMapForConnections.get(connection.getUniqueName()); if (oldNameSet != null && !oldNameSet.isEmpty()) { for (String oldName : oldNameSet) { UpgradeElementHelper.renameData(connection, oldName, oldNameTonewNameMap.get(oldName)); } } } } } } /** * DOC bqian Comment method "makeCopyNodeAndSubjobMapping".<br> * see bug 0004882: Subjob title is not copied when copying/pasting subjobs from one job to another * * @param copiedNode * @param pastedNode */ private void makeCopyNodeAndSubjobMapping(INode copiedNode, INode pastedNode, Map<INode, SubjobContainer> mapping) { for (SubjobContainerPart subjobPart : subjobParts) { SubjobContainer subjob = (SubjobContainer) subjobPart.getModel(); if (subjob != null && subjob.getSubjobStartNode() != null && subjob.getSubjobStartNode().equals(copiedNode)) { mapping.put(pastedNode, subjob); } } } @SuppressWarnings("unchecked") @Override public void execute() { // create the node container list to paste createNodeContainerList(); AbstractMultiPageTalendEditor multiPageTalendEditor = (AbstractMultiPageTalendEditor) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getActiveEditor(); GraphicalViewer viewer = multiPageTalendEditor.getTalendEditor().getViewer(); // save old selection if (!multipleCommand) { oldSelection = new ArrayList<EditPart>(); for (EditPart editPart : (List<EditPart>) viewer.getSelectedEditParts()) { oldSelection.add(editPart); } // remove the old selection viewer.deselectAll(); } // creates the different nodes for (NodeContainer nodeContainer : nodeContainerList) { ((Process) process).addNodeContainer(nodeContainer); } // check that the created connections exists now, or create them if needed for (String newConnectionName : createdNames) { if (process.checkValidConnectionName(newConnectionName, true)) { process.addUniqueConnectionName(newConnectionName); } } process.checkStartNodes(); process.checkProcess(); // set the new node as the current selection if (!multipleCommand) { EditPart processPart = (EditPart) viewer.getRootEditPart().getChildren().get(0); if (processPart instanceof ProcessPart) { // can only be // ProcessPart but still // test List<EditPart> sel = new ArrayList<EditPart>(); for (EditPart editPart : (List<EditPart>) processPart.getChildren()) { if (editPart instanceof SubjobContainerPart) { for (EditPart subjobChildsPart : (List<EditPart>) editPart.getChildren()) { if (subjobChildsPart instanceof NodeContainerPart) { if (nodeContainerList.contains(((NodeContainerPart) subjobChildsPart).getModel())) { NodePart nodePart = ((NodeContainerPart) subjobChildsPart).getNodePart(); if (nodePart != null) { sel.add(nodePart); } } } } } if (editPart instanceof NodePart) { Node currentNode = (Node) editPart.getModel(); if (nodeContainerList.contains(currentNode.getNodeContainer())) { sel.add(editPart); } } } StructuredSelection s = new StructuredSelection(sel); viewer.setSelection(s); } } } @SuppressWarnings("unchecked") @Override public void undo() { // remove the current selection AbstractMultiPageTalendEditor multiPageTalendEditor = (AbstractMultiPageTalendEditor) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getActiveEditor(); GraphicalViewer viewer = multiPageTalendEditor.getTalendEditor().getViewer(); if (!multipleCommand) { viewer.deselectAll(); } for (NodeContainer nodeContainer : nodeContainerList) { // remove the connections name from the list for (Connection connection : (List<Connection>) nodeContainer.getNode().getOutgoingConnections()) { process.removeUniqueConnectionName(connection.getName()); } ((Process) process).removeNodeContainer(nodeContainer); } // check that the created connections are removed, remove them if not for (String newConnectionName : createdNames) { if (!process.checkValidConnectionName(newConnectionName, true)) { process.removeUniqueConnectionName(newConnectionName); } } process.checkStartNodes(); process.checkProcess(); // set the old selection active if (!multipleCommand) { StructuredSelection s = new StructuredSelection(oldSelection); viewer.setSelection(s); } } /** * Getter for multipleCommand. * * @return the multipleCommand */ public boolean isMultipleCommand() { return multipleCommand; } /** * Sets the multipleCommand. * * @param multipleCommand the multipleCommand to set */ public void setMultipleCommand(boolean multipleCommand) { this.multipleCommand = multipleCommand; } /** * Getter for nodeContainerList. * * @return the nodeContainerList */ public List<NodeContainer> getNodeContainerList() { return nodeContainerList; } /** * bqian Comment method "setSelectedSubjobs". <br> * see bug 0004882: Subjob title is not copied when copying/pasting subjobs from one job to another * * @param subjobParts */ public void setSelectedSubjobs(List<SubjobContainerPart> subjobParts) { this.subjobParts = subjobParts; } }
923dc932ffb5765924cc2d476712d686c22480ae
15,166
java
Java
src/test/java/com/napier/sem/IntegrationTests.java
Scott-Darroch/Group_1_Coursework_SEM
017cc5efb0d9c13a67e165b266626e8fef60fcd8
[ "Apache-2.0" ]
null
null
null
src/test/java/com/napier/sem/IntegrationTests.java
Scott-Darroch/Group_1_Coursework_SEM
017cc5efb0d9c13a67e165b266626e8fef60fcd8
[ "Apache-2.0" ]
null
null
null
src/test/java/com/napier/sem/IntegrationTests.java
Scott-Darroch/Group_1_Coursework_SEM
017cc5efb0d9c13a67e165b266626e8fef60fcd8
[ "Apache-2.0" ]
null
null
null
45.543544
147
0.697811
1,000,481
package com.napier.sem; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * * Class that contain all code for conducting integration tests for the project. * @author Euan Holmes, * @author Adam Riddell, * @author Scott Darroch, * @author Robert Denny * Date Last modified 08/04/2021 * Last modified by: Robert */ public class IntegrationTests { static App app; static SQL sql; @BeforeAll static void init() { app = new App(); app.connect("localhost:33060"); sql = new SQL(app.getCon()); } // A test to prove that the report1 function gets a report showing all the countries in the world in order // of largest to smallest population. @Test void testReport1() { int countries_expected_length = 232; int countries_length = sql.report1().size(); assertEquals(countries_expected_length, countries_length, "This asserts that the whole countries " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report2 function gets a report showing all the countries in Africa in order of // of largest to smallest population. @Test void testReport2() { int countries_expected_length = 57; int countries_length = sql.report2().size(); assertEquals(countries_expected_length, countries_length, "This asserts that the whole countries " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report3 function gets a report showing all the countries in the Caribbean in // order of largest to smallest population. @Test void testReport3() { int countries_expected_length = 24; int countries_length = sql.report3().size(); assertEquals(countries_expected_length, countries_length, "This asserts that the whole countries " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report7 function gets a report showing all the cities in the world in order of // of largest to smallest population. @Test void testReport7() { int cities_expected_length = 4079; int cities_length = sql.report7().size(); assertEquals(cities_expected_length, cities_length , "This asserts that the whole cities array is " + "returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report8 function gets a report showing all the cities in the world in order of // of largest to smallest population. @Test void testReport8() { int cities_expected_length = 1766; int cities_length = sql.report8().size(); assertEquals(cities_expected_length, cities_length , "This asserts that the whole cities array is " + "returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report9 function gets a report showing all the cities in the world in order of // of largest to smallest population. @Test void testReport9() { int cities_expected_length = 58; int cities_length = sql.report9().size(); assertEquals(cities_expected_length, cities_length , "This asserts that the whole cities array is " + "returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report10 function gets a report showing all the cities in the world in order of // of largest to smallest population. @Test void testReport10() { int cities_expected_length = 40; int cities_length = sql.report10().size(); assertEquals(cities_expected_length, cities_length , "This asserts that the whole cities array is " + "returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report11 function gets a report showing all the cities in the world in order of // of largest to smallest population. @Test void testReport11() { int cities_expected_length = 4; int cities_length = sql.report11().size(); assertEquals(cities_expected_length, cities_length , "This asserts that the whole cities array is " + "returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report12 function gets a report showing the top N populated cities in the world. @Test void testReport12() { int city_expected_population = 10500000; int city_population = sql.report12(10).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first city in the ArrayLists" + "population is correct by checking against the hardcoded expected population of that city."); } // A test to prove that the report13 function gets a report showing the top N populated cities in a continent. @Test void testReport13() { int city_expected_population = 8591309; int city_population = sql.report13(15).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that city."); } // A test to prove that the report14 function gets a report showing the top N populated cities in a region. @Test void testReport14() { int city_expected_population = 2879052; int city_population = sql.report14(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that city."); } // A test to prove that the report15 function gets a report showing the top N populated cities in a country. @Test void testReport15() { int city_expected_population = 7980230; int city_population = sql.report15(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that city."); } // A test to prove that the report16 function gets a report showing the top N populated cities in a district. @Test void testReport16() { int city_expected_population = 201843; int city_population = sql.report16(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that city."); } // A test to prove that the report17 function gets a report showing all the capital cities in the // world organised by largest population to smallest. @Test void testReport17() { int capital_cities_expected_length = 232; int capital_cities_length = sql.report17().size(); assertEquals(capital_cities_expected_length, capital_cities_length, "This asserts that the whole capital cities " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report18 function gets a report showing all the capital cities in a // continent organised by largest population to smallest. @Test void testReport18() { int capital_cities_expected_length = 46; int capital_cities_length = sql.report18().size(); assertEquals(capital_cities_expected_length, capital_cities_length, "This asserts that the whole capital cities " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report19 function gets a report showing all the capital cities in a // region organised by largest population to smallest. @Test void testReport19() { int capital_cities_expected_length = 24; int capital_cities_length = sql.report19().size(); assertEquals(capital_cities_expected_length, capital_cities_length, "This asserts that the whole capital cities " + "array is returned by checking the actual length returned against the hardcoded expected length."); } // A test to prove that the report20 function gets a report showing the top N populated capital cities in the world. @Test void testReport20() { int city_expected_population = 9981619; int city_population = sql.report20(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first capital city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that capital city."); } // A test to prove that the report21 function gets a report showing the top N populated capital cities in a continent. @Test void testReport21() { int city_expected_population = 8389200; int city_population = sql.report21(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first capital city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that capital city."); } // A test to prove that the report22 function gets a report showing the top N populated capital cities in a region. @Test void testReport22() { int city_expected_population = 2256000; int city_population = sql.report22(5).get(0).getPopulation(); assertEquals(city_expected_population, city_population, "This asserts that the first capital city in the ArrayLists" + "population is correct by checking it against the hardcoded expected population of that capital city."); } // A test to prove that the report23 function gets a report showing the population of each continent that // are living in cities and not living in cities. @Test void testReport23() { long expected_asia_pop = 900937599400L; long actual_asia_pop = sql.report23().get(0).getTotal_population(); assertEquals(expected_asia_pop, actual_asia_pop, "This asserts that the Asia total population generated by the" + "function is the same as the hardcoded expected value."); } // A test to prove that the report24 function gets a report showing the population of each region that // are living in cities and not living in cities. @Test void testReport24() { long expected_southern_and_central_asia_pop = 363665421000L; long actual_southern_and_central_asia_pop = sql.report24().get(0).getTotal_population(); assertEquals(expected_southern_and_central_asia_pop, actual_southern_and_central_asia_pop, "This asserts that the " + "Southern and Central Asia total population generated by the function is the same as the hardcoded expected value."); } // A test to prove that the report25 function gets a report showing the population of each country that // are living in cities and not living in cities. @Test void testReport25() { long expected_afghanistan_pop = 90880000; long actual_afghanistan_pop = sql.report25().get(0).getTotal_population(); assertEquals(expected_afghanistan_pop, actual_afghanistan_pop, "This asserts that the Afghanistan total population generated by the" + "function is the same as the hardcoded expected value."); } // A test to prove that the getworldpopulation method correctly gets the world population from the database. @Test void testGetWorldPopulation() { long testPop = 6078749450L; long worldPop = sql.report26(); assertEquals(testPop, worldPop, "If report 26 produces an output that matches our hardcoded variable then the method runs correctly."); } // A test to prove that the getcontinentpopulation method correctly gets the continent population from the database. @Test void testGetContinentPopulation() { int testpop = 730074600; int continentpop = sql.report27(); assertEquals(testpop, continentpop, "If report 27 produces an output that matches our hardcoded variable then the method runs correctly."); } // A test to prove that the getregionpopulation method correctly gets the region population from the database. @Test void testGetRegionPopulation() { int testpop = 38140000; int regionpop = sql.report28(); assertEquals(testpop, regionpop,"If report 28 produces an output that matches our hardcoded variable then the method runs correctly."); } // A test to prove that the getcountrypopulation method correctly gets the country population from the database. @Test void testGetCountryPopulation() { int testpop = 39441700; int countrypop = sql.report29(); assertEquals(testpop, countrypop, "If report 29 produces an output that matches our hardcoded variable then the method runs correctly."); } // A test to prove that the getcitypopulation method correctly gets the city population from the database @Test void testGetCityPopulation() { int testpop = 3993949; int citypop = sql.report30(); assertEquals(testpop, citypop, "If report 30 produces an output that matches our hardcoded variable then the method runs correctly."); } // A test to prove that the report31 function correctly gets the city population from the database. @Test void testReport31() { int testpop = 450180; int citypop = sql.report31(); assertEquals(testpop, citypop, "This asserts that the city population generated is the same as the " + "hardcoded expected output."); } // A test to prove that the report32 function correctly gets the number of people who speak Chinese, Arabic, // English, Hindi and Spanish from greatest number to smallest. @Test void testReport32() { int expected_chinese_speakers = 1968265500; int actual_chinese_speakers = sql.report32()[0].getLanguage_num(); assertEquals(expected_chinese_speakers, actual_chinese_speakers, "This asserts that the number of chinese speakers" + "matches the hardcoded expected number."); } }
923dc942569f6d498fd95e025ebdd8888a5e287a
470
java
Java
src/main/java/goblinbob/mobends/core/kumo/state/DriverLayerState.java
CitrusHappy/MoBends
8e432defa58fd14d21c1821ead7a21d917e17719
[ "MIT" ]
107
2019-09-28T16:10:05.000Z
2022-03-19T06:18:38.000Z
src/main/java/goblinbob/mobends/core/kumo/state/DriverLayerState.java
CitrusHappy/MoBends
8e432defa58fd14d21c1821ead7a21d917e17719
[ "MIT" ]
214
2019-09-25T05:27:10.000Z
2022-03-29T15:09:48.000Z
src/main/java/goblinbob/mobends/core/kumo/state/DriverLayerState.java
CitrusHappy/MoBends
8e432defa58fd14d21c1821ead7a21d917e17719
[ "MIT" ]
37
2019-10-15T00:17:39.000Z
2022-03-17T04:33:15.000Z
18.076923
70
0.697872
1,000,482
package goblinbob.mobends.core.kumo.state; import goblinbob.mobends.core.kumo.state.template.DriverLayerTemplate; public class DriverLayerState implements ILayerState { public DriverLayerState(DriverLayerTemplate template) { } @Override public void start(IKumoContext context) { // TODO Implement this. } @Override public void update(IKumoContext context, float deltaTime) { // TODO Implement this. } }
923dc9611985a2b04bb4bad327440800e971ddca
3,218
java
Java
library_core/src/main/java/com/td/framework/global/BasicAdapterHelper.java
aohanyao/MvpFramework
0cf83b57ad19fcb8e217507f90c5140b5e1d0d3c
[ "Apache-2.0" ]
1
2019-04-25T02:24:22.000Z
2019-04-25T02:24:22.000Z
library_core/src/main/java/com/td/framework/global/BasicAdapterHelper.java
aohanyao/MvpFramework
0cf83b57ad19fcb8e217507f90c5140b5e1d0d3c
[ "Apache-2.0" ]
null
null
null
library_core/src/main/java/com/td/framework/global/BasicAdapterHelper.java
aohanyao/MvpFramework
0cf83b57ad19fcb8e217507f90c5140b5e1d0d3c
[ "Apache-2.0" ]
2
2018-12-29T00:46:22.000Z
2019-04-25T02:24:26.000Z
39.728395
145
0.665631
1,000,483
package com.td.framework.global; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.td.framework.R; /** * <p>作者:jc on 2016/9/6 17:07</p> * <p>适配器帮助类,统一初始化适配器</p> */ public class BasicAdapterHelper { /** * 垂直的 * * @param mContext * @param mAdapter * @param mRecyclerView */ public static void initAdapterVertical(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView) { initAdapter(mContext, mAdapter, mRecyclerView, LinearLayoutManager.VERTICAL, "", 0); } public static void initAdapterVertical(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView, String emptyTip) { initAdapter(mContext, mAdapter, mRecyclerView, LinearLayoutManager.VERTICAL, emptyTip, 0); } public static void initAdapterVertical(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView, String emptyTip, int emptyLayoutId) { initAdapter(mContext, mAdapter, mRecyclerView, LinearLayoutManager.VERTICAL, emptyTip, emptyLayoutId); } /** * 水平的 * * @param mContext * @param mAdapter * @param mRecyclerView */ public static void initAdapterHorizontal(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView) { initAdapter(mContext, mAdapter, mRecyclerView, LinearLayoutManager.HORIZONTAL, "", 0); } public static void initAdapterHorizontal(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView, int emptyLayoutId) { initAdapter(mContext, mAdapter, mRecyclerView, LinearLayoutManager.HORIZONTAL, "", emptyLayoutId); } public static void initAdapter(Context mContext, BaseQuickAdapter mAdapter, RecyclerView mRecyclerView, int orientation, String emptyTip, int emptyLayoutId) { LinearLayoutManager layoutManager = new LinearLayoutManager(mContext); layoutManager.setOrientation(orientation); mRecyclerView.setLayoutManager(layoutManager); View emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_adatper_empty_view, (ViewGroup) mRecyclerView.getParent(), false); if (emptyLayoutId != 0) { emptyView = LayoutInflater.from(mContext).inflate(emptyLayoutId, (ViewGroup) mRecyclerView.getParent(), false); } TextView tvEmptyTip = (TextView) emptyView.findViewById(R.id.tv_empty_tip); if (!TextUtils.isEmpty(emptyTip) && tvEmptyTip != null) { tvEmptyTip.setText(emptyTip); } mAdapter.setEmptyView(emptyView); // mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN); } }
923dc9c0ec8a1905a28a8a2cd08c468bdf224099
1,279
java
Java
scormbuilder-web/src/main/java/ru/heroicrealm/scormbuilder/util/FileSystemDataProvider.java
heroicrealm/scormbuilder
af64b1c14960406642040a7845d352cf76363d0d
[ "MIT" ]
null
null
null
scormbuilder-web/src/main/java/ru/heroicrealm/scormbuilder/util/FileSystemDataProvider.java
heroicrealm/scormbuilder
af64b1c14960406642040a7845d352cf76363d0d
[ "MIT" ]
null
null
null
scormbuilder-web/src/main/java/ru/heroicrealm/scormbuilder/util/FileSystemDataProvider.java
heroicrealm/scormbuilder
af64b1c14960406642040a7845d352cf76363d0d
[ "MIT" ]
null
null
null
29.744186
73
0.653636
1,000,484
package ru.heroicrealm.scormbuilder.util; import com.vaadin.data.provider.AbstractBackEndHierarchicalDataProvider; import com.vaadin.data.provider.HierarchicalQuery; import java.io.File; import java.io.FilenameFilter; import java.util.stream.Stream; /** * Created by kuran on 01.02.2019. */ public class FileSystemDataProvider extends AbstractBackEndHierarchicalDataProvider<File, FilenameFilter> { private final File root; public FileSystemDataProvider(File root) { this.root = root; } @Override public int getChildCount( HierarchicalQuery<File, FilenameFilter> query) { return (int) fetchChildren(query).count(); } @Override public Stream<File> fetchChildrenFromBackEnd( HierarchicalQuery<File, FilenameFilter> query) { final File parent = query.getParentOptional().orElse(root); return query.getFilter() .map(filter -> Stream.of(parent.listFiles(filter))) .orElse(Stream.of(parent.listFiles())) .skip(query.getOffset()).limit(query.getLimit()); } @Override public boolean hasChildren(File item) { return item.list() != null && item.list().length > 0; } }
923dccaa940e8f44cafb91645c49c5393a58af92
1,220
java
Java
core/src/main/java/org/jdbi/v3/core/statement/StatementBuilderFactory.java
paladin235/jdbi
fc9cbe070291e9c68c168fb72256b1c60eb88880
[ "Apache-2.0" ]
1,396
2015-01-02T17:08:38.000Z
2022-03-31T22:39:30.000Z
core/src/main/java/org/jdbi/v3/core/statement/StatementBuilderFactory.java
paladin235/jdbi
fc9cbe070291e9c68c168fb72256b1c60eb88880
[ "Apache-2.0" ]
1,498
2015-01-01T00:08:02.000Z
2022-03-26T15:02:57.000Z
core/src/main/java/org/jdbi/v3/core/statement/StatementBuilderFactory.java
paladin235/jdbi
fc9cbe070291e9c68c168fb72256b1c60eb88880
[ "Apache-2.0" ]
322
2015-01-17T20:20:30.000Z
2022-03-30T22:21:14.000Z
38.125
99
0.740164
1,000,485
/* * 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.jdbi.v3.core.statement; import java.sql.Connection; /** * Used to specify how prepared statements are built. A factory is attached to a Jdbi instance, and * whenever the Jdbi instance is used to create a Handle the factory will be used to create a * StatementBuilder for that specific handle. */ public interface StatementBuilderFactory { /** * Creates a new {@link StatementBuilder} from a {@link Connection} object. * * @param conn the connection to create a statement builder for * @return a StatementBuilder, called when a new handle is opened */ StatementBuilder createStatementBuilder(Connection conn); }
923dccaef850f20967130b08bbff47f1589bf6ee
288
java
Java
backend/src/main/java/io/github/lzmz/meetups/endpoint/EnrollmentEndpoint.java
LeonelMenendez/meetups
c3c757e4b6529be63a35673da15135c0c36ef70b
[ "MIT" ]
null
null
null
backend/src/main/java/io/github/lzmz/meetups/endpoint/EnrollmentEndpoint.java
LeonelMenendez/meetups
c3c757e4b6529be63a35673da15135c0c36ef70b
[ "MIT" ]
4
2021-08-31T21:22:02.000Z
2022-02-27T10:52:50.000Z
backend/src/main/java/io/github/lzmz/meetups/endpoint/EnrollmentEndpoint.java
lzmz/meetups
c3c757e4b6529be63a35673da15135c0c36ef70b
[ "MIT" ]
null
null
null
32
78
0.732639
1,000,486
package io.github.lzmz.meetups.endpoint; public final class EnrollmentEndpoint { public static final String BASE = "/enrollments"; public static final String CHECK_IN = "/{enrollmentId}/check-in"; public static final String ANT_CHECK_IN = "/{enrollmentId:\\d+}/check-in"; }
923dccbb2e43edd57f0d2acdedce4fc2e1d1767e
1,021
java
Java
subprojects/resources/src/main/java/org/gradle/internal/verifier/HttpRedirectVerifier.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
2
2018-02-10T18:44:02.000Z
2018-03-25T07:17:04.000Z
subprojects/resources/src/main/java/org/gradle/internal/verifier/HttpRedirectVerifier.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
12
2020-07-11T15:43:32.000Z
2020-10-13T23:39:44.000Z
subprojects/resources/src/main/java/org/gradle/internal/verifier/HttpRedirectVerifier.java
jdai8/gradle
0fdb1f3ff5c4e8f3444e14e5cdaa6775f1189a5d
[ "Apache-2.0" ]
1
2022-01-12T12:33:48.000Z
2022-01-12T12:33:48.000Z
31.90625
85
0.742409
1,000,487
/* * Copyright 2019 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.internal.verifier; import java.net.URI; import java.util.Collection; /** * Use {@link HttpRedirectVerifierFactory#create} to instantiate an instance of this. */ @FunctionalInterface public interface HttpRedirectVerifier { /** * Perform verification on the URI's in an HTTP request's redirect chain. */ void validateRedirects(Collection<URI> redirectLocations); }
923dcfba1820a7bb098e44f7dbe1d803710e2f53
6,268
java
Java
modules/citrus-admin/src/test/java/com/consol/citrus/admin/service/SpringBeanServiceTest.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
null
null
null
modules/citrus-admin/src/test/java/com/consol/citrus/admin/service/SpringBeanServiceTest.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
null
null
null
modules/citrus-admin/src/test/java/com/consol/citrus/admin/service/SpringBeanServiceTest.java
greyowlone/citrus
d4c913eec13132282e209284b32fd2cecd82743e
[ "Apache-2.0" ]
null
null
null
42.931507
162
0.692565
1,000,488
/* * Copyright 2006-2013 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 com.consol.citrus.admin.service; import com.consol.citrus.admin.jaxb.JAXBHelper; import com.consol.citrus.model.config.core.*; import com.consol.citrus.util.FileUtils; import org.springframework.core.io.ClassPathResource; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.*; import java.util.List; /** * @author Christoph Deppisch */ public class SpringBeanServiceTest { private SpringBeanService springBeanConfigService = new SpringBeanService(); @BeforeMethod public void beforeMethod() { springBeanConfigService.jaxbHelper = new JAXBHelper(); springBeanConfigService.init(); } @Test public void testAddBeanDefinition() throws Exception { SchemaDefinition xsdSchema1 = new SchemaDefinitionBuilder().withId("1").withLocation("l1").build(); SchemaDefinition xsdSchema2 = new SchemaDefinitionBuilder().withId("2").withLocation("l2").build(); SchemaRepositoryDefinition schemaRepository = new SchemaRepositoryDefinitionBuilder().withId("x").addSchemaReference("1").addSchemaReference("2").build(); File tempFile = createTempContextFile("citrus-context-add"); springBeanConfigService.addBeanDefinition(tempFile, xsdSchema1); springBeanConfigService.addBeanDefinition(tempFile, xsdSchema2); springBeanConfigService.addBeanDefinition(tempFile, schemaRepository); String result = FileUtils.readToString(new FileInputStream(tempFile)); Assert.assertTrue(result.contains("<citrus:schema id=\"1\" location=\"l1\"/>"), "Failed to validate " + result); Assert.assertTrue(result.contains("<citrus:schema id=\"2\" location=\"l2\"/>"), "Failed to validate " + result); Assert.assertTrue(result.contains("<citrus:schema-repository id=\"x\">"), "Failed to validate " + result); } @Test public void testRemoveBeanDefinition() throws Exception { File tempFile = createTempContextFile("citrus-context-remove"); springBeanConfigService.removeBeanDefinition(tempFile, "deleteMe"); springBeanConfigService.removeBeanDefinition(tempFile, "deleteMeName"); springBeanConfigService.removeBeanDefinition(tempFile, "helloSchema"); String result = FileUtils.readToString(new FileInputStream(tempFile)); Assert.assertTrue(result.contains("id=\"preserveMe\""), "Failed to validate " + result); Assert.assertTrue(result.contains("name=\"preserveMeName\""), "Failed to validate " + result); Assert.assertFalse(result.contains("<bean id=\"deleteMe\""), "Failed to validate " + result); Assert.assertFalse(result.contains("<bean name=\"deleteMeName\""), "Failed to validate " + result); } @Test public void testUpdateBeanDefinition() throws Exception { File tempFile = createTempContextFile("citrus-context-update"); SchemaDefinition helloSchema = new SchemaDefinitionBuilder().withId("helloSchema").withLocation("newLocation").build(); springBeanConfigService.updateBeanDefinition(tempFile, "helloSchema", helloSchema); String result = FileUtils.readToString(new FileInputStream(tempFile)); Assert.assertTrue(result.contains("<citrus:schema id=\"helloSchema\" location=\"newLocation\"/>"), "Failed to validate " + result); } @Test public void testGetBeanDefinition() throws Exception { File tempFile = createTempContextFile("citrus-context-find"); SchemaDefinition schema = springBeanConfigService.getBeanDefinition(tempFile, "helloSchema", SchemaDefinition.class); Assert.assertEquals(schema.getId(), "helloSchema"); Assert.assertEquals(schema.getLocation(), "classpath:com/consol/citrus/demo/sayHello.xsd"); schema = springBeanConfigService.getBeanDefinition(tempFile, "helloSchemaExtended", SchemaDefinition.class); Assert.assertEquals(schema.getId(), "helloSchemaExtended"); Assert.assertEquals(schema.getLocation(), "classpath:com/consol/citrus/demo/sayHelloExtended.xsd"); } @Test public void testGetBeanDefinitions() throws Exception { File tempFile = createTempContextFile("citrus-context-find"); List<SchemaDefinition> schemas = springBeanConfigService.getBeanDefinitions(tempFile, SchemaDefinition.class); Assert.assertEquals(schemas.size(), 2); Assert.assertEquals(schemas.get(0).getId(), "helloSchema"); Assert.assertEquals(schemas.get(0).getLocation(), "classpath:com/consol/citrus/demo/sayHello.xsd"); Assert.assertEquals(schemas.get(1).getId(), "helloSchemaExtended"); Assert.assertEquals(schemas.get(1).getLocation(), "classpath:com/consol/citrus/demo/sayHelloExtended.xsd"); } /** * Creates a temporary file in operating system and writes template content to file. * @param templateName * @return */ private File createTempContextFile(String templateName) throws IOException { FileWriter writer = null; File tempFile; try { tempFile = File.createTempFile(templateName, ".xml"); writer = new FileWriter(tempFile); writer.write(FileUtils.readToString(new ClassPathResource(templateName + ".xml", SpringBeanService.class))); } finally { if (writer != null) { writer.flush(); writer.close(); } } return tempFile; } }
923dcfdcfadb55754c4bb1d4eace5474f1516416
599
java
Java
src/main/java/cn/edu/witpt/IntelliGame/event/GameEvent.java
n1ckzhao/IntelliGame
0ce489efb3cf828c9f215ee2ca3ab5399c21899d
[ "MIT" ]
null
null
null
src/main/java/cn/edu/witpt/IntelliGame/event/GameEvent.java
n1ckzhao/IntelliGame
0ce489efb3cf828c9f215ee2ca3ab5399c21899d
[ "MIT" ]
1
2022-02-13T05:23:00.000Z
2022-02-13T05:23:00.000Z
src/main/java/cn/edu/witpt/IntelliGame/event/GameEvent.java
1uciuszzz/IntelliGame
0ce489efb3cf828c9f215ee2ca3ab5399c21899d
[ "MIT" ]
2
2021-11-24T08:54:14.000Z
2021-12-19T11:50:24.000Z
27.227273
61
0.689482
1,000,489
package cn.edu.witpt.IntelliGame.event; import javafx.event.Event; import javafx.event.EventType; /** * @author nIck_ */ public class GameEvent extends Event { public static final EventType<GameEvent> MONSTER_KILLED = new EventType<>(ANY, "MONSTER_KILLED"); public static final EventType<GameEvent> PLAYER_GOT_HIT = new EventType<>(ANY, "PLAYER_GOT_HIT"); public static final EventType<GameEvent> HOME_GOT_HIT = new EventType<>(ANY, "HOME_GOT_HIT"); public GameEvent(EventType<? extends Event> eventType) { super(eventType); } }
923dcfdf0a4d89f9a461b9abc7a187b76b96d9e4
260
java
Java
smalivm/src/main/java/org/cf/smalivm/emulate/MethodStateMethod.java
amikey/simplify
31be5efbfe7a59131ffc743fc004e73e583cd4c8
[ "MIT" ]
2
2015-08-23T02:46:22.000Z
2021-01-04T16:10:15.000Z
smalivm/src/main/java/org/cf/smalivm/emulate/MethodStateMethod.java
amikey/simplify
31be5efbfe7a59131ffc743fc004e73e583cd4c8
[ "MIT" ]
null
null
null
smalivm/src/main/java/org/cf/smalivm/emulate/MethodStateMethod.java
amikey/simplify
31be5efbfe7a59131ffc743fc004e73e583cd4c8
[ "MIT" ]
1
2021-01-04T16:10:20.000Z
2021-01-04T16:10:20.000Z
23.636364
80
0.815385
1,000,490
package org.cf.smalivm.emulate; import org.cf.smalivm.VirtualMachine; import org.cf.smalivm.context.MethodState; public interface MethodStateMethod extends EmulatedMethod { public void execute(VirtualMachine vm, MethodState mState) throws Exception; }
923dcffffd7c92a52907dd33cea3d782ad3376b9
684
java
Java
thinking-in-spring/bean-lifecycle/src/main/java/org/geekbang/thinking/in/spring/bean/lifecycle/aop/impl/OrderServiceImpl.java
hanyang20/geekbang-lessons
903400a46e858a4f7f170cb3bdbb59f3ea175af1
[ "Apache-2.0" ]
null
null
null
thinking-in-spring/bean-lifecycle/src/main/java/org/geekbang/thinking/in/spring/bean/lifecycle/aop/impl/OrderServiceImpl.java
hanyang20/geekbang-lessons
903400a46e858a4f7f170cb3bdbb59f3ea175af1
[ "Apache-2.0" ]
null
null
null
thinking-in-spring/bean-lifecycle/src/main/java/org/geekbang/thinking/in/spring/bean/lifecycle/aop/impl/OrderServiceImpl.java
hanyang20/geekbang-lessons
903400a46e858a4f7f170cb3bdbb59f3ea175af1
[ "Apache-2.0" ]
null
null
null
28.5
79
0.69152
1,000,491
package org.geekbang.thinking.in.spring.bean.lifecycle.aop.impl; import org.geekbang.thinking.in.spring.bean.lifecycle.aop.model.Order; import org.geekbang.thinking.in.spring.bean.lifecycle.aop.service.OrderService; public class OrderServiceImpl implements OrderService { @Override public Order createOrder(String username, String product) { Order order = new Order(); order.setUsername(username); order.setProduct(product); return order; } @Override public Order queryOrder(String username) { Order order = new Order(); order.setUsername("test"); order.setProduct("test"); return order; } }
923dd0f7ae40754c9681a12d044d5dfe0c5490c6
3,498
java
Java
src/main/java/org/bian/dto/CRFinancialMarketInformationAdministrativePlanExecuteInputModel.java
bianapis/sd-market-information-management-v2.0
6ad20d3db38b27dac5da2bf24771ebbba4062177
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/CRFinancialMarketInformationAdministrativePlanExecuteInputModel.java
bianapis/sd-market-information-management-v2.0
6ad20d3db38b27dac5da2bf24771ebbba4062177
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/CRFinancialMarketInformationAdministrativePlanExecuteInputModel.java
bianapis/sd-market-information-management-v2.0
6ad20d3db38b27dac5da2bf24771ebbba4062177
[ "Apache-2.0" ]
null
null
null
42.658537
214
0.855918
1,000,492
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRFinancialMarketInformationAdministrativePlanExecuteInputModelExecuteRecordType; import javax.validation.Valid; /** * CRFinancialMarketInformationAdministrativePlanExecuteInputModel */ public class CRFinancialMarketInformationAdministrativePlanExecuteInputModel { private String marketInformationManagementServicingSessionReference = null; private String financialMarketInformationAdministrativePlanInstanceReference = null; private Object financialMarketInformationAdministrativePlanExecuteActionTaskRecord = null; private CRFinancialMarketInformationAdministrativePlanExecuteInputModelExecuteRecordType executeRecordType = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the active servicing session * @return marketInformationManagementServicingSessionReference **/ public String getMarketInformationManagementServicingSessionReference() { return marketInformationManagementServicingSessionReference; } public void setMarketInformationManagementServicingSessionReference(String marketInformationManagementServicingSessionReference) { this.marketInformationManagementServicingSessionReference = marketInformationManagementServicingSessionReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the Financial Market Information Administrative Plan instance * @return financialMarketInformationAdministrativePlanInstanceReference **/ public String getFinancialMarketInformationAdministrativePlanInstanceReference() { return financialMarketInformationAdministrativePlanInstanceReference; } public void setFinancialMarketInformationAdministrativePlanInstanceReference(String financialMarketInformationAdministrativePlanInstanceReference) { this.financialMarketInformationAdministrativePlanInstanceReference = financialMarketInformationAdministrativePlanInstanceReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The execute service call consolidated processing record * @return financialMarketInformationAdministrativePlanExecuteActionTaskRecord **/ public Object getFinancialMarketInformationAdministrativePlanExecuteActionTaskRecord() { return financialMarketInformationAdministrativePlanExecuteActionTaskRecord; } public void setFinancialMarketInformationAdministrativePlanExecuteActionTaskRecord(Object financialMarketInformationAdministrativePlanExecuteActionTaskRecord) { this.financialMarketInformationAdministrativePlanExecuteActionTaskRecord = financialMarketInformationAdministrativePlanExecuteActionTaskRecord; } /** * Get executeRecordType * @return executeRecordType **/ public CRFinancialMarketInformationAdministrativePlanExecuteInputModelExecuteRecordType getExecuteRecordType() { return executeRecordType; } public void setExecuteRecordType(CRFinancialMarketInformationAdministrativePlanExecuteInputModelExecuteRecordType executeRecordType) { this.executeRecordType = executeRecordType; } }
923dd1519dd3bb37bad291cd51a00a1a37dacab7
16,831
java
Java
android/app/src/main/java/com/microsoft/codepush/react/CodePush.java
AZIMAT/react-native-code-push
f251a761b5e2a9a4f53ba35f711933d84f5c23de
[ "MIT" ]
6,035
2015-10-22T17:27:41.000Z
2019-05-06T20:02:04.000Z
android/app/src/main/java/com/microsoft/codepush/react/CodePush.java
AZIMAT/react-native-code-push
f251a761b5e2a9a4f53ba35f711933d84f5c23de
[ "MIT" ]
1,425
2015-10-21T22:56:21.000Z
2019-05-06T19:09:06.000Z
android/app/src/main/java/com/microsoft/codepush/react/CodePush.java
AZIMAT/react-native-code-push
f251a761b5e2a9a4f53ba35f711933d84f5c23de
[ "MIT" ]
901
2015-10-23T02:14:29.000Z
2019-05-06T08:29:14.000Z
38.87067
186
0.672628
1,000,493
package com.microsoft.codepush.react; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.devsupport.DevInternalSettings; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.uimanager.ViewManager; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.ArrayList; import java.util.List; import java.lang.reflect.Method; public class CodePush implements ReactPackage { private static boolean sIsRunningBinaryVersion = false; private static boolean sNeedToReportRollback = false; private static boolean sTestConfigurationFlag = false; private static String sAppVersion = null; private boolean mDidUpdate = false; private String mAssetsBundleFileName; // Helper classes. private CodePushUpdateManager mUpdateManager; private CodePushTelemetryManager mTelemetryManager; private SettingsManager mSettingsManager; // Config properties. private String mDeploymentKey; private static String mServerUrl = "https://codepush.appcenter.ms/"; private Context mContext; private final boolean mIsDebugMode; private static String mPublicKey; private static ReactInstanceHolder mReactInstanceHolder; private static CodePush mCurrentInstance; public CodePush(String deploymentKey, Context context) { this(deploymentKey, context, false); } public static String getServiceUrl() { return mServerUrl; } public CodePush(String deploymentKey, Context context, boolean isDebugMode) { mContext = context.getApplicationContext(); mUpdateManager = new CodePushUpdateManager(context.getFilesDir().getAbsolutePath()); mTelemetryManager = new CodePushTelemetryManager(mContext); mDeploymentKey = deploymentKey; mIsDebugMode = isDebugMode; mSettingsManager = new SettingsManager(mContext); if (sAppVersion == null) { try { PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0); sAppVersion = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { throw new CodePushUnknownException("Unable to get package info for " + mContext.getPackageName(), e); } } mCurrentInstance = this; String publicKeyFromStrings = getCustomPropertyFromStringsIfExist("PublicKey"); if (publicKeyFromStrings != null) mPublicKey = publicKeyFromStrings; String serverUrlFromStrings = getCustomPropertyFromStringsIfExist("ServerUrl"); if (serverUrlFromStrings != null) mServerUrl = serverUrlFromStrings; clearDebugCacheIfNeeded(null); initializeUpdateAfterRestart(); } public CodePush(String deploymentKey, Context context, boolean isDebugMode, String serverUrl) { this(deploymentKey, context, isDebugMode); mServerUrl = serverUrl; } public CodePush(String deploymentKey, Context context, boolean isDebugMode, int publicKeyResourceDescriptor) { this(deploymentKey, context, isDebugMode); mPublicKey = getPublicKeyByResourceDescriptor(publicKeyResourceDescriptor); } public CodePush(String deploymentKey, Context context, boolean isDebugMode, String serverUrl, Integer publicKeyResourceDescriptor) { this(deploymentKey, context, isDebugMode); if (publicKeyResourceDescriptor != null) { mPublicKey = getPublicKeyByResourceDescriptor(publicKeyResourceDescriptor); } mServerUrl = serverUrl; } private String getPublicKeyByResourceDescriptor(int publicKeyResourceDescriptor){ String publicKey; try { publicKey = mContext.getString(publicKeyResourceDescriptor); } catch (Resources.NotFoundException e) { throw new CodePushInvalidPublicKeyException( "Unable to get public key, related resource descriptor " + publicKeyResourceDescriptor + " can not be found", e ); } if (publicKey.isEmpty()) { throw new CodePushInvalidPublicKeyException("Specified public key is empty"); } return publicKey; } private String getCustomPropertyFromStringsIfExist(String propertyName) { String property; String packageName = mContext.getPackageName(); int resId = mContext.getResources().getIdentifier("CodePush" + propertyName, "string", packageName); if (resId != 0) { property = mContext.getString(resId); if (!property.isEmpty()) { return property; } else { CodePushUtils.log("Specified " + propertyName + " is empty"); } } return null; } private boolean isLiveReloadEnabled(ReactInstanceManager instanceManager) { // Use instanceManager for checking if we use LiveReload mode. In this case we should not remove ReactNativeDevBundle.js file // because we get error with trying to get this after reloading. Issue: https://github.com/microsoft/react-native-code-push/issues/1272 if (instanceManager != null) { DevSupportManager devSupportManager = instanceManager.getDevSupportManager(); if (devSupportManager != null) { DevInternalSettings devInternalSettings = (DevInternalSettings)devSupportManager.getDevSettings(); Method[] methods = devInternalSettings.getClass().getMethods(); for (Method m : methods) { if (m.getName().equals("isReloadOnJSChangeEnabled")) { try { return (boolean) m.invoke(devInternalSettings); } catch (Exception x) { return false; } } } } } return false; } public void clearDebugCacheIfNeeded(ReactInstanceManager instanceManager) { if (mIsDebugMode && mSettingsManager.isPendingUpdate(null) && !isLiveReloadEnabled(instanceManager)) { // This needs to be kept in sync with https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManager.java#L78 File cachedDevBundle = new File(mContext.getFilesDir(), "ReactNativeDevBundle.js"); if (cachedDevBundle.exists()) { cachedDevBundle.delete(); } } } public boolean didUpdate() { return mDidUpdate; } public String getAppVersion() { return sAppVersion; } public String getAssetsBundleFileName() { return mAssetsBundleFileName; } public String getPublicKey() { return mPublicKey; } long getBinaryResourcesModifiedTime() { try { String packageName = this.mContext.getPackageName(); int codePushApkBuildTimeId = this.mContext.getResources().getIdentifier(CodePushConstants.CODE_PUSH_APK_BUILD_TIME_KEY, "string", packageName); // replace double quotes needed for correct restoration of long value from strings.xml // https://github.com/microsoft/cordova-plugin-code-push/issues/264 String codePushApkBuildTime = this.mContext.getResources().getString(codePushApkBuildTimeId).replaceAll("\"",""); return Long.parseLong(codePushApkBuildTime); } catch (Exception e) { throw new CodePushUnknownException("Error in getting binary resources modified time", e); } } public String getPackageFolder() { JSONObject codePushLocalPackage = mUpdateManager.getCurrentPackage(); if (codePushLocalPackage == null) { return null; } return mUpdateManager.getPackageFolderPath(codePushLocalPackage.optString("packageHash")); } @Deprecated public static String getBundleUrl() { return getJSBundleFile(); } @Deprecated public static String getBundleUrl(String assetsBundleFileName) { return getJSBundleFile(assetsBundleFileName); } public Context getContext() { return mContext; } public String getDeploymentKey() { return mDeploymentKey; } public static String getJSBundleFile() { return CodePush.getJSBundleFile(CodePushConstants.DEFAULT_JS_BUNDLE_NAME); } public static String getJSBundleFile(String assetsBundleFileName) { if (mCurrentInstance == null) { throw new CodePushNotInitializedException("A CodePush instance has not been created yet. Have you added it to your app's list of ReactPackages?"); } return mCurrentInstance.getJSBundleFileInternal(assetsBundleFileName); } public String getJSBundleFileInternal(String assetsBundleFileName) { this.mAssetsBundleFileName = assetsBundleFileName; String binaryJsBundleUrl = CodePushConstants.ASSETS_BUNDLE_PREFIX + assetsBundleFileName; String packageFilePath = null; try { packageFilePath = mUpdateManager.getCurrentPackageBundlePath(this.mAssetsBundleFileName); } catch (CodePushMalformedDataException e) { // We need to recover the app in case 'codepush.json' is corrupted CodePushUtils.log(e.getMessage()); clearUpdates(); } if (packageFilePath == null) { // There has not been any downloaded updates. CodePushUtils.logBundleUrl(binaryJsBundleUrl); sIsRunningBinaryVersion = true; return binaryJsBundleUrl; } JSONObject packageMetadata = this.mUpdateManager.getCurrentPackage(); if (isPackageBundleLatest(packageMetadata)) { CodePushUtils.logBundleUrl(packageFilePath); sIsRunningBinaryVersion = false; return packageFilePath; } else { // The binary version is newer. this.mDidUpdate = false; if (!this.mIsDebugMode || hasBinaryVersionChanged(packageMetadata)) { this.clearUpdates(); } CodePushUtils.logBundleUrl(binaryJsBundleUrl); sIsRunningBinaryVersion = true; return binaryJsBundleUrl; } } public String getServerUrl() { return mServerUrl; } void initializeUpdateAfterRestart() { // Reset the state which indicates that // the app was just freshly updated. mDidUpdate = false; JSONObject pendingUpdate = mSettingsManager.getPendingUpdate(); if (pendingUpdate != null) { JSONObject packageMetadata = this.mUpdateManager.getCurrentPackage(); if (packageMetadata == null || !isPackageBundleLatest(packageMetadata) && hasBinaryVersionChanged(packageMetadata)) { CodePushUtils.log("Skipping initializeUpdateAfterRestart(), binary version is newer"); return; } try { boolean updateIsLoading = pendingUpdate.getBoolean(CodePushConstants.PENDING_UPDATE_IS_LOADING_KEY); if (updateIsLoading) { // Pending update was initialized, but notifyApplicationReady was not called. // Therefore, deduce that it is a broken update and rollback. CodePushUtils.log("Update did not finish loading the last time, rolling back to a previous version."); sNeedToReportRollback = true; rollbackPackage(); } else { // There is in fact a new update running for the first // time, so update the local state to ensure the client knows. mDidUpdate = true; // Mark that we tried to initialize the new update, so that if it crashes, // we will know that we need to rollback when the app next starts. mSettingsManager.savePendingUpdate(pendingUpdate.getString(CodePushConstants.PENDING_UPDATE_HASH_KEY), /* isLoading */true); } } catch (JSONException e) { // Should not happen. throw new CodePushUnknownException("Unable to read pending update metadata stored in SharedPreferences", e); } } } void invalidateCurrentInstance() { mCurrentInstance = null; } boolean isDebugMode() { return mIsDebugMode; } boolean isRunningBinaryVersion() { return sIsRunningBinaryVersion; } private boolean isPackageBundleLatest(JSONObject packageMetadata) { try { Long binaryModifiedDateDuringPackageInstall = null; String binaryModifiedDateDuringPackageInstallString = packageMetadata.optString(CodePushConstants.BINARY_MODIFIED_TIME_KEY, null); if (binaryModifiedDateDuringPackageInstallString != null) { binaryModifiedDateDuringPackageInstall = Long.parseLong(binaryModifiedDateDuringPackageInstallString); } String packageAppVersion = packageMetadata.optString("appVersion", null); long binaryResourcesModifiedTime = this.getBinaryResourcesModifiedTime(); return binaryModifiedDateDuringPackageInstall != null && binaryModifiedDateDuringPackageInstall == binaryResourcesModifiedTime && (isUsingTestConfiguration() || sAppVersion.equals(packageAppVersion)); } catch (NumberFormatException e) { throw new CodePushUnknownException("Error in reading binary modified date from package metadata", e); } } private boolean hasBinaryVersionChanged(JSONObject packageMetadata) { String packageAppVersion = packageMetadata.optString("appVersion", null); return !sAppVersion.equals(packageAppVersion); } boolean needToReportRollback() { return sNeedToReportRollback; } public static void overrideAppVersion(String appVersionOverride) { sAppVersion = appVersionOverride; } private void rollbackPackage() { JSONObject failedPackage = mUpdateManager.getCurrentPackage(); mSettingsManager.saveFailedUpdate(failedPackage); mUpdateManager.rollbackPackage(); mSettingsManager.removePendingUpdate(); } public void setNeedToReportRollback(boolean needToReportRollback) { CodePush.sNeedToReportRollback = needToReportRollback; } /* The below 3 methods are used for running tests.*/ public static boolean isUsingTestConfiguration() { return sTestConfigurationFlag; } public void setDeploymentKey(String deploymentKey) { mDeploymentKey = deploymentKey; } public static void setUsingTestConfiguration(boolean shouldUseTestConfiguration) { sTestConfigurationFlag = shouldUseTestConfiguration; } public void clearUpdates() { mUpdateManager.clearUpdates(); mSettingsManager.removePendingUpdate(); mSettingsManager.removeFailedUpdates(); } public static void setReactInstanceHolder(ReactInstanceHolder reactInstanceHolder) { mReactInstanceHolder = reactInstanceHolder; } static ReactInstanceManager getReactInstanceManager() { if (mReactInstanceHolder == null) { return null; } return mReactInstanceHolder.getReactInstanceManager(); } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) { CodePushNativeModule codePushModule = new CodePushNativeModule(reactApplicationContext, this, mUpdateManager, mTelemetryManager, mSettingsManager); CodePushDialog dialogModule = new CodePushDialog(reactApplicationContext); List<NativeModule> nativeModules = new ArrayList<>(); nativeModules.add(codePushModule); nativeModules.add(dialogModule); return nativeModules; } // Deprecated in RN v0.47. public List<Class<? extends JavaScriptModule>> createJSModules() { return new ArrayList<>(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) { return new ArrayList<>(); } }
923dd24e10487ea699101f0f7967dd80435cab07
3,001
java
Java
src/main/java/com/github/jaemon/dinger/config/BeanConfiguration.java
AnswerAIL/dingtalk-spring-boot-starter
040dc77520a4c60d17c38cc6474966517636b45d
[ "Apache-2.0" ]
162
2020-08-03T02:54:34.000Z
2022-03-30T08:09:59.000Z
src/main/java/com/github/jaemon/dinger/config/BeanConfiguration.java
lw201608/dingtalk-spring-boot-starter
571cd157aa29516cfb828669da53f175abe2f4b0
[ "Apache-2.0" ]
17
2020-08-25T03:21:04.000Z
2022-02-23T11:20:14.000Z
src/main/java/com/github/jaemon/dinger/config/BeanConfiguration.java
AnswerAIL/dingtalk-spring-boot-starter
040dc77520a4c60d17c38cc6474966517636b45d
[ "Apache-2.0" ]
35
2020-09-24T05:32:00.000Z
2022-03-25T08:15:31.000Z
28.046729
91
0.723426
1,000,494
/* * Copyright ©2015-2021 Jaemon. 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.github.jaemon.dinger.config; import com.github.jaemon.dinger.support.sign.DingTalkSignAlgorithm; import com.github.jaemon.dinger.support.sign.DingerSignAlgorithm; import com.github.jaemon.dinger.multi.MultiDingerAlgorithmInjectRegister; import com.github.jaemon.dinger.support.*; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import static com.github.jaemon.dinger.constant.DingerConstant.MARKDOWN_MESSAGE; import static com.github.jaemon.dinger.constant.DingerConstant.TEXT_MESSAGE; /** * 实例化bean配置 * * @author Jaemon * @since 1.0 */ @Configuration @Import(AutoBeanConfiguration.class) public class BeanConfiguration { /** * 默认Text消息格式配置 * * @return CustomMessage */ @ConditionalOnMissingBean(name = TEXT_MESSAGE) @Bean(TEXT_MESSAGE) public CustomMessage textMessage() { return new TextMessage(); } /** * 默认markdown消息格式配置 * * @return CustomMessage */ @ConditionalOnMissingBean(name = MARKDOWN_MESSAGE) @Bean(MARKDOWN_MESSAGE) public CustomMessage markDownMessage() { return new MarkDownMessage(); } /** * 默认签名算法 * * @return 签名实体 */ @Bean @ConditionalOnMissingBean(DingerSignAlgorithm.class) public DingerSignAlgorithm dingerSignAlgorithm() { return new DingTalkSignAlgorithm(); } /** * 默认dkid生成配置 * * @return 返回dkid */ @Bean @ConditionalOnMissingBean(DingerIdGenerator.class) public DingerIdGenerator dingerIdGenerator() { return new DefaultDingerIdGenerator(); } /** * 默认异步执行回调实例 * * @return 回调实例 */ @Bean @ConditionalOnMissingBean(DingerAsyncCallback.class) public DingerAsyncCallback dingerAsyncCallback() { return new DefaultDingerAsyncCallable(); } @Bean @ConditionalOnMissingBean(DingerExceptionCallback.class) public DingerExceptionCallback dingerExceptionCallback() { return new DefaultDingerExceptionCallback(); } @Bean public static MultiDingerAlgorithmInjectRegister multiDingerAlgorithmInjectRegister() { return new MultiDingerAlgorithmInjectRegister(); } }
923dd2bf867cce9427b11efc7fe6d2e05f8a1d30
5,715
java
Java
libs/kg-commons/src/main/java/eu/ebrains/kg/commons/semantics/vocabularies/HBPVocabulary.java
HumanBrainProject/kg-core
496fc78792bdb10e1783163b0e09a1f0aafceecb
[ "Apache-2.0" ]
2
2020-12-20T16:11:50.000Z
2021-11-23T11:20:56.000Z
libs/kg-commons/src/main/java/eu/ebrains/kg/commons/semantics/vocabularies/HBPVocabulary.java
HumanBrainProject/kg-core
496fc78792bdb10e1783163b0e09a1f0aafceecb
[ "Apache-2.0" ]
7
2020-03-31T20:04:38.000Z
2021-06-04T07:53:33.000Z
libs/kg-commons/src/main/java/eu/ebrains/kg/commons/semantics/vocabularies/HBPVocabulary.java
HumanBrainProject/kg-core
496fc78792bdb10e1783163b0e09a1f0aafceecb
[ "Apache-2.0" ]
null
null
null
56.029412
116
0.76273
1,000,495
/* * Copyright 2018 - 2021 Swiss Federal Institute of Technology Lausanne (EPFL) * * 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. * * This open source software code was developed in part or in whole in the * Human Brain Project, funded from the European Union's Horizon 2020 * Framework Programme for Research and Innovation under * Specific Grant Agreements No. 720270, No. 785907, and No. 945539 * (Human Brain Project SGA1, SGA2 and SGA3). */ package eu.ebrains.kg.commons.semantics.vocabularies; public class HBPVocabulary { public static final String ALIAS = "hbp"; public static final String NAMESPACE = "https://schema.hbp.eu/"; public static final String CLIENT_NAMESPACE = NAMESPACE + "client/"; public static final String SHORT_NAME = NAMESPACE + "shortName"; public static final String RELATIVE_URL_OF_INTERNAL_LINK = NAMESPACE + "relativeUrl"; // FOR LINKING public static final String LINKING_INSTANCE_TYPE = NAMESPACE + "LinkingInstance"; public static final String LINKING_INSTANCE_FROM = LINKING_INSTANCE_TYPE.toLowerCase() + "/from"; public static final String LINKING_INSTANCE_TO = LINKING_INSTANCE_TYPE.toLowerCase() + "/to"; // FOR PROVENANCE private static final String PROVENANCE = NAMESPACE + "provenance/"; public static final String PROVENANCE_MODIFIED_AT = PROVENANCE + "modifiedAt"; public static final String PROVENANCE_CREATED_AT = PROVENANCE + "createdAt"; public static final String PROVENANCE_LAST_MODIFICATION_USER_ID = PROVENANCE + "lastModificationUserId"; public static final String PROVENANCE_REVISION = PROVENANCE + "revision"; public static final String PROVENANCE_IMMEDIATE_INDEX = PROVENANCE + "immediateIndex"; public static final String PROVENANCE_CREATED_BY = PROVENANCE + "createdBy"; // FOR RELEASING public static final String RELEASE_TYPE = HBPVocabulary.NAMESPACE + "Release"; public static final String RELEASE_INSTANCE = RELEASE_TYPE.toLowerCase() + "/instance"; public static final String RELEASE_REVISION = RELEASE_TYPE.toLowerCase() + "/revision"; public static final String RELEASE_STATE = RELEASE_TYPE.toLowerCase() + "/state"; public static final String RELEASE_LAST_DATE = RELEASE_TYPE.toLowerCase() + "/lastReleaseAt"; public static final String RELEASE_FIRST_DATE = RELEASE_TYPE.toLowerCase() + "/firstReleaseAt"; public static final String RELEASE_LAST_BY = RELEASE_TYPE.toLowerCase() + "/lastReleaseBy"; public static final String RELEASE_FIRST_BY = RELEASE_TYPE.toLowerCase() + "/firstReleaseBy"; //FOR INFERENCE public final static String INFERENCE_TYPE = HBPVocabulary.NAMESPACE + "Inference"; /** * declares the relationship of e.g. an editor instance which extends another (original) entity */ public final static String INFERENCE_EXTENDS = INFERENCE_TYPE.toLowerCase() + "/extends"; public final static String INFERENCE_ALTERNATIVES_TYPE = HBPVocabulary.NAMESPACE + "Alternative"; public final static String INFERENCE_ALTERNATIVES = INFERENCE_TYPE.toLowerCase() + "/alternatives"; public final static String INFERENCE_ALTERNATIVES_VALUE = INFERENCE_ALTERNATIVES.toLowerCase() + "/value"; public final static String INFERENCE_ALTERNATIVES_USERIDS = INFERENCE_ALTERNATIVES.toLowerCase() + "/userIds"; public final static String INFERENCE_ALTERNATIVES_SELECTED = INFERENCE_ALTERNATIVES.toLowerCase() + "/selected"; //FOR SPATIAL public static final String SPATIAL_TYPE = HBPVocabulary.NAMESPACE + "SpatialAnchoring"; public static final String SPATIAL_NAMESPACE = SPATIAL_TYPE.toLowerCase() + "/"; public static final String SPATIAL_FORMAT = SPATIAL_NAMESPACE + "format"; public static final String SPATIAL_COORDINATES = SPATIAL_NAMESPACE + "coordinates"; public static final String SPATIAL_REFERENCESPACE = SPATIAL_NAMESPACE + "referenceSpace"; public static final String SPATIAL_LOCATED_INSTANCE = SPATIAL_NAMESPACE + "locatedInstance"; public static final String SUGGESTION = HBPVocabulary.NAMESPACE + "suggestion"; public static final String SUGGESTION_OF = SUGGESTION + "/suggestionOf"; public static final String SUGGESTION_USER_ID = SUGGESTION + "/userId"; public static final String SUGGESTION_USER = SUGGESTION + "/user"; public static final String SUGGESTION_STATUS = SUGGESTION + "/status"; public static final String SUGGESTION_STATUS_CHANGED_BY = SUGGESTION_STATUS + "/updatedBy"; // FOR UPDATE public static final String INTERNAL = HBPVocabulary.NAMESPACE + "internal"; public static final String INTERNAL_HASHCODE = HBPVocabulary.INTERNAL + "/hashcode"; // FOR META public static final String TYPE = HBPVocabulary.NAMESPACE + "type"; public static final String TYPES =HBPVocabulary.NAMESPACE + "types"; public static final String TYPE_FIELDS = HBPVocabulary.TYPES + "/fields"; public static final String LINKED_TYPES = HBPVocabulary.NAMESPACE + "linkedTypes"; public static final String NUMBER_OF_OCCURRENCES = HBPVocabulary.NAMESPACE + "numberOfOccurrences"; public static final String CLIENT_DEFINED_FIELDS = HBPVocabulary.NAMESPACE + "client/types/fields"; }
923dd3eead946aa95d096630d6cdd951bd2f260d
3,234
java
Java
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/client/TraceWebAsyncClientAutoConfiguration.java
wangymd/spring-cloud
e9a7c8aa2b8780200ddd8929dd66c8c2f88e9f8e
[ "Apache-2.0" ]
1
2020-04-26T01:06:43.000Z
2020-04-26T01:06:43.000Z
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/client/TraceWebAsyncClientAutoConfiguration.java
heric-liu/spring-cloud-sleuth
f9578a5b697e73526694a0c568d3e19b61d8daa9
[ "Apache-2.0" ]
null
null
null
spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/client/TraceWebAsyncClientAutoConfiguration.java
heric-liu/spring-cloud-sleuth
f9578a5b697e73526694a0c568d3e19b61d8daa9
[ "Apache-2.0" ]
1
2022-03-26T08:24:51.000Z
2022-03-26T08:24:51.000Z
38.047059
117
0.810761
1,000,496
/* * Copyright 2013-2018 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.springframework.cloud.sleuth.instrument.web.client; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collection; import java.util.List; import brave.http.HttpTracing; import brave.spring.web.TracingAsyncClientHttpRequestInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.AsyncClientHttpRequestFactory; import org.springframework.http.client.AsyncClientHttpRequestInterceptor; import org.springframework.web.client.AsyncRestTemplate; /** * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} * enables span information propagation for {@link AsyncClientHttpRequestFactory} and * {@link AsyncRestTemplate} * * @author Marcin Grzejszczak * @since 1.0.0 */ @Configuration @SleuthWebClientEnabled @ConditionalOnProperty(value = "spring.sleuth.web.async.client.enabled", matchIfMissing = true) @ConditionalOnClass(AsyncRestTemplate.class) @ConditionalOnBean(HttpTracing.class) @AutoConfigureAfter(TraceWebServletAutoConfiguration.class) public class TraceWebAsyncClientAutoConfiguration { @ConditionalOnBean(AsyncRestTemplate.class) static class AsyncRestTemplateConfig { @Bean public TracingAsyncClientHttpRequestInterceptor asyncTracingClientHttpRequestInterceptor(HttpTracing httpTracing) { return (TracingAsyncClientHttpRequestInterceptor) TracingAsyncClientHttpRequestInterceptor.create(httpTracing); } @Configuration protected static class TraceInterceptorConfiguration { @Autowired(required = false) private Collection<AsyncRestTemplate> restTemplates; @Autowired private TracingAsyncClientHttpRequestInterceptor clientInterceptor; @PostConstruct public void init() { if (this.restTemplates != null) { for (AsyncRestTemplate restTemplate : this.restTemplates) { List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>( restTemplate.getInterceptors()); interceptors.add(this.clientInterceptor); restTemplate.setInterceptors(interceptors); } } } } } }
923dd3f8fab3ee61695cda5e6e728221a3c821b6
6,815
java
Java
src/main/java/net/andreho/aop/api/redefine/Redefinition.java
andreho/aop
b17265ca48bd365b473609ae682ea6e2a3cf27e5
[ "Apache-2.0" ]
null
null
null
src/main/java/net/andreho/aop/api/redefine/Redefinition.java
andreho/aop
b17265ca48bd365b473609ae682ea6e2a3cf27e5
[ "Apache-2.0" ]
null
null
null
src/main/java/net/andreho/aop/api/redefine/Redefinition.java
andreho/aop
b17265ca48bd365b473609ae682ea6e2a3cf27e5
[ "Apache-2.0" ]
null
null
null
22.055016
93
0.634923
1,000,497
package net.andreho.aop.api.redefine; /** * <br/>Created by a.hofmann on 23.03.2017 at 17:49. */ public abstract class Redefinition<T> { private static final Redefinition NONE = new Redefinition() { @Override public boolean isNeeded() { return false; } @Override public boolean isCompatibleWith(final Class type) { return type != null && !type.isPrimitive(); } }; /** * Checks whether the underlying redefinition instance is compatible with given type or not * @param type to test against * @return <b>true</b> if compatible; <b>false</b> otherwise. */ public abstract boolean isCompatibleWith(Class<?> type); /** * @return <b>true</b> if the redefinition must be done or <b>false</b> to do nothing. */ public boolean isNeeded() { return true; } public boolean toBoolean() { throw new UnsupportedOperationException(); } public byte toByte() { throw new UnsupportedOperationException(); } public short toShort() { throw new UnsupportedOperationException(); } public char toChar() { throw new UnsupportedOperationException(); } public int toInt() { throw new UnsupportedOperationException(); } public float toFloat() { throw new UnsupportedOperationException(); } public long toLong() { throw new UnsupportedOperationException(); } public double toDouble() { throw new UnsupportedOperationException(); } public T toObject() { throw new UnsupportedOperationException(); } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final boolean asBoolean(boolean value) { return isNeeded()? toBoolean() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final byte asByte(byte value) { return isNeeded()? toByte() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final short asShort(short value) { return isNeeded()? toShort() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final char asChar(char value) { return isNeeded()? toChar() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final int asInt(int value) { return isNeeded()? toInt() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final float asFloat(float value) { return isNeeded()? toFloat() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final long asLong(long value) { return isNeeded()? toLong() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final double asDouble(double value) { return isNeeded()? toDouble() : value; } /** * This method is going be called from intercepted method-call * @param value is the current result value * @return a new result value if needed */ public final T asObject(T value) { return isNeeded()? toObject() : value; } @Override public String toString() { return "Redefinition {" + String.valueOf(toObject()) + "}"; } /** * @param <T> * @return */ public static <T> Redefinition<T> none() { return NONE; } /** * @param <T> * @return */ public static <T> Redefinition<T> asNull() { return NullableRedefinition.INSTANCE; } /** * @param value * @return */ public static Redefinition<Boolean> as(boolean value) { return new BooleanRedefinition(value); } /** * @param value * @return */ public static Redefinition<Byte> as(byte value) { return new ByteRedefinition(value); } /** * @param value * @return */ public static Redefinition<Short> as(short value) { return new ShortRedefinition(value); } /** * @param value * @return */ public static Redefinition<Character> as(char value) { return new CharRedefinition(value); } /** * @param value * @return */ public static Redefinition<Integer> as(int value) { return new IntRedefinition(value); } /** * @param value * @return */ public static Redefinition<Float> as(float value) { return new FloatRedefinition(value); } /** * @param value * @return */ public static Redefinition<Long> as(long value) { return new LongRedefinition(value); } /** * @param value * @return */ public static Redefinition<Double> as(double value) { return new DoubleRedefinition(value); } /** * @param value * @return */ public static Redefinition<Boolean> as(Boolean value) { return value == null ? asNull() : as(value.booleanValue()); } /** * @param value * @return */ public static Redefinition<Byte> as(Byte value) { return value == null ? asNull() : as(value.byteValue()); } /** * @param value * @return */ public static Redefinition<Short> as(Short value) { return value == null ? asNull() : as(value.shortValue()); } /** * @param value * @return */ public static Redefinition<Character> as(Character value) { return value == null ? asNull() : as(value.charValue()); } /** * @param value * @return */ public static Redefinition<Integer> as(Integer value) { return value == null ? asNull() : as(value.intValue()); } /** * @param value * @return */ public static Redefinition<Float> as(Float value) { return value == null ? asNull() : as(value.floatValue()); } /** * @param value * @return */ public static Redefinition<Long> as(Long value) { return value == null ? asNull() : as(value.longValue()); } /** * @param value * @return */ public static Redefinition<Double> as(Double value) { return value == null ? asNull() : as(value.doubleValue()); } /** * @param value * @return */ public static <T> Redefinition<T> as(T value) { return value == null ? asNull() : new ObjectRedefinition<>(value); } }
923dd560a28f382298195477a82284f385fc8029
398
java
Java
src/main/java/com/erhannis/theallforum/data/events/post/PostTextUpdated.java
Erhannis/TheAllForum
897991ca3f6dc31cb2c2973aa1df95871060e5d9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/erhannis/theallforum/data/events/post/PostTextUpdated.java
Erhannis/TheAllForum
897991ca3f6dc31cb2c2973aa1df95871060e5d9
[ "Apache-2.0" ]
3
2020-03-04T23:37:48.000Z
2021-01-21T00:24:58.000Z
src/main/java/com/erhannis/theallforum/data/events/post/PostTextUpdated.java
Erhannis/TheAllForum
897991ca3f6dc31cb2c2973aa1df95871060e5d9
[ "Apache-2.0" ]
null
null
null
22.111111
79
0.738693
1,000,498
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.erhannis.theallforum.data.events.post; import javax.persistence.Entity; /** * * @author erhannis */ @Entity public class PostTextUpdated extends PostEvent { public String text; //TODO byte[]? }
923dd65fee4f3a3cd5bde168585acd00a9af1b16
646
java
Java
ocp-ui-api/src/main/java/gov/samhsa/ocp/ocpuiapi/service/dto/OrganizationDto.java
osehra-ocp/ocp-ui-api
5d0e2d78d9f336b9daaf36d7553842bd9416d04a
[ "Apache-2.0" ]
null
null
null
ocp-ui-api/src/main/java/gov/samhsa/ocp/ocpuiapi/service/dto/OrganizationDto.java
osehra-ocp/ocp-ui-api
5d0e2d78d9f336b9daaf36d7553842bd9416d04a
[ "Apache-2.0" ]
null
null
null
ocp-ui-api/src/main/java/gov/samhsa/ocp/ocpuiapi/service/dto/OrganizationDto.java
osehra-ocp/ocp-ui-api
5d0e2d78d9f336b9daaf36d7553842bd9416d04a
[ "Apache-2.0" ]
1
2020-03-23T03:18:30.000Z
2020-03-23T03:18:30.000Z
25.84
52
0.798762
1,000,499
package gov.samhsa.ocp.ocpuiapi.service.dto; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Optional; @Data @Builder @AllArgsConstructor @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class OrganizationDto { private String logicalId; private List<IdentifierDto> identifiers; private boolean active; private String name; private List<AddressDto> addresses; private List<TelecomDto> telecoms; private Optional<List<ContactDto>> contacts; }
923dd6673bbfb70639ff354a18454857c79596ea
627
java
Java
LAB_WORK/lab_4/src/main/java/devops1/lab5/MonthName.java
theabhishek07/Build_And_Release_Management_Lab
23462e3a9bd6b19878ab7471ca7730382e29b57a
[ "MIT" ]
3
2020-04-29T13:43:57.000Z
2020-05-18T09:54:02.000Z
LAB_WORK/lab_4/src/main/java/devops1/lab5/MonthName.java
theabhishek07/Build_And_Release_Management_Lab
23462e3a9bd6b19878ab7471ca7730382e29b57a
[ "MIT" ]
null
null
null
LAB_WORK/lab_4/src/main/java/devops1/lab5/MonthName.java
theabhishek07/Build_And_Release_Management_Lab
23462e3a9bd6b19878ab7471ca7730382e29b57a
[ "MIT" ]
null
null
null
28.5
41
0.676236
1,000,500
package devops1.lab5; public class MonthName { public static void main(String args[]) { int month= Integer.parseInt(args[0]); if(month==1){System.out.println("Jan");} if(month==2){System.out.println("Feb");} if(month==3){System.out.println("Mar");} if(month==4){System.out.println("Apr");} if(month==5){System.out.println("May");} if(month==6){System.out.println("June");} if(month==7){System.out.println("Jul");} if(month==8){System.out.println("Aug");} if(month==9){System.out.println("Sep");} if(month==10){System.out.println("Oct");} if(month==11){System.out.println("Nov");} if(month==12){System.out.println("Dec");} } }
923dd696b0e4a69ec253fc436236dbb3f0a1fb91
5,091
java
Java
src/test/java/com/gnopai/ji65/assembler/DirectiveDataAssemblerTest.java
gnopai/ji65
034c0e8e169cf99930ed34c8fb2f28ff9ac742bf
[ "MIT" ]
null
null
null
src/test/java/com/gnopai/ji65/assembler/DirectiveDataAssemblerTest.java
gnopai/ji65
034c0e8e169cf99930ed34c8fb2f28ff9ac742bf
[ "MIT" ]
null
null
null
src/test/java/com/gnopai/ji65/assembler/DirectiveDataAssemblerTest.java
gnopai/ji65
034c0e8e169cf99930ed34c8fb2f28ff9ac742bf
[ "MIT" ]
null
null
null
40.086614
101
0.685327
1,000,501
package com.gnopai.ji65.assembler; import com.gnopai.ji65.DirectiveType; import com.gnopai.ji65.parser.expression.Expression; import com.gnopai.ji65.parser.expression.ExpressionEvaluator; import com.gnopai.ji65.parser.expression.PrimaryExpression; import com.gnopai.ji65.parser.statement.DirectiveStatement; import com.gnopai.ji65.scanner.FileLoader; import com.gnopai.ji65.scanner.TokenType; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class DirectiveDataAssemblerTest { private final ExpressionEvaluator expressionEvaluator = mock(ExpressionEvaluator.class); private final FileLoader fileLoader = mock(FileLoader.class); private final Environment environment = new Environment(); @Test void testReserveDirective() { int size = 44; Expression sizeExpression = new PrimaryExpression(TokenType.NUMBER, size); when(expressionEvaluator.evaluate(sizeExpression, environment)).thenReturn(size); DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.RESERVE) .expression(sizeExpression) .build(); List<SegmentData> segmentData = assemble(statement); List<SegmentData> expectedSegmentData = List.of( new ReservedData(size) ); assertEquals(expectedSegmentData, segmentData); } @Test void testByteDirective() { Expression expression1 = new PrimaryExpression(TokenType.NUMBER, 11); Expression expression2 = new PrimaryExpression(TokenType.NUMBER, 22); Expression expression3 = new PrimaryExpression(TokenType.NUMBER, 33); DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.BYTE) .expressions(List.of(expression1, expression2, expression3)) .build(); List<SegmentData> segmentData = assemble(statement); List<SegmentData> expectedSegmentData = List.of( new UnresolvedExpression(expression1, true), new UnresolvedExpression(expression2, true), new UnresolvedExpression(expression3, true) ); assertEquals(expectedSegmentData, segmentData); } @Test void testWordDirective() { Expression expression1 = new PrimaryExpression(TokenType.NUMBER, 11); Expression expression2 = new PrimaryExpression(TokenType.NUMBER, 22); Expression expression3 = new PrimaryExpression(TokenType.NUMBER, 33); DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.WORD) .expressions(List.of(expression1, expression2, expression3)) .build(); List<SegmentData> segmentData = assemble(statement); List<SegmentData> expectedSegmentData = List.of( new UnresolvedExpression(expression1, false), new UnresolvedExpression(expression2, false), new UnresolvedExpression(expression3, false) ); assertEquals(expectedSegmentData, segmentData); } @Test void testIncludeBinaryDirective() { String filename = "wheeee.chr"; DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.INCLUDE_BINARY) .name(filename) .build(); List<Byte> bytes = List.of((byte) 0x12, (byte) 0xFF); when(fileLoader.loadBinaryFile(filename)).thenReturn(Optional.of(bytes)); List<SegmentData> segmentData = assemble(statement); List<SegmentData> expectedSegmentData = List.of(new RawData(bytes)); assertEquals(expectedSegmentData, segmentData); } @Test void testIncludeBinaryDirective_badFile() { String filename = "whee.chr"; DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.INCLUDE_BINARY) .name(filename) .build(); when(fileLoader.loadBinaryFile(filename)).thenReturn(Optional.empty()); RuntimeException exception = assertThrows(RuntimeException.class, () -> assemble(statement)); assertEquals("Failed to open binary file: whee.chr", exception.getMessage()); } @Test void testUnsupportedDirectiveType() { DirectiveStatement statement = DirectiveStatement.builder() .type(DirectiveType.MACRO_END) .build(); RuntimeException exception = assertThrows(RuntimeException.class, () -> assemble(statement)); assertEquals("Directive type not supported: MACRO_END", exception.getMessage()); } private List<SegmentData> assemble(DirectiveStatement statement) { return new DirectiveDataAssembler(expressionEvaluator, fileLoader) .assemble(statement, environment); } }
923dd9188585ade81cc83651eac5f3d7f2ba20ad
1,148
java
Java
chapter_004/src/main/java/ru/job4j/map/UserHash.java
EvgeniyUlanov/eulanov
329195847d164e27bd5079290241eb70ad5c6e6d
[ "Apache-2.0" ]
null
null
null
chapter_004/src/main/java/ru/job4j/map/UserHash.java
EvgeniyUlanov/eulanov
329195847d164e27bd5079290241eb70ad5c6e6d
[ "Apache-2.0" ]
null
null
null
chapter_004/src/main/java/ru/job4j/map/UserHash.java
EvgeniyUlanov/eulanov
329195847d164e27bd5079290241eb70ad5c6e6d
[ "Apache-2.0" ]
null
null
null
22.509804
103
0.559233
1,000,502
package ru.job4j.map; import java.util.Calendar; /** * class UserHash. */ public class UserHash { /** name.*/ private String name; /** number of children.*/ private int children; /** birthdate.*/ private Calendar birthday; /** * constructor. * @param name - name. * @param children - children. * @param birthday - birthday. */ public UserHash(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } /** * method to string. * @return string. */ @Override public String toString() { return String.format("%s(%s children) - %s.%s.%s", name, children, birthday.get(Calendar.YEAR), birthday.get(Calendar.MONTH), birthday.get(Calendar.DATE)); } /** * metod hashCode. * @return int. */ @Override public int hashCode() { int result = 17; result = result * 31 + name.hashCode(); result = result * 31 + children; result = result * 31 + birthday.hashCode(); return result; } }
923ddaa0a02ae5f15c185405bcbf5878aafcdc10
1,351
java
Java
src/main/java/com/fun/project/system/post/mapper/PostMapper.java
mrdjun/FunBoot-fast
57301891ab208038e5dd643eb57b22813738ab2d
[ "Apache-2.0" ]
25
2019-09-12T03:40:46.000Z
2021-02-02T01:27:42.000Z
src/main/java/com/fun/project/system/post/mapper/PostMapper.java
mrdjun/FunBoot-fast
57301891ab208038e5dd643eb57b22813738ab2d
[ "Apache-2.0" ]
2
2020-08-09T12:36:06.000Z
2020-10-13T03:37:34.000Z
src/main/java/com/fun/project/system/post/mapper/PostMapper.java
mrdjun/FunBoot-fast
57301891ab208038e5dd643eb57b22813738ab2d
[ "Apache-2.0" ]
10
2019-10-12T07:40:56.000Z
2020-09-28T03:33:58.000Z
16.083333
55
0.530718
1,000,503
package com.fun.project.system.post.mapper; import java.util.List; import com.fun.project.system.post.domain.Post; /** * 岗位信息 数据层 * * @author fun */ public interface PostMapper { /** * 查询岗位数据集合 * * @param post 岗位信息 * @return 岗位数据集合 */ public List<Post> selectPostList(Post post); /** * 查询所有岗位 * * @return 岗位列表 */ public List<Post> selectPostAll(); /** * 根据用户ID查询岗位 * * @param userId 用户ID * @return 岗位列表 */ public List<Post> selectPostsByUserId(Long userId); /** * 通过岗位ID查询岗位信息 * * @param postId 岗位ID * @return 角色对象信息 */ public Post selectPostById(Long postId); /** * 批量删除岗位信息 * * @param ids 需要删除的数据ID * @return 结果 */ public int deletePostByIds(Long[] ids); /** * 修改岗位信息 * * @param post 岗位信息 * @return 结果 */ public int updatePost(Post post); /** * 新增岗位信息 * * @param post 岗位信息 * @return 结果 */ public int insertPost(Post post); /** * 校验岗位名称 * * @param postName 岗位名称 * @return 结果 */ public Post checkPostNameUnique(String postName); /** * 校验岗位编码 * * @param postCode 岗位编码 * @return 结果 */ public Post checkPostCodeUnique(String postCode); }
923ddb03024105c6b26123e75c280ebdd3ee70e0
1,564
java
Java
src/main/java/frc/robot/commands/AvoidWall.java
Team-1922/Scarecrow2021
15ac003b619cf3004043a7a56324c7acf3f15ae1
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/java/frc/robot/commands/AvoidWall.java
Team-1922/Scarecrow2021
15ac003b619cf3004043a7a56324c7acf3f15ae1
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/main/java/frc/robot/commands/AvoidWall.java
Team-1922/Scarecrow2021
15ac003b619cf3004043a7a56324c7acf3f15ae1
[ "BSD-3-Clause", "MIT" ]
null
null
null
25.639344
74
0.70844
1,000,504
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands; //ea is bill gates // not fubnny did not laughn import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.DriveTrainSubsystem; import frc.robot.subsystems.TOF; public class AvoidWall extends CommandBase { DriveTrainSubsystem m_driveTrain; TOF m_eyes; private double leftTOF; private double rightTOF; /** Creates a new AvoidWall. */ public AvoidWall(DriveTrainSubsystem driveTrain, TOF eyes ) { m_driveTrain = driveTrain; m_eyes = eyes; // Use addRequirements() here to declare subsystem dependencies. addRequirements(m_driveTrain, m_eyes); } // Called when the command is initially scheduled. @Override public void initialize() {} // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { leftTOF = m_eyes.getDistanceLeft(); rightTOF = m_eyes.getDistanceRight(); if (leftTOF <= 500 || rightTOF <= 500) { m_driveTrain.drive(-.1,.1); } else m_driveTrain.drive(-.1, -.1); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { m_driveTrain.drive(0, 0); } // Returns true when the command should end. @Override public boolean isFinished() { if (leftTOF <= 100 || rightTOF <= 100) { return true; } return false; } }
923ddb76bc2aa8a308e8625018b8b91db8653e6e
4,946
java
Java
src/main/java/com/github/lampaa/smi/dtoV1/PowerReadingsType.java
lampaa/nvidia-smi-rest
31f7e39e1f20b770e6fbc3976efa403087f340a3
[ "MIT" ]
3
2021-04-15T08:40:27.000Z
2022-01-23T23:57:30.000Z
src/main/java/com/github/lampaa/smi/dtoV1/PowerReadingsType.java
lampaa/nvidia-smi-rest
31f7e39e1f20b770e6fbc3976efa403087f340a3
[ "MIT" ]
1
2021-11-04T08:26:54.000Z
2022-01-23T23:57:49.000Z
src/main/java/com/github/lampaa/smi/dtoV1/PowerReadingsType.java
lampaa/nvidia-smi-rest
31f7e39e1f20b770e6fbc3976efa403087f340a3
[ "MIT" ]
1
2022-01-06T03:37:44.000Z
2022-01-06T03:37:44.000Z
24.364532
63
0.595835
1,000,505
package com.github.lampaa.smi.dtoV1; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "power_readingsType", propOrder = { "powerState", "powerManagement", "powerDraw", "powerLimit", "defaultPowerLimit", "enforcedPowerLimit", "minPowerLimit", "maxPowerLimit" }) public class PowerReadingsType { @XmlElement(name = "power_state", required = true) protected String powerState; @XmlElement(name = "power_management", required = true) protected String powerManagement; @XmlElement(name = "power_draw", required = true) protected String powerDraw; @XmlElement(name = "power_limit", required = true) protected String powerLimit; @XmlElement(name = "default_power_limit", required = true) protected String defaultPowerLimit; @XmlElement(name = "enforced_power_limit", required = true) protected String enforcedPowerLimit; @XmlElement(name = "min_power_limit", required = true) protected String minPowerLimit; @XmlElement(name = "max_power_limit", required = true) protected String maxPowerLimit; /** * Gets the value of the powerState property. * * @return possible object is * {@link String } */ public String getPowerState() { return powerState; } /** * Sets the value of the powerState property. * * @param value allowed object is * {@link String } */ public void setPowerState(String value) { this.powerState = value; } /** * Gets the value of the powerManagement property. * * @return possible object is * {@link String } */ public String getPowerManagement() { return powerManagement; } /** * Sets the value of the powerManagement property. * * @param value allowed object is * {@link String } */ public void setPowerManagement(String value) { this.powerManagement = value; } /** * Gets the value of the powerDraw property. * * @return possible object is * {@link String } */ public String getPowerDraw() { return powerDraw; } /** * Sets the value of the powerDraw property. * * @param value allowed object is * {@link String } */ public void setPowerDraw(String value) { this.powerDraw = value; } /** * Gets the value of the powerLimit property. * * @return possible object is * {@link String } */ public String getPowerLimit() { return powerLimit; } /** * Sets the value of the powerLimit property. * * @param value allowed object is * {@link String } */ public void setPowerLimit(String value) { this.powerLimit = value; } /** * Gets the value of the defaultPowerLimit property. * * @return possible object is * {@link String } */ public String getDefaultPowerLimit() { return defaultPowerLimit; } /** * Sets the value of the defaultPowerLimit property. * * @param value allowed object is * {@link String } */ public void setDefaultPowerLimit(String value) { this.defaultPowerLimit = value; } /** * Gets the value of the enforcedPowerLimit property. * * @return possible object is * {@link String } */ public String getEnforcedPowerLimit() { return enforcedPowerLimit; } /** * Sets the value of the enforcedPowerLimit property. * * @param value allowed object is * {@link String } */ public void setEnforcedPowerLimit(String value) { this.enforcedPowerLimit = value; } /** * Gets the value of the minPowerLimit property. * * @return possible object is * {@link String } */ public String getMinPowerLimit() { return minPowerLimit; } /** * Sets the value of the minPowerLimit property. * * @param value allowed object is * {@link String } */ public void setMinPowerLimit(String value) { this.minPowerLimit = value; } /** * Gets the value of the maxPowerLimit property. * * @return possible object is * {@link String } */ public String getMaxPowerLimit() { return maxPowerLimit; } /** * Sets the value of the maxPowerLimit property. * * @param value allowed object is * {@link String } */ public void setMaxPowerLimit(String value) { this.maxPowerLimit = value; } }
923ddb7a118ee6dd58405ea0257d3a0be8145170
1,711
java
Java
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/CFUtil.java
Danielzhulin/activemq-artemis
fe42fd9155929a30e4bf4e42b5a971fbb4b313e1
[ "Apache-2.0" ]
868
2015-05-07T07:38:19.000Z
2022-03-22T08:36:33.000Z
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/CFUtil.java
Danielzhulin/activemq-artemis
fe42fd9155929a30e4bf4e42b5a971fbb4b313e1
[ "Apache-2.0" ]
2,100
2015-04-29T15:29:35.000Z
2022-03-31T20:21:54.000Z
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/util/CFUtil.java
Danielzhulin/activemq-artemis
fe42fd9155929a30e4bf4e42b5a971fbb4b313e1
[ "Apache-2.0" ]
967
2015-05-03T14:28:27.000Z
2022-03-31T11:53:21.000Z
38.886364
101
0.70602
1,000,506
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.util; import javax.jms.ConnectionFactory; import org.apache.qpid.jms.JmsConnectionFactory; public class CFUtil { public static ConnectionFactory createConnectionFactory(String protocol, String uri) { if (protocol.toUpperCase().equals("OPENWIRE")) { return new org.apache.activemq.ActiveMQConnectionFactory(uri); } else if (protocol.toUpperCase().equals("AMQP")) { if (uri.startsWith("tcp://")) { // replacing tcp:// by amqp:// uri = "amqp" + uri.substring(3); } return new JmsConnectionFactory(uri); } else if (protocol.toUpperCase().equals("CORE") || protocol.toUpperCase().equals("ARTEMIS")) { return new org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory(uri); } else { throw new IllegalStateException("Unkown:" + protocol); } } }
923ddc5e367b10530203e362b9635136b447d92f
809
java
Java
src/main/java/nc/crafting/machine/ElectrolyserRecipes.java
impbk2002/NuclearCraft
3e4619e7be3f2cd5d4d90d055738f51fcf694b77
[ "CC0-1.0" ]
null
null
null
src/main/java/nc/crafting/machine/ElectrolyserRecipes.java
impbk2002/NuclearCraft
3e4619e7be3f2cd5d4d90d055738f51fcf694b77
[ "CC0-1.0" ]
null
null
null
src/main/java/nc/crafting/machine/ElectrolyserRecipes.java
impbk2002/NuclearCraft
3e4619e7be3f2cd5d4d90d055738f51fcf694b77
[ "CC0-1.0" ]
null
null
null
35.173913
195
0.747837
1,000,507
package nc.crafting.machine; import nc.crafting.NCRecipeHelper; import nc.item.NCItems; import net.minecraft.item.ItemStack; public class ElectrolyserRecipes extends NCRecipeHelper { private static final ElectrolyserRecipes recipes = new ElectrolyserRecipes(); public ElectrolyserRecipes(){ super(1, 4); } public static final NCRecipeHelper instance() { return recipes; } public void addRecipes() { //addRecipe(new ItemStack(NCItems.fuel, 12, 34), new ItemStack(NCItems.fuel, 4, 35), new ItemStack(NCItems.fuel, 4, 36), new ItemStack(NCItems.fuel, 3, 36), new ItemStack(NCItems.fuel, 1, 37)); addRecipe(new ItemStack(NCItems.fuel, 12, 45), new ItemStack(NCItems.fuel, 4, 35), new ItemStack(NCItems.fuel, 4, 36), new ItemStack(NCItems.fuel, 3, 36), new ItemStack(NCItems.fuel, 1, 37)); } }
923ddd88bdd235e7c1694caf9b672dc788a8d6cd
1,735
java
Java
persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/CustomRepositoryLiveTest.java
sebx59/tutorials
a47dcd75c2305dd938b11d3893c92878d9d61787
[ "MIT" ]
null
null
null
persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/CustomRepositoryLiveTest.java
sebx59/tutorials
a47dcd75c2305dd938b11d3893c92878d9d61787
[ "MIT" ]
null
null
null
persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/CustomRepositoryLiveTest.java
sebx59/tutorials
a47dcd75c2305dd938b11d3893c92878d9d61787
[ "MIT" ]
null
null
null
29.40678
109
0.725072
1,000,508
package com.baeldung.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.config.CustomRepositoryMongoConfig; import com.baeldung.model.Book; /** * * This test requires: * * mongodb instance running on the environment * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CustomRepositoryMongoConfig.class) public class CustomRepositoryLiveTest { @Autowired private BookRepository bookRepository; @Autowired private MongoOperations mongoOps; @Before public void testSetup() { if (!mongoOps.collectionExists(Book.class)) { mongoOps.createCollection(Book.class); } } @After public void tearDown() { mongoOps.dropCollection(Book.class); } @Test public void whenInsertingBook_thenBookIsInserted() { final Book book = new Book(); book.setTitle("The Lord of the Rings"); book.setAuthor("JRR Tolkien"); Book savedBook = bookRepository.save(book); Book result = mongoOps.findOne(Query.query(Criteria.where("_id").is(savedBook.getId())), Book.class); assertEquals(result.getTitle(), "The Lord of the Rings"); } }
923dddfc016989b8a0ea9a4329b7fb79f32d321f
312
java
Java
src/main/java/com/example/so/grpc/ComponentWithGrpcClientInside.java
bcamel/stackoverflow_grpc_starter
e8903ce17d6e560b5180b9c1b2c5b2501162d8aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/so/grpc/ComponentWithGrpcClientInside.java
bcamel/stackoverflow_grpc_starter
e8903ce17d6e560b5180b9c1b2c5b2501162d8aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/so/grpc/ComponentWithGrpcClientInside.java
bcamel/stackoverflow_grpc_starter
e8903ce17d6e560b5180b9c1b2c5b2501162d8aa
[ "Apache-2.0" ]
null
null
null
24
93
0.830128
1,000,509
package com.example.so.grpc; import net.devh.boot.grpc.client.inject.GrpcClient; import org.springframework.stereotype.Component; @Component public class ComponentWithGrpcClientInside { @GrpcClient("stocks") private StockStaticDataRequestServiceGrpc.StockStaticDataRequestServiceBlockingStub stub; }
923ddf6fd6a3af79ae387076504c33da719db266
1,530
java
Java
src/main/java/org/noop/goodfsm/akka/AbstractFsmWithStash.java
noop1000/goodfsm
2bac1955f1a2a7dc6b5a3f7f8b1b74f337233436
[ "Apache-2.0" ]
1
2016-08-17T00:23:37.000Z
2016-08-17T00:23:37.000Z
src/main/java/org/noop/goodfsm/akka/AbstractFsmWithStash.java
noop1000/goodfsm
2bac1955f1a2a7dc6b5a3f7f8b1b74f337233436
[ "Apache-2.0" ]
null
null
null
src/main/java/org/noop/goodfsm/akka/AbstractFsmWithStash.java
noop1000/goodfsm
2bac1955f1a2a7dc6b5a3f7f8b1b74f337233436
[ "Apache-2.0" ]
null
null
null
28.867925
98
0.677124
1,000,510
package org.noop.goodfsm.akka; import org.noop.goodfsm.fsm.AbstractFsm; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ public abstract class AbstractFsmWithStash<T> extends AbstractFsm<T> implements IFsmWithStash<T> { private IStashAware stashAdaptor; @Override public void stash() { if (stashAdaptor != null) { stashAdaptor.stash(); } } @Override public void unstashAll() { if (stashAdaptor != null) { stashAdaptor.stash(); } } @Override public void unstash() { if (stashAdaptor != null) { stashAdaptor.stash(); } } @Override public void setStashAdaptor(IStashAware adaptor) { this.stashAdaptor = adaptor; } }
923ddfac7310a0a7435df1539cd0c7cffda50147
2,791
java
Java
algorithms/code/leetcode/lc235_lowest_common_ancestor_of_a_binary_search_tree/LC235LowestCommonAncestorOfABinarySearchTreeTests.java
altermarkive/training
6a13f5b2f466156ad5db0e25da0e601d2404b4c3
[ "MIT" ]
null
null
null
algorithms/code/leetcode/lc235_lowest_common_ancestor_of_a_binary_search_tree/LC235LowestCommonAncestorOfABinarySearchTreeTests.java
altermarkive/training
6a13f5b2f466156ad5db0e25da0e601d2404b4c3
[ "MIT" ]
1
2022-02-16T11:28:56.000Z
2022-02-16T11:28:56.000Z
algorithms/code/leetcode/lc235_lowest_common_ancestor_of_a_binary_search_tree/LC235LowestCommonAncestorOfABinarySearchTreeTests.java
altermarkive/training
6a13f5b2f466156ad5db0e25da0e601d2404b4c3
[ "MIT" ]
null
null
null
39.871429
123
0.668219
1,000,511
package leetcode.lc235_lowest_common_ancestor_of_a_binary_search_tree; import org.junit.jupiter.api.Test; import leetcode.lc235_lowest_common_ancestor_of_a_binary_search_tree.LC235LowestCommonAncestorOfABinarySearchTree.TreeNode; import static org.junit.jupiter.api.Assertions.assertEquals; public final class LC235LowestCommonAncestorOfABinarySearchTreeTests { @Test public void testExample() throws Exception { TreeNode tree = new TreeNode(6); tree.left = new TreeNode(2); tree.right = new TreeNode(8); tree.left.left = new TreeNode(0); tree.left.right = new TreeNode(4); tree.left.right.left = new TreeNode(3); tree.left.right.right = new TreeNode(5); tree.right.left = new TreeNode(7); tree.right.right = new TreeNode(9); assertEquals(tree, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree.left, tree.right)); assertEquals(tree.left, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree.left, tree.left.right)); } @Test public void testExample1() throws Exception { TreeNode tree = new TreeNode(5); tree.left = new TreeNode(3); tree.right = new TreeNode(6); tree.left.left = new TreeNode(2); tree.left.right = new TreeNode(4); tree.left.left.left = new TreeNode(1); assertEquals(3, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree.left.left.left, tree.left.right).val); } @Test public void testExample2() throws Exception { TreeNode tree = new TreeNode(6); tree.left = new TreeNode(2); tree.right = new TreeNode(8); tree.left.left = new TreeNode(0); tree.left.right = new TreeNode(4); tree.left.left = new TreeNode(7); tree.right.right = new TreeNode(9); tree.left.right.left = new TreeNode(3); tree.left.right.right = new TreeNode(5); assertEquals(4, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree.left.right.left, tree.left.right.right).val); } @Test public void testExample3() throws Exception { TreeNode tree = new TreeNode(2); tree.left = new TreeNode(1); assertEquals(2, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree, tree.left).val); } @Test public void testExample4() throws Exception { TreeNode tree = new TreeNode(2); tree.right = new TreeNode(3); assertEquals(2, new LC235LowestCommonAncestorOfABinarySearchTree().lowestCommonAncestor(tree, tree.right, tree).val); } }
923ddffe0632e61aed42d07cf2eec12fbd94be8b
727
java
Java
Variant Programs/4/4-37/C3063467A2.java
hjc851/SourceCodePlagiarismDetectionDataset
f67bc79576a8df85e8a7b4f5d012346e3a76db37
[ "MIT" ]
null
null
null
Variant Programs/4/4-37/C3063467A2.java
hjc851/SourceCodePlagiarismDetectionDataset
f67bc79576a8df85e8a7b4f5d012346e3a76db37
[ "MIT" ]
null
null
null
Variant Programs/4/4-37/C3063467A2.java
hjc851/SourceCodePlagiarismDetectionDataset
f67bc79576a8df85e8a7b4f5d012346e3a76db37
[ "MIT" ]
null
null
null
27.961538
89
0.679505
1,000,512
import Simulations.ProcedureSimulation; import static java.lang.System.out; public class C3063467A2 { public static synchronized void main(String[] variable) { String less; less = ("SQLSypSzGQslKLyTbfu"); if (variable.length < 1) { out.println("Error: No input file provided. Please run again with a input param."); } else { java.lang.String representations; Simulations.ProcedureSimulation component; representations = (""); for (java.lang.String fh : variable) { representations = (fh); } component = (new Simulations.ProcedureSimulation()); component.drive(representations); } } public static final double crucial = 0.2942075478126498; }
923de07403e4f2d387661eb5f83f201f005a69fe
2,711
java
Java
src/main/java/com/manning/hip/ch7/friendsofafriend/CalcMapReduce.java
JLLeitschuh/hadoop-book
edf568190375b61f37498b892db174d8234b1692
[ "Apache-2.0" ]
114
2015-01-06T16:00:30.000Z
2022-02-17T04:23:35.000Z
src/main/java/com/manning/hip/ch7/friendsofafriend/CalcMapReduce.java
jesman/hadoop-book
c6ac47eb621ef9ba23fc62c1f1b37bb60c65f92d
[ "Apache-2.0" ]
3
2015-07-24T22:29:15.000Z
2019-06-13T10:19:56.000Z
src/main/java/com/manning/hip/ch7/friendsofafriend/CalcMapReduce.java
jesman/hadoop-book
c6ac47eb621ef9ba23fc62c1f1b37bb60c65f92d
[ "Apache-2.0" ]
135
2015-01-18T13:22:44.000Z
2022-02-25T00:01:37.000Z
28.239583
71
0.616378
1,000,513
package com.manning.hip.ch7.friendsofafriend; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; import java.io.IOException; public final class CalcMapReduce { public static class TextPair extends Text { public static char separator = '\t'; public TextPair() { super(); } public TextPair(String person1, String person2) { super(joinPersonsLexicographically(person1, person2)); } public void set(String person1, String person2) { super.set(joinPersonsLexicographically(person1, person2)); } public static String joinPersonsLexicographically(String person1, String person2) { if (person1.compareTo(person2) < 0) { return person1 + separator + person2; } return person2 + separator + person1; } } public static class Map extends Mapper<Text, Text, TextPair, IntWritable> { private TextPair pair = new TextPair(); private IntWritable one = new IntWritable(1); private IntWritable two = new IntWritable(2); @Override protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { String[] friends = StringUtils.split(value.toString()); for (int i = 0; i < friends.length; i++) { // they already know each other, so emit the pair with // a "1" to indicate this // pair.set(key.toString(), friends[i]); context.write(pair, one); // go through all the remaining friends in the list // and emit the fact that they are 2nd-degree friends // for (int j = i + 1; j < friends.length; j++) { pair.set(friends[i], friends[j]); context.write(pair, two); } } } } public static class Reduce extends Reducer<TextPair, IntWritable, TextPair, IntWritable> { private IntWritable friendsInCommon = new IntWritable(); public void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int commonFriends = 0; boolean alreadyFriends = false; // if the friends know each other then we'll eventually // see a value will be a "1", which will cause us to // break out of the loop // for (IntWritable hops : values) { if (hops.get() == 1) { alreadyFriends = true; break; } commonFriends++; } if (!alreadyFriends) { friendsInCommon.set(commonFriends); context.write(key, friendsInCommon); } } } }
923de0e772aa06fe82c0003f0ce2db4847b1c3ba
2,641
java
Java
Ghidra/Features/Base/src/main/java/ghidra/app/services/StringTranslationService.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Features/Base/src/main/java/ghidra/app/services/StringTranslationService.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Features/Base/src/main/java/ghidra/app/services/StringTranslationService.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
3
2019-12-02T13:36:50.000Z
2019-12-04T05:40:12.000Z
34.75
88
0.757289
1,000,514
/* ### * 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.services; import java.util.List; import ghidra.framework.plugintool.Plugin; import ghidra.framework.plugintool.util.PluginDescription; import ghidra.program.model.listing.Program; import ghidra.program.util.ProgramLocation; import ghidra.util.HelpLocation; /** * Interface for providing string translating services. * <p> * Implementations of this interface are usually done via a Plugin * and then registered via {@link Plugin}'s registerServiceProvided(). */ public interface StringTranslationService { /** * Returns the name of this translation service. Used when building menus to allow * the user to pick a translation service. * * @return string name. */ public String getTranslationServiceName(); /** * Returns the {@link HelpLocation} instance that describes where to direct the user * for help when they hit f1. * * @return {@link HelpLocation} instance or null. */ public default HelpLocation getHelpLocation() { return null; } /** * Requests this translation service to translate the specified string data instances. * <p> * The implementation generally should not block when performing this action. * * @param program the program containing the data instances. * @param stringLocations {@link List} of string locations. */ public void translate(Program program, List<ProgramLocation> stringLocations); /** * Helper that creates a {@link HelpLocation} based on the plugin and sts. * * @param pluginClass Plugin that provides the string translation service * @param sts {@link StringTranslationService} * @return HelpLocation with topic equal to the plugin name and anchor something like * "MyTranslationServiceName_String_Translation_Service". */ public static HelpLocation createStringTranslationServiceHelpLocation( Class<? extends Plugin> pluginClass, StringTranslationService sts) { return new HelpLocation(PluginDescription.getPluginDescription(pluginClass).getName(), sts.getTranslationServiceName() + "_String_Translation_Service"); } }
923de17d4a0d7db155495378b3c3bca9acb84b54
1,492
java
Java
concurrent/src/main/java/com/sqh/concurrent/SyncContainer.java
Fiibio/sturdy-boot
458f3d052579b0cebdf21cb850edef0d1899cc76
[ "Apache-2.0" ]
null
null
null
concurrent/src/main/java/com/sqh/concurrent/SyncContainer.java
Fiibio/sturdy-boot
458f3d052579b0cebdf21cb850edef0d1899cc76
[ "Apache-2.0" ]
null
null
null
concurrent/src/main/java/com/sqh/concurrent/SyncContainer.java
Fiibio/sturdy-boot
458f3d052579b0cebdf21cb850edef0d1899cc76
[ "Apache-2.0" ]
null
null
null
24.064516
72
0.431635
1,000,515
package com.sqh.concurrent; import java.util.ArrayList; /** * 实现一个容器 提供add size方法 * 写两个线程 线程1添加10个元素到容器中,线程2监控容器中元素个数 * 当个数到5个时,线程2给出提示并结束 */ public class SyncContainer { volatile ArrayList arrayList = new ArrayList(); void add(Object o) { arrayList.add(o); } int size() { return arrayList.size(); } public void test1() { Object o1 = "o"; for (int i = 0; i < 10; i++) { add(o1); } } public static void main(String[] args) throws InterruptedException { SyncContainer sc = new SyncContainer(); new Thread(() -> { for (int i = 0; i < 10; i++) { sc.add(new Object()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread 1----" + sc.size()); } }).start(); new Thread(() -> { while (true) { // System.out.println("----thread 2 " + sc.size()); // try { // Thread.sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } if (sc.size() == 5) { System.out.println("55555"); break; } } }).start(); System.out.println("---------"); } }
923de26ab4d0bccf8f6f73807d9316bd8126ac1b
1,711
java
Java
fathom-rest/src/main/java/fathom/rest/controller/extractors/IntExtractor.java
gitblit/fathom
e05b5527fb2cbcb0f09b8996fe2caae5d1f6e635
[ "Apache-2.0" ]
28
2015-05-16T06:52:34.000Z
2017-07-26T04:51:09.000Z
fathom-rest/src/main/java/fathom/rest/controller/extractors/IntExtractor.java
gitblit/fathom
e05b5527fb2cbcb0f09b8996fe2caae5d1f6e635
[ "Apache-2.0" ]
18
2015-06-08T21:51:23.000Z
2022-01-21T23:22:12.000Z
fathom-rest/src/main/java/fathom/rest/controller/extractors/IntExtractor.java
gitblit/fathom
e05b5527fb2cbcb0f09b8996fe2caae5d1f6e635
[ "Apache-2.0" ]
8
2016-02-16T07:37:43.000Z
2021-07-13T10:55:42.000Z
25.537313
100
0.687317
1,000,516
/* * Copyright (C) 2015 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 fathom.rest.controller.extractors; import fathom.rest.Context; import fathom.rest.controller.Int; import ro.pippo.core.ParameterValue; /** * @author James Moger */ public class IntExtractor implements ArgumentExtractor, NamedExtractor, ConfigurableExtractor<Int> { private String name; private int defaultValue; @Override public Class<Int> getAnnotationClass() { return Int.class; } @Override public void configure(Int annotation) { setName(annotation.value()); setDefaultValue(annotation.defaultValue()); } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public int getDefaultValue() { return defaultValue; } public void setDefaultValue(int defaultValue) { this.defaultValue = defaultValue; } @Override public Object extract(Context context) { ParameterValue pv = context.getParameter(name); int i = pv.toInt(defaultValue); return i; } }
923de2aeb5b200a747ac46a176ba84c009048388
4,489
java
Java
src/com/hjcrm/system/service/impl/UserServiceImpl.java
yangfang710/CRM
145dd7a2e5f0f6566eabc1c2ed8b008d275858ad
[ "Apache-2.0" ]
1
2021-06-22T23:50:26.000Z
2021-06-22T23:50:26.000Z
src/com/hjcrm/system/service/impl/UserServiceImpl.java
yangfang710/CRM_jar
145dd7a2e5f0f6566eabc1c2ed8b008d275858ad
[ "Apache-2.0" ]
4
2020-03-04T22:18:25.000Z
2021-12-09T21:38:05.000Z
src/com/hjcrm/system/service/impl/UserServiceImpl.java
yangfang710/CRM_jar
145dd7a2e5f0f6566eabc1c2ed8b008d275858ad
[ "Apache-2.0" ]
null
null
null
25.505682
86
0.688795
1,000,517
package com.hjcrm.system.service.impl; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.hjcrm.publics.dao.IDataAccess; import com.hjcrm.publics.util.MD5Tools; import com.hjcrm.publics.util.PageBean; import com.hjcrm.publics.util.UserContext; import com.hjcrm.system.entity.User; import com.hjcrm.system.service.IUserService; @Service @Transactional(rollbackFor = Exception.class) public class UserServiceImpl implements IUserService{ @Autowired private IDataAccess<User> userDao; /** * 保存或者修改用户信息 */ @CacheEvict(value = "baseCache",key = "#e.userid") public void saveOrUpdate(User e) { if (e.getUserid()!= null) {//修改 if(StringUtils.hasText(e.getPassword())){ User oldUser = (User) userDao.queryByIdentity(User.class, e.getUserid()); if(oldUser != null && StringUtils.hasText(oldUser.getPassword())){ if(!oldUser.getPassword().equals(e.getPassword())){ e.setPassword(MD5Tools.encode(e.getPassword())); } }else{ e.setPassword(MD5Tools.encode(e.getPassword())); } } e.setUpdate_time(new Timestamp(System.currentTimeMillis())); if((UserContext.getLoginUser() != null)){ e.setUpdate_id(UserContext.getLoginUser().getUserid()); } userDao.update(e); } else {//新增 if (StringUtils.hasText(e.getPassword())){ e.setPassword(MD5Tools.encode(e.getPassword())); }else{ e.setPassword(MD5Tools.encode("123123")); } e.setCreate_time(new Timestamp(System.currentTimeMillis())); if(UserContext.getLoginUser() != null){ e.setCreate_id(UserContext.getLoginUser().getUserid()); } userDao.insert(e); } } /** * 删除用户 */ public void delete(String ids) { User ue = new User(); for (String id : ids.split(",")) { ue.setUserid(Long.valueOf(id)); userDao.delete(ue); } } /** * 获取用户列表 */ public List<User> queryUserList(User user, PageBean pageBean) { Map<String , Object> param = new HashMap<String, Object>(); if (user != null) { param.put("phone", user.getPhone()); param.put("email", user.getEmail()); } return userDao.queryByStatment("queryUserList", user, pageBean); } /** * 根据用户ID,查询用户信息 */ @Cacheable(value = "baseCache",key = "#user_id+'queryByIdentity'") public User queryByIdentity(Long user_id) { List<User> users = userDao.queryByStatment("queryByIdentity", user_id,null); if (users != null && users.size() > 0) { return users.get(0); } return null; } /** * 验证手机号或邮箱是否存在 */ public boolean authPhoneOrEmailIsExist(String phone, String email) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("phone", phone); hashMap.put("eamil", email); List<User> list = userDao.queryByStatment("authPhoneOrEmailIsExist", hashMap, null); if(list.size() > 0){ return true; } return false; } /** * 根据手机号或者邮箱查询用户信息 */ public User queryUserByPhoneOrEmail(String phone, String email) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("phone", phone); hashMap.put("email", email); List<User> list = userDao.queryByStatment("authPhoneOrEmailIsExist", hashMap, null); if (list != null && list.size() > 0 ) { return list.get(0); } return null; } /** * 查询所有运营部人员 + 销售部主管人员 */ public List<User> queryAllDirectors() { List<User> list = userDao.queryByStatment("queryAllDirectors", null, null); return list; } /** * 查询所有销售 +行政+客服 */ public List<User> queryAllusers() { List<User> list = userDao.queryByStatment("queryAllusers", null, null); return list; } public User queryUserByUsername(String username) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("username", username); List<User> list = userDao.queryByStatment("queryUserByUsername", hashMap, null); if (list != null && list.size() > 0 ) { return list.get(0); } return null; } public User queryusertestByid(String id) { List<User> list = userDao.queryByStatment("queryUserByUsername", null, null); if (list != null && list.size() > 0 ) { return list.get(0); } return null; } }
923de2fe2bc927b5b78970d29fcba17ad7a90f77
1,898
java
Java
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/firebase/client/core/Repo$5.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/firebase/client/core/Repo$5.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Ibotta_com.ibotta.android/javafiles/com/firebase/client/core/Repo$5.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
32.169492
132
0.600105
1,000,518
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.firebase.client.core; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; // Referenced classes of package com.firebase.client.core: // Repo class Repo$5 implements Runnable { public void run() { val$onComplete.onComplete(val$error, val$ref); // 0 0:aload_0 // 1 1:getfield #25 <Field com.firebase.client.Firebase$CompletionListener val$onComplete> // 2 4:aload_0 // 3 5:getfield #27 <Field FirebaseError val$error> // 4 8:aload_0 // 5 9:getfield #29 <Field Firebase val$ref> // 6 12:invokeinterface #40 <Method void com.firebase.client.Firebase$CompletionListener.onComplete(FirebaseError, Firebase)> // 7 17:return } final Repo this$0; final FirebaseError val$error; final com.firebase.client.e.CompletionListener val$onComplete; final Firebase val$ref; Repo$5() { this$0 = final_repo; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #23 <Field Repo this$0> val$onComplete = completionlistener; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #25 <Field com.firebase.client.Firebase$CompletionListener val$onComplete> val$error = firebaseerror; // 6 10:aload_0 // 7 11:aload_3 // 8 12:putfield #27 <Field FirebaseError val$error> val$ref = Firebase.this; // 9 15:aload_0 // 10 16:aload 4 // 11 18:putfield #29 <Field Firebase val$ref> super(); // 12 21:aload_0 // 13 22:invokespecial #32 <Method void Object()> // 14 25:return } }
923de3e4358838fa579d3dd7b6031acd9144e7f9
1,142
java
Java
mvc/src/main/java/com/truthbean/debbie/mvc/request/RequestParameterType.java
TruthBean/debbie
f49f0c27d327d3d0849b5641a82ebd2880785561
[ "MulanPSL-1.0" ]
10
2018-12-22T07:12:21.000Z
2022-01-09T07:31:55.000Z
mvc/src/main/java/com/truthbean/debbie/mvc/request/RequestParameterType.java
TruthBean/debbie
f49f0c27d327d3d0849b5641a82ebd2880785561
[ "MulanPSL-1.0" ]
null
null
null
mvc/src/main/java/com/truthbean/debbie/mvc/request/RequestParameterType.java
TruthBean/debbie
f49f0c27d327d3d0849b5641a82ebd2880785561
[ "MulanPSL-1.0" ]
1
2019-10-21T17:53:40.000Z
2019-10-21T17:53:40.000Z
16.550725
204
0.56042
1,000,519
/** * Copyright (c) 2021 TruthBean(Rogar·Q) * Debbie is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package com.truthbean.debbie.mvc.request; /** * @author TruthBean * @since 0.0.1 * Created on 2018-03-11 13:20 */ public enum RequestParameterType { /** * query */ QUERY, /** * uri matrix */ MATRIX, /** * uri path */ PATH, /** * params */ PARAM, /** * mix all */ MIX, /** * request body */ BODY, /** * request head */ HEAD, /** * session attribute */ SESSION, /** * cookie attribute */ COOKIE, /** * inner attribute */ INNER }
923de40bf6178c4989475d03fa6b33144459b40b
1,982
java
Java
nio-multipart-parser/src/main/java/org/synchronoss/cloud/nio/multipart/NioMultipartParserListener.java
jinxxik/nio-multipart
3e20f1e6921ea26c9cf674e039e86e47559e40ab
[ "Apache-2.0" ]
88
2015-11-03T05:00:36.000Z
2022-03-30T16:22:19.000Z
nio-multipart-parser/src/main/java/org/synchronoss/cloud/nio/multipart/NioMultipartParserListener.java
jinxxik/nio-multipart
3e20f1e6921ea26c9cf674e039e86e47559e40ab
[ "Apache-2.0" ]
10
2016-06-24T15:17:14.000Z
2020-05-02T07:25:34.000Z
nio-multipart-parser/src/main/java/org/synchronoss/cloud/nio/multipart/NioMultipartParserListener.java
jinxxik/nio-multipart
3e20f1e6921ea26c9cf674e039e86e47559e40ab
[ "Apache-2.0" ]
21
2016-01-26T10:37:58.000Z
2022-03-30T01:13:24.000Z
30.030303
116
0.699294
1,000,520
/* * Copyright (C) 2015 Synchronoss Technologies * * 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.synchronoss.cloud.nio.multipart; import org.synchronoss.cloud.nio.stream.storage.StreamStorage; import java.util.List; import java.util.Map; /** * <p> Listener that will be notified with the progress of the multipart parsing. * * @author Silvano Riz. */ public interface NioMultipartParserListener { /** * <p> Called when a part has been parsed. * * @param partBodyStreamStorage The {@code StreamStorage} from where the part body can be read. * @param headersFromPart The part headers. */ void onPartFinished(final StreamStorage partBodyStreamStorage, final Map<String, List<String>> headersFromPart); /** * <p> Called when all the parts have been read. */ void onAllPartsFinished(); /** * <p> Called when the parser is about to start a nested multipart. * * @param headersFromParentPart The headers from the parent part. */ void onNestedPartStarted(final Map<String, List<String>> headersFromParentPart); /** * <p> Called when a nested part has completed. */ void onNestedPartFinished(); /** * <p> Called if an error occurs during the multipart parsing. * * @param message The error message * @param cause The error cause or null if there is no cause. */ void onError(final String message, final Throwable cause); }
923de607e710fc9955a629010c5bc2bad40558ab
467
java
Java
Task 2/FaceDetection/app/src/main/java/com/sumitsoftwares/facedetection/LCOFaceDetection.java
vlingawar/LGMVIP-Android
0cea8d7507a0d8d27f7051bb73b52a008f5a6cc8
[ "Apache-2.0" ]
null
null
null
Task 2/FaceDetection/app/src/main/java/com/sumitsoftwares/facedetection/LCOFaceDetection.java
vlingawar/LGMVIP-Android
0cea8d7507a0d8d27f7051bb73b52a008f5a6cc8
[ "Apache-2.0" ]
null
null
null
Task 2/FaceDetection/app/src/main/java/com/sumitsoftwares/facedetection/LCOFaceDetection.java
vlingawar/LGMVIP-Android
0cea8d7507a0d8d27f7051bb73b52a008f5a6cc8
[ "Apache-2.0" ]
null
null
null
24.578947
64
0.700214
1,000,521
package com.sumitsoftwares.facedetection; import android.app.Application; import com.google.firebase.FirebaseApp; public class LCOFaceDetection extends Application { public final static String RESULT_TEXT = "RESULT_TEXT"; public final static String RESULT_DIALOG = "RESULT_DIALOG"; // initializing our firebase @Override public void onCreate() { super.onCreate(); FirebaseApp.initializeApp(this); } }
923de6c9ced506de67e5caab50c4e93acbb74fa7
2,603
java
Java
app/src/main/java/com/material/components/fragment/FragmentTabsGallery.java
vimalcvs/MaterialX
4bce23844b7c4f0d1c8ae91e89eae3910e1e5890
[ "Apache-2.0" ]
4
2020-08-14T17:04:43.000Z
2021-10-03T08:33:45.000Z
app/src/main/java/com/material/components/fragment/FragmentTabsGallery.java
vimalcvs/MaterialX
4bce23844b7c4f0d1c8ae91e89eae3910e1e5890
[ "Apache-2.0" ]
1
2021-06-04T00:57:09.000Z
2021-06-04T00:57:09.000Z
app/src/main/java/com/material/components/fragment/FragmentTabsGallery.java
vimalcvs/MaterialX
4bce23844b7c4f0d1c8ae91e89eae3910e1e5890
[ "Apache-2.0" ]
3
2020-08-14T17:07:16.000Z
2020-12-01T17:28:45.000Z
36.661972
110
0.705724
1,000,522
package com.material.components.fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.material.components.R; import com.material.components.adapter.AdapterGridSectioned; import com.material.components.data.DataGenerator; import com.material.components.model.SectionImage; import java.util.ArrayList; import java.util.List; public class FragmentTabsGallery extends Fragment { public FragmentTabsGallery() { } public static FragmentTabsGallery newInstance() { FragmentTabsGallery fragment = new FragmentTabsGallery(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_tabs_gallery, container, false); RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)); recyclerView.setHasFixedSize(true); List<Integer> items_img = DataGenerator.getNatureImages(getActivity()); items_img.addAll(DataGenerator.getNatureImages(getActivity())); items_img.addAll(DataGenerator.getNatureImages(getActivity())); items_img.addAll(DataGenerator.getNatureImages(getActivity())); items_img.addAll(DataGenerator.getNatureImages(getActivity())); List<SectionImage> items = new ArrayList<>(); for (Integer i : items_img) { items.add(new SectionImage(i, "IMG_" + i + ".jpg", false)); } int sect_count = 0; int sect_idx = 0; List<String> months = DataGenerator.getStringsMonth(getActivity()); for (int i = 0; i < items.size() / 10; i++) { items.add(sect_count, new SectionImage(-1, months.get(sect_idx), true)); sect_count = sect_count + 10; sect_idx++; } //set data and list adapter AdapterGridSectioned mAdapter = new AdapterGridSectioned(getActivity(), items); recyclerView.setAdapter(mAdapter); // on item list clicked mAdapter.setOnItemClickListener(new AdapterGridSectioned.OnItemClickListener() { @Override public void onItemClick(View view, SectionImage obj, int position) { } }); return root; } }
923de6f8f1619664ea98ab2bee95f7b4326d3c09
2,159
java
Java
ontopia-engine/src/main/java/net/ontopia/topicmaps/query/impl/rdbms/JDOBasicPredicate.java
ontopia/ontopia
d1d51458dc3a18393545fc0dfafc1ec00506e282
[ "Apache-2.0" ]
41
2015-06-15T11:08:50.000Z
2022-02-04T11:17:58.000Z
ontopia-engine/src/main/java/net/ontopia/topicmaps/query/impl/rdbms/JDOBasicPredicate.java
qsiebers/ontopia
fce3d8de1991bb9e355a40dc745db6e25ea6fd45
[ "Apache-2.0" ]
79
2015-06-17T10:39:21.000Z
2022-01-21T23:09:49.000Z
ontopia-engine/src/main/java/net/ontopia/topicmaps/query/impl/rdbms/JDOBasicPredicate.java
qsiebers/ontopia
fce3d8de1991bb9e355a40dc745db6e25ea6fd45
[ "Apache-2.0" ]
18
2015-06-25T11:34:05.000Z
2022-03-28T04:50:12.000Z
24.816092
83
0.728115
1,000,523
/* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.topicmaps.query.impl.rdbms; import java.util.List; import net.ontopia.topicmaps.query.core.InvalidQueryException; import net.ontopia.topicmaps.query.impl.basic.BasicPredicateIF; import net.ontopia.topicmaps.query.impl.basic.QueryMatches; /** * INTERNAL: A predicate wrapper that delegates all it's method calls * to the nested basic predicate. */ public class JDOBasicPredicate implements JDOPredicateIF { protected BasicPredicateIF pred; public JDOBasicPredicate(BasicPredicateIF pred) { this.pred = pred; } // --- PredicateIF implementation @Override public String getName() { return pred.getName(); } @Override public String getSignature() throws InvalidQueryException { return pred.getSignature(); } @Override public int getCost(boolean[] boundparams) { return pred.getCost(boundparams); } // --- BasicPredicateIF implementation @Override public QueryMatches satisfy(QueryMatches result, Object[] arguments) throws InvalidQueryException { return pred.satisfy(result, arguments); } // --- JDOPredicateIF implementation @Override public boolean isRecursive() { return false; } @Override public void prescan(QueryBuilder builder, List arguments) { // no-op } @Override public boolean buildQuery(QueryBuilder builder, List expressions, List arguments) throws InvalidQueryException { // this predicate should be executed through basic predicate return false; } }
923de706eb3fcc1f1fd2f9b0aa52509f23a27869
765
java
Java
examples/ru.iiec.cxxdroid/sources/qwe/qweqwe/texteditor/foldernav/b.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
examples/ru.iiec.cxxdroid/sources/qwe/qweqwe/texteditor/foldernav/b.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
examples/ru.iiec.cxxdroid/sources/qwe/qweqwe/texteditor/foldernav/b.java
vietnux/CodeEditorMobile
acd29a6a647342276eb557f3af579535092ab377
[ "Apache-2.0" ]
null
null
null
31.875
81
0.704575
1,000,524
package qwe.qweqwe.texteditor.foldernav; import android.content.DialogInterface; import qwe.qweqwe.texteditor.foldernav.IconTreeItemHolder; /* compiled from: lambda */ public final /* synthetic */ class b implements DialogInterface.OnClickListener { /* renamed from: b reason: collision with root package name */ private final /* synthetic */ h f9636b; /* renamed from: c reason: collision with root package name */ private final /* synthetic */ IconTreeItemHolder.b f9637c; public /* synthetic */ b(h hVar, IconTreeItemHolder.b bVar) { this.f9636b = hVar; this.f9637c = bVar; } public final void onClick(DialogInterface dialogInterface, int i2) { this.f9636b.a(this.f9637c, dialogInterface, i2); } }
923de71406561e801c855a27b282e4c4b4a92e32
6,533
java
Java
src/main/java/open/commons/maven/pom/LibraryTarget.java
parkjunhong/open-commons-maven-pom
c83f48a594d3941525ab74259150945c063c3927
[ "MIT" ]
null
null
null
src/main/java/open/commons/maven/pom/LibraryTarget.java
parkjunhong/open-commons-maven-pom
c83f48a594d3941525ab74259150945c063c3927
[ "MIT" ]
2
2021-12-14T21:01:52.000Z
2021-12-14T21:36:45.000Z
src/main/java/open/commons/maven/pom/LibraryTarget.java
parkjunhong/open-commons-maven-pom
c83f48a594d3941525ab74259150945c063c3927
[ "MIT" ]
null
null
null
19.443452
58
0.37854
1,000,525
/* * * This file is generated under this project, "maven-pom". * * Date : 2019. 12. 4. 오후 2:17:33 * * Author: Park_Jun_Hong_(fafanmama_at_naver_com) * */ package open.commons.maven.pom; /** * * @since 2019. 12. 4. * @version * @author Park_Jun_Hong_(fafanmama_at_naver_com) */ public class LibraryTarget { private String filepath; private String modelVersion; private String groupId; private String artifactId; private String version; private String description; /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @since 2019. 12. 4. * @version */ public LibraryTarget() { } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the artifactId * * @since 2019. 12. 4. * @version * * @see #artifactId */ public String getArtifactId() { return artifactId; } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the description * * @since 2019. 12. 4. * @version * * @see #description */ public String getDescription() { return description; } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the file * * @since 2019. 12. 4. * @version * * @see #filepath */ public String getFilepath() { return filepath; } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the groupId * * @since 2019. 12. 4. * @version * * @see #groupId */ public String getGroupId() { return groupId; } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the modelVersion * * @since 2019. 12. 4. * @version * * @see #modelVersion */ public String getModelVersion() { return modelVersion; } /** * * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @return the version * * @since 2019. 12. 4. * @version * * @see #version */ public String getVersion() { return version; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param artifactId * the artifactId to set * * @since 2019. 12. 4. * @version * * @see #artifactId */ public void setArtifactId(String artifactId) { this.artifactId = artifactId; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param description * the description to set * * @since 2019. 12. 4. * @version * * @see #description */ public void setDescription(String description) { this.description = description; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param filepath * the file to set * * @since 2019. 12. 4. * @version * * @see #filepath */ public void setFilepath(String filepath) { this.filepath = filepath; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param groupId * the groupId to set * * @since 2019. 12. 4. * @version * * @see #groupId */ public void setGroupId(String groupId) { this.groupId = groupId; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param modelVersion * the modelVersion to set * * @since 2019. 12. 4. * @version * * @see #modelVersion */ public void setModelVersion(String modelVersion) { this.modelVersion = modelVersion; } /** * <br> * * <pre> * [개정이력] * 날짜 | 작성자 | 내용 * ------------------------------------------ * 2019. 12. 4. 박준홍 최초 작성 * </pre> * * @param version * the version to set * * @since 2019. 12. 4. * @version * * @see #version */ public void setVersion(String version) { this.version = version; } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("LibraryTarget [filepath="); builder.append(filepath); builder.append(", modelVersion="); builder.append(modelVersion); builder.append(", groupId="); builder.append(groupId); builder.append(", artifactId="); builder.append(artifactId); builder.append(", version="); builder.append(version); builder.append(", description="); builder.append(description); builder.append("]"); return builder.toString(); } }
923de7f7821ebef5a05270ec2a827c5e37bc9be0
1,721
java
Java
library/jaudiotagger226/src/main/java/org/jaudiotagger/tag/datatype/EventTimingCodeList.java
thawee/musixmate
00075dfe11229d7e0ddd6f807b241beef0510167
[ "Apache-2.0" ]
19
2019-09-07T12:55:10.000Z
2022-01-25T16:09:55.000Z
app/src/main/java/org/jaudiotagger/tag/datatype/EventTimingCodeList.java
MrRight1990/MusicStreamer
805d59240d34d75a3a3fe6617e03ec30d8a3be60
[ "MIT" ]
24
2019-06-29T10:44:48.000Z
2021-10-18T19:47:16.000Z
app/src/main/java/org/jaudiotagger/tag/datatype/EventTimingCodeList.java
MrRight1990/MusicStreamer
805d59240d34d75a3a3fe6617e03ec30d8a3be60
[ "MIT" ]
7
2020-02-24T12:29:14.000Z
2021-03-15T16:35:59.000Z
35.081633
109
0.727749
1,000,526
/* * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.datatype; import org.jaudiotagger.tag.id3.framebody.FrameBodyETCO; /** * List of {@link EventTimingCode}s. * * @author <a href="mailto:anpch@example.com">Hendrik Schreiber</a> * @version $Id:$ */ public class EventTimingCodeList extends AbstractDataTypeList<EventTimingCode> { /** * Mandatory, concretely-typed copy constructor, as required by * {@link AbstractDataTypeList#AbstractDataTypeList(AbstractDataTypeList)}. * * @param copy instance to copy */ public EventTimingCodeList(final EventTimingCodeList copy) { super(copy); } public EventTimingCodeList(final FrameBodyETCO body) { super(DataTypes.OBJ_TIMED_EVENT_LIST, body); } @Override protected EventTimingCode createListElement() { return new EventTimingCode(DataTypes.OBJ_TIMED_EVENT, frameBody); } }
923de86ae5b6b05c83014925cf871d202ee3dab6
659
java
Java
htb/fatty-10.10.10.174/fatty-client/org/springframework/expression/spel/CompilablePropertyAccessor.java
benhunter/ctf
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
[ "MIT" ]
null
null
null
htb/fatty-10.10.10.174/fatty-client/org/springframework/expression/spel/CompilablePropertyAccessor.java
benhunter/ctf
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
[ "MIT" ]
1
2022-03-31T22:44:36.000Z
2022-03-31T22:44:36.000Z
htb/fatty-10.10.10.174/fatty-client/org/springframework/expression/spel/CompilablePropertyAccessor.java
benhunter/ctf
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
[ "MIT" ]
null
null
null
34.684211
154
0.778452
1,000,527
package org.springframework.expression.spel; import org.springframework.asm.MethodVisitor; import org.springframework.asm.Opcodes; import org.springframework.expression.PropertyAccessor; public interface CompilablePropertyAccessor extends PropertyAccessor, Opcodes { boolean isCompilable(); Class<?> getPropertyType(); void generateCode(String paramString, MethodVisitor paramMethodVisitor, CodeFlow paramCodeFlow); } /* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/expression/spel/CompilablePropertyAccessor.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
923de8be65a618da473123db34f32299b9bdba14
703
java
Java
src/a4/p1/ACustomDuplexObjectInputPortFactory.java
bwproud/Custom_RPC_Implementation
ab6f120c40c9068ac5a979cd79877c4cb3905f15
[ "MIT" ]
null
null
null
src/a4/p1/ACustomDuplexObjectInputPortFactory.java
bwproud/Custom_RPC_Implementation
ab6f120c40c9068ac5a979cd79877c4cb3905f15
[ "MIT" ]
null
null
null
src/a4/p1/ACustomDuplexObjectInputPortFactory.java
bwproud/Custom_RPC_Implementation
ab6f120c40c9068ac5a979cd79877c4cb3905f15
[ "MIT" ]
null
null
null
41.352941
120
0.876245
1,000,528
package a4.p1; import inputport.datacomm.duplex.DuplexClientInputPort; import inputport.datacomm.duplex.DuplexServerInputPort; import inputport.datacomm.duplex.object.ADuplexObjectInputPortFactory; import java.nio.ByteBuffer; public class ACustomDuplexObjectInputPortFactory extends ADuplexObjectInputPortFactory{ public DuplexClientInputPort<Object> createDuplexClientInputPort(DuplexClientInputPort<ByteBuffer> bbClientInputPort) { return new ACustomDuplexObjectClientInputPort(bbClientInputPort); } public DuplexServerInputPort<Object> createDuplexServerInputPort(DuplexServerInputPort<ByteBuffer> bbServerInputPort) { return new ACustomDuplexObjectServerInputPort(bbServerInputPort); } }
923de92eb30b6405ab93580f668d6686b5b957c5
795
java
Java
spigot/src/main/java/org/apsarasmc/spigot/command/SpigotSender.java
ApsarasMC/Apsaras
8cb6bd2b4f668b8a0d413521f52f050d7bf34274
[ "MIT" ]
2
2021-07-16T08:12:32.000Z
2021-07-30T23:12:20.000Z
spigot/src/main/java/org/apsarasmc/spigot/command/SpigotSender.java
ApsarasMC/Apsaras
8cb6bd2b4f668b8a0d413521f52f050d7bf34274
[ "MIT" ]
null
null
null
spigot/src/main/java/org/apsarasmc/spigot/command/SpigotSender.java
ApsarasMC/Apsaras
8cb6bd2b4f668b8a0d413521f52f050d7bf34274
[ "MIT" ]
null
null
null
34.565217
108
0.811321
1,000,529
package org.apsarasmc.spigot.command; import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; import org.apsarasmc.spigot.util.TextComponentUtil; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; public class SpigotSender implements org.apsarasmc.apsaras.command.CommandSender { private final CommandSender sender; public SpigotSender(CommandSender sender){ this.sender = sender; } @Override public void sendMessage(@Nonnull Identity source, @Nonnull Component message, @Nonnull MessageType type) { sender.spigot().sendMessage(source.uuid(), TextComponentUtil.toBukkit(message)); } }
923de96e14b182e26c1866a99ce905711e4831e0
3,895
java
Java
src/cv/SpecularReflexion.java
yanntrividic/glass-computer-vision
6839cbcdb2727f9d05311d1f94b7ce3678cca052
[ "MIT" ]
null
null
null
src/cv/SpecularReflexion.java
yanntrividic/glass-computer-vision
6839cbcdb2727f9d05311d1f94b7ce3678cca052
[ "MIT" ]
null
null
null
src/cv/SpecularReflexion.java
yanntrividic/glass-computer-vision
6839cbcdb2727f9d05311d1f94b7ce3678cca052
[ "MIT" ]
null
null
null
39.343434
107
0.696791
1,000,530
package cv; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.imgproc.Imgproc; public class SpecularReflexion { /** * Method that extracts two point that describes the rectangle in which a glass * has been detected by using its reflexive properties (i.e. the specular * reflexions of the glass) * * @param src The source image where we look for the specular * reflexion * @param intensityThreshold The first binarization (the specular reflexions * must be found and the rest left apart * @param contourThreshold Second binarization, only the biggest gradient * values must be kept * @return a couple of points (top left and bottom right that indicate the * rectangle in which the glass is) * * @author Yann Trividic */ public static Point[] findSpecularReflexion(Mat src, double intensityThreshold, double contourThreshold) { // TODO: For this part, we will have to base our algorithm on a few assumptions. // Maybe we could assume that the object is usually more in the center on the // sides ? (floodfill ?) // And that the bigger the binerized area is, the less there are chances for it // to be a specular reflexion ? // The less "clusters" we have, the less we can infer on the position of the // glass // TODO: Improve the small features extraction by substracting the opened image // to the original one Mat norm, simpleBin, sum, contour, binContour; norm = new Mat(); simpleBin = new Mat(); sum = new Mat(); contour = new Mat(); binContour = new Mat(); // First, we normalize the image to be sure we have white pixels for the // binarization Core.normalize(src, norm, 0, 255, Core.NORM_MINMAX); // The result is stored into a matrix int threshold = 255; do { simpleBin = Segmentation.simpleBinarization(norm, threshold, false); threshold--; // System.out.println(Core.countNonZero(simpleBin)) ; } while ((double) Core.countNonZero(simpleBin) / simpleBin.total() < intensityThreshold); // We exit the loop once one percent of the image has been included in the // binarization // We extract the contour of the image Core.normalize(ContourUtils.sobelFilter(src), contour, 0, 50, Core.NORM_MINMAX); // And remove the lowest values // And we binarize the contour threshold = 100; do { binContour = Segmentation.simpleBinarization(contour, threshold, false); threshold -= 3; // System.out.println(Core.countNonZero(binContour)) ; } while ((double) Core.countNonZero(binContour) / binContour.total() < contourThreshold); // until it fills a certain portion of the reference image total size Imgproc.dilate(binContour, binContour, Mat.ones(3, 3, CvType.CV_32F)); // View.displayImage(binContour, "contour2"); // contour = Segmentation.simpleBinarization(contour, // contourBinarizationThreshold, false) ; // Then we multiply the first binarization and the contours Core.multiply(simpleBin, binContour, simpleBin); // And finally we add it to the low contrast image Core.add(norm, simpleBin, sum); int[] offset = { sum.height() / 5, sum.width() / 7, sum.height() / 10, sum.width() / 7 }; // offset = new int[] {0,0,0,0} ; // a rectangle is drawn around the found blobs try { int[] coor = ProcessingUtils.getMaskBoundaries(simpleBin); ProcessingUtils.drawRectFromBoudaries(sum, ProcessingUtils.getMaskBoundaries(simpleBin), offset); // ui.Utils.displayImage(sum, "Image found before cropping") ; return ProcessingUtils.getTwoCornersPlusBoundaries(sum, coor, offset); } catch (Exception e) { System.out.println("No glass found."); return new Point[] { new Point(0, 0), new Point(src.width() - 1, src.height() - 1) }; } } }
923de999472ced7a596172450f6dd3af6a213b24
2,336
java
Java
LearningJava/src/main/java/org/pengfei/Lesson13_Common_Data_Structure/L13_S2_Linked_lists/MySinglyLinkedList.java
pengfei99/JavaBasic
c8190a429d6bab5b39d90450dae1a45e894e0060
[ "MIT" ]
null
null
null
LearningJava/src/main/java/org/pengfei/Lesson13_Common_Data_Structure/L13_S2_Linked_lists/MySinglyLinkedList.java
pengfei99/JavaBasic
c8190a429d6bab5b39d90450dae1a45e894e0060
[ "MIT" ]
4
2021-02-19T08:40:21.000Z
2021-04-28T15:46:13.000Z
LearningJava/src/main/java/org/pengfei/Lesson13_Common_Data_Structure/L13_S2_Linked_lists/MySinglyLinkedList.java
pengfei99/JavaBasic
c8190a429d6bab5b39d90450dae1a45e894e0060
[ "MIT" ]
1
2020-05-15T15:42:53.000Z
2020-05-15T15:42:53.000Z
24.333333
109
0.528682
1,000,531
package org.pengfei.Lesson13_Common_Data_Structure.L13_S2_Linked_lists; public class MySinglyLinkedList<E> { /* * WE could declare the node as a nested class, but for reuse in other class, we declare a Node separatedly * *//****************************Nested Node class ***********************//* private static class Node<E>{ private E element; private Node<E> next; //Node public constructor public Node(E e, Node<E> n){ element=e; next=n; } public E getElement(){ return element; } public Node<E> getNext(){ return next; } public void setNext(Node<E> n) { next=n; } }*/ private Node<E> head=null; private Node<E> tail=null; private int size=0; // MySinglyLinkedList public constructor, it builds an empty list at the beginning public MySinglyLinkedList(){} /* Getters for the list */ public int size() { return size; } public boolean isEmpty(){ return size==0; } public E first() { return (E)head.getElement(); } public E last() { return tail.getElement(); } /* Setters for the list */ public void addFirst(E e) { //Set head to newly created node Node<E> newNode=new Node(e,head); this.head = newNode; // if null list, set tail to newly created node too if (size==0) tail=newNode; // increment list size size++; } public void addLast(E e){ Node<E> newNode=new Node(e,null); //if null list, set head, tail to new node if(size==0) { head=newNode; } else { //set current tail next reference to the new node tail.setNext(newNode); } //set current tail to new node tail=newNode; size++; } public E removeFirst() { // Before removing, we need to check if the list is null if (size == 0) { return null; } else { E first = head.getElement(); head = head.getNext(); size--; // After removing the first, we need to check if the list become null if(size==0) tail=null; return first; } } }
923dea3780a3b99b8b8295ba4aa48d51b168683b
5,181
java
Java
java/matematiko/real/array/RVLinearSpace.java
jgomezpe/matematiko
5b6cd0d0c46bef503d51671296e0545df7ac2ad5
[ "Unlicense" ]
1
2021-04-30T23:11:34.000Z
2021-04-30T23:11:34.000Z
java/matematiko/real/array/RVLinearSpace.java
jgomezpe/matematiko
5b6cd0d0c46bef503d51671296e0545df7ac2ad5
[ "Unlicense" ]
null
null
null
java/matematiko/real/array/RVLinearSpace.java
jgomezpe/matematiko
5b6cd0d0c46bef503d51671296e0545df7ac2ad5
[ "Unlicense" ]
null
null
null
29.628571
111
0.628544
1,000,532
/** * <p>Copyright: Copyright (c) 2019</p> * * <h3>License</h3> * * Copyright (c) 2019 by Jonatan Gomez-Perdomo. <br> * All rights reserved. <br> * * <p>Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <ul> * <li> Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * <li> 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. * <li> Neither the name of the copyright owners, their employers, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * </ul> * <p>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 OWNERS 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. * * * * @author <A HREF="http://disi.unal.edu.co/profesores/jgomezpe"> Jonatan Gomez-Perdomo </A> * (E-mail: <A HREF="mailto:dycjh@example.com"kenaa@example.com.co</A> ) * @version 1.0 */ package matematiko.real.array; import matematiko.algebra.linear.LinearSpace; import speco.real.RealUtil; /** * <p>Linear space of real vectors.</p> * */ public class RVLinearSpace implements LinearSpace<double[]> { /** * Gets the identity element 0. A real vector fill with 0 with the same dimension of the real vector <i>x</i> * @param x Real vector for determining the dimension of the 0 real vector to return * @return 0(x) */ @Override public double[] identity( double[] x ){ return RealUtil.create(x.length, 0.0); } /** * Gets inverse real vector (fast version, may return the same object) of <i>x</i>. * @param x Real vector * @return <i>-x</i> */ @Override public double[] fastInverse( double[] x ){ for( int i=0; i<x.length; i++ ) x[i] = -x[i]; return x; } /** * Gets inverse real vector of <i>x</i>. * @param x Real vector * @return <i>-x</i> */ @Override public double[] inverse( double[] x ){ double[] y = new double[x.length]; for( int i=0; i<x.length; i++ ) y[i] = -x[i]; return y; } /** * Adds x and y (returns the result in object <i>x</i>) * @param x First real vector * @param y Second real vector * @return <i>x + y</i> */ @Override public double[] fastPlus(double[] x, double[] y) { int n = x.length; for (int i = 0; i < n; i++) x[i] += y[i]; return x; } /** * Adds x and -y (returns the result in object <i>x</i>) * @param x First real vector * @param y Second real vector * @return <i>x - y</i> */ @Override public double[] fastMinus(double[] x, double[] y) { int n = x.length; for (int i = 0; i < n; i++) x[i] -= y[i]; return x; } /** * Adds x and -y * @param x First real vector * @param y Second real vector * @return <i>x - y</i> */ @Override public double[] minus(double[] x, double[] y) { return fastMinus(x.clone(),y); } /** * Adds x and y * @param x First real vector * @param y Second real vector * @return <i>x + y</i> */ @Override public double[] plus(double[] x, double[] y) { return fastPlus(x.clone(),y); } /** * Divides real vector x by scalar k * @param x Real vector * @param k Scalar * @return <i>(1/k)*x</i> */ @Override public double[] divide(double[] x, double k) { return fastDivide(x.clone(), k); } /** * Divides real vector x by scalar k (return the result in object <i>x</i>) * @param x Real vector * @param k Scalar * @return <i>(1/k)*x</i> */ @Override public double[] fastDivide(double[] x, double k) { int n = x.length; for (int i = 0; i < n; i++) x[i] /= k; return x; } /** * Multiplies real vector x by scalar k (return the result in object <i>x</i>) * @param x Real vector * @param k Scalar * @return <i>k*x</i> */ @Override public double[] fastMultiply(double[] x, double k) { int n = x.length; for (int i = 0; i < n; i++) x[i] *= k; return x; } /** * Multiplies real vector x by scalar k * @param x Real vector * @param k Scalar * @return <i>k*x</i> */ @Override public double[] multiply(double[] x, double k) { return fastMultiply(x.clone(), k); } }
923deaa8d2f7fa305e13b0920279ce15bf003c50
2,331
java
Java
integration/spark/src/main/common/java/io/openlineage/spark/agent/lifecycle/plan/TruncateTableCommandVisitor.java
AlexRogalskiy/OpenLineage
4fee12f52fd02ccae825451d3ba2e7028a81676b
[ "Apache-2.0" ]
null
null
null
integration/spark/src/main/common/java/io/openlineage/spark/agent/lifecycle/plan/TruncateTableCommandVisitor.java
AlexRogalskiy/OpenLineage
4fee12f52fd02ccae825451d3ba2e7028a81676b
[ "Apache-2.0" ]
1
2022-02-17T09:43:38.000Z
2022-02-17T09:43:52.000Z
integration/spark/src/main/common/java/io/openlineage/spark/agent/lifecycle/plan/TruncateTableCommandVisitor.java
AlexRogalskiy/OpenLineage
4fee12f52fd02ccae825451d3ba2e7028a81676b
[ "Apache-2.0" ]
null
null
null
37
99
0.724153
1,000,533
/* SPDX-License-Identifier: Apache-2.0 */ package io.openlineage.spark.agent.lifecycle.plan; import io.openlineage.client.OpenLineage; import io.openlineage.client.OpenLineage.OutputDataset; import io.openlineage.spark.agent.facets.TableStateChangeFacet; import io.openlineage.spark.agent.util.DatasetIdentifier; import io.openlineage.spark.agent.util.PathUtils; import io.openlineage.spark.agent.util.PlanUtils; import io.openlineage.spark.api.DatasetFactory; import io.openlineage.spark.api.OpenLineageContext; import io.openlineage.spark.api.QueryPlanVisitor; import java.util.Collections; import java.util.List; import java.util.Optional; import lombok.extern.slf4j.Slf4j; import org.apache.spark.sql.catalyst.catalog.CatalogTable; import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan; import org.apache.spark.sql.execution.command.TruncateTableCommand; /** * {@link LogicalPlan} visitor that matches an {@link TruncateTableCommand} and extracts the output * {@link OpenLineage.Dataset} being written. */ @Slf4j public class TruncateTableCommandVisitor extends QueryPlanVisitor<TruncateTableCommand, OutputDataset> { public TruncateTableCommandVisitor(OpenLineageContext context) { super(context); } @Override public List<OutputDataset> apply(LogicalPlan x) { TruncateTableCommand command = (TruncateTableCommand) x; Optional<CatalogTable> tableOpt = catalogTableFor(command.tableName()); if (tableOpt.isPresent()) { CatalogTable table = tableOpt.get(); DatasetIdentifier datasetIdentifier = PathUtils.fromCatalogTable(table); DatasetFactory<OutputDataset> datasetFactory = outputDataset(); return Collections.singletonList( datasetFactory.getDataset( datasetIdentifier, new OpenLineage.DatasetFacetsBuilder() .schema(null) .dataSource( PlanUtils.datasourceFacet( context.getOpenLineage(), datasetIdentifier.getNamespace())) .put( "tableStateChange", new TableStateChangeFacet(TableStateChangeFacet.StateChange.TRUNCATE)) .build())); } else { // table does not exist, cannot prepare an event return Collections.emptyList(); } } }
923deaba0cc7c01d1fb4b64cb37d090fed62c186
1,634
java
Java
src/test/java/test/util/JSONHelperTest.java
tejido18/inciDashboard
5b7fc31c51716f23210782a66d39d30a1eea19d6
[ "MIT" ]
1
2018-03-25T03:37:44.000Z
2018-03-25T03:37:44.000Z
src/test/java/test/util/JSONHelperTest.java
Arquisoft/InciDashboard_i2b
c90739ca23f4bc0e6870636a7adc3ab89368bea2
[ "MIT" ]
33
2018-03-07T21:43:33.000Z
2018-05-10T22:31:51.000Z
src/test/java/test/util/JSONHelperTest.java
tejido18/inciDashboard
5b7fc31c51716f23210782a66d39d30a1eea19d6
[ "MIT" ]
5
2018-03-07T20:29:12.000Z
2018-05-03T11:28:52.000Z
30.259259
77
0.687271
1,000,534
package test.util; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.uniovi.main.InciDashboardI2bApplication; import com.uniovi.util.JSONHelper; @SpringBootTest(classes= { InciDashboardI2bApplication.class }) @RunWith(SpringJUnit4ClassRunner.class) public class JSONHelperTest { @Autowired private JSONHelper jsonHelper; @Test public void testJSONToMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); map.put("key2", 42); map.put("key3", new Double(5.3)); map.put("key4", new String[] {"hi", "just", "testing"}); String result = jsonHelper.mapToJson(map); String expected = "{\"key1\":\"value1\",\"key2\":42,\"key3\":5.3," + "\"key4\":[\"hi\",\"just\",\"testing\"]}"; assertEquals(expected, result); } @Test public void testMapToJSON() { String json = "{\"key1\":\"value1\",\"key2\":42,\"key3\":5.3," + "\"key4\":[\"hi\",\"just\",\"testing\"], \"key5\":{\"subkey1\": 5.2}}"; Map<String, Object> result = jsonHelper.jsonToMap(json); assertEquals(5, result.size()); assertEquals("value1", result.get("key1")); assertEquals(42.0, result.get("key2")); assertEquals(5.3, result.get("key3")); assertEquals("[hi, just, testing]", result.get("key4").toString()); assertEquals("{subkey1=5.2}", result.get("key5").toString()); } }
923debb5c07e6a114a517862e8dc1c0e4544c89c
6,891
java
Java
test/com/twu/biblioteca/LibraryManagerTest.java
Achal-Aggarwal/twu-biblioteca-achal
8dcdbfd6574f226b6ef40d58dd10e8713bbeca04
[ "Apache-2.0" ]
null
null
null
test/com/twu/biblioteca/LibraryManagerTest.java
Achal-Aggarwal/twu-biblioteca-achal
8dcdbfd6574f226b6ef40d58dd10e8713bbeca04
[ "Apache-2.0" ]
null
null
null
test/com/twu/biblioteca/LibraryManagerTest.java
Achal-Aggarwal/twu-biblioteca-achal
8dcdbfd6574f226b6ef40d58dd10e8713bbeca04
[ "Apache-2.0" ]
null
null
null
34.623116
120
0.685922
1,000,535
package com.twu.biblioteca; import org.junit.Before; import org.junit.Test; import java.util.List; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.assertTrue; public class LibraryManagerTest { BookLibrary bookLibrary; Book letusc = new Book("Let Us C", "Yashwant Kanetkar", "2000"); Book galvin = new Book("Operating System", "Galvin", "2005"); Book internetSec = new Book("Internet Security", "Ankit Fadia", "1995"); Book fivePoint = new Book("Five Point Someone", "Chetan Bhagat", "2012"); MovieLibrary movieLibrary; Movie seven = new Movie("Seven", "1995", "David Fincher", "8"); Movie darkKnight = new Movie("The Dark Knight", "2008", "Christopher Nolan", "unrated"); User achal = new User("000-0000", "achal", "Achal", "hzdkv@example.com", "1234567890"); User abhishek = new User("000-0001", "abhishek", "Abhishek", "ychag@example.com", "0987654321"); LibraryManager manager; @Before public void setUp() { bookLibrary = new BookLibrary(); bookLibrary.addItem(letusc); bookLibrary.addItem(galvin); bookLibrary.addItem(internetSec); bookLibrary.addItem(fivePoint); movieLibrary = new MovieLibrary(); movieLibrary.addItem(seven); movieLibrary.addItem(darkKnight); manager = new LibraryManager(bookLibrary, movieLibrary); } @Test public void testCheckingOutABook() { manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); assertTrue(manager.checkoutBook(letusc.getTitle())); assertTrue(manager.isBookCheckedOut(letusc.getTitle())); } @Test public void testCheckingOutAMovie() { manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); assertTrue(manager.checkoutMovie(seven.getTitle())); assertTrue(manager.isMovieCheckedOut(seven.getTitle())); } @Test public void testCheckingInABook() { manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutBook(letusc.getTitle()); assertTrue(manager.checkinBook(letusc.getTitle())); assertFalse(manager.isBookCheckedOut(letusc.getTitle())); } @Test public void testCheckingInAMovie() { manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutMovie(seven.getTitle()); assertTrue(manager.checkinMovie(seven.getTitle())); assertFalse(manager.isMovieCheckedOut(seven.getTitle())); } @Test public void testListOfAvailableBooks() { List<String> bookList = manager.getListOfAvailableBooks(); assertTrue(bookList.contains(letusc.getFormattedString())); assertTrue(bookList.contains(galvin.getFormattedString())); assertTrue(bookList.contains(internetSec.getFormattedString())); assertTrue(bookList.contains(fivePoint.getFormattedString())); } @Test public void testListOfIssuedBooks() { manager.registerUser(achal); manager.registerUser(abhishek); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutBook(letusc.getTitle()); manager.setCurrentUser(abhishek.getLibraryNumber()); manager.checkoutBook(internetSec.getTitle()); List<String> bookList = manager.getListOfIssuedBooks(); assertTrue(bookList.contains(letusc.getFormattedString() + " issued by " + achal.contactInformation())); assertTrue(bookList.contains(internetSec.getFormattedString() + " issued by " + abhishek.contactInformation())); assertEquals(2, bookList.size()); } @Test public void testListOfIssuedMovies() { manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutMovie(seven.getTitle()); List<String> movieList = manager.getListOfIssuedMovies(); assertTrue(movieList.contains(seven.getFormattedString() + " issued by " + achal.contactInformation())); assertEquals(1, movieList.size()); } @Test public void testListOfAvailableMovies() { List<String> movieList = manager.getListOfAvailableMovies(); assertTrue(movieList.contains(seven.getFormattedString())); assertTrue(movieList.contains(darkKnight.getFormattedString())); } @Test public void testRegistrationOfUser(){ manager.registerUser(achal); assertTrue(manager.isUserPresent("000-0000")); } @Test public void testValidationOfValidUser(){ manager.registerUser(achal); assertTrue(manager.isUserValid("000-0000", "achal")); } @Test public void testValidationOfInvalidUser(){ manager.registerUser(achal); assertFalse(manager.isUserValid("000-0000", "asd")); } @Test public void testSettingOfRegisterUserAsCurrentUser(){ manager.registerUser(achal); assertTrue(manager.setCurrentUser(achal.getLibraryNumber())); } @Test public void testSettingOfUnregisterUserAsCurrentUser(){ assertFalse(manager.setCurrentUser(achal.getLibraryNumber())); } @Test public void testTrackingOfUserOnCheckoutOfABook(){ manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutBook(letusc.getTitle()); assertSame(achal, letusc.getBorrower()); } @Test public void testTrackingOfUserOnCheckoutOfAMovie(){ manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutMovie(seven.getTitle()); assertSame(achal, seven.getBorrower()); } @Test public void testValidationOfValidUserOnCheckinOfAMovie(){ manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutBook(letusc.getTitle()); assertTrue(manager.checkinBook(letusc.getTitle())); } @Test public void testValidationOfInvalidUserOnCheckinOfAMovie(){ User abhishek = new User("000-0001", "abhishek", "", "", ""); manager.registerUser(achal); manager.registerUser(abhishek); manager.setCurrentUser(achal.getLibraryNumber()); manager.checkoutBook(letusc.getTitle()); manager.setCurrentUser(abhishek.getLibraryNumber()); assertFalse(manager.checkinBook(letusc.getTitle())); } @Test public void testUnsettingOfCurrentUser(){ manager.registerUser(achal); manager.setCurrentUser(achal.getLibraryNumber()); manager.unSetCurrentUser(); assertNull(manager.getCurrentUser()); } }
923debb7af59fcb69cc09fac19b938616a9d92d0
84,584
java
Java
src/main/java/de/codesourcery/javr/ui/panels/EditorPanel.java
toby1984/javr
8d7c3573ffb7daacd6b266326e1a9f1584120b68
[ "Apache-2.0" ]
3
2020-02-27T02:55:56.000Z
2020-11-12T06:56:12.000Z
src/main/java/de/codesourcery/javr/ui/panels/EditorPanel.java
toby1984/javr
8d7c3573ffb7daacd6b266326e1a9f1584120b68
[ "Apache-2.0" ]
null
null
null
src/main/java/de/codesourcery/javr/ui/panels/EditorPanel.java
toby1984/javr
8d7c3573ffb7daacd6b266326e1a9f1584120b68
[ "Apache-2.0" ]
null
null
null
36.014049
194
0.51834
1,000,536
/** * Copyright 2015-2018 Tobias Gierke <ychag@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codesourcery.javr.ui.panels; import de.codesourcery.javr.assembler.CompilationContext; import de.codesourcery.javr.assembler.CompilationUnit; import de.codesourcery.javr.assembler.CompilerSettings; import de.codesourcery.javr.assembler.ICompilationContext; import de.codesourcery.javr.assembler.IObjectCodeWriter; import de.codesourcery.javr.assembler.ObjectCodeWriter; import de.codesourcery.javr.assembler.PrettyPrinter; import de.codesourcery.javr.assembler.Segment; import de.codesourcery.javr.assembler.arch.AbstractArchitecture; import de.codesourcery.javr.assembler.exceptions.ParseException; import de.codesourcery.javr.assembler.parser.Identifier; import de.codesourcery.javr.assembler.parser.Parser.CompilationMessage; import de.codesourcery.javr.assembler.parser.Parser.Severity; import de.codesourcery.javr.assembler.parser.TextRegion; import de.codesourcery.javr.assembler.parser.ast.AST; import de.codesourcery.javr.assembler.parser.ast.ASTNode; import de.codesourcery.javr.assembler.parser.ast.CommentNode; import de.codesourcery.javr.assembler.parser.ast.DirectiveNode; import de.codesourcery.javr.assembler.parser.ast.FunctionCallNode; import de.codesourcery.javr.assembler.parser.ast.IdentifierNode; import de.codesourcery.javr.assembler.parser.ast.InstructionNode; import de.codesourcery.javr.assembler.parser.ast.IntNumberLiteralNode; import de.codesourcery.javr.assembler.parser.ast.LabelNode; import de.codesourcery.javr.assembler.parser.ast.OperatorNode; import de.codesourcery.javr.assembler.parser.ast.PreprocessorNode; import de.codesourcery.javr.assembler.parser.ast.RegisterNode; import de.codesourcery.javr.assembler.parser.ast.StatementNode; import de.codesourcery.javr.assembler.phases.ParseSourcePhase; import de.codesourcery.javr.assembler.symbols.Symbol; import de.codesourcery.javr.assembler.symbols.Symbol.Type; import de.codesourcery.javr.assembler.symbols.SymbolTable; import de.codesourcery.javr.assembler.util.Resource; import de.codesourcery.javr.assembler.util.StringResource; import de.codesourcery.javr.ui.CaretPositionTracker; import de.codesourcery.javr.ui.CaretPositionTracker.CaretPosition; import de.codesourcery.javr.ui.EditorSettings.SourceElement; import de.codesourcery.javr.ui.IDEMain; import de.codesourcery.javr.ui.IProject; import de.codesourcery.javr.ui.SourceMap; import de.codesourcery.javr.ui.config.IApplicationConfig; import de.codesourcery.javr.ui.config.IApplicationConfigProvider; import de.codesourcery.javr.ui.frames.EditorFrame; import de.codesourcery.javr.ui.frames.MessageFrame; import de.codesourcery.swing.autocomplete.AutoCompleteBehaviour; import de.codesourcery.swing.autocomplete.AutoCompleteBehaviour.DefaultAutoCompleteCallback; import de.codesourcery.swing.autocomplete.AutoCompleteBehaviour.InitialUserInput; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.log4j.Logger; import javax.swing.DefaultListCellRenderer; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.table.TableModel; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; import javax.swing.text.JTextComponent; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.file.Files; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public abstract class EditorPanel extends JPanel { private static final Logger LOG = Logger.getLogger(EditorFrame.class); public static final Duration RECOMPILATION_DELAY = Duration.ofMillis( 500 ); private final JScrollPane editorPane; private final JTextPane editor = new JTextPane(); private final GutterPanel gutterPanel; private final StatusLinePanel statusLinePanel; private final EditorFrame topLevelWindow; private final AutoCompleteBehaviour<Symbol> autoComplete = new AutoCompleteBehaviour<>(); private final IApplicationConfigProvider appConfigProvider; private final Consumer<IApplicationConfig> configListener = config -> { setupStyles(); }; private final SourceMap sourceMap = new SourceMap( editor::getText ); private final ShadowDOM frontDOM = new ShadowDOM(); private final ShadowDOM backDOM = new ShadowDOM(); private ShadowDOM currentDOM = frontDOM; private boolean ignoreEditEvents; private boolean indentFilterEnabled=true; private final UndoManagerWrapper undoManager = new UndoManagerWrapper(); private IProject project; private final JLabel cursorPositionLabel = new JLabel("0"); private final ASTTreeModel astTreeModel = new ASTTreeModel(); private JFrame astWindow = null; private JFrame searchWindow = null; private JFrame symbolWindow = null; private final SymbolTableModel symbolModel = new SymbolTableModel(); private final RecompilationThread recompilationThread = new RecompilationThread(); protected Style STYLE_TOPLEVEL; protected Style STYLE_LABEL; protected Style STYLE_NUMBER; protected Style STYLE_REGISTER; protected Style STYLE_PREPROCESSOR; protected Style STYLE_MNEMONIC; protected Style STYLE_COMMENT; protected Style STYLE_HIGHLIGHTED; protected Style STYLE_TODO; private CompilationUnit currentUnit = new CompilationUnit( new StringResource("dummy", "" ) ); private final MessageFrame messageFrame; private final SearchHelper searchHelper=new SearchHelper(); private ASTNode highlight; private boolean controlKeyPressed; private boolean wasCompiledAtLeastOnce = false; private final List<Runnable> afterCompilation = new ArrayList<>(); protected class MyMouseListener extends MouseAdapter { private final Point point = new Point(); @Override public void mouseClicked(MouseEvent e) { if ( e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1 ) { final IdentifierNode node = getNodeOnlyIfCtrl( e ); if ( node != null ) { final Symbol symbol = getSymbol( node ); if ( symbol != null && symbol.getTextRegion() != null ) { final TextRegion region = symbol.getTextRegion(); if ( symbol.getCompilationUnit().hasSameResourceAs( currentUnit ) ) { setSelection( region ); } else { try { final EditorPanel editor = topLevelWindow.openEditor( project , symbol.getCompilationUnit() ); SwingUtilities.invokeLater( () -> editor.setSelection( region ) ); } catch (IOException e1) { LOG.error("mouseClicked(): Failed to open editor",e1); IDEMain.showError( "Failed to open editor", e1 ); } } } } } } private Symbol getSymbol(IdentifierNode node) { Symbol result = node.getSymbol(); if ( result == null ) { final SymbolTable table = currentUnit.getSymbolTable().getTopLevelTable(); result = table.maybeGet( node.name ).orElse( null ); if ( result == null ) { // maybe this is the name of a local variable. // // Traverse the AST backwards until we find the next global label while looking for a match, // if this fails try traversing the AST forwards until we reach the next global label StatementNode statement = node.getStatement(); while ( true ) { final List<LabelNode> labels = statement.findLabels(); boolean foundGlobalLabel = false; for ( LabelNode ln : labels ) { if ( ln.isGlobal() ) { foundGlobalLabel = true; result = table.maybeGet( Identifier.newLocalGlobalIdentifier( ln.identifier , node.name ) ).orElse( null ); if ( result != null ) { return result; } } } final int previousIdx = statement.getParent().indexOf( statement )-1; if ( foundGlobalLabel || previousIdx < 0 ) { break; } statement = (StatementNode) statement.getParent().child( previousIdx ); } } } return result; } @Override public void mouseMoved(MouseEvent e) { final IdentifierNode node = getNode( e ); String toolTipText = null; if ( node != null ) { final Symbol symbol = getSymbol( node ); if ( symbol != null ) { final long value = AbstractArchitecture.toIntValue( symbol.getValue() ); if ( value != AbstractArchitecture.VALUE_UNAVAILABLE ) { toolTipText = symbol.name()+" = "+value+" (0x"+Integer.toHexString( (int) value )+")"; } } } editor.setToolTipText( toolTipText ); if ( controlKeyPressed ) { setHighlight( node ); } } private IdentifierNode getNode(MouseEvent e) { point.x = e.getX(); point.y = e.getY(); final int pos = editor.viewToModel( point ); ASTNode node = null; if ( pos >= 0 ) { node = astTreeModel.getAST().getNodeAtOffset( pos ); } return node == null || node.getTextRegion() == null || !(node instanceof IdentifierNode)? null : (IdentifierNode) node; } private IdentifierNode getNodeOnlyIfCtrl(MouseEvent e) { return controlKeyPressed ? getNode( e ) : null; } } protected class SearchHelper { private int currentPosition; private String term; public boolean searchBackward() { if ( ! canSearch() ) { return false; } String text = editor.getText().toLowerCase(); if ( currentPosition ==0 ) { currentPosition = text.length()-1; } int startIndex = 0; final String searchTerm = term.toLowerCase(); int previousMatch = text.indexOf( searchTerm, 0 ); boolean searchWrapped = false; while ( previousMatch != -1 && startIndex < ( text.length()-1 ) ) { final int match = text.indexOf( searchTerm , startIndex ); if ( match == -1 || match >= (currentPosition-1) ) { if ( searchWrapped || previousMatch < (currentPosition-1 ) ) { break; } startIndex = 0; currentPosition = text.length(); searchWrapped = true; continue; } previousMatch = match; startIndex = previousMatch+1; } if ( previousMatch != -1 ) { currentPosition = previousMatch; gotoMatch( currentPosition ); return true; } return false; } private void gotoMatch(int cursorPos) { editor.setCaretPosition( cursorPos ); editor.select( cursorPos , cursorPos+term.length() ); editor.requestFocus(); currentPosition = cursorPos+1; } public boolean searchForward() { if ( ! canSearch() ) { return false; } final String text = editor.getText(); if ( currentPosition >= text.length()) { currentPosition = 0; } final int nextMatch = text.substring( currentPosition , text.length() ).toLowerCase().indexOf( term.toLowerCase() ); if ( nextMatch != -1 ) { gotoMatch( currentPosition + nextMatch ); return true; } return false; } public void startFromBeginning() { currentPosition = 0; } public boolean canSearch() { final String text = editor.getText(); return term != null && term.length() > 0 && text != null && text.length() != 0; } public void setTerm(String term) { this.term = term; } public String getTerm() { return term; } } protected static final class FilteredList<T> extends AbstractList<T> { private final List<T> unfiltered = new ArrayList<T>(); private final List<T> filtered = new ArrayList<T>(); private Function<T,Boolean> filterFunc = x -> true; public void setFilterFunc(Function<T,Boolean> filterFunc ) { Validate.notNull(filterFunc, "filterFunc must not be NULL"); this.filterFunc = filterFunc; doFilter(); } private void doFilter() { filtered.clear(); for ( T elem : unfiltered ) { if ( filterFunc.apply( elem ) == Boolean.TRUE ) { filtered.add( elem ); } } } @Override public boolean addAll(Collection<? extends T> c) { boolean result = false; for ( T elem : c ) { result |= add(elem); } return result; } @Override public boolean add(T e) { Validate.notNull(e, "e must not be NULL"); unfiltered.add( e ); if ( filterFunc.apply( e ) == Boolean.TRUE ) { filtered.add(e); return true; } return false; } @Override public void clear() { filtered.clear(); unfiltered.clear(); } @Override public Iterator<T> iterator() { return filtered.iterator(); } @Override public T get(int index) { return filtered.get(index); } @Override public int size() { return filtered.size(); } } protected class IndentFilter extends DocumentFilter { private static final String NEWLINE = "\n"; public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { if ( indentFilterEnabled ) { super.insertString(fb, offs, replaceTabs(str), a); } else { super.insertString(fb,offs,str,a); } } private boolean isNewline(String s) { return NEWLINE.equals( s ); } private String replaceTabs(String in) { return in.replace("\t" , project.getConfig().getEditorIndentString() ); } @Override public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { if ( indentFilterEnabled ) { final int oldLength = editor.getDocument().getLength(); fb.remove(offset, length); documentLengthDecreased(oldLength - length); } else { super.remove(fb,offset,length); } } private void documentLengthDecreased(int newLength) { frontDOM.truncate( newLength ); backDOM.truncate( newLength); } @Override public void replace(FilterBypass fb, int offs, int toDeleteLength, String origReplacement, AttributeSet a) throws BadLocationException { if ( ! indentFilterEnabled ) { super.replace(fb,offs,toDeleteLength,origReplacement,a); return; } final String newReplacement; if ( isNewline( origReplacement ) ) { newReplacement = "\n "; } else { newReplacement = replaceTabs( origReplacement ); } final int oldLength = editor.getDocument().getLength(); super.replace( fb, offs, toDeleteLength, newReplacement, a ); if ( toDeleteLength > newReplacement.length() ) { final int delta = toDeleteLength - newReplacement.length(); documentLengthDecreased( oldLength - delta ); } } } protected final class RecompilationThread extends Thread { private long lastChange = -1; private final AtomicBoolean terminate = new AtomicBoolean(false); private final Object SLEEP_LOCK = new Object(); { setDaemon(true); setName("recompilation"); } public void run() { while ( ! terminate.get() ) { long ts = -1; synchronized( SLEEP_LOCK ) { try { SLEEP_LOCK.wait(); ts = lastChange; } catch (InterruptedException e) { /* */ } } if ( ts == -1 ) { continue; } boolean doRecompile = false; while( ! terminate.get() ) { try { Thread.sleep( (int) RECOMPILATION_DELAY.toMillis() ); } catch(Exception e) { /* */ } synchronized( SLEEP_LOCK ) { if( lastChange == ts ) { lastChange = -1; doRecompile = true; break; } ts = lastChange; } } if ( doRecompile ) { try { SwingUtilities.invokeAndWait( () -> compile() ); } catch(Exception e) { // ignore } } } } public void documentChanged(DocumentEvent event) { synchronized ( SLEEP_LOCK ) { lastChange = System.currentTimeMillis(); SLEEP_LOCK.notifyAll(); } } } private final class SymbolTableModel implements TableModel { private final FilteredList<Symbol> symbols = new FilteredList<>(); private final List<TableModelListener> listeners = new ArrayList<>(); private String filterString = null; public void setSymbolTable(SymbolTable table) { Validate.notNull(table,"table must not be NULL"); this.symbols.clear(); final List<Symbol> allSymbolsSorted = table.getAllSymbolsSorted(); this.symbols.addAll( allSymbolsSorted ); tableChanged(); } public void clear() { symbols.clear(); setFilterString( this.filterString ); } private void tableChanged() { final TableModelEvent ev = new TableModelEvent( this ); listeners.forEach( l -> l.tableChanged( ev ) ); } public void setFilterString(String s) { this.filterString = s == null ? null : s.toLowerCase(); final Function<Symbol,Boolean> func; if ( filterString == null ) { func = symbol -> true; } else { func = symbol -> filterString == null ? Boolean.TRUE : Boolean.valueOf( symbol.name().value.toLowerCase().contains( filterString ) ); } symbols.setFilterFunc( func ); tableChanged(); } @Override public int getRowCount() { return symbols.size(); } @Override public int getColumnCount() { return 8; } private void assertValidColumn(int columnIndex) { if ( columnIndex < 0 || columnIndex > 7 ) { throw new RuntimeException("Invalid column: "+columnIndex); } } @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return "Name"; case 1: return "Symbol Type"; case 2: return "Object Type"; case 3: return "Object Size"; case 4: return "Segment"; case 5: return "Value"; case 6: return "Node"; case 7: return "Compilation unit"; default: throw new RuntimeException("Invalid column: "+columnIndex); } } @Override public Class<?> getColumnClass(int columnIndex) { assertValidColumn(columnIndex); return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { final Symbol symbol = symbols.get(rowIndex); switch( columnIndex ) { case 0: return symbol.name().value; case 1: return symbol.getType().toString(); case 2: return symbol.getObjectType().toString(); case 3: return Integer.toString( symbol.getObjectSize() ); case 4: final Segment segment = symbol.getSegment(); return segment == null ? "--" : segment.toString(); case 5: final Object value = symbol.getValue(); return value == null ? "<no value>" : value.toString(); case 6: return symbol.getNode() == null ? null : symbol.getNode().toString(); case 7: return symbol.getCompilationUnit().getResource().toString(); default: throw new RuntimeException("Invalid column: "+columnIndex); } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { throw new UnsupportedOperationException(); } @Override public void addTableModelListener(TableModelListener l) { listeners.add(l); } @Override public void removeTableModelListener(TableModelListener l) { listeners.remove(l); } } private final class ASTTreeModel implements TreeModel { private final List<TreeModelListener> listeners = new ArrayList<>(); private AST ast = new AST(); public void setAST(AST ast) { this.ast = ast; final TreeModelEvent ev = new TreeModelEvent(this, new TreePath(this.ast) ); listeners.forEach( l -> l.treeStructureChanged( ev ) ); } public AST getAST() { return ast; } @Override public AST getRoot() { return ast; } @Override public Object getChild(Object parent, int index) { return ((ASTNode) parent).child(index); } @Override public int getChildCount(Object parent) { return ((ASTNode) parent).childCount(); } @Override public boolean isLeaf(Object node) { return ((ASTNode) node).hasNoChildren(); } @Override public void valueForPathChanged(TreePath path, Object newValue) { final TreeModelEvent ev = new TreeModelEvent(this , path ); listeners.forEach( l -> l.treeNodesChanged( ev ) ); } @Override public int getIndexOfChild(Object parent, Object child) { return ((ASTNode) parent).indexOf( (ASTNode) child); } @Override public void addTreeModelListener(TreeModelListener l) { listeners.add(l); } @Override public void removeTreeModelListener(TreeModelListener l) { listeners.remove(l); } } public EditorPanel(IProject project, EditorFrame topLevelWindow , CompilationUnit unit,IApplicationConfigProvider appConfigProvider,MessageFrame messageFrame, CaretPositionTracker caretTracker) throws IOException { Validate.notNull(project, "project must not be NULL"); Validate.notNull(unit, "unit must not be NULL"); Validate.notNull(appConfigProvider, "appConfigProvider must not be NULL"); Validate.notNull(messageFrame, "messageFrame must not be NULL"); Validate.notNull(caretTracker,"caretTracker must not be NULL"); this.messageFrame = messageFrame; this.appConfigProvider = appConfigProvider; this.project = project; this.currentUnit = unit; this.topLevelWindow = topLevelWindow; this.caretTracker = caretTracker; // symbol auto completion callback autoComplete.setCallback( new DefaultAutoCompleteCallback<Symbol>() { private Symbol previousGlobalSymbol; private final char[] separatorChars = new char[] {'(',')',','}; private boolean matches(Identifier name,String userInput) { for ( int i = 0 , matchCount = 0 , len = name.value.length() < userInput.length() ? name.value.length() : userInput.length() ; i < len ; i++ ) { final char c = Character.toLowerCase( name.value.charAt( i ) ); if ( c == userInput.charAt(i) ) { matchCount++; if ( matchCount == 3 ) { return true; } } else { break; } } if ( name.value.toLowerCase().contains( userInput ) ) { return true; } return false; } private boolean matches(Symbol symbol,String userInput) { if ( previousGlobalSymbol != null ) { if ( symbol.isLocalLabel() ) { if ( symbol.getGlobalNamePart().equals( previousGlobalSymbol.name() ) ) { if ( matches( symbol.getLocalNamePart() , userInput) ) { return true; } } } else if ( matches( symbol.name() , userInput ) ) // global label { return true; } } else { // no previous global symbol, only consider global labels if ( symbol.isGlobalLabel() && matches( symbol.name() , userInput ) ) { return true; } } return false; } @Override protected boolean isSeparatorChar(char c) { if ( Character.isWhitespace( c ) ) { return true; } for ( int i = 0, len = separatorChars.length ; i < len ; i++ ) { if ( c == separatorChars[i] ) { return true; } } return false; } @Override public List<Symbol> getProposals(String input) { final String lower = input.toLowerCase(); final List<Symbol> globalMatches = new ArrayList<>(); final List<Symbol> localMatches = new ArrayList<>(); final SymbolTable globalTable = currentUnit.getSymbolTable().getTopLevelTable(); globalTable.visitSymbols( (symbol) -> { switch( symbol.getType() ) { case ADDRESS_LABEL: if ( matches(symbol , lower ) ) { if ( symbol.isLocalLabel() ) { localMatches.add(symbol); } else { globalMatches.add(symbol); } } break; case EQU: case PREPROCESSOR_MACRO: if ( symbol.name().value.toLowerCase().contains( lower ) ) { globalMatches.add( symbol ); } break; default: break; } return Boolean.TRUE; }); globalMatches.sort( (a,b) -> a.name().value.compareTo( b.name().value ) ); localMatches.sort( (a,b) -> a.getLocalNamePart().value.compareTo( b.getLocalNamePart().value ) ); final List<Symbol> result = new ArrayList<>( globalMatches.size() + localMatches.size() ); result.addAll( localMatches ); result.addAll( globalMatches ); return result; } @Override public String getStringToInsert(Symbol value) { if ( value.isLocalLabel() ) { return value.getLocalNamePart().value; } return value.name().value; } @Override public InitialUserInput getInitialUserInput(JTextComponent editor, int caretPosition) { previousGlobalSymbol = null; final ASTNode node = astTreeModel.getAST().getNodeAtOffset( caretPosition-1 ); if ( node != null ) { final SymbolTable globalTable = currentUnit.getSymbolTable().getTopLevelTable(); node.searchBackwards( n -> { if ( n instanceof LabelNode) { if ( ((LabelNode) n).isGlobal() ) { final Optional<Symbol> symbol = globalTable.maybeGet( ((LabelNode) n).identifier , Type.ADDRESS_LABEL ); if ( symbol.isPresent() ) { previousGlobalSymbol = symbol.get(); return true; } } } return false; } ); } else { System.err.println("Failed to find AST node for current offset ?"); } return super.getInitialUserInput(editor, caretPosition); } }); autoComplete.setListCellRenderer( new DefaultListCellRenderer() { public Component getListCellRendererComponent(javax.swing.JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final Symbol symbol = (Symbol) value; setText( symbol.isLocalLabel() ? symbol.getLocalNamePart().value : symbol.name().value ); return result; }; }); autoComplete.setInitialPopupSize( new Dimension(250,200 ) ); autoComplete.setVisibleRowCount( 10 ); editor.setFont( new Font(Font.MONOSPACED, Font.PLAIN, 12) ); editor.addCaretListener( new CaretListener() { @Override public void caretUpdate(CaretEvent e) { cursorPositionLabel.setText( Integer.toString( e.getDot() ) ); if ( currentUnit != null && ! ignoreEditEvents ) { caretTracker.rememberCaretPosition( e.getDot(), currentUnit ); } } }); final MyMouseListener mouseListener = new MyMouseListener(); editor.addMouseMotionListener( mouseListener); editor.addMouseListener( mouseListener ); editor.addKeyListener( new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if ( isCtrlDown( e ) && e.getKeyCode() == KeyEvent.VK_W ) { EditorPanel.this.close( true ); } else if ( e.getKeyCode() == KeyEvent.VK_CONTROL ) { controlKeyPressed = true; } } @Override public void keyReleased(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_CONTROL ) { setHighlight( null ); controlKeyPressed = false; } } private boolean isCtrlDown(KeyEvent e) { return ( e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK ) != 0; } private boolean isAltDown(KeyEvent e) { return ( e.getModifiersEx() & KeyEvent.ALT_DOWN_MASK ) != 0; } /** * Returns a {@link TextRegion} for the line that holds a given * caret position. * * Note that the returned region <b>include</b> the EOL character at the end of the line (if any). * * @param caretPosition * @return region describing the current line or <code>NULL</code> if the text editor is empty. */ private TextRegion getLineAt(int caretPosition) { final Optional<SourceMap.Line> line = sourceMap.getLineByOffset(caretPosition); return line.map(l -> { final int col = 1 + caretPosition - l.startOffset; return new TextRegion(l.startOffset,l.endOffset-l.startOffset,l.lineNum,col); }).orElseGet(() -> { LOG.error("getLineAt(): Found no line for caret position "+caretPosition); return null; }); } @Override public void keyTyped(KeyEvent e) { if ( isCtrlDown(e) ) { final byte[] bytes = Character.toString( e.getKeyChar() ).getBytes(); if ( e.getKeyChar() == 6 ) // CTRL-F ... search { toggleSearchWindow(); } else if ( e.getKeyChar() == 0x12 ) // CTRL-R ... delete to end of line { final TextRegion line = getLineAt( editor.getCaretPosition() ); if ( line != null && editor.getText().charAt( line.start() ) != '\n' ) { try { final int toRemove = line.end() - editor.getCaretPosition(); editor.getDocument().remove( editor.getCaretPosition() , toRemove ); } catch (BadLocationException e1) { LOG.error("keyTyped(): Failed to remove()",e1); IDEMain.showError( "Failed to remove()", e1 ); } } } else if ( e.getKeyChar() == 0x04 ) // CTRL-D ... delete line { final TextRegion line = getLineAt( editor.getCaretPosition() ); if ( line != null ) { restoreCaretPositionAfter( () -> { try { editor.getDocument().remove( line.start(), line.length()+1 ); } catch (BadLocationException e1) { LOG.error("keyTyped(): Failed to remove()",e1); IDEMain.showError( "Failed to remove()", e1 ); } }); } } else if ( e.getKeyChar() == 0x0b && searchHelper.canSearch() ) // CTRL-K ... search forward { searchHelper.searchForward(); } else if ( e.getKeyChar() == 0x02 && searchHelper.canSearch() ) // CTRL-B ... search backwards { searchHelper.searchBackward(); } else if ( e.getKeyChar() == 0x07 ) // CTRL-G ... goto line { gotoLine(); } else if ( e.getKeyChar() == 0x0d ) // CTRL+S ... save { try { saveSource(); } catch (IOException e1) { IDEMain.showError("Failed to save file",e1); } } else if ( e.getKeyChar() == 0x1a && undoManager.canUndo() ) { // CTRL-Z restoreCaretPositionAfter( () -> { undoManager.undo(); e.consume(); }); } else if ( e.getKeyChar() == 0x19 && undoManager.canRedo() ) { // CTRL-Y restoreCaretPositionAfter( () -> { undoManager.redo(); e.consume(); }); } } } }); editor.setFont(new Font("monospaced", Font.PLAIN, 12)); final JPanel panel = new JPanel(); panel.setLayout( new GridBagLayout() ); // add toolbar GridBagConstraints cnstrs = new GridBagConstraints(); cnstrs.gridx = 0; cnstrs.gridy = 0; cnstrs.gridwidth=2; cnstrs.gridheight = 1 ; cnstrs.weightx = 1.0; cnstrs.weighty=0; cnstrs.fill = GridBagConstraints.HORIZONTAL; panel.add( createToolbar() , cnstrs ); // gutter editorPane = new JScrollPane( editor ); gutterPanel = new GutterPanel( editorPane, this, appConfigProvider ); final int gutterWidth = 50; gutterPanel.setMinimumSize( new Dimension(gutterWidth,10) ); gutterPanel.setMaximumSize( new Dimension(gutterWidth,5000) ); cnstrs = new GridBagConstraints(); cnstrs.insets = new Insets(0,0,0,0); cnstrs.gridx = 0; cnstrs.gridy = 1; cnstrs.gridwidth=1; cnstrs.gridheight = 1 ; cnstrs.weightx = 0; cnstrs.weighty=1; cnstrs.fill = GridBagConstraints.VERTICAL; panel.add( gutterPanel, cnstrs ); // editor // ugly hack to adjust splitpane size after it has become visible addAncestorListener( new AncestorListener() { @Override public void ancestorRemoved(AncestorEvent event) { appConfigProvider.removeChangeListener( configListener ); } @Override public void ancestorMoved(AncestorEvent event) { } @Override public void ancestorAdded(AncestorEvent event) { appConfigProvider.addChangeListener( configListener ); } }); cnstrs = new GridBagConstraints(); cnstrs.insets = new Insets(0,0,0,0); cnstrs.gridx = 1; cnstrs.gridy = 1; cnstrs.gridwidth=1; cnstrs.gridheight = 1 ; cnstrs.weightx = 1.0; cnstrs.weighty=1; cnstrs.fill = GridBagConstraints.BOTH; panel.add( editorPane , cnstrs ); // status line statusLinePanel = new StatusLinePanel( sourceMap,editor ); final int statusLineHeight = 16; statusLinePanel.setMinimumSize( new Dimension(10,statusLineHeight) ); statusLinePanel.setMaximumSize( new Dimension(5000,statusLineHeight) ); cnstrs = new GridBagConstraints(); cnstrs.insets = new Insets(0,0,0,0); cnstrs.gridx = 0; cnstrs.gridy = 2; cnstrs.gridwidth=2; cnstrs.gridheight = 1 ; cnstrs.weightx = 1; cnstrs.weighty=0; cnstrs.fill = GridBagConstraints.HORIZONTAL; panel.add( statusLinePanel, cnstrs ); // add panel we used for composition setLayout( new GridBagLayout() ); cnstrs = new GridBagConstraints(); cnstrs.gridx = 0; cnstrs.gridy = 0; cnstrs.gridwidth=1; cnstrs.gridheight = 1 ; cnstrs.weightx = 1.0; cnstrs.weighty=1; cnstrs.fill = GridBagConstraints.BOTH; add( panel , cnstrs ); // setup styles setupStyles(); // setup recompilation recompilationThread.start(); setProject( project , currentUnit ); } private void restoreCaretPositionAfter(Runnable r) { final int oldPos = editor.getCaretPosition(); r.run(); try { editor.setCaretPosition( oldPos ); } catch(IllegalArgumentException e) { // can't help it, probably the last line got deleted or something else } } private void setupStyles() { final StyleContext ctx = new StyleContext(); final Style topLevelStyle = ctx.addStyle( "topLevelStyle" , null); STYLE_TOPLEVEL = topLevelStyle; STYLE_LABEL = createStyle( "labelStyle" , SourceElement.LABEL, ctx ); STYLE_NUMBER = createStyle( "numberStyle" , SourceElement.NUMBER, ctx ); STYLE_REGISTER = createStyle( "registerStyle" , SourceElement.REGISTER , ctx ); STYLE_MNEMONIC = createStyle( "mnemonicStyle" , SourceElement.MNEMONIC, ctx ); STYLE_COMMENT = createStyle( "commentStyle" , SourceElement.COMMENT , ctx ); STYLE_TODO = createStyle( "todoStyle" , SourceElement.TODO , ctx ); STYLE_PREPROCESSOR = createStyle( "preprocStyle" , SourceElement.PREPROCESSOR , ctx ); // highlight STYLE_HIGHLIGHTED = ctx.addStyle( "highlight", topLevelStyle ); STYLE_HIGHLIGHTED.addAttribute(StyleConstants.Foreground, Color.BLUE); STYLE_HIGHLIGHTED.addAttribute(StyleConstants.Underline, Boolean.TRUE ); } private Style createStyle(String name,SourceElement sourceElement,StyleContext ctx) { final Color col = appConfigProvider.getApplicationConfig().getEditorSettings().getColor( sourceElement ); final Style style = ctx.addStyle( name , STYLE_TOPLEVEL ); style.addAttribute(StyleConstants.Foreground, col ); return style; } private Document createDocument() { final Document doc = editor.getEditorKit().createDefaultDocument(); // setup styles ignoreEditEvents = false; // setup auto-indent ((AbstractDocument) doc).setDocumentFilter( new IndentFilter() ); doc.addDocumentListener( new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { if ( ! ignoreEditEvents ) { lastEditLocation = e.getOffset(); recompilationThread.documentChanged(e); } sourceMap.invalidate(); } @Override public void removeUpdate(DocumentEvent e) { if ( ! ignoreEditEvents ) { lastEditLocation = e.getOffset(); recompilationThread.documentChanged(e); } sourceMap.invalidate(); } @Override public void changedUpdate(DocumentEvent e) { if ( ! ignoreEditEvents ) { lastEditLocation = e.getOffset(); recompilationThread.documentChanged(e); } sourceMap.invalidate(); } }); undoManager.discardAllEdits(); doc.addUndoableEditListener( new UndoableEditListener() { @Override public void undoableEditHappened(UndoableEditEvent e) { if ( ! ignoreEditEvents ) { if ( e.getEdit() instanceof AttributeUndoableEdit || e.getEdit().getClass().getName().contains("StyleChangeUndoableEdit") ) { return; } undoManager.undoableEditHappened( e ); } } }); return doc; } private JToolBar createToolbar() { final JToolBar result = new JToolBar(JToolBar.HORIZONTAL); result.add( button("Compile" , ev -> this.compile() ) ); result.add( button("AST" , ev -> this.toggleASTWindow() ) ); result.add( button("Goto last edit" , ev -> this.gotoLastEditLocation() ) ); result.add( button("Goto previous" , ev -> setCaretPosition( caretTracker.getPreviousCaretPosition() ) ) ); result.add( button("Goto next" , ev -> setCaretPosition( caretTracker.getNextCaretPosition() ) ) ); result.add( button("Indent" , ev -> this.indentSources() ) ); result.add( button("Symbols" , ev -> this.toggleSymbolTableWindow() ) ); result.add( button("Upload to uC" , ev -> this.uploadToController() ) ); result.add( button("Show as avr-as" , ev -> { hidePrettyPrint(); showPrettyPrint(true); } ) ); result.add( button("Pretty print" , ev -> { hidePrettyPrint(); showPrettyPrint(false); } ) ); result.add( new JLabel("Cursor pos:" ) ); result.add( cursorPositionLabel ); return result; } private final CaretPositionTracker caretTracker; private int lastEditLocation = -1; private PrettyPrintWindow prettyPrintWindow; private final class PrettyPrintWindow extends JFrame { private JTextArea textArea = new JTextArea(); public boolean gnuSyntax = true; public void astChanged() { final PrettyPrinter printer = new PrettyPrinter(); try { printer.setGNUSyntax( gnuSyntax ); final String source = printer.prettyPrint( getCompilationUnit().getAST() ); textArea.setText( source ); } catch(Exception e) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try ( PrintWriter pw = new PrintWriter( out ) ) { e.printStackTrace( pw ); } final String stacktrace = new String( out.toByteArray() ); textArea.setText( stacktrace ); } textArea.setCaretPosition( 0 ); } public PrettyPrintWindow() { super("Pretty print"); setMinimumSize( new Dimension(400,200 ) ); getContentPane().setLayout( new GridBagLayout() ); textArea.setEditable( false ); GridBagConstraints cnstrs = new GridBagConstraints(); cnstrs.fill = GridBagConstraints.BOTH; cnstrs.gridx = 0; cnstrs.gridy = 0; cnstrs.gridheight = 1; cnstrs.gridwidth = 1; cnstrs.weightx = 1; cnstrs.weighty = 1; cnstrs.insets = new Insets(0,0,0,0); getContentPane().add( new JScrollPane( textArea ) , cnstrs ); pack(); setVisible( true ); textArea.setFont( new Font( Font.MONOSPACED , getFont().getStyle() , getFont().getSize() ) ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { prettyPrintWindow = null; dispose(); } }); } } private boolean isPrettyPrintShown() { return prettyPrintWindow != null; } private void hidePrettyPrint() { if ( isPrettyPrintShown() ) { prettyPrintWindow.dispose(); } } private void showPrettyPrint(boolean gnuSyntax) { if ( ! isPrettyPrintShown() ) { prettyPrintWindow = new PrettyPrintWindow(); } prettyPrintWindow.gnuSyntax = gnuSyntax; prettyPrintWindow.astChanged(); prettyPrintWindow.toFront(); } private void gotoLastEditLocation() { if ( lastEditLocation != -1 ) { runAfterCompilation( () -> { if ( lastEditLocation != -1 ) { editor.setCaretPosition( lastEditLocation ); editor.requestFocus(); } }); } else { editor.requestFocus(); } } private void setCaretPosition(CaretPosition position) { boolean caretMoved = false; if ( position != null ) { if ( currentUnit.hasSameResourceAs( position.unit ) ) { setCaretPosition( position.offset ); caretMoved = true; } else { // TODO: Switch to editor panel for the compilation unit the caret was in try { final EditorPanel editorPanel = topLevelWindow.openEditor( project, position.unit ); } catch (IOException e) { e.printStackTrace(); } } } if ( ! caretMoved ) { editor.requestFocus(); } } private void uploadToController() { if ( project.canUploadToController() ) { try { project.uploadToController(); } catch(Exception e) { LOG.error("UPLOAD failed",e); IDEMain.showError("Upload to uC failed",e); } } else { IDEMain.showError( "Program upload failed", "Compilation failed, project uses incompatible output format or no upload command configured " ); } } private void saveSource() throws IOException { String text = editor.getText(); text = text == null ? "" : text; final Resource resource = currentUnit.getResource(); LOG.info("saveSource(): Saving source to "+currentUnit.getResource()); try ( OutputStream out = currentUnit.getResource().createOutputStream() ) { final byte[] bytes = text.getBytes( resource.getEncoding() ); out.write( bytes ); } } public void compile() { highlight = null; messageFrame.clearMessages(); currentUnit.clearMessages(); symbolModel.clear(); // save source to file try { saveSource(); } catch(IOException e) { LOG.error("compile(): Failed to save changes",e); currentUnit.addMessage( CompilationMessage.error( currentUnit, "Failed to save changes: "+e.getMessage()) ); IDEMain.showError( "Failed to save changes", e ); return; } // parse only this compilation unit // to get an AST suitable for syntax highlighting that does // NOT nodes for expanded macros/includes like the regular compilation does astTreeModel.setAST( new AST() ); // also do not use the current compilation unit here as this will // trigger "duplicate symbol" errors during the actual compilation // later on final CompilationUnit tmpUnit = new CompilationUnit( currentUnit.getResource() ); final long parseStart = System.currentTimeMillis(); try { final CompilerSettings compilerSettings = new CompilerSettings(); final IObjectCodeWriter writer = new ObjectCodeWriter(); final SymbolTable globalSymbolTable = new SymbolTable( SymbolTable.GLOBAL ); // fake global symbol table so we don't fail parsing because of duplicate symbols already in the real one final ICompilationContext context = new CompilationContext( tmpUnit , globalSymbolTable , writer , project , compilerSettings , project.getConfig() ); ParseSourcePhase.parseWithoutIncludes( context, tmpUnit , project ); } catch(Exception e) { LOG.error("Parsing source failed",e); IDEMain.showError( "Parsing source failed", e ); } astTreeModel.setAST( tmpUnit.getAST() ); final long parseEnd = System.currentTimeMillis(); // do syntax highlighting doSyntaxHighlighting(); final long highlightEnd = System.currentTimeMillis(); // assemble final CompilationUnit root = project.getCompileRoot(); boolean compilationSuccessful = false; try { compilationSuccessful = project.compile(); } catch(Exception e) { LOG.error("compile(): Compilation failed "+e.getMessage(), LOG.isDebugEnabled() ? e : null ); currentUnit.addMessage( toCompilationMessage( currentUnit, e ) ); } symbolModel.setSymbolTable( currentUnit.getSymbolTable() ); final long compileEnd = System.currentTimeMillis(); // generation info message about compilation outcome final long parseTime = parseEnd - parseStart; final long highlightTime = highlightEnd - parseEnd; final long compileTime = compileEnd - highlightEnd; final String assembleTime = "parsing: "+parseTime+" ms,highlighting: "+highlightTime+" ms,compile: "+compileTime+" ms"; final String success = compilationSuccessful ? "successful" : "failed"; final DateTimeFormatter df = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss"); currentUnit.addMessage( CompilationMessage.info(currentUnit,"Compilation "+success+" ("+assembleTime+") on "+df.format( ZonedDateTime.now() ) ) ); if ( isPrettyPrintShown() ) { showPrettyPrint( prettyPrintWindow.gnuSyntax ); } messageFrame.addAll( root.getMessages(true) ); gutterPanel.repaint(); wasCompiledAtLeastOnce = true; // execute deferred callbacks that were waiting on compilation to complete if ( ! afterCompilation.isEmpty() ) { for ( Runnable r : afterCompilation ) { try { r.run(); } catch(Exception e) { IDEMain.showError("Closure failed to execute: "+r,e); } } afterCompilation.clear(); } } private static CompilationMessage toCompilationMessage(CompilationUnit unit,Exception e) { if ( e instanceof ParseException ) { return new CompilationMessage(unit,Severity.ERROR , e.getMessage() , new TextRegion( ((ParseException ) e).getOffset() , 0 ,-1 , -1 ) ); } return new CompilationMessage(unit,Severity.ERROR , e.getMessage() ); } private void doSyntaxHighlighting() { doSyntaxHighlighting( astTreeModel.getAST() ); } private void doSyntaxHighlighting(ASTNode subtree) { updateShadowDOM( dom -> { subtree.visitBreadthFirst( (node, ctx) -> setNodeStyle( node, dom ) ); }); } private void updateShadowDOM(Consumer<ShadowDOM> domCallback) { final boolean oldState = ignoreEditEvents; ignoreEditEvents = true; try { final ShadowDOM frontBuffer = currentDOM; final ShadowDOM backBuffer = frontBuffer == frontDOM ? backDOM : frontDOM; // render style to back buffer domCallback.accept( backBuffer ); // apply changes to StyledDocuments backBuffer.applyDelta( editor.getStyledDocument(), frontBuffer ); // swap back & front buffer currentDOM = backBuffer; } catch(RuntimeException e) { LOG.error("doSyntaxHighlighting(): Failed ",e); IDEMain.showError( "Highlighting failed",e ); } finally { ignoreEditEvents = oldState; } } private TextRegion getVisibleRegion() { final JViewport viewport = editorPane.getViewport(); Point startPoint = viewport.getViewPosition(); Dimension size = viewport.getExtentSize(); Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height); int start = editor.viewToModel( startPoint ); int end = editor.viewToModel( endPoint ); return new TextRegion(start,end-start,0,0); } private void setNodeStyle(ASTNode node,ShadowDOM shadowDOM) { final TextRegion region = node.getTextRegion(); if ( region != null ) { Style style = null; if ( node instanceof PreprocessorNode ) { style = STYLE_PREPROCESSOR; } else if ( node instanceof RegisterNode) { style = STYLE_REGISTER; } else if ( node instanceof InstructionNode ) { style = STYLE_MNEMONIC; } else if ( node instanceof CommentNode ) { final String comment = ((CommentNode) node).value; if ( comment.contains("TODO") ) { style = STYLE_TODO; } else { style = STYLE_COMMENT; } } else if ( node instanceof LabelNode || node instanceof IdentifierNode) { style = STYLE_LABEL; } else if ( node instanceof IntNumberLiteralNode) { style = STYLE_NUMBER; } if ( style != null ) { shadowDOM.setCharacterAttributes( region, style ); } else { shadowDOM.setCharacterAttributes( region, STYLE_TOPLEVEL ); } } } private void setHighlight(ASTNode newHighlight) { if ( this.highlight == newHighlight ) { return; } if ( newHighlight != null && newHighlight.getTextRegion() == null ) { throw new IllegalStateException("Cannot highlight a node that has no text region assigned"); } if ( this.highlight != null && newHighlight != null && this.highlight.getTextRegion().equals( newHighlight.getTextRegion() ) ) { return; } if ( this.highlight != null ) { doSyntaxHighlighting( this.highlight ); } this.highlight = newHighlight; if ( newHighlight != null ) { final TextRegion region = newHighlight.getTextRegion(); ignoreEditEvents = true; try { updateShadowDOM( dom -> dom.setCharacterAttributes( region, STYLE_HIGHLIGHTED ) ); } finally { ignoreEditEvents = false; } } } private JButton button(String label,ActionListener l) { final JButton astButton = new JButton( label ); astButton.addActionListener( l ); return astButton; } private void toggleASTWindow() { if ( astWindow != null ) { astWindow.dispose(); astWindow=null; return; } astWindow = createASTWindow(); astWindow.pack(); astWindow.setLocationRelativeTo( this ); astWindow.setVisible( true ); } private void toggleSearchWindow() { if ( searchWindow != null ) { searchWindow.dispose(); searchWindow=null; return; } searchWindow = createSearchWindow(); searchWindow.pack(); searchWindow.setLocationRelativeTo( this ); searchWindow.setVisible( true ); } private void indentSources() { restoreCaretPositionAfter( () -> setText( indent( this.editor.getText() ) ) ); } public static String indent(String text) { final int indent = 2; if ( text == null ) { return text; } final String[] lines = text.split("\n"); final StringBuilder result = new StringBuilder(); for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if ( line.length() == 0 ) { result.append("\n"); continue; } if ( isWhitespace( line.charAt(0) ) ) { int j = 0; int len=line.length(); for ( ; j < len && isWhitespace( line.charAt(j) ); j++ ) { } for ( int k = indent ; k > 0 ; k-- ) { result.append( ' '); } for ( ; j < len ; j++ ) { result.append( line.charAt(j) ); } } else { result.append( line ); } // append trailing newline except for when we're on the last line if ( (i+1) < lines.length ) { result.append("\n"); } } return result.toString(); } private static boolean isWhitespace(char c) { return c == ' ' || c == '\t'; } private void toggleSymbolTableWindow() { if ( symbolWindow != null ) { symbolWindow.dispose(); symbolWindow=null; return; } symbolWindow = createSymbolWindow(); symbolWindow.pack(); symbolWindow.setLocationRelativeTo( this ); symbolWindow.setVisible( true ); } private JFrame createASTWindow() { final JFrame frame = new JFrame("AST"); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); astWindow = null; } }); final JTree tree = new JTree( astTreeModel ); final MouseAdapter mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if ( e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1 ) { final TreePath path = tree.getClosestPathForLocation( e.getX() , e.getY() ); if ( path != null && path.getPath() != null && path.getPath().length >= 1 ) { final ASTNode node = (ASTNode) path.getLastPathComponent(); if ( node.getTextRegion() != null ) { setSelection( node.getTextRegion() ); } } } } }; tree.addMouseListener( mouseListener); tree.setCellRenderer( new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { final Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,hasFocus); if ( value instanceof ASTNode) { final ASTNode node = (ASTNode) value; String text=node.getClass().getSimpleName(); if ( node instanceof FunctionCallNode ) { text = ((FunctionCallNode) node).functionName.value+"(...)"; } else if ( node instanceof DirectiveNode) { text = "."+((DirectiveNode) node).directive.literal; } else if ( node instanceof PreprocessorNode) { text = "#"+((PreprocessorNode) node).type.literal; } else if ( node instanceof OperatorNode) { text = "OperatorNode: "+((OperatorNode) node).type.getSymbol(); } else if ( node instanceof IdentifierNode) { text = "IdentifierNode: "+((IdentifierNode) node).name.value; } else if ( node instanceof StatementNode) { text = "StatementNode"; } else if ( node instanceof LabelNode) { text = "LabelNode:"+((LabelNode) node).identifier.value; } else if ( node instanceof CommentNode) { text = "CommentNode: "+((CommentNode) node).value; } else if ( node instanceof IntNumberLiteralNode) { final IntNumberLiteralNode node2 = (IntNumberLiteralNode) value; switch( node2.getType() ) { case BINARY: text = "0b"+Integer.toBinaryString( node2.getValue() ); break; case DECIMAL: text = Integer.toString( node2.getValue() ); break; case HEXADECIMAL: text = "0x"+Integer.toHexString( node2.getValue() ); break; default: throw new RuntimeException("Unreachable code reached"); } } else if ( node instanceof InstructionNode ) { text = "insn: "+((InstructionNode) node).instruction.getMnemonic(); } else if ( node instanceof RegisterNode) { text = "reg: "+((RegisterNode) node).register.toString(); } setText( text + " - " + ((ASTNode) node).getTextRegion() + " - merged: "+((ASTNode) node).getMergedTextRegion() ); } return result; } }); tree.setRootVisible( true ); tree.setVisibleRowCount( 5 ); final JPanel panel = new JPanel(); panel.setLayout( new BorderLayout() ); final JScrollPane pane = new JScrollPane(); pane.getViewport().add( tree ); panel.add( pane , BorderLayout.CENTER ); frame.getContentPane().add( panel ); return frame; } private JFrame createSearchWindow() { final boolean[] wrap = { true }; final JFrame frame = new JFrame("Search"); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); searchWindow = null; } }); final JLabel label = new JLabel("Enter text to search."); final JTextField filterField = new JTextField(); if ( searchHelper.getTerm() != null ) { filterField.setText( searchHelper.getTerm() ); } filterField.getDocument().addDocumentListener( new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { resetLabel(); } @Override public void removeUpdate(DocumentEvent e) { resetLabel(); } @Override public void changedUpdate(DocumentEvent e) { resetLabel(); } private void resetLabel() { label.setText( "Hit enter to start searching"); searchHelper.startFromBeginning(); } }); filterField.addKeyListener( new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_ESCAPE ) { e.consume(); toggleSearchWindow(); } } }); filterField.addActionListener( ev -> { searchHelper.setTerm( filterField.getText() ); boolean foundMatch = false; if ( searchHelper.canSearch() ) { foundMatch = searchHelper.searchForward(); if ( ! foundMatch && wrap[0] ) { searchHelper.startFromBeginning(); foundMatch = searchHelper.searchForward(); } } frame.toFront(); filterField.requestFocus(); if ( foundMatch ) { label.setText("Hit enter to continue searching"); } else { label.setText("No (more) matches."); } }); final JPanel panel = new JPanel(); panel.setLayout( new GridBagLayout() ); // add search textfield GridBagConstraints cnstrs = new GridBagConstraints(); cnstrs.weightx = 1.0; cnstrs.weightx = 0.33; cnstrs.gridheight = 1 ; cnstrs.gridwidth = 1; cnstrs.gridx = 0; cnstrs.gridy = 0; cnstrs.fill = GridBagConstraints.HORIZONTAL; panel.add( filterField , cnstrs ); // add 'wrap?' checkbox final JCheckBox wrapCheckbox = new JCheckBox("Wrap?" , wrap[0] ); wrapCheckbox.addActionListener( ev -> { wrap[0] = wrapCheckbox.isSelected(); }); cnstrs = new GridBagConstraints(); cnstrs.weightx = 1.0; cnstrs.weightx = 0.33; cnstrs.gridheight = 1 ; cnstrs.gridwidth = 1; cnstrs.gridx = 0; cnstrs.gridy = 1; cnstrs.fill = GridBagConstraints.HORIZONTAL; panel.add( wrapCheckbox , cnstrs ); // add status line cnstrs = new GridBagConstraints(); cnstrs.weightx = 1.0; cnstrs.weightx = 0.33; cnstrs.gridheight = 1 ; cnstrs.gridwidth = 1; cnstrs.gridx = 0; cnstrs.gridy = 2; cnstrs.fill = GridBagConstraints.HORIZONTAL; panel.add( label , cnstrs ); frame.getContentPane().add( panel ); frame.setPreferredSize( new Dimension(200,100 ) ); return frame; } private JFrame createSymbolWindow() { final JFrame frame = new JFrame("Symbols"); frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); symbolWindow = null; } }); final JTextField filterField = new JTextField(); filterField.addActionListener( ev -> { symbolModel.setFilterString( filterField.getText() ); }); filterField.getDocument().addDocumentListener( new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { symbolModel.setFilterString( filterField.getText() ); } @Override public void removeUpdate(DocumentEvent e) { symbolModel.setFilterString( filterField.getText() ); } @Override public void changedUpdate(DocumentEvent e) { symbolModel.setFilterString( filterField.getText() ); } }); final JTable table= new JTable( symbolModel ); final JPanel panel = new JPanel(); panel.setLayout( new BorderLayout() ); final JScrollPane pane = new JScrollPane(); pane.getViewport().add( table ); panel.add( filterField , BorderLayout.NORTH ); panel.add( pane , BorderLayout.CENTER ); frame.getContentPane().add( panel ); return frame; } private void gotoLine() { final String lineNo = JOptionPane.showInputDialog(null, "Enter line number", "Go to line", JOptionPane.QUESTION_MESSAGE ); if ( StringUtils.isNotBlank( lineNo ) ) { int no = -1; try { no = Integer.parseInt( lineNo ); } catch (Exception e) { e.printStackTrace(); } if ( no > 0 ) { String text = editor.getText(); if ( text == null ) { text = ""; } int offset = 0; for ( final int len=text.length() ; no > 1 && offset < len ; offset++ ) { final char c = text.charAt( offset ); if ( c == '\r' && (offset+1) < len && text.charAt(offset+1) == '\n' ) { no--; offset++; } else if ( c == '\n' ) { no--; } } editor.setCaretPosition( offset ); editor.requestFocus(); } } } public void setProject(IProject project,CompilationUnit unit) throws IOException { Validate.notNull(project, "project must not be NULL"); Validate.notNull(unit, "unit must not be NULL"); LOG.info("addWindows(): Now editing "+unit.getResource()); this.project = project; this.currentUnit = unit; // Read source file. // The following code INTENTIONALLY converts all line endings to \n // as this is what the Scanner class does as well (see Scanner#isSkipCarriageReturn() default) // The reason for this is that Java TextComponents internally always use \n as EOL sequence // and we otherwise could not line up text offsets generated by the scanner with text offsets // generated by the editor TextPane final String source; try (var reader = new BufferedReader( new InputStreamReader( unit.getResource().createInputStream(), unit.getResource().getEncoding() ) ) ) { source = reader.lines().collect( Collectors.joining( "\n" ) ); } lastEditLocation = -1; autoComplete.detach(); editor.setDocument( createDocument() ); autoComplete.attachTo( editor ); setText(source); undoManager.discardAllEdits(); editor.setCaretPosition( 0 ); } public void save(File file) throws FileNotFoundException { try ( PrintWriter w = new PrintWriter(file ) ) { if ( editor.getText() != null ) { w.write( editor.getText() ); } currentUnit.addMessage( CompilationMessage.info( currentUnit , "Source saved to "+file.getAbsolutePath() ) ); } } public boolean close(boolean askIfDirty) { lastEditLocation = -1; setVisible( false ); final Container parent = getParent(); parent.remove( this ); parent.revalidate(); try { return true; } finally { afterRemove(); } } protected abstract void afterRemove(); public IProject getProject() { return project; } public CompilationUnit getCompilationUnit() { return currentUnit; } public void gotoMessage(CompilationMessage message) { final int len = editor.getText().length(); if ( message.region != null && 0 <= message.region.start() && message.region.start() < len ) { setSelection( message.region ); } else { System.err.println("Index "+message.region+" is out of range, cannot set caret"); } } public void setSelection(TextRegion region) { final Runnable r = () -> { editor.setCaretPosition( region.start() ); editor.setSelectionStart( region.start() ); editor.setSelectionEnd( region.end() ); editor.requestFocus(); }; runAfterCompilation(r); } private void runAfterCompilation(Runnable r) { if ( wasCompiledAtLeastOnce ) { r.run(); } else { afterCompilation.add( r ); } } private void setCaretPosition(int position) { runAfterCompilation( () -> { ignoreEditEvents = true; try { editor.setCaretPosition( position ); } finally { ignoreEditEvents = false; } editor.requestFocus(); } ); } private void setText(String text) { backDOM.clear(); frontDOM.clear(); indentFilterEnabled = false; try { editor.setText(text); } finally { indentFilterEnabled = true; } } public AST getAST() { return astTreeModel.getAST(); } public CompilationUnit currentUnit() { return currentUnit; } public SourceMap getSourceMap() { return sourceMap; } }
923deceee9ab2efb7c89e1f801e6b6391dbb819b
641
java
Java
distributed/hystrix/eshop-cache-ha/src/main/java/cn/lastwhisper/cache/ha/hystrix/command/UpdateProductInfoCommand.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
59
2020-04-08T06:48:13.000Z
2021-11-10T06:20:36.000Z
distributed/hystrix/eshop-cache-ha/src/main/java/cn/lastwhisper/cache/ha/hystrix/command/UpdateProductInfoCommand.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
26
2020-11-01T03:16:16.000Z
2022-03-18T02:50:29.000Z
distributed/hystrix/eshop-cache-ha/src/main/java/cn/lastwhisper/cache/ha/hystrix/command/UpdateProductInfoCommand.java
lastwhispers/code
8d4b926c5577525828e4f077e3901f4e869c7e4a
[ "Apache-2.0" ]
44
2020-04-09T01:34:40.000Z
2021-03-02T12:33:23.000Z
22.892857
75
0.736349
1,000,537
package cn.lastwhisper.cache.ha.hystrix.command; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * 清空hystrix的request cache * @author lastwhisper * @date 2019/12/20 */ public class UpdateProductInfoCommand extends HystrixCommand<Boolean> { private Long productId; public UpdateProductInfoCommand(Long productId) { super(HystrixCommandGroupKey.Factory.asKey("GetProductInfoGroup")); this.productId=productId; } @Override protected Boolean run() throws Exception { GetProductInfoCommand.flushCache(productId); return true; } }
923deddd6af290b9cf6b1679663a95435a58616c
336
java
Java
test/org/nutz/json/NumBean.java
chenchi2038/nutz
9ee5334e43a32aa3195e67cb2c963c9aa1ec1569
[ "Apache-2.0" ]
2,177
2015-01-05T06:38:16.000Z
2022-03-26T01:27:52.000Z
test/org/nutz/json/NumBean.java
chenchi2038/nutz
9ee5334e43a32aa3195e67cb2c963c9aa1ec1569
[ "Apache-2.0" ]
896
2015-01-02T06:17:31.000Z
2022-03-30T10:02:53.000Z
test/org/nutz/json/NumBean.java
luozc1993/nutz
741aca859780c10376bffd6048c21198be88251f
[ "Apache-2.0" ]
828
2015-01-02T03:17:34.000Z
2022-03-26T01:27:54.000Z
14
35
0.553571
1,000,538
package org.nutz.json; /** * * @author hxy */ public class NumBean { @JsonField(dataFormat="00.00") private int num1; @JsonField(dataFormat="00.00") private Integer num2 = 2; public int getNum1() { return num1; } public void setNum1(int num1) { this.num1 = num1; } }
923dee19a09987ec515df016652b3b65b70de210
568
java
Java
src/main/java/com/eztexting/api/client/AccessForbiddenException.java
CallFire/eztexting-api-client-java
05984a99b44e45707221e76866cae1dfaa116878
[ "MIT" ]
null
null
null
src/main/java/com/eztexting/api/client/AccessForbiddenException.java
CallFire/eztexting-api-client-java
05984a99b44e45707221e76866cae1dfaa116878
[ "MIT" ]
null
null
null
src/main/java/com/eztexting/api/client/AccessForbiddenException.java
CallFire/eztexting-api-client-java
05984a99b44e45707221e76866cae1dfaa116878
[ "MIT" ]
null
null
null
23.666667
99
0.693662
1,000,539
package com.eztexting.api.client; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.List; /** * Exception thrown in case if platform returns HTTP code 403 - Forbidden, insufficient permissions * * @since 1.0 */ public class AccessForbiddenException extends EzTextingApiException { public AccessForbiddenException(List<String> errors) { super(403, errors); } @Override public String toString() { return new ToStringBuilder(this) .appendSuper(super.toString()) .toString(); } }
923dee530c8cbb19d08bbf561365d6a7cd736129
428
java
Java
7. Hibernate Code First - Exercises/Bills Payment System/src/main/java/demo/BillsPaymentSystem.java
emarinova/Databases-Frameworks---Hibernate-Spring-Data
0e9f79f8abb6fabb8bc0dcac5e9913bc06e584aa
[ "MIT" ]
null
null
null
7. Hibernate Code First - Exercises/Bills Payment System/src/main/java/demo/BillsPaymentSystem.java
emarinova/Databases-Frameworks---Hibernate-Spring-Data
0e9f79f8abb6fabb8bc0dcac5e9913bc06e584aa
[ "MIT" ]
null
null
null
7. Hibernate Code First - Exercises/Bills Payment System/src/main/java/demo/BillsPaymentSystem.java
emarinova/Databases-Frameworks---Hibernate-Spring-Data
0e9f79f8abb6fabb8bc0dcac5e9913bc06e584aa
[ "MIT" ]
null
null
null
28.533333
96
0.742991
1,000,540
package demo; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class BillsPaymentSystem { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("payment_system"); EntityManager em = factory.createEntityManager(); em.close(); factory.close(); } }
923df1939b07029ff85463ea366779bad98dd57b
381
java
Java
src/main/java/com/ujuji/navigation/service/EmailService.java
Xwudao/ujuji_backend
b408e6d4a7161f6997507f21cebfb3dad0e5ccfc
[ "Apache-2.0" ]
28
2021-02-06T03:27:22.000Z
2022-03-29T08:36:07.000Z
src/main/java/com/ujuji/navigation/service/EmailService.java
Xwudao/ujuji_backend
b408e6d4a7161f6997507f21cebfb3dad0e5ccfc
[ "Apache-2.0" ]
1
2022-01-23T10:16:45.000Z
2022-01-23T10:20:13.000Z
src/main/java/com/ujuji/navigation/service/EmailService.java
Xwudao/ujuji_backend
b408e6d4a7161f6997507f21cebfb3dad0e5ccfc
[ "Apache-2.0" ]
4
2021-02-06T03:34:08.000Z
2021-09-16T11:21:25.000Z
18.142857
54
0.661417
1,000,541
package com.ujuji.navigation.service; import com.ujuji.navigation.model.dto.ForgotPassDto; public interface EmailService { /** * 先检查是否已经发送过了 * * @param forgotPassDto forgotPassDto */ boolean checkHasSent(ForgotPassDto forgotPassDto); /** * 发送重置密码的邮件 * * @param email 待发送的邮箱地址 */ void sendForgotPassEmail(String email); }
923df1a0fa70f6f6ebb9c0ccaa59c748bc07ee93
2,141
java
Java
plugin/itests/addon/src/main/java/org/nuxeo/web/ui/itests/listeners/GlobalValidationListener.java
s-guillaume/nuxeo-web-ui
72abdc5a3cd2d28d7ead61845cda2cd016105b3b
[ "Apache-2.0" ]
54
2016-02-02T16:56:25.000Z
2022-02-09T01:32:36.000Z
plugin/itests/addon/src/main/java/org/nuxeo/web/ui/itests/listeners/GlobalValidationListener.java
s-guillaume/nuxeo-web-ui
72abdc5a3cd2d28d7ead61845cda2cd016105b3b
[ "Apache-2.0" ]
1,344
2016-05-09T11:07:22.000Z
2022-03-28T15:53:38.000Z
plugin/itests/addon/src/main/java/org/nuxeo/web/ui/itests/listeners/GlobalValidationListener.java
s-guillaume/nuxeo-web-ui
72abdc5a3cd2d28d7ead61845cda2cd016105b3b
[ "Apache-2.0" ]
66
2015-12-10T16:18:14.000Z
2022-02-08T01:52:38.000Z
40.396226
119
0.697338
1,000,542
/* * (C) Copyright 2019 Nuxeo (http://nuxeo.com/) and others. * * 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. * * Contributors: * Guillaume Renard */ package org.nuxeo.web.ui.itests.listeners; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.event.DocumentEventTypes; import org.nuxeo.ecm.core.api.validation.DocumentValidationException; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; /** * Tests listener that throws a {@link DocumentValidationException} when a Validation document is created or saved. * * @since 11.1 */ public class GlobalValidationListener implements EventListener { @Override public void handleEvent(Event event) { if (event.getContext() instanceof DocumentEventContext) { DocumentEventContext docCtx = (DocumentEventContext) event.getContext(); DocumentModel targetDoc = docCtx.getSourceDocument(); if ("Validation".equals(targetDoc.getType()) && (DocumentEventTypes.ABOUT_TO_CREATE.equals(event.getName()) || DocumentEventTypes.BEFORE_DOC_UPDATE.equals(event.getName()))) { Long first = (Long) targetDoc.getPropertyValue("validation:firstNumber"); Long second = (Long) targetDoc.getPropertyValue("validation:secondNumber"); if (first + second != 10) { event.markBubbleException(); throw new DocumentValidationException("sum.of.numbers.must.be.equal.ten"); } } } } }
923df1dce1b863928fecdea11806028d2f3e9202
347
java
Java
src/main/java/com/albert/dao/MetasMapper.java
zyqwst/albertBlog
d339572b140ab4809bbd8d6983eac192be1911de
[ "Apache-2.0" ]
null
null
null
src/main/java/com/albert/dao/MetasMapper.java
zyqwst/albertBlog
d339572b140ab4809bbd8d6983eac192be1911de
[ "Apache-2.0" ]
null
null
null
src/main/java/com/albert/dao/MetasMapper.java
zyqwst/albertBlog
d339572b140ab4809bbd8d6983eac192be1911de
[ "Apache-2.0" ]
null
null
null
20.411765
50
0.755043
1,000,543
package com.albert.dao; import com.albert.domain.table.Metas; public interface MetasMapper { int deleteByPrimaryKey(Integer mid); int insert(Metas record); int insertSelective(Metas record); Metas selectByPrimaryKey(Integer mid); int updateByPrimaryKeySelective(Metas record); int updateByPrimaryKey(Metas record); }
923df2089fcf1d109534ae423f9a348be13e6223
3,327
java
Java
src/main/java/io/dropwizard/redis/topology/ClusterTopologyRefreshOptionsFactory.java
dennyac/dropwizard-redis
f052f744a02cb0ea4c82bea5217af4fb45cfbf1a
[ "Apache-2.0" ]
10
2019-06-03T17:02:25.000Z
2022-02-15T14:37:27.000Z
src/main/java/io/dropwizard/redis/topology/ClusterTopologyRefreshOptionsFactory.java
dennyac/dropwizard-redis
f052f744a02cb0ea4c82bea5217af4fb45cfbf1a
[ "Apache-2.0" ]
50
2019-05-24T17:44:41.000Z
2022-02-21T12:29:54.000Z
src/main/java/io/dropwizard/redis/topology/ClusterTopologyRefreshOptionsFactory.java
netfonds/dwtools-redis
9e153c6404806e103d23688da3eb1a9ec4226eb4
[ "Apache-2.0" ]
7
2019-06-03T17:02:29.000Z
2021-09-15T10:17:40.000Z
35.774194
131
0.772768
1,000,544
package io.dropwizard.redis.topology; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.util.Duration; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import java.util.Set; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class ClusterTopologyRefreshOptionsFactory { @JsonProperty private boolean periodicRefreshEnabled = ClusterTopologyRefreshOptions.DEFAULT_PERIODIC_REFRESH_ENABLED; @NotNull @JsonProperty private Duration refreshPeriod = Duration.seconds(ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD); @JsonProperty private boolean closeStaleConnections = ClusterTopologyRefreshOptions.DEFAULT_CLOSE_STALE_CONNECTIONS; @JsonProperty private boolean dynamicRefreshSources = ClusterTopologyRefreshOptions.DEFAULT_DYNAMIC_REFRESH_SOURCES; @NotNull @JsonProperty private Set<ClusterTopologyRefreshOptions.RefreshTrigger> adaptiveRefreshTriggers = ClusterTopologyRefreshOptions.DEFAULT_ADAPTIVE_REFRESH_TRIGGERS; @Min(0) @JsonProperty private int refreshTriggersReconnectAttempts = ClusterTopologyRefreshOptions.DEFAULT_REFRESH_TRIGGERS_RECONNECT_ATTEMPTS; public boolean isPeriodicRefreshEnabled() { return periodicRefreshEnabled; } public void setPeriodicRefreshEnabled(final boolean periodicRefreshEnabled) { this.periodicRefreshEnabled = periodicRefreshEnabled; } public Duration getRefreshPeriod() { return refreshPeriod; } public void setRefreshPeriod(final Duration refreshPeriod) { this.refreshPeriod = refreshPeriod; } public boolean isCloseStaleConnections() { return closeStaleConnections; } public void setCloseStaleConnections(final boolean closeStaleConnections) { this.closeStaleConnections = closeStaleConnections; } public boolean isDynamicRefreshSources() { return dynamicRefreshSources; } public void setDynamicRefreshSources(final boolean dynamicRefreshSources) { this.dynamicRefreshSources = dynamicRefreshSources; } public Set<ClusterTopologyRefreshOptions.RefreshTrigger> getAdaptiveRefreshTriggers() { return adaptiveRefreshTriggers; } public void setAdaptiveRefreshTriggers(final Set<ClusterTopologyRefreshOptions.RefreshTrigger> adaptiveRefreshTriggers) { this.adaptiveRefreshTriggers = adaptiveRefreshTriggers; } public int getRefreshTriggersReconnectAttempts() { return refreshTriggersReconnectAttempts; } public void setRefreshTriggersReconnectAttempts(final int refreshTriggersReconnectAttempts) { this.refreshTriggersReconnectAttempts = refreshTriggersReconnectAttempts; } public ClusterTopologyRefreshOptions build() { return ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh(periodicRefreshEnabled) .refreshPeriod(java.time.Duration.ofSeconds(refreshPeriod.toSeconds())) .closeStaleConnections(closeStaleConnections) .dynamicRefreshSources(dynamicRefreshSources) .enableAdaptiveRefreshTrigger(adaptiveRefreshTriggers.toArray(new ClusterTopologyRefreshOptions.RefreshTrigger[0])) .build(); } }
923df295e2597987294a453e9e0755fcdedc3251
1,495
java
Java
java/Compression/src/de/uni_passau/visit/compression/exceptions/UnsupportedModelException.java
ViSIT-Dev/compression-container
c2c935b6e0e0e353b4719aa71c51d76354b40fd2
[ "Apache-2.0" ]
null
null
null
java/Compression/src/de/uni_passau/visit/compression/exceptions/UnsupportedModelException.java
ViSIT-Dev/compression-container
c2c935b6e0e0e353b4719aa71c51d76354b40fd2
[ "Apache-2.0" ]
null
null
null
java/Compression/src/de/uni_passau/visit/compression/exceptions/UnsupportedModelException.java
ViSIT-Dev/compression-container
c2c935b6e0e0e353b4719aa71c51d76354b40fd2
[ "Apache-2.0" ]
1
2019-09-30T15:03:48.000Z
2019-09-30T15:03:48.000Z
26.22807
81
0.71505
1,000,545
package de.uni_passau.visit.compression.exceptions; /** * This exception shall be thrown if an algorithm is restricted to models with * certain properties that are not satisfied for a given model fed to this * algorithm. * * @author Florian Schlenker * */ public class UnsupportedModelException extends Exception { private static final long serialVersionUID = 1032007018704809354L; /** * This constructor creates an instance of the exception without any further * information. */ public UnsupportedModelException() { super(); } /** * This constructor creates an instance of the exception with the given message. * * @param message * A message describing the reason for the error */ public UnsupportedModelException(String msg) { super(msg); } /** * This constructor creates an instance of the exception with a reference to * another exception causing this exception. * * @param causedBy * The exception causing this exception */ public UnsupportedModelException(Throwable causedBy) { super(causedBy); } /** * This constructor creates an instance of the exception with the given message * and a reference to another exception causing this exception. * * @param message * A message describing the reason for the error * @param causedBy * The exception causing this exception */ public UnsupportedModelException(String msg, Throwable causedBy) { super(msg, causedBy); } }
923df3091a531cd6653d90df58796ac88644597f
579
java
Java
Node.java
SuryaSudharshan/FibHeap
fbcc0ee603361572fbfbdbd99acd211d0da99530
[ "MIT" ]
null
null
null
Node.java
SuryaSudharshan/FibHeap
fbcc0ee603361572fbfbdbd99acd211d0da99530
[ "MIT" ]
null
null
null
Node.java
SuryaSudharshan/FibHeap
fbcc0ee603361572fbfbdbd99acd211d0da99530
[ "MIT" ]
null
null
null
27.571429
55
0.583765
1,000,546
public class Node{ //Declaring the parameters of a node. Node left,right,child,parent; int degree = 0; boolean child_cut = false; private String keyword; int key; //Initializing a node's default parameters Node(String keyword, int key){ this.keyword = keyword; this.key = key; this.left= this; this.right = this; this.parent = null; this.degree = 0; } //Getter for a node's information i.e the Keyword. public String getKeyword(){ return this.keyword; } }
923df4090b7f6c21bf0ce77a19f851a3dc78e425
3,100
java
Java
fastmodel-parser/src/test/java/com/aliyun/fastmodel/parser/statement/InsertTest.java
alibaba/fast-modeling-language
5366f85b4795ca43e03b5fa5ad67c1d9b0255f42
[ "Apache-2.0" ]
9
2022-03-25T08:24:39.000Z
2022-03-28T01:43:43.000Z
fastmodel-parser/src/test/java/com/aliyun/fastmodel/parser/statement/InsertTest.java
alibaba/fast-modeling-language
5366f85b4795ca43e03b5fa5ad67c1d9b0255f42
[ "Apache-2.0" ]
null
null
null
fastmodel-parser/src/test/java/com/aliyun/fastmodel/parser/statement/InsertTest.java
alibaba/fast-modeling-language
5366f85b4795ca43e03b5fa5ad67c1d9b0255f42
[ "Apache-2.0" ]
3
2022-03-25T10:24:24.000Z
2022-03-30T12:40:36.000Z
37.349398
91
0.693226
1,000,547
/* * Copyright 2021-2022 Alibaba Group Holding Ltd. * * 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.aliyun.fastmodel.parser.statement; import java.util.List; import com.aliyun.fastmodel.core.parser.DomainLanguage; import com.aliyun.fastmodel.core.tree.BaseStatement; import com.aliyun.fastmodel.core.tree.QualifiedName; import com.aliyun.fastmodel.core.tree.expr.BaseExpression; import com.aliyun.fastmodel.core.tree.expr.Identifier; import com.aliyun.fastmodel.core.tree.expr.Row; import com.aliyun.fastmodel.core.tree.expr.literal.LongLiteral; import com.aliyun.fastmodel.core.tree.expr.literal.StringLiteral; import com.aliyun.fastmodel.core.tree.relation.querybody.BaseQueryBody; import com.aliyun.fastmodel.core.tree.relation.querybody.Values; import com.aliyun.fastmodel.core.tree.statement.insert.Insert; import com.aliyun.fastmodel.core.tree.statement.select.Query; import com.aliyun.fastmodel.core.tree.util.QueryUtil; import com.aliyun.fastmodel.parser.NodeParser; import com.google.common.collect.ImmutableList; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Insert Test * * @author panguanjing * @date 2020/11/20 */ public class InsertTest { NodeParser nodeParser = new NodeParser(); @Test public void testInsert() { String sql = "insert into u.t1(a, b, c) values('a', 1, 2)"; BaseStatement parse = nodeParser.parse(new DomainLanguage(sql)); Insert insert = (Insert)parse; assertEquals(insert.getQualifiedName(), QualifiedName.of("u.t1")); Query query = insert.getQuery(); BaseQueryBody queryBody = query.getQueryBody(); Values values = (Values)queryBody; List<BaseExpression> rows = values.getRows(); Row row = (Row)rows.get(0); assertEquals(row.getItems().size(), 3); assertEquals(row.getItems().get(0), new StringLiteral("a")); } @Test public void testInsertToString() { Query a = QueryUtil.query(new Values(ImmutableList.of( new Row( ImmutableList.of(new StringLiteral("a"), new LongLiteral("1"), new LongLiteral("2")) )))); Insert insert = new Insert( QualifiedName.of("u.t1"), a, ImmutableList.of(new Identifier("a"), new Identifier("b"), new Identifier("c")) ); assertEquals(insert.getColumns().get(0), new Identifier("a")); assertTrue(insert.toString().contains("a")); } }
923df50b4d2efc6056872987f6c7128ef967d9fb
1,869
java
Java
squidlib-util/src/main/java/squidpony/squidai/Threat.java
SquidPony/SquidLib
e59517a6192bfafdaa019c0cd44101abff619876
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
344
2015-01-01T17:34:46.000Z
2020-10-20T07:28:47.000Z
squidlib-util/src/main/java/squidpony/squidai/Threat.java
SquidPony/SquidLib
e59517a6192bfafdaa019c0cd44101abff619876
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
165
2015-01-18T20:24:48.000Z
2019-07-25T02:29:26.000Z
squidlib-util/src/main/java/squidpony/squidai/Threat.java
SquidPony/SquidLib
e59517a6192bfafdaa019c0cd44101abff619876
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
46
2015-05-07T19:11:34.000Z
2020-05-31T03:21:22.000Z
36.647059
118
0.728197
1,000,548
/* * Copyright (c) 2022 Eben Howard, Tommy Ettinger, and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package squidpony.squidai; import squidpony.squidgrid.Radius; import squidpony.squidmath.Coord; import java.io.Serializable; /** * A small class to store the area that a creature is perceived by other creatures to threaten. * Created by Tommy Ettinger on 11/8/2015. */ public class Threat implements Serializable { private static final long serialVersionUID = 1L; public Coord position; public Reach reach; public Threat(Coord position, int maxThreatDistance) { this.position = position; reach = new Reach(maxThreatDistance); } public Threat(Coord position, int minThreatDistance, int maxThreatDistance) { this.position = position; reach = new Reach(minThreatDistance, maxThreatDistance); } public Threat(Coord position, int minThreatDistance, int maxThreatDistance, Radius measurement) { this.position = position; reach = new Reach(minThreatDistance, maxThreatDistance, measurement); } public Threat(Coord position, int minThreatDistance, int maxThreatDistance, Radius measurement, AimLimit limits) { this.position = position; reach = new Reach(minThreatDistance, maxThreatDistance, measurement, limits); } }
923df52bd038a606a45ea3b438d54e969eedd66f
715
java
Java
src/main/java/br/com/swaggsige/model/service/repository/MarcaLocalRepository.java
sergiostorinojr/SwaggSigePortal
2d699754bce292c0bcb4b64358f193046c0c7ac6
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/swaggsige/model/service/repository/MarcaLocalRepository.java
sergiostorinojr/SwaggSigePortal
2d699754bce292c0bcb4b64358f193046c0c7ac6
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/swaggsige/model/service/repository/MarcaLocalRepository.java
sergiostorinojr/SwaggSigePortal
2d699754bce292c0bcb4b64358f193046c0c7ac6
[ "Apache-2.0" ]
null
null
null
27.5
105
0.794406
1,000,549
package br.com.swaggsige.model.service.repository; import java.util.Collection; import javax.ejb.Local; import br.com.swaggsige.model.domain.Marca; import br.com.swaggsige.model.service.exception.PersistenceException; @Local public interface MarcaLocalRepository { public Collection<Marca> getAll() throws PersistenceException; public Marca getById(Long id) throws PersistenceException; public Collection<Marca> getAllByDescriptionStartsWith(String description) throws PersistenceException; public void save(Marca obj) throws PersistenceException; public Marca update(Marca obj) throws PersistenceException; public void toRemove(Long id) throws PersistenceException; }
923df6a377dc0033ae0e09b05f8f882d474b19f6
470
java
Java
note/src/main/java/com/designpattern/builder/message/Director.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
23
2018-02-11T13:28:42.000Z
2021-12-24T05:53:13.000Z
note/src/main/java/com/designpattern/builder/message/Director.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
5
2019-12-23T01:51:45.000Z
2021-11-30T15:12:08.000Z
note/src/main/java/com/designpattern/builder/message/Director.java
CodingSoldier/java-learn
c480f0c26c95b65f49c082e0ffeb10706bd366b1
[ "Apache-2.0" ]
17
2018-02-11T13:28:03.000Z
2022-01-24T20:30:02.000Z
27.647059
65
0.668085
1,000,550
package com.designpattern.builder.message; public class Director { Builder builder; public Director(Builder builder){ this.builder = builder; } public void construct(String toAddress , String fromAddress){ this.builder.buildTo(toAddress); this.builder.buildFrom(fromAddress); this.builder.buildSubject(); this.builder.buildBody(); this.builder.buildSendDate(); this.builder.sendMessage(); } }
923df6fc603f9105a4ae18ff1210191007aab31b
9,414
java
Java
application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java
antomy-gc/art-java
45c8b03356b28c404b508c46a562027649fb4434
[ "Apache-2.0" ]
null
null
null
application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java
antomy-gc/art-java
45c8b03356b28c404b508c46a562027649fb4434
[ "Apache-2.0" ]
null
null
null
application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java
antomy-gc/art-java
45c8b03356b28c404b508c46a562027649fb4434
[ "Apache-2.0" ]
null
null
null
38.581967
168
0.727427
1,000,551
/* * ART Java * * Copyright 2019 ART * * 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 ru.art.grpc.client.communicator; import io.grpc.*; import lombok.*; import org.apache.logging.log4j.*; import ru.art.core.lazy.*; import ru.art.core.runnable.*; import ru.art.core.validator.*; import ru.art.entity.*; import ru.art.entity.Value; import ru.art.entity.interceptor.*; import ru.art.entity.mapper.*; import ru.art.grpc.client.handler.*; import ru.art.grpc.client.model.*; import ru.art.service.model.*; import static java.util.Objects.*; import static java.util.concurrent.TimeUnit.*; import static lombok.AccessLevel.PRIVATE; import static ru.art.core.caster.Caster.*; import static ru.art.core.checker.CheckerForEmptiness.*; import static ru.art.core.constants.StringConstants.*; import static ru.art.core.lazy.LazyLoadingValue.*; import static ru.art.core.wrapper.ExceptionWrapper.*; import static ru.art.grpc.client.communicator.GrpcCommunicatorChannelFactory.*; import static ru.art.grpc.client.constants.GrpcClientModuleConstants.*; import static ru.art.logging.LoggingModule.*; import java.util.concurrent.*; public class GrpcCommunicatorImplementation implements GrpcCommunicator, GrpcCommunicator.GrpcAsynchronousCommunicator { private final GrpcCommunicationConfiguration configuration = new GrpcCommunicationConfiguration(); private final BuilderValidator validator = new BuilderValidator(GrpcCommunicator.class.getName()); private final LazyLoadingValue<ManagedChannel> channel = lazyValue(() -> createChannel(configuration)); @Getter(lazy = true, value = PRIVATE) private static final Logger logger = loggingModule().getLogger(GrpcCommunicator.class); GrpcCommunicatorImplementation(String host, int port, String path) { configuration.setUrl(validator.notEmptyField(host, "host") + COLON + validator.notNullField(port, "port")); configuration.setPath(validator.notEmptyField(path, "path")); } GrpcCommunicatorImplementation(String url, String path) { configuration.setUrl(validator.notEmptyField(url, "url")); configuration.setPath(validator.notEmptyField(path, "path")); } GrpcCommunicatorImplementation(String url) { configuration.setUrl(validator.notEmptyField(url, "url")); } GrpcCommunicatorImplementation(GrpcCommunicationTargetConfiguration targetConfiguration) { configuration.setPath(validator.notEmptyField(targetConfiguration.path(), "path")); deadlineTimeout(targetConfiguration.timeout()); keepAliveTimeNanos(targetConfiguration.keepAliveTimeNanos()); keepAliveTimeNanos(targetConfiguration.keepAliveTimeOutNanos()); keepAliveWithoutCalls(targetConfiguration.keepAliveWithoutCalls()); if (targetConfiguration.secured()) { secured(); } if (targetConfiguration.waitForReady()) { waitForReady(); } if (isNotEmpty(targetConfiguration.url())) { configuration.setUrl(targetConfiguration.url()); return; } configuration.setUrl(validator.notEmptyField(targetConfiguration.host(), "host") + COLON + validator.notNullField(targetConfiguration.port(), "port")); } @Override public GrpcCommunicator serviceId(String id) { configuration.setServiceId(validator.notEmptyField(id, "serviceId")); return this; } @Override public GrpcCommunicator methodId(String id) { configuration.setMethodId(validator.notEmptyField(id, "methodId")); return this; } @Override public GrpcCommunicator functionId(String id) { configuration.setServiceId(GRPC_FUNCTION_SERVICE); configuration.setMethodId(validator.notEmptyField(id, "functionId")); return this; } @Override public <RequestType> GrpcCommunicator requestMapper(ValueFromModelMapper<RequestType, ? extends Value> mapper) { configuration.setRequestMapper(validator.notNullField(cast(mapper), "requestMapper")); return this; } @Override public <ResponseType> GrpcCommunicator responseMapper(ValueToModelMapper<ResponseType, ? extends Value> mapper) { configuration.setResponseMapper(validator.notNullField(cast(mapper), "responseMapper")); return this; } @Override public GrpcCommunicator deadlineTimeout(long timeout) { configuration.setDeadlineTimeout(timeout); return this; } @Override public GrpcCommunicator waitForReady() { configuration.setWaitForReady(true); return this; } @Override public GrpcCommunicator addInterceptor(ClientInterceptor interceptor) { configuration.getInterceptors().add(validator.notNullField(interceptor, "interceptor")); return this; } @Override public GrpcCommunicator executor(Executor executor) { configuration.setOverrideExecutor(validator.notNullField(executor, "executor")); return this; } @Override public GrpcCommunicator secured() { configuration.setUseSecuredTransport(true); return this; } @Override public GrpcCommunicator keepAliveTimeNanos(long time) { configuration.setKeepAliveTimeNanos(time); return this; } @Override public GrpcCommunicator keepAliveTimeOutNanos(long timeOut) { configuration.setKeepAliveTimeNanos(timeOut); return this; } @Override public GrpcCommunicator keepAliveWithoutCalls(boolean keepAliveWithoutCalls) { configuration.setKeepAliveWithoutCalls(keepAliveWithoutCalls); return null; } @Override public void shutdownChannel() { ManagedChannel channel = this.channel.safeValue(); if (isNull(channel) || channel.isShutdown() || channel.isTerminated()) { return; } ignoreException((ExceptionRunnable) () -> channel .shutdownNow() .awaitTermination(GRPC_CHANNEL_SHUTDOWN_TIMEOUT, MILLISECONDS), getLogger()::error); } @Override public GrpcAsynchronousCommunicator asynchronous() { return this; } @Override public <ResponseType> ServiceResponse<ResponseType> execute() { validator.validate(); configuration.validateRequiredFields(); return GrpcCommunicationExecutor.execute(channel.safeValue(), configuration, null); } @Override public <RequestType, ResponseType> ServiceResponse<ResponseType> execute(RequestType request) { request = validator.notNullField(request, "request"); validator.validate(); configuration.validateRequiredFields(); return GrpcCommunicationExecutor.execute(channel.safeValue(), configuration, request); } @Override public GrpcCommunicator addRequestValueInterceptor(ValueInterceptor<Entity, Entity> interceptor) { configuration.getRequestValueInterceptors().add(validator.notNullField(interceptor, "requestValueInterceptor")); return this; } @Override public GrpcCommunicator addResponseValueInterceptor(ValueInterceptor<Entity, Entity> interceptor) { configuration.getResponseValueInterceptors().add(validator.notNullField(interceptor, "responseValueInterceptor")); return this; } @Override public GrpcAsynchronousCommunicator asynchronousFuturesExecutor(Executor executor) { configuration.setAsynchronousFuturesExecutor(validator.notNullField(executor, "asynchronousFuturesExecutor")); return this; } @Override public <RequestType, ResponseType> GrpcAsynchronousCommunicator completionHandler(GrpcCommunicationCompletionHandler<RequestType, ResponseType> completionHandler) { configuration.setCompletionHandler(validator.notNullField(completionHandler, "completionHandler")); return this; } @Override public <RequestType> GrpcAsynchronousCommunicator exceptionHandler(GrpcCommunicationExceptionHandler<RequestType> exceptionHandler) { configuration.setExceptionHandler(validator.notNullField(exceptionHandler, "exceptionHandler")); return this; } @Override public <ResponseType> CompletableFuture<ServiceResponse<ResponseType>> executeAsynchronous() { validator.validate(); configuration.validateRequiredFields(); return GrpcCommunicationAsynchronousExecutor.execute(channel.safeValue(), configuration, null); } @Override public <RequestType, ResponseType> CompletableFuture<ServiceResponse<ResponseType>> executeAsynchronous(RequestType request) { request = validator.notNullField(request, "request"); validator.validate(); configuration.validateRequiredFields(); return GrpcCommunicationAsynchronousExecutor.execute(channel.safeValue(), configuration, request); } }
923df7150546da479cb0f065a57e3ae4b6a4e7db
2,422
java
Java
test/jdk/javax/swing/border/Test4252164.java
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
2
2017-02-05T10:25:47.000Z
2017-02-07T00:55:29.000Z
test/jdk/javax/swing/border/Test4252164.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/jdk/javax/swing/border/Test4252164.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
32.72973
89
0.712634
1,000,552
/* * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4252164 8041917 * @summary Tests rounded LineBorder for components * @author Sergey Malenkov * @run applet/manual=yesno Test4252164.html */ import java.awt.Color; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; public class Test4252164 extends JApplet implements MouseWheelListener { private int thickness; private JLabel rounded; private JLabel straight; public void mouseWheelMoved(MouseWheelEvent event) { update(event.getWheelRotation()); } public void init() { add(createUI()); addMouseWheelListener(this); } private JPanel createUI() { this.rounded = new JLabel("ROUNDED"); // NON-NLS: the label for rounded border this.straight = new JLabel("STRAIGHT"); // NON-NLS: the label for straight border JPanel panel = new JPanel(); panel.add(this.rounded); panel.add(this.straight); update(10); return panel; } private void update(int thickness) { this.thickness += thickness; this.rounded.setBorder(new LineBorder(Color.RED, this.thickness, true)); this.straight.setBorder(new LineBorder(Color.RED, this.thickness, false)); } }
923df716b38c77009e965db1b0047e21fba850bc
248
java
Java
DIO/InterJavaDeveloper/01-DevBasicJava/src/poo3/heranca/exemplo002/Exemplo002.java
nauam/vuepress-next
4f39162aa38e36b85d74bf5fc858770cbf87d1f4
[ "MIT" ]
null
null
null
DIO/InterJavaDeveloper/01-DevBasicJava/src/poo3/heranca/exemplo002/Exemplo002.java
nauam/vuepress-next
4f39162aa38e36b85d74bf5fc858770cbf87d1f4
[ "MIT" ]
2
2021-11-02T11:37:02.000Z
2021-11-02T11:37:53.000Z
DIO/InterJavaDeveloper/01-DevBasicJava/src/poo3/heranca/exemplo002/Exemplo002.java
nauam/courses
4f39162aa38e36b85d74bf5fc858770cbf87d1f4
[ "MIT" ]
null
null
null
15.5
45
0.600806
1,000,553
package poo3.heranca.exemplo002; public class Exemplo002 { public static void main(String[] args) { Carro carro = new Carro(); carro.acelera(); Motocicleta moto = new Motocicleta(); moto.acelera(); } }
923df736a73b3a1033120351416cced693209e99
2,648
java
Java
src/test/java/com/github/zg2pro/formatter/plugin/ForceFormatIT.java
zg2pro/zg2pro-formatter-plugin
054887d10f9c34286e78aca6f494fde681a8e961
[ "MIT" ]
1
2020-06-22T22:45:27.000Z
2020-06-22T22:45:27.000Z
src/test/java/com/github/zg2pro/formatter/plugin/ForceFormatIT.java
zg2pro/zg2pro-formatter-plugin
054887d10f9c34286e78aca6f494fde681a8e961
[ "MIT" ]
12
2020-05-04T07:35:55.000Z
2021-10-13T11:47:52.000Z
src/test/java/com/github/zg2pro/formatter/plugin/ForceFormatIT.java
zg2pro/zg2pro-formatter-plugin
054887d10f9c34286e78aca6f494fde681a8e961
[ "MIT" ]
null
null
null
36.777778
80
0.720544
1,000,554
/* * The MIT License * * Copyright 2020 Gregory Anne. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.zg2pro.formatter.plugin; import io.takari.maven.testing.TestResources; import io.takari.maven.testing.executor.MavenRuntime; import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder; import io.takari.maven.testing.executor.MavenVersions; import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author zg2pro */ @RunWith(MavenJUnitTestRunner.class) @MavenVersions({ "3.8.3" }) public class ForceFormatIT { @Rule public final TestResources resources = new TestResources( "C:\\workspace\\test\\", "C:\\workspace\\test2\\" ); public final MavenRuntime verifier; public ForceFormatIT(MavenRuntimeBuilder runtimeBuilder) throws Exception { this.verifier = runtimeBuilder.build(); //.withCliOptions(opts) // // } @Test public void checkSpringDataExamples() throws Exception { File projectDir = new File("C:\\workspace\\test\\project"); File projectDirTransformed = new File("C:\\workspace\\test2\\project"); if (projectDirTransformed.exists()) { FileUtils.cleanDirectory(projectDirTransformed); projectDirTransformed.delete(); } verifier .forProject(projectDir) // .withCliOption("-B") .execute("clean", "compile") .assertErrorFreeLog(); } }
923df745ea45a68bb0cb9d416759112d9ee3faa4
341
java
Java
src/cn/year2021/number/DecimalUtils.java
chywx/JavaSE-chy
e6d1908e2904541de4b94d6a387294119ae879f2
[ "MIT" ]
4
2019-04-23T03:29:41.000Z
2020-03-03T15:53:26.000Z
src/cn/year2021/number/DecimalUtils.java
chywx/JavaSE-chy
e6d1908e2904541de4b94d6a387294119ae879f2
[ "MIT" ]
null
null
null
src/cn/year2021/number/DecimalUtils.java
chywx/JavaSE-chy
e6d1908e2904541de4b94d6a387294119ae879f2
[ "MIT" ]
3
2020-01-09T09:54:29.000Z
2020-06-09T08:00:07.000Z
18.944444
75
0.706745
1,000,555
package cn.year2021.number; import java.text.DecimalFormat; /** * decimal工具类 * * @author chy * @date 2019/11/1 0001 */ public class DecimalUtils { private static DecimalFormat decimalFormat = new DecimalFormat("0.00"); public static String getTwoDecimal(Double balance){ return decimalFormat.format(balance); } }
923df79b34295c3828d93a7f637fbffefc0cb6d4
1,078
java
Java
ccbs-database/src/test/java/team/yingyingmonster/ccbs/database/JuerUserMapperTest.java
czhmater/CompanyBodyCheckSystem
b29c40af691cd90aaf864fb40cf7af1ffe48ea62
[ "MIT" ]
null
null
null
ccbs-database/src/test/java/team/yingyingmonster/ccbs/database/JuerUserMapperTest.java
czhmater/CompanyBodyCheckSystem
b29c40af691cd90aaf864fb40cf7af1ffe48ea62
[ "MIT" ]
null
null
null
ccbs-database/src/test/java/team/yingyingmonster/ccbs/database/JuerUserMapperTest.java
czhmater/CompanyBodyCheckSystem
b29c40af691cd90aaf864fb40cf7af1ffe48ea62
[ "MIT" ]
null
null
null
33.6875
139
0.808905
1,000,556
package team.yingyingmonster.ccbs.database; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import team.yingyingmonster.ccbs.database.mapper.juergenie.JuerUserMapper; import team.yingyingmonster.ccbs.json.JsonUtil; /** * @author Juer Whang <br/> * - project: CompanyBodyCheckSystem * - create: 14:53 2018/11/12 * - **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-database.xml") @Transactional @Rollback(true) public class JuerUserMapperTest { @Autowired private JuerUserMapper juerUserMapper; @Test public void selectJuerUserByUserCheckIdTest() { System.out.println(JsonUtil.beanToJson(juerUserMapper.selectJuerUserByUsercheckid(230l), JsonUtil.TYPE.PRETTY_AND_SERIALIZE_NULL)); } }
923df7a938e056a635a452f33f23f6e19c5a8d4d
1,767
java
Java
NaturalAPI_Develop/src/main/java/fourcats/usecaseinteractor/ModifyPla.java
fourcatsteam/NaturalAPI
eb612e47de99893f307f6549feaa889becda2b8a
[ "MIT" ]
null
null
null
NaturalAPI_Develop/src/main/java/fourcats/usecaseinteractor/ModifyPla.java
fourcatsteam/NaturalAPI
eb612e47de99893f307f6549feaa889becda2b8a
[ "MIT" ]
56
2020-04-23T16:46:40.000Z
2020-10-13T22:15:26.000Z
NaturalAPI_Develop/src/main/java/fourcats/usecaseinteractor/ModifyPla.java
fourcatsteam/NaturalAPI
eb612e47de99893f307f6549feaa889becda2b8a
[ "MIT" ]
1
2020-05-22T05:10:57.000Z
2020-05-22T05:10:57.000Z
34.647059
96
0.667233
1,000,557
package fourcats.usecaseinteractor; import fourcats.interfaceaccess.RepositoryAccess; import fourcats.port.ModifyPlaInputPort; import fourcats.port.ModifyPlaOutputPort; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; public class ModifyPla implements ModifyPlaInputPort { private RepositoryAccess repositoryAccess; private ModifyPlaOutputPort modifyPlaOutputPort; public ModifyPla(RepositoryAccess repositoryAccess,ModifyPlaOutputPort modifyPlaOutputPort){ this.repositoryAccess = repositoryAccess; this.modifyPlaOutputPort = modifyPlaOutputPort; } public void loadPlaToModify(String filename){ File file = repositoryAccess.openFile(filename); try (BufferedReader br = new BufferedReader(new FileReader(file))){ String line; String text = ""; line = br.readLine(); //SERVE PER SALTARE LA PRIMA RIGA while((line = br.readLine()) != null){ text = text.concat(line); text = text.concat("\n"); } String[] split = text.split("\ncustom class\n"); String[] splitTest = split[1].split("\ntest class\n"); modifyPlaOutputPort.showLoadPla(split[0],splitTest[0],splitTest[1]); } catch (IOException e) { Logger logger = Logger.getAnonymousLogger(); logger.log(Level.SEVERE, "IOException", e); } } public void modify(String filename,String text) throws IOException{ String pla = repositoryAccess.loadPLA(filename); String extension = pla.split("\n",2)[0]; repositoryAccess.writePla(filename,extension + "\n" + text); modifyPlaOutputPort.showMessage("Pla modified!"); } }
923df83acd73670881a3856add43c392bfa3d0eb
35,177
java
Java
src/main/java/com/yunchuang/crm/config/utils/MyUtils.java
yidao2000/crm
9ea61f89159ae71165fe3a8d40570c0d41f57ac2
[ "Xerox", "Intel" ]
1
2018-06-30T18:54:59.000Z
2018-06-30T18:54:59.000Z
src/main/java/com/yunchuang/crm/config/utils/MyUtils.java
yidao2000/crm
9ea61f89159ae71165fe3a8d40570c0d41f57ac2
[ "Xerox", "Intel" ]
null
null
null
src/main/java/com/yunchuang/crm/config/utils/MyUtils.java
yidao2000/crm
9ea61f89159ae71165fe3a8d40570c0d41f57ac2
[ "Xerox", "Intel" ]
1
2021-03-16T16:02:24.000Z
2021-03-16T16:02:24.000Z
27.35381
164
0.69011
1,000,558
package com.yunchuang.crm.config.utils; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import com.yunchuang.crm.config.message.*; import com.yunchuang.crm.config.zip.FileAndPath; import com.yunchuang.crm.console.user.domain.User; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.util.ClassUtils; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.swing.ImageIcon; import javax.validation.constraints.NotNull; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.*; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static org.apache.poi.ss.usermodel.CellType.NUMERIC; /** * 工具包 * * @author 尹冬飞 * @create 2017-12-27 13:20 */ public class MyUtils { /** * 1.创建druid数据源 * * @param driverClassName 数据库驱动 * @param url 数据库url * @param username 数据库用户名 * @param password 数据库用户密码 * @return druid数据源 */ public static DruidDataSource getDruidDataSource(String driverClassName, String url, String username, String password) { DruidDataSource dataSource = new DruidDataSource(); //这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName dataSource.setDriverClassName(driverClassName); //连接数据库的url dataSource.setUrl(url); //连接数据库的用户名 dataSource.setUsername(username); //连接数据库的密码 dataSource.setPassword(password); //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 dataSource.setInitialSize(1); //最小连接池数量 dataSource.setMinIdle(1); //最大连接池数量 dataSource.setMaxActive(20); //获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 dataSource.setMaxWait(1000); return dataSource; } /** * 2.数据源里引入多组xml的方法 * org.mybatis.spring.boot.autoconfigure包下MybatisProperties里面的方法直接拿来用 * * @param mapperLocations xml路径数组 * @return 资源数组 */ public static Resource[] resolveMapperLocations(String[] mapperLocations) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); List<Resource> resources = new ArrayList<>(); if (mapperLocations != null) { for (String mapperLocation : mapperLocations) { try { Resource[] mappers = resourceResolver.getResources(mapperLocation); resources.addAll(Arrays.asList(mappers)); } catch (IOException e) { // ignore } } } return resources.toArray(new Resource[resources.size()]); } //1.文件操作相关 /** * 保存图片 * * @param newFileName 上传照片文件名 * @param file 文件 * @param fileName src下的文件名称 * @param key 文件里变量名 * @return 系统时间 */ public static String saveFile(String newFileName, MultipartFile file, String fileName, String key) throws IOException { String saveFilePath = getValueByKey(fileName, key); String now = (new SimpleDateFormat("yyyyMM")).format(new Date()); // 按月份构建文件夹 saveFilePath += "/" + now; /* 构建文件目录 */ File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } FileOutputStream out = new FileOutputStream(saveFilePath + "\\" + newFileName); // 写入文件 out.write(file.getBytes()); out.flush(); out.close(); return now; } /** * 功能描述:删除图片 * * @param picName 图片名称 * @param fileName Properties文件名 * @param key Properties文件名中的变量名 */ public static boolean deleteFile(String picName, String fileName, String key) throws IOException { // Properties文件名中的变量值 String picDir = getValueByKey(fileName, key); /* 构建文件目录 */ File fileDir = new File(picDir + "/" + picName); if (fileDir.isFile() && fileDir.exists()) { // 图片删除 以免太多没用的图片占据空间 fileDir.delete(); return true; } return false; } /** * 功能描述 保存图片 * * @param file 上传照片文件名 * @param propertiesName 文件数据 * @param fileUrl src下的文件名称 * @param uploaderID 文件里变量名 * <p> * 修改历史 :(修改人,修改时间,修改原因/内容) */ public static Map<String, Object> saveFiles(MultipartFile file, String propertiesName, String fileUrl, String uploaderID, HttpSession session) throws IOException { Map<String, Object> map = new HashMap<>(); // 获取图片的文件名 String fileName = file.getOriginalFilename(); // 获取图片的扩展名 String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1); String webappsPath = getWebappsPath(session); // 新的图片文件名 = 获取时间戳+"."图片扩展名,以后会改 UUID uuid = UUID.randomUUID(); String newFileName = String.valueOf(System.currentTimeMillis()) + "_" + uuid.toString() + "." + extensionName; String fileUrlPath = getValueByKey(propertiesName, fileUrl); String path = (new SimpleDateFormat("yyyyMM")).format(new Date()) + "/" + uploaderID + "/"; String saveFilePath = webappsPath + fileUrlPath + path; // 按月份和上传人构建文件夹 /* 构建文件目录 */ File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } FileOutputStream out = new FileOutputStream(saveFilePath + "\\" + newFileName); // 写入文件 out.write(file.getBytes()); out.flush(); out.close(); map.put("fileUrl", fileUrlPath + path + newFileName); map.put("fileName", fileName); return map; } /** * 功能描述:删除文件 * * @param fileUrl 文件绝对路径 */ public static void deleteFile(String fileUrl) { /* 构建文件目录 */ File fileDir = new File(fileUrl); if (fileDir.isFile() && fileDir.exists()) { // 图片删除 以免太多没用的图片占据空间 boolean delete = fileDir.delete(); } } /** * 逆向递归删除空目录 * * @param path 文件绝对路径 */ public static void delEmptyPath(String path) { File file = new File(path); if (file.exists() && file.isDirectory() && !"upload".equals(file.getName())) { File[] files = file.listFiles(); if (files != null && files.length > 0) return; if (file.delete()) { delEmptyPath(file.getParent()); } } } /** * 删除文件和空文件夹 * * @param fileUrl 文件绝对路径 */ public static void delDirectories(String fileUrl) { File file = new File(fileUrl); deleteFile(fileUrl); delEmptyPath(file.getParent()); } /** * 1.下载压缩文件 */ public static void downloadZip(HttpServletResponse response, HttpServletRequest request, List<FileAndPath> fileAndPaths) throws ArchiveException, IOException { // 设置并获取下载压缩文件的名字 String zipFilePath = getZipFilePath(request); String zipFileName = getZipFileName(request); String zipFile = zipFilePath + zipFileName; // 建立压缩文件 createZip(fileAndPaths, zipFilePath, zipFileName); // 下载文件 downloadFile(response, request, "批量打包下载.zip", zipFile); // 删除文件 deleteFile(zipFile); } /** * 2.设置并获取下载压缩文件的路径 */ public static String getZipFilePath(HttpServletRequest request) throws IOException { // 例如E:/tomcat8/webapps String webappsPath = getWebappsPath(request); // 例如 upload/temp String tempFilePath = getValueByKey("fileUrl.properties", "tempFilePath"); return webappsPath + tempFilePath; } /** * 3.设置并获取下载压缩文件的文件名 */ public static String getZipFileName(HttpServletRequest request) { return UUID.randomUUID().toString() + ".zip"; } /** * 3.建立压缩文件 * * @throws IOException * @throws ArchiveException */ public static void createZip(List<FileAndPath> fileAndPaths, String zipFilePath, String zipFileName) throws IOException, ArchiveException { String zipFile = zipFilePath + zipFileName; File fileDir = new File(zipFilePath); if (!fileDir.exists()) { fileDir.mkdir(); } OutputStream out = new FileOutputStream(zipFile); ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out); zos.setEncoding("UTF-8"); zos.setUseZip64(Zip64Mode.AsNeeded); for (FileAndPath fileAndPath : fileAndPaths) { File file = fileAndPath.getFile(); if (file.isFile() || file.exists()) { ZipArchiveEntry entry = new ZipArchiveEntry(file, fileAndPath.getFilePathInZip());// zipOutput.createArchiveEntry(logFile, logFile.getName()); zos.putArchiveEntry(entry); InputStream in = new FileInputStream(file); IOUtils.copy(in, zos); zos.closeArchiveEntry(); in.close(); } } zos.finish(); zos.close(); out.flush(); out.close(); } /** * 4.下载普通文件 * * @param response response * @param request request * @param fileName fileName 文件下载时的名字 * @param url url 文件在服务器端的绝对路径 * @throws IOException */ public static void downloadFile(HttpServletResponse response, HttpServletRequest request, String fileName, String url) throws IOException { // 根据不同浏览器设置不同编码的fileName fileName = setFileDownloadHeaderName(fileName, request); // 把文件读入到输入流中 InputStream is = new BufferedInputStream(new FileInputStream(url)); byte[] buffer = new byte[is.available()]; is.read(buffer); is.close(); // 设置文件下载名字,\+fileName+\ 解决有空格名字不完整的bug response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\""); // 表示下载的文件是*格式. response.setContentType("application/octet-stream;charset=UTF-8"); // 设置编码 response.setCharacterEncoding("UTF-8"); // 将文件输入到客户端 OutputStream os = response.getOutputStream(); os.write(buffer); os.flush(); os.close(); } /** * 5.根据不同浏览器设置不同编码的fileName,防止中文乱码 * * @param fileName fileName 文件下载时的名字 * @param request request */ public static String setFileDownloadHeaderName(String fileName, HttpServletRequest request) throws UnsupportedEncodingException { // 获取浏览器标识 String userAgent = request.getHeader("USER-AGENT"); if (contains(userAgent, "Firefox")) {// Firefox浏览器 fileName = new String(fileName.getBytes("gb2312"), "iso-8859-1"); } else { fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器 } return fileName; } /** * 功能描述 流程保存文件,后4个参数都是为了拼绝对的保存路径<br> * 流程文件保存的目录是upload/workFlow/ +流程定义名/流程实例ID/任务ID * * @param file 文件 * @param path 为了获取绝对路径的最后一段路径 * @param session 为了获取绝对路径的第一段 * @throws IOException IO异常 */ public static Map<String, Object> saveFile(MultipartFile file, String fileUrlPath, String path, HttpSession session) throws IOException { Map<String, Object> map = new HashMap<>(); // 1.保存的文件路径 // 文件路径的第一部分:E:/tomcat8/webapps/ String webappsPath = getWebappsPath(session); // 文件路径的第二部分fileUrlPath:upload/yunchuang/workFlow/ // 文件最后保存的路径,例如:E:/tomcat8/webapps/ upload/workFlow/ ProjectCheck/流程实例ID/任务ID/ String saveFilePath = webappsPath + fileUrlPath + path; // 2.保存的文件名 // 最后实际保存的文件名 UUID uuid = UUID.randomUUID(); // 获取文件的文件名 String fileName = file.getOriginalFilename(); // 获取文件的扩展名 String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1); String newFileName = String.valueOf(System.currentTimeMillis()) + "_" + uuid.toString() + "." + extensionName; // 3.写入文件到路径下 writeFile(file, saveFilePath, newFileName); map.put("fileUrl", fileUrlPath + path + newFileName); map.put("fileName", fileName); return map; } /** * 写入文件到目录. * * @param file 文件 * @param saveFilePath 保存路径 * @param newFileName 文件名 * @throws IOException 异常 */ public static void writeFile(MultipartFile file, String saveFilePath, String newFileName) throws IOException { // 如果没有文件夹,创建文件夹 File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } // 写入文件输出流 FileOutputStream out = null; try { out = new FileOutputStream(saveFilePath + "\\" + newFileName); // 写入文件 out.write(file.getBytes()); } finally { out.flush(); out.close(); } } /** * 由输入流获取输出流 * * @param response 响应 * @param inputStream 输入流 */ public static void getOutputStreamByInputStream(HttpServletResponse response, InputStream inputStream) throws IOException { byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); // 从response对象获取输出流 OutputStream outputStream = response.getOutputStream(); outputStream.write(buffer); outputStream.flush(); outputStream.close(); } /** * 给图片添加水印 * * @param iconPath 水印图片路径 * @param srcImgPath 源图片路径 * @param targetImgPath 目标图片路径 */ public static void markImageByIcon(String iconPath, String srcImgPath, String targetImgPath) throws IOException { OutputStream os = null; try { Image srcImg = ImageIO.read(new File(srcImgPath)); BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); // 得到画笔对象 Graphics2D g = buffImg.createGraphics(); // 设置对线段的锯齿状边缘处理 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度 ImageIcon imgIcon = new ImageIcon(iconPath); // 得到Image对象。 Image img = imgIcon.getImage(); float alpha = 0.5f; // 透明度 //float alpha = 0.5f; // 透明度 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 表示水印图片的位置,中间的位置 g.drawImage(img, buffImg.getWidth() / 4, buffImg.getHeight() / 2, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); os = new FileOutputStream(targetImgPath); // 生成图片 ImageIO.write(buffImg, "PNG", os); System.out.println("图片完成添加Icon印章。。。。。。"); } finally { if (null != os) os.close(); } } //2.excel操作相关 /** * 1.打印excel,并删除临时文件. * * @param targetPath 临时文件 */ public static void printExcel(String targetPath) throws Exception { //初始化COM线程 ComThread.InitSTA(); //新建Excel对象 ActiveXComponent xl = new ActiveXComponent("Excel.Application"); try { //System.out.println("version=" + xl.getProperty("Version")); //不打开文档,false不显示打开Excel Dispatch.put(xl, "Visible", new Variant(false)); //打开具体的工作簿 Dispatch workbooks = xl.getProperty("Workbooks").toDispatch(); //打开文档 Dispatch excel = Dispatch.call(workbooks, "Open", targetPath).toDispatch(); //开始打印 Dispatch.get(excel, "PrintOut"); //解决文件无法删除bug Dispatch.call(excel, "save"); Dispatch.call(excel, "Close", new Variant(true)); xl.invoke("Quit", new Variant[]{}); } finally { //始终释放资源 ComThread.Release(); //删除临时文件 deleteFile(targetPath); } } /** * 1.将excel文件导出到客户端 * * @param response 响应 * @param request 请求 * @param wb excel * @param fileName 文件名 * @throws IOException 异常 */ public static void exportExcelToClient(HttpServletResponse response, HttpServletRequest request, HSSFWorkbook wb, String fileName) throws IOException { response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); fileName = setFileDownloadHeaderName(fileName, request); response.setHeader("Content-disposition", "attachment;filename=" + fileName); OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } /** * 2.生成excel的HSSFWorkbook * * @param excelHeader 头文件 * @param sheetName sheet名字 * @param excelHeaderWidth 头宽度 * @return HSSFWorkbook */ public static HSSFWorkbook template(String[] excelHeader, String sheetName, int[] excelHeaderWidth) { HSSFWorkbook wb = new HSSFWorkbook(); getSheet(excelHeader, sheetName, excelHeaderWidth, wb); return wb; } /** * 根据MultipartFile获取Sheet * * @param file 文件 * @return sheet * @throws Exception 异常 */ @SuppressWarnings("resource") public static Sheet getSheetByMultipartFile(MultipartFile file) throws Exception { InputStream stream; Workbook wb; stream = file.getInputStream(); /* 文件全名 */ String fileName = file.getOriginalFilename(); /* 文件扩展名 */ int last = fileName.lastIndexOf("."); String fileType = last == -1 ? "" : fileName.substring(last + 1); switch (fileType) { case "xls": wb = new HSSFWorkbook(stream); break; case "xlsx": wb = new XSSFWorkbook(stream); break; default: throw new Exception("您输入的excel格式不正确"); } return wb.getSheetAt(0); } /** * 判断是否是空行 * * @param row 行 * @return 是否是空行 */ public static boolean isBlankRow(HSSFRow row) { if (row == null) return true; boolean result = true; for (int i = 0; i <= row.getLastCellNum(); i++) { HSSFCell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL); String value = ""; if (cell != null) { switch (cell.getCellTypeEnum()) { case STRING: value = cell.getStringCellValue(); break; case NUMERIC: value = String.valueOf((int) cell.getNumericCellValue()); break; case BOOLEAN: value = String.valueOf(cell.getBooleanCellValue()); break; case FORMULA: value = String.valueOf(cell.getCellFormula()); break; // case Cell.CELL_TYPE_BLANK: // break; default: break; } if (!value.trim().equals("")) { result = false; break; } } } return result; } /** * 转化单元格日期格式 * * @param cell 单元格 * @return 单元格的值 * @throws Exception 异常 */ public static String parseExcelCell(Cell cell) throws Exception { String value = null; if (cell != null) { switch (cell.getCellTypeEnum()) { case STRING: String cellString1 = cell.getStringCellValue(); Date date1; /* 格式化2种格式的字符串日期,防止用户格式不正确,尽量兼容各种格式 */ if (cellString1.contains("-")) { date1 = new SimpleDateFormat("yyyy-MM-dd").parse(cellString1); } else if (cellString1.contains("/")) { date1 = new SimpleDateFormat("yyyy/MM/dd").parse(cellString1); } else { date1 = HSSFDateUtil.getJavaDate(Double.valueOf(cellString1)); } /* 存入数据库的是标准的yyyy-MM-dd格式 */ value = new SimpleDateFormat("yyyy-MM-dd").format(date1); break; case NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd"); value = dformat.format(date); } else { value = String.valueOf(cell.getNumericCellValue()); } break; case BOOLEAN: value = String.valueOf(cell.getBooleanCellValue()); break; //case Cell.CELL_TYPE_FORMULA: case FORMULA: value = String.valueOf(cell.getCellFormula()); break; // case Cell.CELL_TYPE_BLANK: // break; default: break; } } return value; } /** * 获取sheet * * @param excelHeader 头部 * @param sheetName sheet名字 * @param excelHeaderWidth 头部宽度 * @param wb excel文件 * @return sheet */ public static HSSFSheet getSheet(String[] excelHeader, String sheetName, int[] excelHeaderWidth, HSSFWorkbook wb) { HSSFSheet sheet = wb.createSheet(sheetName); HSSFRow row = sheet.createRow(0); HSSFCellStyle style = wb.createCellStyle(); // 设置字体 Font headerFont = wb.createFont(); // headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerFont.setColor(IndexedColors.WHITE.getIndex()); style.setFont(headerFont); // 设置居中样式 style.setAlignment(HorizontalAlignment.CENTER);// 水平居中 style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 // 背景颜色 style.setFillForegroundColor(IndexedColors.DARK_TEAL.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置边框 style.setBorderBottom(BorderStyle.THIN); // 下边框 style.setBorderLeft(BorderStyle.THIN);// 左边框 style.setBorderTop(BorderStyle.THIN);// 上边框 style.setBorderRight(BorderStyle.THIN);// 右边框 for (int i = 0; i < excelHeader.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(excelHeader[i]); cell.setCellStyle(style); // sheet.autoSizeColumn(i); } // 设置列宽度(像素)3000的话就是11.7 for (int i = 0; i < excelHeaderWidth.length; i++) { sheet.setColumnWidth(i, 32 * excelHeaderWidth[i]); } return sheet; } /** * 设置单元格的值 * * @param cell 单元格 * @param obj 值 */ public static void setExcelCellValue(HSSFCell cell, Object obj) { if (cell != null) { if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Integer) { cell.setCellType(NUMERIC); cell.setCellValue((Integer) obj); } else if (obj instanceof Double) { cell.setCellType(NUMERIC); cell.setCellValue((Double) obj); } else if (obj instanceof BigDecimal) { cell.setCellType(NUMERIC); // Double格式的数字,可能会有精度的问题. cell.setCellValue(Double.parseDouble(obj.toString())); } } } /** * 3.Properties操作相关 */ /** * 获取properties文件 * * @param filePath 文件路径 * @return properties文件 */ public static Properties getProperties(String filePath) throws IOException { Properties pps = new Properties(); /* 用类的反射获取路径 */ InputStream in = MyUtils.class.getClassLoader().getResourceAsStream(filePath); pps.load(in); in.close(); return pps; } /** * 根据配置文件名(含配置文件路径)和配置文件里变量的key获取value * * @param propertiesName 配置文件名(含配置文件路径) * @param key 配置文件里变量的key * @return value */ public static String getValueByKey(String propertiesName, String key) throws IOException { Properties pps = new Properties(); /* 用类的反射获取路径 */ InputStream in = MyUtils.class.getClassLoader().getResourceAsStream(propertiesName); pps.load(in); in.close(); String value = pps.getProperty(key); return value; } /** * 读取Properties的全部信息 * * @param filePath 文件路径 */ @SuppressWarnings("rawtypes") public static void getAllProperties(String filePath) throws IOException { Properties pps = new Properties(); /* 用类的反射获取路径 */ InputStream in = MyUtils.class.getClassLoader().getResourceAsStream(filePath); pps.load(in); Enumeration en = pps.propertyNames(); // 得到配置文件的名字 while (en.hasMoreElements()) { String strKey = (String) en.nextElement(); String strValue = pps.getProperty(strKey); System.out.println(strKey + "=" + strValue); } } /** * 写入Properties信息 * * @param filePath 文件路径 * @param pKey key * @param pValue value */ public static void writeProperties(String filePath, String pKey, String pValue) throws IOException { Properties pps = new Properties(); /* 用类的反射获取路径 */ InputStream in = MyUtils.class.getClassLoader().getResourceAsStream(filePath); // 从输入流中读取属性列表(键和元素对) pps.load(in); // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。 // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。 OutputStream out = new FileOutputStream(filePath); pps.setProperty(pKey, pValue); // 以适合使用 load 方法加载到 Properties 表中的格式, // 将此 Properties 表中的属性列表(键和元素对)写入输出流 pps.store(out, "Update " + pKey + " name"); } /** * 4.字符串操作相关 */ /** * 1.字符串name是否包含字符串name2 */ public static boolean contains(String name, String name2) { int a = name.indexOf(name2); return a >= 0; } /** * 2.获取今天日期的字符串 */ public static String getToday() { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateString = formatter.format(date); return dateString; } /** * 3.获取今天日期时间的字符串 */ public static String getTime() { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(date); return dateString; } /** * 4.获取今天日期时间的字符串 */ public static String getMonth() { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月"); String dateString = formatter.format(date); return dateString; } /** * 3.获取今天日期时间的字符串 */ public static int getDate(String dateString) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(dateString); Date now = new Date(); int days = (int) ((now.getTime() - date.getTime()) / (1000 * 3600 * 24)); return days; } /** * @param session * @return */ public static String getWebappsPath(HttpSession session) { // 获取项目所在绝对路径 String path = session.getServletContext().getRealPath(""); // 最后一个\的出现位置的索引 int b = path.lastIndexOf("\\"); // 倒数第二个\出现位置的索引 int c = path.substring(0, b).lastIndexOf("\\"); // 截取字符串开始到倒数第二个\的字符串 String d = path.substring(0, c + 1); // 转义将\替换为/ 存文件时需要这样转 String e = d.replaceAll("\\\\", "/"); return e; } /** * 获取wegapp路径 * * @param request 请求 * @return webapp路径 */ public static String getWebappsPath(HttpServletRequest request) { // 获取项目所在绝对路径 String path = request.getSession().getServletContext().getRealPath(""); // 最后一个\的出现位置的索引 int b = path.lastIndexOf("\\"); // 倒数第二个\出现位置的索引 int c = path.substring(0, b).lastIndexOf("\\"); // 截取字符串开始到倒数第二个\的字符串 String d = path.substring(0, c + 1); // 转义将\替换为/ 存文件时需要这样转 String e = d.replaceAll("\\\\", "/"); return e; } /** * 由类路径下的相对路径获取物理绝对路径 * * @param url 类路径下的相对路径 * @return */ public static String getFilePathInClassPath(String url) { return ClassUtils.getDefaultClassLoader().getResource("").getPath() + url; } /** * 将字符串转换成各种类型,包含字符串b为空的情况 * * @param a 类的类型比如String.class * @param b 要转换的字符串 */ @SuppressWarnings("unchecked") public static <T> T convertStringToObject(String a, Class<T> b) { T t = null; String c = a.trim(); if (null == c || c.equals("")) { return t; } if (b.equals(BigDecimal.class)) { t = (T) new BigDecimal(c); } else if (b.equals(Integer.class)) { t = (T) Integer.valueOf(c); } else if (b.equals(Double.class)) { t = (T) Double.valueOf(c); } else { t = (T) c; } return t; } /** * 获取编号 * * @param maxCode 最大编号 比如XMHC201600001 * @param noFormat 编号格式 比如00001 * @param prefix 编号前缀 比如XMHC */ public static String getNo(String maxCode, String noFormat, String prefix) { // 获取系统年份 Calendar calendar = Calendar.getInstance(); int currentYear = calendar.get(Calendar.YEAR); int prefixlen = prefix.length(); int intlen = noFormat.length(); // 格式化编号为00000 DecimalFormat df = new DecimalFormat(noFormat); String no; // 如果表里没有编号,说明还没有一个编号存在,所以最大编号设置为0 if (maxCode == null || maxCode.equals("")) { maxCode = prefix + currentYear + df.format(0); } // 取最大编号中的年份 String year = maxCode.substring(prefixlen + 0, prefixlen + 4); // 如果系统年份等于最大编号中的年份,编号+1 if ((currentYear + "").equals(year)) { no = prefix + currentYear + df.format((Integer.valueOf(maxCode.substring(prefixlen + 4, prefixlen + 4 + intlen)) + 1)); } else { // 如果系统年份不等于最大编号中的年份,则编号从1开始 no = prefix + currentYear + df.format(1); } return no; } /** * 由spring上下文获取spring托管的bean */ public static Object getBeanBySpring(String name) { WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext(); Object obj = ac.getBean(name); return obj; } /** * 把<>转化为&lt和&gt */ public static String convertStringGtLt(String b) { if (b == null) { return null; } String c = b.replaceAll("<", "&lt;").replaceAll(">", "&gt;"); return c; } /** * 根据openid和name把user存入session */ public static void setLoginNameToConsole(String openid, String name, HttpSession httpSession) { User admin = new User(); admin.setName(openid); admin.setNickname(name); httpSession.setAttribute("loginUser", admin); } /** * 根据openid和name把user存入session */ public static String getUserNameBySession(HttpSession httpSession) { User admin = (User) httpSession.getAttribute("loginUser"); if (admin != null) { return admin.getName(); } return null; } /** * 根据输入流获取输出流到客户端 * * @param response 给客户端响应 * @param in 输入流 */ public static void getOutputStreamToClientByInputStream(HttpServletResponse response, InputStream in) throws IOException { OutputStream out = response.getOutputStream(); for (int i; (i = in.read()) != -1; ) { out.write(i); } out.close(); in.close(); } /** * 将格式为123456789<尹冬飞>的字符串转化为数组,返回数组,分为123456789和尹冬飞 * * @param str 格式为123456789<尹冬飞>的字符串 * @return 返回数组, 分为2部分123456789和尹冬飞 */ public static String[] getOpenidAndName(String str) { String[] split = str.split("<"); split[1] = split[1].replaceAll(">", ""); return split; } /** * 4.云之家发送消息相关 */ /** * HttpPost发送信息 * * @param contentMessage 发送的消息 * @param httpURL 发送的URL * @return 返回状态码 * @throws IOException */ public static int readContentFromChunkedPost(String contentMessage, String httpURL) throws IOException { URL postUrl = new URL(httpURL); // 打开连接 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); // 发送POST请求必须设置如下两行 connection.setDoOutput(true); connection.setDoInput(true); // post方法提交 connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); // 按照文档上的格式,此处需要设置成application/json connection.setRequestProperty("Content-Type", "application/json"); connection.setChunkedStreamingMode(5); connection.connect(); PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8")); // 乱码过滤器 out.print(contentMessage); out.flush(); out.close(); int statusCode = connection.getResponseCode(); connection.disconnect(); return statusCode; } public static String getContestMessage(InitMessage initMessage) { // from Tfrom tfrom = new Tfrom(); tfrom.setNo(initMessage.getNo()); tfrom.setNonce(initMessage.getNonce()); tfrom.setPub(initMessage.getPub()); tfrom.setPubtoken(initMessage.getPubtoken()); tfrom.setTime(initMessage.getTime()); // to Tto tto = new Tto(); tto.setNo(initMessage.getNo()); List<String> user = new ArrayList<>(); user.add(initMessage.getOpenid()); tto.setUser(user); List<Tto> ttos = new ArrayList<>(); ttos.add(tto); // msg2 Tmsg2 tmsg2 = new Tmsg2(); tmsg2.setText(initMessage.getType2Text()); // message Tmessage tmessage = new Tmessage(); tmessage.setFrom(tfrom); tmessage.setTo(ttos); tmessage.setType(initMessage.getType()); tmessage.setMsg(tmsg2); return JSON.toJSONString(tmessage); } /** * sha加密算法. * 本方法由金蝶指定的,直接copy过来就能用. * * @param data (工作圈编号,公共号编号,公共号的pubkey,随机数,随机时间) * @return */ public static String sha(String... data) { // 按字母顺序排序数组 Arrays.sort(data); // 把数组连接成字符串(无分隔符),并sha1哈希 return DigestUtils.sha1Hex(StringUtils.join(data, null)); //return DigestUtils.shaHex(StringUtils.join(data, null)); } /** * 返回随机数 * * @return 随机数 */ public static int nextInt() { Random rand = new Random(); int tmp = Math.abs(rand.nextInt()); return tmp % (999999 - 100000 + 1) + 100000; } /** * 查询状态码对应的错误 * * @param statusCode 状态码 * @return 错误信息 */ public static Map<String, Object> getStatusCode(int statusCode) { Map<String, Object> map = new HashMap<>(); map.put("200", "您的消息发送成功"); map.put("5000", "一般参数错误,如:from/to不完整、必须传入参数xxx"); map.put("5001", "公共号不存在或未审核"); map.put("5002", "数据长度超限错误,如:传入数据长度超过了1M"); map.put("5003", "发送的公司或用户错误,如:发送到其他企业,无发送用户或错误的openid"); map.put("5004", "公共号密钥验证失败,from.pubtoken=sha(from.no,from.pub,公共号.pubkey,from.nonce,from.time)"); map.put("5005", "发往公共号消息过多,请等x分钟"); Map<String, Object> newMap = new HashMap<>(); for (String a : map.keySet()) { if (statusCode == Integer.valueOf(a)) { newMap.put("statusCode", statusCode); newMap.put("status", map.get(a)); } } return newMap; } //5.加密相关开始 /** * md5加密 * * @param inputText 字符串 * @return 加密后的字符串 */ public static String md5(String inputText) throws UnsupportedEncodingException, NoSuchAlgorithmException { return encrypt(inputText, "md5"); } /** * md5或者sha-1加密 * * @param inputText 要加密的内容 * @param algorithmName 加密算法名称:md5或者sha-1,不区分大小写 * @return 加密后的字符串 */ private static String encrypt(String inputText, String algorithmName) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (inputText == null || "".equals(inputText.trim())) { throw new IllegalArgumentException("请输入要加密的内容"); } if (algorithmName == null || "".equals(algorithmName.trim())) { algorithmName = "md5"; } MessageDigest m = MessageDigest.getInstance(algorithmName); m.update(inputText.getBytes("UTF8")); byte s[] = m.digest(); // m.digest(inputText.getBytes("UTF8")); return hex(s); } /** * 返回十六进制字符串 * * @param arr 字符 * @return 十六进制字符串 */ @NotNull private static String hex(byte[] arr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; ++i) { sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } /** * 获取resouce下面的文件的内容 比如"classpath:\\static\\about.json" * * @param fileName 文件名称 about.json * @return 文件内容 */ private static String getJsonContentInStatic(String fileName) { String url = "classpath:\\static\\" + fileName; return getFileContent(url); } /** * 获取resouce下面的文件的内容 * * @param url 比如"classpath:\\static\\about.json" * @return 文件内容 */ private static String getFileContent(String url) { ResourceLoader resourceLoader = new DefaultResourceLoader(); Resource resource = resourceLoader.getResource(url); InputStream inputStream = null; StringBuilder stringBuilder = null; BufferedReader bufferedReader = null; try { inputStream = resource.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return stringBuilder.toString(); } }
923df84b7e729f9ab5eb733a9db12cf045088dac
669
java
Java
admin-node/src/main/java/com/bee/scheduler/admin/web/ConfigController.java
justinlxf/bee-scheduler
cba4fb0967b1b2847e63bc5b4d0c88fe3dd29f47
[ "MIT" ]
null
null
null
admin-node/src/main/java/com/bee/scheduler/admin/web/ConfigController.java
justinlxf/bee-scheduler
cba4fb0967b1b2847e63bc5b4d0c88fe3dd29f47
[ "MIT" ]
null
null
null
admin-node/src/main/java/com/bee/scheduler/admin/web/ConfigController.java
justinlxf/bee-scheduler
cba4fb0967b1b2847e63bc5b4d0c88fe3dd29f47
[ "MIT" ]
null
null
null
29.086957
65
0.793722
1,000,559
package com.bee.scheduler.admin.web; import com.bee.scheduler.admin.model.HttpResponseBodyWrapper; import org.quartz.Scheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; @Controller public class ConfigController { @Autowired private Scheduler scheduler; @ResponseBody @RequestMapping("/server-time") HttpResponseBodyWrapper configs() throws Exception { return new HttpResponseBodyWrapper(new Date().getTime()); } }
923df866ebe20fc309da775f2e6ad108c7230a81
1,377
java
Java
src/main/java/com/recurly/v3/resources/SubscriptionChangeBillingInfo.java
recurly/recurly-client-java
ec9371e45219e58db1dbd8cd20214c0fb0c7df7f
[ "MIT" ]
32
2019-12-04T11:26:51.000Z
2021-06-17T22:12:13.000Z
src/main/java/com/recurly/v3/resources/SubscriptionChangeBillingInfo.java
recurly/recurly-client-java
ec9371e45219e58db1dbd8cd20214c0fb0c7df7f
[ "MIT" ]
28
2019-07-18T04:10:16.000Z
2022-03-11T22:06:48.000Z
src/main/java/com/recurly/v3/resources/SubscriptionChangeBillingInfo.java
recurly/recurly-client-java
ec9371e45219e58db1dbd8cd20214c0fb0c7df7f
[ "MIT" ]
8
2019-08-22T21:34:39.000Z
2022-03-30T08:47:08.000Z
36.236842
100
0.780683
1,000,560
/** * This file is automatically created by Recurly's OpenAPI generation process and thus any edits you * make by hand will be lost. If you wish to make a change to this file, please create a Github * issue explaining the changes you need and we will usher them to the appropriate places. */ package com.recurly.v3.resources; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.recurly.v3.Resource; public class SubscriptionChangeBillingInfo extends Resource { /** * A token generated by Recurly.js after completing a 3-D Secure device fingerprinting or * authentication challenge. */ @SerializedName("three_d_secure_action_result_token_id") @Expose private String threeDSecureActionResultTokenId; /** * A token generated by Recurly.js after completing a 3-D Secure device fingerprinting or * authentication challenge. */ public String getThreeDSecureActionResultTokenId() { return this.threeDSecureActionResultTokenId; } /** * @param threeDSecureActionResultTokenId A token generated by Recurly.js after completing a 3-D * Secure device fingerprinting or authentication challenge. */ public void setThreeDSecureActionResultTokenId(final String threeDSecureActionResultTokenId) { this.threeDSecureActionResultTokenId = threeDSecureActionResultTokenId; } }
923df99ec9fd00ff73d9cc4a3b3b263c1b0bd586
4,503
java
Java
sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/SecretValue.java
FThompsonAWS/aws-iot-device-sdk-java-v2
b0aa0542869663e5f3c27a519687363358a08cb6
[ "Apache-2.0" ]
57
2019-11-29T19:28:27.000Z
2022-03-27T18:49:16.000Z
sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/SecretValue.java
FThompsonAWS/aws-iot-device-sdk-java-v2
b0aa0542869663e5f3c27a519687363358a08cb6
[ "Apache-2.0" ]
95
2020-01-22T01:47:05.000Z
2022-03-31T19:28:24.000Z
sdk/greengrass/greengrass-client/src/event-stream-rpc-java/model/software/amazon/awssdk/aws/greengrass/model/SecretValue.java
FThompsonAWS/aws-iot-device-sdk-java-v2
b0aa0542869663e5f3c27a519687363358a08cb6
[ "Apache-2.0" ]
63
2019-12-19T19:12:42.000Z
2022-03-29T07:14:51.000Z
31.270833
260
0.713524
1,000,561
package software.amazon.awssdk.aws.greengrass.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class SecretValue implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "aws.greengrass#SecretValue"; private transient UnionMember setUnionMember; @Expose( serialize = true, deserialize = true ) private Optional<String> secretString; @Expose( serialize = true, deserialize = true ) private Optional<byte[]> secretBinary; public SecretValue() { this.secretString = Optional.empty(); this.secretBinary = Optional.empty(); } public String getSecretString() { if (secretString.isPresent() && (setUnionMember == UnionMember.SECRET_STRING)) { return secretString.get(); } return null; } public void setSecretString(final String secretString) { if (setUnionMember != null) { setUnionMember.nullify(this); } this.secretString = Optional.of(secretString); this.setUnionMember = UnionMember.SECRET_STRING; } public byte[] getSecretBinary() { if (secretBinary.isPresent() && (setUnionMember == UnionMember.SECRET_BINARY)) { return secretBinary.get(); } return null; } public void setSecretBinary(final byte[] secretBinary) { if (setUnionMember != null) { setUnionMember.nullify(this); } this.secretBinary = Optional.of(secretBinary); this.setUnionMember = UnionMember.SECRET_BINARY; } /** * Returns an indicator for which enum member is set. Can be used to convert to proper type. * @return {@link UnionMember} */ public UnionMember getSetUnionMember() { return setUnionMember; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } public void selfDesignateSetUnionMember() { int setCount = 0; UnionMember[] members = UnionMember.values(); for (int memberIdx = 0; memberIdx < UnionMember.values().length; ++memberIdx) { if (members[memberIdx].isPresent(this)) { ++setCount; this.setUnionMember = members[memberIdx]; } } // only bad outcome here is if there's more than one member set. It's possible for none to be set if (setCount > 1) { throw new IllegalArgumentException("More than one union member set for type: " + getApplicationModelType()); } } @Override public void postFromJson() { selfDesignateSetUnionMember(); } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof SecretValue)) return false; if (this == rhs) return true; final SecretValue other = (SecretValue)rhs; boolean isEquals = true; isEquals = isEquals && this.secretString.equals(other.secretString); isEquals = isEquals && EventStreamRPCServiceModel.blobTypeEquals(this.secretBinary, other.secretBinary); isEquals = isEquals && this.setUnionMember.equals(other.setUnionMember); return isEquals; } @Override public int hashCode() { return Objects.hash(secretString, secretBinary, setUnionMember); } public enum UnionMember { SECRET_STRING("SECRET_STRING", (software.amazon.awssdk.aws.greengrass.model.SecretValue obj) -> obj.secretString = Optional.empty(), (software.amazon.awssdk.aws.greengrass.model.SecretValue obj) -> obj.secretString != null && obj.secretString.isPresent()), SECRET_BINARY("SECRET_BINARY", (software.amazon.awssdk.aws.greengrass.model.SecretValue obj) -> obj.secretBinary = Optional.empty(), (software.amazon.awssdk.aws.greengrass.model.SecretValue obj) -> obj.secretBinary != null && obj.secretBinary.isPresent()); private String fieldName; private Consumer<SecretValue> nullifier; private Predicate<SecretValue> isPresent; UnionMember(String fieldName, Consumer<SecretValue> nullifier, Predicate<SecretValue> isPresent) { this.fieldName = fieldName; this.nullifier = nullifier; this.isPresent = isPresent; } void nullify(SecretValue obj) { nullifier.accept(obj); } boolean isPresent(SecretValue obj) { return isPresent.test(obj); } } }
923df9ba5dfec46fee82685cefe42ec3eb3465a3
303
java
Java
plugins/IntentionPowerPak/test/com/siyeh/ipp/exceptions/catchToThrows/TryWithConflictingDeclaration.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
plugins/IntentionPowerPak/test/com/siyeh/ipp/exceptions/catchToThrows/TryWithConflictingDeclaration.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
plugins/IntentionPowerPak/test/com/siyeh/ipp/exceptions/catchToThrows/TryWithConflictingDeclaration.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
20.2
45
0.567657
1,000,562
class TryWithConflictingDeclaration { abstract void f(String s) throws Exception; void m() { try { /* important comment */ String s = "hello"; f(); // another comment } catch (Exception <caret>ignore) { } String s = "bye"; System.out.println(s); } }
923dfa5dfefc9b1882989de51eb336c9de144498
1,522
java
Java
custom/src/main/java/com/scottlogic/datahelix/generator/custom/example/RandomLoremIpsum.java
maoo/datahelix-2
2f145b077d16472f56e7bc079ac66c69b54383c3
[ "Apache-2.0" ]
103
2019-07-05T16:45:36.000Z
2022-02-22T10:49:58.000Z
custom/src/main/java/com/scottlogic/datahelix/generator/custom/example/RandomLoremIpsum.java
maoo/datahelix-2
2f145b077d16472f56e7bc079ac66c69b54383c3
[ "Apache-2.0" ]
512
2019-01-23T11:20:14.000Z
2019-07-02T12:40:31.000Z
custom/src/main/java/com/scottlogic/datahelix/generator/custom/example/RandomLoremIpsum.java
maoo/datahelix-2
2f145b077d16472f56e7bc079ac66c69b54383c3
[ "Apache-2.0" ]
47
2019-07-03T10:44:08.000Z
2022-03-03T14:35:26.000Z
27.672727
75
0.630092
1,000,563
/* * Copyright 2019 Scott Logic Ltd * * 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.scottlogic.datahelix.generator.custom.example; import java.util.Random; public class RandomLoremIpsum { private Random random = new Random(); public String generateString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Lorem ipsum"); int length = random.nextInt(950); while (stringBuilder.length() < length){ stringBuilder.append(getRandomPunctuation()); stringBuilder.append(getRandomWord()); } return stringBuilder.toString(); } private String getRandomWord() { return "lorem ipsum"; } private String getRandomPunctuation() { int i = random.nextInt(20); switch (i) { case 1: case 2: return ", "; case 3: return ". "; default: return " "; } } }
923dfaab13a5f917e1bf6522acd0545d0b6407a3
1,385
java
Java
src/interval/InsertInterval.java
ShogoAkiyama54/leetcode
f44eacd5028c9eaeee3d1a1d84d423a876edd8bb
[ "MIT" ]
3
2021-06-07T08:45:46.000Z
2022-03-08T04:23:21.000Z
src/interval/InsertInterval.java
shogo54/leetcode
f44eacd5028c9eaeee3d1a1d84d423a876edd8bb
[ "MIT" ]
null
null
null
src/interval/InsertInterval.java
shogo54/leetcode
f44eacd5028c9eaeee3d1a1d84d423a876edd8bb
[ "MIT" ]
null
null
null
19.236111
90
0.574007
1,000,564
package interval; import java.util.*; /** * @author Shogo Akiyama * Solved on 12/11/2019 * * 57. Insert Interval * https://leetcode.com/problems/insert-interval/ * Difficulty: Hard * * Approach: Iteration * Runtime: 3 ms, faster than 24.04% of Java online submissions for Insert Interval. * Memory Usage: 41.7 MB, less than 68.75% of Java online submissions for Insert Interval. * * Time Complexity: O(n) * Space Complexity: O(n) * Where n is the number of intervals * * @see IntervalTest#testInsertInterval() */ public class InsertInterval { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> list = new ArrayList<int[]>(); boolean added = false; for (int[] i : intervals) { if (!added && i[0] >= newInterval[0]) { list.add(newInterval); added = true; } list.add(i); } if (!added) { list.add(newInterval); } int index = 1; int count = 0; while (index < list.size()) { int[] prev = list.get(index - 1); int[] curr = list.get(index); if (prev[1] >= curr[0]) { curr[0] = prev[0]; curr[1] = Math.max(curr[1], prev[1]); prev[0] = -1; prev[1] = -1; count++; } index++; } int[][] result = new int[list.size() - count][2]; int j = 0; for (int[] i : list) { if (i[0] != -1 && i[1] != -1) { result[j] = i; j++; } } return result; } }
923dfbee2f1548c5daf8e6aa174de1f809bb4144
2,069
java
Java
game-sceneserver/src/main/java/com/wjybxx/fastjgame/gameobject/Player.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
1
2021-04-13T08:54:49.000Z
2021-04-13T08:54:49.000Z
game-sceneserver/src/main/java/com/wjybxx/fastjgame/gameobject/Player.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
null
null
null
game-sceneserver/src/main/java/com/wjybxx/fastjgame/gameobject/Player.java
taojhlwkl/fastjgame
281f8aa2ea53ea600614508ad6e45f47deab39da
[ "Apache-2.0" ]
null
null
null
25.231707
103
0.698888
1,000,565
/* * Copyright 2019 wjybxx * * 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.wjybxx.fastjgame.gameobject; import com.wjybxx.fastjgame.misc.CenterServerId; import com.wjybxx.fastjgame.net.session.Session; import com.wjybxx.fastjgame.scene.Scene; import com.wjybxx.fastjgame.scene.gameobjectdata.PlayerData; import com.wjybxx.fastjgame.timeprovider.TimeProvider; import javax.annotation.Nonnull; /** * 玩家对象,也是机器人对象; * 暂时先直接继承GameObject; * * @author wjybxx * @version 1.0 * date - 2019/6/4 16:58 * github - https://github.com/hl845740757 */ public class Player extends GameObject<PlayerData> { /** * player的一些与场景无关的数据 */ private final PlayerData playerData; /** * 玩家身上的session */ private Session gateSession; public Player(Scene scene, TimeProvider timeProvider, PlayerData playerData, Session gateSession) { super(scene, timeProvider); this.playerData = playerData; this.gateSession = gateSession; } @Nonnull @Override public PlayerData getData() { return playerData; } // 常用方法代理 /** * 玩家注册账号时的服务器id。 * 是玩家的逻辑服,它并不一定是一个真实的服务器。 */ public CenterServerId getOriginalServerId() { return playerData.getOriginalServerId(); } public CenterServerId getActualServerId() { return playerData.getActualServerId(); } public Session getGateSession() { return gateSession; } public void setGateSession(Session gateSession) { this.gateSession = gateSession; } }
923dfc421ad8462326296c3529be1afa2b348964
142
java
Java
example/android/app/src/main/java/com/fuadarradhi/example/MainActivity.java
fuadarradhi/double_back_to_close
a26e43c81b86dee7d85c7d61472be205040d8dc4
[ "MIT" ]
4
2020-05-30T07:39:46.000Z
2020-08-26T08:39:55.000Z
example/android/app/src/main/java/com/fuadarradhi/example/MainActivity.java
fuadarradhi/double_back_to_close
a26e43c81b86dee7d85c7d61472be205040d8dc4
[ "MIT" ]
2
2021-03-30T03:48:31.000Z
2021-11-21T15:38:25.000Z
example/android/app/src/main/java/com/fuadarradhi/example/MainActivity.java
fuadarradhi/double_back_to_close
a26e43c81b86dee7d85c7d61472be205040d8dc4
[ "MIT" ]
null
null
null
20.285714
52
0.838028
1,000,566
package com.fuadarradhi.example; import io.flutter.embedding.android.FlutterActivity; public class MainActivity extends FlutterActivity { }
923dfca1a384d189906d29dfbb0a996e8ab8935a
551
java
Java
book-store/src/main/java/com/base/bookstore/delegate/customer/service/CustomerDelegateService.java
SaWLeaDeR/book-store
ebda0e27a053a1af5ec6fc69b9284dc734dc4510
[ "Apache-2.0" ]
null
null
null
book-store/src/main/java/com/base/bookstore/delegate/customer/service/CustomerDelegateService.java
SaWLeaDeR/book-store
ebda0e27a053a1af5ec6fc69b9284dc734dc4510
[ "Apache-2.0" ]
null
null
null
book-store/src/main/java/com/base/bookstore/delegate/customer/service/CustomerDelegateService.java
SaWLeaDeR/book-store
ebda0e27a053a1af5ec6fc69b9284dc734dc4510
[ "Apache-2.0" ]
null
null
null
36.733333
82
0.842105
1,000,567
package com.base.bookstore.delegate.customer.service; import com.base.bookstore.delegate.customer.model.dto.CustomerDto; import com.base.bookstore.domain.model.request.CustomerCreateRequest; import com.base.bookstore.domain.model.request.CustomerGetRequest; import com.base.model.dto.ListDto; import com.base.model.response.ServiceResponse; public interface CustomerDelegateService { ServiceResponse<CustomerDto> saveCustomer(CustomerCreateRequest request); ServiceResponse<ListDto<CustomerDto>> getCustomer(CustomerGetRequest request); }
923dfcc320e167e49031189923f062fd911e280d
6,029
java
Java
edexOsgi/com.raytheon.uf.common.mpe/src/com/raytheon/uf/common/mpe/util/DPAFile.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
edexOsgi/com.raytheon.uf.common.mpe/src/com/raytheon/uf/common/mpe/util/DPAFile.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
null
null
null
edexOsgi/com.raytheon.uf.common.mpe/src/com/raytheon/uf/common/mpe/util/DPAFile.java
drjoeycadieux/awips2
3b467b15915cba23d9216eefd97a21758e66c748
[ "Apache-2.0" ]
1
2021-10-30T00:03:05.000Z
2021-10-30T00:03:05.000Z
27.78341
84
0.54752
1,000,568
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.common.mpe.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import com.raytheon.uf.common.mpe.constants.DPAConstants; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; /** * Read the DPA file. * * <pre> * * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jul 29, 2009 ? mpduff Initial creation * Sep 16, 2016 5631 bkowal Cleanup. Eliminated duplicated * DPA Constants. * * </pre> * * @author mpduff */ public class DPAFile { private static final IUFStatusHandler handler = UFStatus .getHandler(DPAFile.class); private static final double radarZero = Math.pow(10.0, -98.0 / 10.0); /** * Raw radar field. */ private double[][] stage1i; /** * Unbiased radar field (= raw radar * bias) */ private double[][] stage1u; /** * Zero data for mask. */ private double[][] zeroData; /** The DAP file. */ private File file; /** The Bias Value */ private double biasValue; /** * Constructor. * * @param fileName * filename as String */ public DPAFile(String fileName) { this(new File(fileName)); } /** * Constructor. * * @param file * Filename as file */ public DPAFile(File file) { this.file = file; } /** * Load the data. * * @throws Exception * * @throws IOException */ public void load() throws DPAException { if (file == null) { throw new DPAException("No DPA radar file has been specified."); } FileInputStream fis; try { fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer byteBuf = fc.map(MapMode.READ_ONLY, 0, fis.available()); readData(byteBuf); fis.close(); } catch (FileNotFoundException e) { throw new DPAException("Unable to find DPA radar file: " + file.getAbsolutePath() + ".", e); } catch (IOException e) { throw new DPAException("Failed to read DPA radar file: " + file.getAbsolutePath() + ".", e); } } /** * Read the data out of the byte buffer. * * stage1i array contains raw radar field stage1u array contains unbiased * radar field (= raw radar * bias) both arrays are read in as mm and * multiplied by 100 to make them look like RMOSAIC * * @param byteBuf * @throws IOException */ private void readData(ByteBuffer byteBuf) throws IOException { stage1i = new double[DPAConstants.NUM_DPA_ROWS][DPAConstants.NUM_DPA_COLS]; stage1u = new double[DPAConstants.NUM_DPA_ROWS][DPAConstants.NUM_DPA_COLS]; zeroData = new double[DPAConstants.NUM_DPA_ROWS][DPAConstants.NUM_DPA_COLS]; byteBuf.order(ByteOrder.LITTLE_ENDIAN); byteBuf.rewind(); for (int i = DPAConstants.NUM_DPA_ROWS - 1; i >= 0; i--) { for (int j = 0; j < DPAConstants.NUM_DPA_COLS; j++) { float f = byteBuf.getFloat(); if (f > -99.) { if (f == -98) { stage1i[i][j] = radarZero * 100; stage1u[i][j] = radarZero * 100 * biasValue; } else { stage1i[i][j] = Math.pow(10, f / 10) * 100; stage1u[i][j] = Math.pow(10, f / 10) * 100 * biasValue; } zeroData[i][j] = radarZero * 100; } else { // Set to missing for colorbar stage1i[i][j] = DPAConstants.DPA_MISSING; stage1u[i][j] = DPAConstants.DPA_MISSING; zeroData[i][j] = DPAConstants.DPA_MISSING; } } } } /** * @return the file */ public File getFile() { return file; } /** * Get the raw radar field. * * @return */ public double[][] getStage1i() { handler.debug("Getting Radar Data..."); return stage1i; } /** * Get the unbiased radar field (= raw radar * bias) * * @return */ public double[][] getStage1u() { handler.debug("Getting Radar Data multiplied by MFB..."); return stage1u; } /** * Get an array of zero data to use as a mask. * * @return */ public double[][] getZeroData() { return zeroData; } /** * Set the bias value. * * @param biasValue * The bias value to set */ public void setBiasValue(double biasValue) { handler.debug("Bias Value set to " + biasValue); this.biasValue = biasValue; } }