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
3e084e9a70e6f28b35a65a3aa51e756b1e9a6c79
1,985
java
Java
modules/platform/nuxeo-platform-forms-layout-api/src/main/java/org/nuxeo/ecm/platform/forms/layout/api/impl/WidgetTypeDefinitionComparator.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
1
2021-02-15T19:07:59.000Z
2021-02-15T19:07:59.000Z
modules/platform/nuxeo-platform-forms-layout-api/src/main/java/org/nuxeo/ecm/platform/forms/layout/api/impl/WidgetTypeDefinitionComparator.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
3
2021-07-03T21:32:41.000Z
2022-03-23T13:15:18.000Z
modules/platform/nuxeo-platform-forms-layout-api/src/main/java/org/nuxeo/ecm/platform/forms/layout/api/impl/WidgetTypeDefinitionComparator.java
atchertchian/nuxeo
bd28297e11151135a90a933cab6d05ce825ad539
[ "Apache-2.0" ]
1
2022-03-17T14:55:30.000Z
2022-03-17T14:55:30.000Z
29.626866
89
0.658942
3,518
/* * (C) Copyright 2010 Nuxeo SA (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: * Anahide Tchertchian */ package org.nuxeo.ecm.platform.forms.layout.api.impl; import java.util.Comparator; import org.nuxeo.ecm.platform.forms.layout.api.WidgetTypeConfiguration; import org.nuxeo.ecm.platform.forms.layout.api.WidgetTypeDefinition; /** * Compares widget types on id or label. * * @author Anahide Tchertchian * @since 5.4.2 */ public class WidgetTypeDefinitionComparator implements Comparator<WidgetTypeDefinition> { protected boolean compareLabels = false; public WidgetTypeDefinitionComparator(boolean compareLabels) { super(); this.compareLabels = compareLabels; } @Override public int compare(WidgetTypeDefinition o1, WidgetTypeDefinition o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } return getComparisonString(o1).compareTo(getComparisonString(o2)); } protected String getComparisonString(WidgetTypeDefinition def) { String res = def.getName(); if (compareLabels) { WidgetTypeConfiguration conf = def.getConfiguration(); if (conf != null && conf.getTitle() != null) { res = conf.getTitle(); } } return res; } }
3e084ea72944a7d85d013f2a31f43ecbf710b959
2,885
java
Java
src/main/java/com/github/mdevloo/multi/tenancy/fwk/auth0/security/SecurityConfig.java
trailrunner-taulia/Spring-boot-auth0-discriminator-multitenancy
a9cd67c8e5e19553427610af875c6eca717101b8
[ "Apache-2.0" ]
23
2020-09-29T11:14:03.000Z
2022-03-17T12:18:59.000Z
src/main/java/com/github/mdevloo/multi/tenancy/fwk/auth0/security/SecurityConfig.java
trailrunner-taulia/Spring-boot-auth0-discriminator-multitenancy
a9cd67c8e5e19553427610af875c6eca717101b8
[ "Apache-2.0" ]
8
2020-09-29T12:39:02.000Z
2021-09-21T15:37:08.000Z
src/main/java/com/github/mdevloo/multi/tenancy/fwk/auth0/security/SecurityConfig.java
trailrunner-taulia/Spring-boot-auth0-discriminator-multitenancy
a9cd67c8e5e19553427610af875c6eca717101b8
[ "Apache-2.0" ]
5
2021-02-16T17:12:02.000Z
2022-02-12T13:58:38.000Z
44.384615
124
0.803813
3,519
package com.github.mdevloo.multi.tenancy.fwk.auth0.security; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtDecoders; import org.springframework.security.oauth2.jwt.JwtValidators; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import static com.github.mdevloo.multi.tenancy.core.AppConstants.API; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private final String audience; private final String issuer; public SecurityConfig( @Value("${auth0.audience}") final String audience, @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") final String issuer) { this.audience = audience; this.issuer = issuer; } @Override public void configure(final HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); http.headers() .referrerPolicy( referrerPolicyConfig -> referrerPolicyConfig.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.authorizeRequests() .mvcMatchers(API + "/**") .authenticated() .and() .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); } @Bean JwtDecoder jwtDecoder() { final NimbusJwtDecoder nimbusJwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(this.issuer); final OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(this.audience); final OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(this.issuer); final OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator); nimbusJwtDecoder.setJwtValidator(withAudience); return nimbusJwtDecoder; } }
3e084f12b7fe12f0943d6c01c61144d929707171
4,434
java
Java
reflection/src/main/java/org/bndly/common/reflection/GetterBeanPropertyAccessor.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
1
2020-07-24T08:58:39.000Z
2020-07-24T08:58:39.000Z
reflection/src/main/java/org/bndly/common/reflection/GetterBeanPropertyAccessor.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
2
2020-12-02T18:45:34.000Z
2022-01-21T23:45:25.000Z
reflection/src/main/java/org/bndly/common/reflection/GetterBeanPropertyAccessor.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
2
2020-07-21T17:44:10.000Z
2020-07-22T13:31:10.000Z
34.640625
164
0.735679
3,520
package org.bndly.common.reflection; /*- * #%L * Reflection * %% * Copyright (C) 2013 - 2020 Cybercon 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. * #L% */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; public class GetterBeanPropertyAccessor extends AbstractBeanPropertyAccessorWriter implements BeanPropertyAccessor { @Override public Object get(String propertyName, Object target, TypeHint... typeHints) { if (target == null) { throw new IllegalArgumentException("target can not be null"); } String uppercasePropertyName = propertyName; CollectionProperty collectionDescriptor = null; if (propertyNameRefersToElementInCollection(propertyName)) { collectionDescriptor = collectionPropertyDescriptor(propertyName); uppercasePropertyName = collectionDescriptor.getCollectionPropertyName(); } uppercasePropertyName = uppercaseName(uppercasePropertyName); Map<String, Method> methods = ReflectionUtil.collectMethodsImplementedBy(target); Method method = methods.get("get" + uppercasePropertyName); if (method == null) { method = methods.get("is" + uppercasePropertyName); } Object propertyValue = null; if (method != null) { boolean ia = method.isAccessible(); try { method.setAccessible(true); propertyValue = method.invoke(target); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { // this will be ignored. maybe some runtime expception might make sense here. } finally { method.setAccessible(ia); } } if (propertyValue != null && collectionDescriptor != null) { List list = (List) propertyValue; int index = collectionDescriptor.getCollectionIndex(); if (list.size() <= index) { return null; } return list.get(index); } return propertyValue; } @Override public Class<?> typeOf(String propertyName, Object target, TypeHint... typeHints) { Class<?> targetType = target.getClass(); String uppercasePropertyName = propertyName; CollectionProperty collectionDescriptor = null; boolean isCollection = false; if (propertyNameRefersToElementInCollection(propertyName)) { isCollection = true; collectionDescriptor = collectionPropertyDescriptor(propertyName); uppercasePropertyName = collectionDescriptor.getCollectionPropertyName(); } for (TypeHint typeHint : typeHints) { if (typeHint.getPath().isEmpty() && ((isCollection && typeHint.isCollection()) || (!isCollection && !typeHint.isCollection()))) { return typeHint.getType(); } } uppercasePropertyName = uppercaseName(uppercasePropertyName); Map<String, Method> methods = ReflectionUtil.collectMethodsImplementedBy(target); Method method = methods.get("get" + uppercasePropertyName); if (method == null) { method = methods.get("is" + uppercasePropertyName); } if (method != null) { if (collectionDescriptor != null) { Class<?> listItemType = ReflectionUtil.getCollectionParameterType(method.getGenericReturnType()); if (listItemType == null) { throw new UnresolvablePropertyException(propertyName, targetType, "could not resolve list item type of " + propertyName + " in " + targetType.getSimpleName()); } return listItemType; } else { return method.getReturnType(); } } else { throw new UnresolvablePropertyException( propertyName, targetType, "could not resolve type of " + propertyName + " in " + targetType.getSimpleName() + " because no getter method was found." ); } } private String uppercaseName(String uppercasePropertyName) { if (uppercasePropertyName.length() > 1) { uppercasePropertyName = uppercasePropertyName.substring(0, 1).toUpperCase() + uppercasePropertyName.substring(1); } else { uppercasePropertyName = uppercasePropertyName.toUpperCase(); } return uppercasePropertyName; } }
3e084f2591c2b4451925404ce2bb800127c70355
2,577
java
Java
bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminGrpcClient.java
igorbernstein2/cloud-bigtable-client
65786f6ee9ab2807d81bd16b81fc277ccee61a3b
[ "Apache-2.0" ]
null
null
null
bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminGrpcClient.java
igorbernstein2/cloud-bigtable-client
65786f6ee9ab2807d81bd16b81fc277ccee61a3b
[ "Apache-2.0" ]
null
null
null
bigtable-client-core-parent/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableTableAdminGrpcClient.java
igorbernstein2/cloud-bigtable-client
65786f6ee9ab2807d81bd16b81fc277ccee61a3b
[ "Apache-2.0" ]
null
null
null
30.317647
83
0.75553
3,521
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigtable.grpc; import com.google.bigtable.admin.v2.BigtableTableAdminGrpc; import com.google.bigtable.admin.v2.CreateTableRequest; import com.google.bigtable.admin.v2.DeleteTableRequest; import com.google.bigtable.admin.v2.DropRowRangeRequest; import com.google.bigtable.admin.v2.GetTableRequest; import com.google.bigtable.admin.v2.ListTablesRequest; import com.google.bigtable.admin.v2.ListTablesResponse; import com.google.bigtable.admin.v2.ModifyColumnFamiliesRequest; import com.google.bigtable.admin.v2.Table; import io.grpc.Channel; /** * A gRPC client for accessing the Bigtable Table Admin API. * * @author sduskis * @version $Id: $Id */ public class BigtableTableAdminGrpcClient implements BigtableTableAdminClient { private final BigtableTableAdminGrpc.BigtableTableAdminBlockingStub blockingStub; /** * <p>Constructor for BigtableTableAdminGrpcClient.</p> * * @param channel a {@link io.grpc.Channel} object. */ public BigtableTableAdminGrpcClient(Channel channel) { blockingStub = BigtableTableAdminGrpc.newBlockingStub(channel); } /** {@inheritDoc} */ @Override public ListTablesResponse listTables(ListTablesRequest request) { return blockingStub.listTables(request); } /** {@inheritDoc} */ @Override public Table getTable(GetTableRequest request) { return blockingStub.getTable(request); } /** {@inheritDoc} */ @Override public void createTable(CreateTableRequest request) { blockingStub.createTable(request); } /** {@inheritDoc} */ @Override public void modifyColumnFamily(ModifyColumnFamiliesRequest request) { blockingStub.modifyColumnFamilies(request); } /** {@inheritDoc} */ @Override public void deleteTable(DeleteTableRequest request) { blockingStub.deleteTable(request); } /** {@inheritDoc} */ @Override public void dropRowRange(DropRowRangeRequest request) { blockingStub.dropRowRange(request); } }
3e084f267a4b85896c54d989d35e5105f55ecc05
1,870
java
Java
nevis_activiti/nevis-bn/bn-dao/src/main/java/com/cqut/mapper/OrganizationUserMapper.java
yangqiang1997/yangqaing1997.GitHub.io
b7d385a9e813255afb71382d0bb982ca21908b99
[ "Apache-2.0" ]
null
null
null
nevis_activiti/nevis-bn/bn-dao/src/main/java/com/cqut/mapper/OrganizationUserMapper.java
yangqiang1997/yangqaing1997.GitHub.io
b7d385a9e813255afb71382d0bb982ca21908b99
[ "Apache-2.0" ]
null
null
null
nevis_activiti/nevis-bn/bn-dao/src/main/java/com/cqut/mapper/OrganizationUserMapper.java
yangqiang1997/yangqaing1997.GitHub.io
b7d385a9e813255afb71382d0bb982ca21908b99
[ "Apache-2.0" ]
null
null
null
22.53012
79
0.636898
3,522
package com.cqut.mapper; import com.cqut.entity.dto.role.ElTreeDTO; import com.cqut.entity.entity.OrganizationUser; import com.cqut.entity.entity.User; import com.github.pagehelper.Page; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 作者:谭勇 * 时间:2018-04-07 * */ public interface OrganizationUserMapper { int insert(@Param("record") OrganizationUser record); int update(OrganizationUser organizationUser); List<OrganizationUser> selectAll(); /** * 找到用户对应的组织机构id * @param userId 用户id * */ List<String> selectUserOrganizations(@Param("userId") String userId); boolean selectUserExesit(@Param("orgId") String orgId); /** * 删除用户关联的组织机构 * 在执行硬删除操作删除用户时,需要先删除用户关联的组织机构 * @param userId 用户id * */ int deleteUserOrganization(@Param("userId") String userId); /** * 删除组织机构关联的用户 * 在执行硬删除操作删除组织机构是,需要先删除组织机构关联的用户 * @param * */ int deleteOrganizationUser(@Param("organizationId") String organizationId); /** * 删除关联表中的相关信息 删除用户 * @param userId * @param organizationId * @return */ int deleteByUserIdAndOrgID(@Param("userId") String userId, @Param("organizationId") String organizationId); boolean deleteByOrgId(@Param("organizationId") String organizationId); /** * 找到该用户对应的组织机构条数 * 作者:罗杏函 * 时间:2018.4.13 * @param userId * @return */ int findUserOrganization(@Param("userId") String userId); /** * 查找到对应组织机构下的用户所有信息 * 作者:罗杏函 * 时间:2018.4.13 * @param organizationId * @return 用户信息列表 可直接在用户管理界面使用作为tableDate */ Page<User> selectOrgUsers(@Param("orgId") String organizationId); /** * 查询所有的组织机构 * 树形 * 作者:罗杏函 * 时间:2018.4.15 * @return */ List<ElTreeDTO> selectAllOrg(); }
3e084f509a54457d0f8c04338f06843918244386
1,168
java
Java
src/cmaker/ExpansionPoint.java
daviscook477/DotPaths
c28c4683982f94fb5df21f10021f04490388207a
[ "MIT" ]
null
null
null
src/cmaker/ExpansionPoint.java
daviscook477/DotPaths
c28c4683982f94fb5df21f10021f04490388207a
[ "MIT" ]
null
null
null
src/cmaker/ExpansionPoint.java
daviscook477/DotPaths
c28c4683982f94fb5df21f10021f04490388207a
[ "MIT" ]
null
null
null
25.391304
64
0.631849
3,523
package cmaker; import java.awt.Color; public class ExpansionPoint extends DraggableDrawableCircle { private InteractiveSpline sp; private ControlPoint cp; public ExpansionPoint(InteractiveSpline sp, ControlPoint cp) { super(0, 0, 5, Color.BLUE); int index = sp.cPoints.indexOf(cp); this.sp = sp; this.cp = cp; Point p1 = sp.points.get(index - 1); Point p2 = sp.points.get(index); Curve c = new Curve(p1, p2); float[] pos = c.pointAt(0.5f); x = pos[0]; y = pos[1]; } // Update the position of the expansion point public void updatePosition() { int index = sp.cPoints.indexOf(cp); Point p1 = sp.points.get(index - 1); Point p2 = sp.points.get(index); Curve c = new Curve(p1, p2); float[] pos = c.pointAt(0.5f); x = pos[0]; y = pos[1]; } @Override public void pickedUp(int cursorX, int cursorY) { int index = sp.cPoints.indexOf(cp); Point p1 = sp.points.get(index - 1); Point p2 = sp.points.get(index); Curve c = new Curve(p1, p2); float[] deriv = c.derivativeAt(0.5f); sp.addPoint(new Point(x, y, deriv[0], deriv[1]), index); sp.ePoints.remove(this); } }
3e084fbaa2617e7414140a6abdb96efda7e88660
483
java
Java
src/main/java/nl/hu/bdsd/kafka_broker/IKafkaConstants.java
nstuivenberg/NiNi
865ac45686c57059748fa06cfaf851c185a40db7
[ "Apache-2.0" ]
null
null
null
src/main/java/nl/hu/bdsd/kafka_broker/IKafkaConstants.java
nstuivenberg/NiNi
865ac45686c57059748fa06cfaf851c185a40db7
[ "Apache-2.0" ]
null
null
null
src/main/java/nl/hu/bdsd/kafka_broker/IKafkaConstants.java
nstuivenberg/NiNi
865ac45686c57059748fa06cfaf851c185a40db7
[ "Apache-2.0" ]
null
null
null
30.1875
52
0.751553
3,524
package nl.hu.bdsd.kafka_broker; public interface IKafkaConstants { String KAFKA_BROKERS = "nigelvanhattum.nl:9092"; //String KAFKA_BROKERS = "localhost:9092"; Integer MESSAGE_COUNT=1000; String CLIENT_ID="poliFLWProducer"; //String TOPIC_NAME="demo"; String GROUP_ID_CONFIG="PoliFLWConsumer"; Integer MAX_NO_MESSAGE_FOUND_COUNT=100; String OFFSET_RESET_EARLIER="earliest"; String OFFSET_RESET_LATEST="latest"; Integer MAX_POLL_RECORDS=1; }
3e08500e6817d33d6fd87d2f80bf65f5b2477933
8,994
java
Java
src/main/java/thut/crafts/proxy/ClientProxy.java
MetaltyrantMk2/Pokecube-Issues-and-Wiki
a64f19bcccc75db26d59d0c0cdd1d3d0ec59ea07
[ "MIT" ]
1
2020-06-17T06:47:04.000Z
2020-06-17T06:47:04.000Z
src/main/java/thut/crafts/proxy/ClientProxy.java
MetaltyrantMk2/Pokecube-Issues-and-Wiki
a64f19bcccc75db26d59d0c0cdd1d3d0ec59ea07
[ "MIT" ]
null
null
null
src/main/java/thut/crafts/proxy/ClientProxy.java
MetaltyrantMk2/Pokecube-Issues-and-Wiki
a64f19bcccc75db26d59d0c0cdd1d3d0ec59ea07
[ "MIT" ]
null
null
null
48.616216
117
0.657438
3,525
package thut.crafts.proxy; import org.lwjgl.glfw.GLFW; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.client.settings.KeyConflictContext; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.TickEvent.Phase; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import thut.api.entity.blockentity.render.RenderBlockEntity; import thut.api.maths.Vector3; import thut.crafts.ThutCrafts; import thut.crafts.entity.CraftController; import thut.crafts.entity.EntityCraft; import thut.crafts.network.PacketCraftControl; public class ClientProxy extends CommonProxy { KeyBinding UP; KeyBinding DOWN; KeyBinding ROTATERIGHT; KeyBinding ROTATELEFT; @OnlyIn(Dist.CLIENT) @SubscribeEvent public void clientTick(final TickEvent.PlayerTickEvent event) { if (event.phase == Phase.START || event.player != Minecraft.getInstance().player) return; control: if (event.player.isPassenger() && Minecraft.getInstance().currentScreen == null) { final Entity e = event.player.getRidingEntity(); if (e instanceof EntityCraft) { final ClientPlayerEntity player = (ClientPlayerEntity) event.player; final CraftController controller = ((EntityCraft) e).controller; if (controller == null) break control; controller.backInputDown = player.movementInput.backKeyDown; controller.forwardInputDown = player.movementInput.forwardKeyDown; controller.leftInputDown = player.movementInput.leftKeyDown; controller.rightInputDown = player.movementInput.rightKeyDown; controller.upInputDown = this.UP.isKeyDown(); controller.downInputDown = this.DOWN.isKeyDown(); if (ThutCrafts.conf.canRotate) { controller.rightRotateDown = this.ROTATERIGHT.isKeyDown(); controller.leftRotateDown = this.ROTATELEFT.isKeyDown(); } PacketCraftControl.sendControlPacket(e, controller); } } } @Override public PlayerEntity getPlayer() { return Minecraft.getInstance().player; } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void RenderBounds(final DrawBlockHighlightEvent event) { if (!(event.getTarget() instanceof BlockRayTraceResult)) return; final BlockRayTraceResult target = (BlockRayTraceResult) event.getTarget(); ItemStack held; final PlayerEntity player = Minecraft.getInstance().player; if (!(held = player.getHeldItemMainhand()).isEmpty() || !(held = player.getHeldItemOffhand()).isEmpty()) { BlockPos pos = target.getPos(); if (pos == null || held.getItem() != ThutCrafts.CRAFTMAKER) return; if (!player.world.getBlockState(pos).getMaterial().isSolid()) { final Vec3d loc = player.getPositionVector().add(0, player.getEyeHeight(), 0).add(player.getLookVec() .scale(2)); pos = new BlockPos(loc); } if (held.getTag() != null && held.getTag().contains("min")) { BlockPos min = Vector3.readFromNBT(held.getTag().getCompound("min"), "").getPos(); BlockPos max = pos; AxisAlignedBB box = new AxisAlignedBB(min, max); min = new BlockPos(box.minX, box.minY, box.minZ); max = new BlockPos(box.maxX, box.maxY, box.maxZ).add(1, 1, 1); box = new AxisAlignedBB(min, max); final float partialTicks = event.getPartialTicks(); final double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; final double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; final double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; box = box.offset(-d0, -d1 - player.getEyeHeight(), -d2); GlStateManager.enableBlend(); GlStateManager.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.color4f(0.0F, 0.0F, 0.0F, 0.4F); GlStateManager.lineWidth(2.0F); GlStateManager.disableTexture(); GlStateManager.depthMask(false); GlStateManager.color4f(1.0F, 0.0F, 0.0F, 1F); final Tessellator tessellator = Tessellator.getInstance(); final BufferBuilder vertexbuffer = tessellator.getBuffer(); vertexbuffer.begin(3, DefaultVertexFormats.POSITION); vertexbuffer.pos(box.minX, box.minY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.minY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.minY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.minY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.minY, box.minZ).endVertex(); tessellator.draw(); vertexbuffer.begin(3, DefaultVertexFormats.POSITION); vertexbuffer.pos(box.minX, box.maxY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.maxY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.maxY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.maxY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.maxY, box.minZ).endVertex(); tessellator.draw(); vertexbuffer.begin(1, DefaultVertexFormats.POSITION); vertexbuffer.pos(box.minX, box.minY, box.minZ).endVertex(); vertexbuffer.pos(box.minX, box.maxY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.minY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.maxY, box.minZ).endVertex(); vertexbuffer.pos(box.maxX, box.minY, box.maxZ).endVertex(); vertexbuffer.pos(box.maxX, box.maxY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.minY, box.maxZ).endVertex(); vertexbuffer.pos(box.minX, box.maxY, box.maxZ).endVertex(); tessellator.draw(); GlStateManager.depthMask(true); GlStateManager.enableTexture(); GlStateManager.disableBlend(); } } } @Override public void setup(final FMLCommonSetupEvent event) { super.setup(event); } @Override public void setupClient(final FMLClientSetupEvent event) { this.UP = new KeyBinding("crafts.key.up", GLFW.GLFW_KEY_SPACE, "keys.crafts"); this.DOWN = new KeyBinding("crafts.key.down", GLFW.GLFW_KEY_LEFT_CONTROL, "keys.crafts"); final KeyConflictContext inGame = KeyConflictContext.IN_GAME; this.UP.setKeyConflictContext(inGame); this.DOWN.setKeyConflictContext(inGame); this.ROTATERIGHT = new KeyBinding("crafts.key.left", GLFW.GLFW_KEY_RIGHT_BRACKET, "keys.crafts"); this.ROTATELEFT = new KeyBinding("crafts.key.right", GLFW.GLFW_KEY_LEFT_BRACKET, "keys.crafts"); this.ROTATELEFT.setKeyConflictContext(inGame); this.ROTATERIGHT.setKeyConflictContext(inGame); ClientRegistry.registerKeyBinding(this.UP); ClientRegistry.registerKeyBinding(this.DOWN); ClientRegistry.registerKeyBinding(this.ROTATELEFT); ClientRegistry.registerKeyBinding(this.ROTATERIGHT); RenderingRegistry.registerEntityRenderingHandler(EntityCraft.class, (manager) -> new RenderBlockEntity<>( manager)); } }
3e08508504206358eba1b839c1888f1b756ccebe
1,976
java
Java
src/main/java/io/nem/sdk/infrastructure/UInt64DTO.java
alexjavabraz/nem2-sdk-java
ae798231e63707ccb045769c6f4993abeeb8ad20
[ "Apache-2.0" ]
1
2019-02-13T22:06:16.000Z
2019-02-13T22:06:16.000Z
src/main/java/io/nem/sdk/infrastructure/UInt64DTO.java
alexjavabraz/nem2-sdk-java
ae798231e63707ccb045769c6f4993abeeb8ad20
[ "Apache-2.0" ]
null
null
null
src/main/java/io/nem/sdk/infrastructure/UInt64DTO.java
alexjavabraz/nem2-sdk-java
ae798231e63707ccb045769c6f4993abeeb8ad20
[ "Apache-2.0" ]
null
null
null
25.333333
104
0.671053
3,526
/* * Copyright 2019 NEM * * 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. * * Catapult REST API Reference * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0.12 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.nem.sdk.infrastructure; import java.util.ArrayList; import java.util.Objects; /** * UInt64DTO * @author alexjavabraz * @since 4/8/2019 */ public class UInt64DTO extends ArrayList<Integer> { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UInt64DTO {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0850eea16bcf4009040b77621d50a2b343f941
7,230
java
Java
storage/src/main/java/tech/pegasys/teku/storage/server/kvstore/schema/V6SchemaCombinedTreeState.java
ajsutton/artemis
ef53e247e64bb0a14fd91bb8734c5fa8784c727b
[ "Apache-2.0" ]
77
2020-02-26T16:40:27.000Z
2020-10-19T13:21:49.000Z
storage/src/main/java/tech/pegasys/teku/storage/server/kvstore/schema/V6SchemaCombinedTreeState.java
ajsutton/artemis
ef53e247e64bb0a14fd91bb8734c5fa8784c727b
[ "Apache-2.0" ]
840
2020-02-25T21:38:02.000Z
2020-10-22T21:12:58.000Z
storage/src/main/java/tech/pegasys/teku/storage/server/kvstore/schema/V6SchemaCombinedTreeState.java
ajsutton/artemis
ef53e247e64bb0a14fd91bb8734c5fa8784c727b
[ "Apache-2.0" ]
40
2020-02-25T21:36:42.000Z
2020-10-20T12:04:50.000Z
45.471698
130
0.781466
3,527
/* * Copyright ConsenSys Software Inc., 2020 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package tech.pegasys.teku.storage.server.kvstore.schema; import static tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer.BLOCK_ROOTS_SERIALIZER; import static tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer.BYTES32_SERIALIZER; import static tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer.BYTES_SERIALIZER; import static tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer.COMPRESSED_BRANCH_INFO_KV_STORE_SERIALIZER; import static tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer.UINT64_SERIALIZER; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import tech.pegasys.teku.infrastructure.ssz.tree.TreeNodeSource.CompressedBranchInfo; import tech.pegasys.teku.infrastructure.unsigned.UInt64; import tech.pegasys.teku.spec.Spec; import tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock; import tech.pegasys.teku.storage.server.kvstore.serialization.KvStoreSerializer; public class V6SchemaCombinedTreeState extends V6SchemaCombined implements SchemaCombinedTreeState { private final KvStoreColumn<Bytes32, UInt64> slotsByFinalizedRoot; private final KvStoreColumn<UInt64, SignedBeaconBlock> finalizedBlocksBySlot; private final KvStoreColumn<Bytes32, SignedBeaconBlock> nonCanonicalBlocksByRoot; private final KvStoreColumn<Bytes32, UInt64> slotsByFinalizedStateRoot; private final KvStoreColumn<UInt64, Set<Bytes32>> nonCanonicalBlockRootsBySlot; private final KvStoreColumn<UInt64, Bytes32> finalizedStateRootsBySlot; private final KvStoreColumn<Bytes32, Bytes> finalizedStateTreeLeavesByRoot; private final KvStoreColumn<Bytes32, CompressedBranchInfo> finalizedStateTreeBranchesByRoot; public V6SchemaCombinedTreeState(final Spec spec, final boolean storeVotesEquivocation) { super(spec, storeVotesEquivocation, V6_FINALIZED_OFFSET); slotsByFinalizedRoot = KvStoreColumn.create(V6_FINALIZED_OFFSET + 1, BYTES32_SERIALIZER, UINT64_SERIALIZER); slotsByFinalizedStateRoot = KvStoreColumn.create(V6_FINALIZED_OFFSET + 2, BYTES32_SERIALIZER, UINT64_SERIALIZER); nonCanonicalBlockRootsBySlot = KvStoreColumn.create(V6_FINALIZED_OFFSET + 3, UINT64_SERIALIZER, BLOCK_ROOTS_SERIALIZER); finalizedStateRootsBySlot = KvStoreColumn.create(V6_FINALIZED_OFFSET + 4, UINT64_SERIALIZER, BYTES32_SERIALIZER); finalizedStateTreeLeavesByRoot = KvStoreColumn.create(V6_FINALIZED_OFFSET + 5, BYTES32_SERIALIZER, BYTES_SERIALIZER); finalizedStateTreeBranchesByRoot = KvStoreColumn.create( V6_FINALIZED_OFFSET + 6, BYTES32_SERIALIZER, COMPRESSED_BRANCH_INFO_KV_STORE_SERIALIZER); finalizedBlocksBySlot = KvStoreColumn.create( V6_FINALIZED_OFFSET + 7, UINT64_SERIALIZER, KvStoreSerializer.createSignedBlockSerializer(spec)); nonCanonicalBlocksByRoot = KvStoreColumn.create( V6_FINALIZED_OFFSET + 8, BYTES32_SERIALIZER, KvStoreSerializer.createSignedBlockSerializer(spec)); } @Override public KvStoreColumn<UInt64, Bytes32> getColumnFinalizedStateRootsBySlot() { return finalizedStateRootsBySlot; } @Override public KvStoreColumn<Bytes32, Bytes> getColumnFinalizedStateMerkleTreeLeaves() { return finalizedStateTreeLeavesByRoot; } @Override public KvStoreColumn<Bytes32, CompressedBranchInfo> getColumnFinalizedStateMerkleTreeBranches() { return finalizedStateTreeBranchesByRoot; } @Override public KvStoreColumn<Bytes32, UInt64> getColumnSlotsByFinalizedRoot() { return slotsByFinalizedRoot; } @Override public KvStoreColumn<UInt64, SignedBeaconBlock> getColumnFinalizedBlocksBySlot() { return finalizedBlocksBySlot; } @Override public KvStoreColumn<Bytes32, UInt64> getColumnSlotsByFinalizedStateRoot() { return slotsByFinalizedStateRoot; } @Override public KvStoreColumn<Bytes32, SignedBeaconBlock> getColumnNonCanonicalBlocksByRoot() { return nonCanonicalBlocksByRoot; } @Override public KvStoreColumn<UInt64, Set<Bytes32>> getColumnNonCanonicalRootsBySlot() { return nonCanonicalBlockRootsBySlot; } @Override public Map<String, KvStoreVariable<?>> getVariableMap() { return Map.of( "GENESIS_TIME", getVariableGenesisTime(), "JUSTIFIED_CHECKPOINT", getVariableJustifiedCheckpoint(), "BEST_JUSTIFIED_CHECKPOINT", getVariableBestJustifiedCheckpoint(), "FINALIZED_CHECKPOINT", getVariableFinalizedCheckpoint(), "LATEST_FINALIZED_STATE", getVariableLatestFinalizedState(), "MIN_GENESIS_TIME_BLOCK", getVariableMinGenesisTimeBlock(), "WEAK_SUBJECTIVITY_CHECKPOINT", getVariableWeakSubjectivityCheckpoint(), "ANCHOR_CHECKPOINT", getVariableAnchorCheckpoint(), "OPTIMISTIC_TRANSITION_BLOCK_SLOT", getOptimisticTransitionBlockSlot()); } @Override public Map<String, KvStoreColumn<?, ?>> getColumnMap() { return ImmutableMap.<String, KvStoreColumn<?, ?>>builder() .put("HOT_BLOCKS_BY_ROOT", getColumnHotBlocksByRoot()) .put("CHECKPOINT_STATES", getColumnCheckpointStates()) .put("VOTES", getColumnVotes()) .put("DEPOSITS_FROM_BLOCK_EVENTS", getColumnDepositsFromBlockEvents()) .put("STATE_ROOT_TO_SLOT_AND_BLOCK_ROOT", getColumnStateRootToSlotAndBlockRoot()) .put("HOT_STATES_BY_ROOT", getColumnHotStatesByRoot()) .put("HOT_BLOCK_CHECKPOINT_EPOCHS_BY_ROOT", getColumnHotBlockCheckpointEpochsByRoot()) .put("SLOTS_BY_FINALIZED_ROOT", getColumnSlotsByFinalizedRoot()) .put("FINALIZED_BLOCKS_BY_SLOT", getColumnFinalizedBlocksBySlot()) .put("FINALIZED_STATE_ROOTS_BY_SLOT", getColumnFinalizedStateRootsBySlot()) .put("FINALIZED_STATE_TREE_LEAVES", getColumnFinalizedStateMerkleTreeLeaves()) .put("FINALIZED_STATE_TREE_BRANCHES", getColumnFinalizedStateMerkleTreeBranches()) .put("SLOTS_BY_FINALIZED_STATE_ROOT", getColumnSlotsByFinalizedStateRoot()) .put("NON_CANONICAL_BLOCKS_BY_ROOT", getColumnNonCanonicalBlocksByRoot()) .put("NON_CANONICAL_BLOCK_ROOTS_BY_SLOT", getColumnNonCanonicalRootsBySlot()) .build(); } @Override public Collection<KvStoreColumn<?, ?>> getAllColumns() { return getColumnMap().values(); } @Override public Collection<KvStoreVariable<?>> getAllVariables() { return getVariableMap().values(); } }
3e0852f720ee2d4f51e821855a2f7cb2fee86bfa
2,126
java
Java
servicio-bienes/src/main/java/edu/central/servicio/bienes/service/ViviendaServiceImpl.java
johnalbh/MimpuestoAPI
1628e943f223d5e1c985e67b4902b8eb63c23d1b
[ "Apache-2.0" ]
1
2021-11-22T18:54:04.000Z
2021-11-22T18:54:04.000Z
servicio-bienes/src/main/java/edu/central/servicio/bienes/service/ViviendaServiceImpl.java
johnalbh/MimpuestoAPI
1628e943f223d5e1c985e67b4902b8eb63c23d1b
[ "Apache-2.0" ]
null
null
null
servicio-bienes/src/main/java/edu/central/servicio/bienes/service/ViviendaServiceImpl.java
johnalbh/MimpuestoAPI
1628e943f223d5e1c985e67b4902b8eb63c23d1b
[ "Apache-2.0" ]
null
null
null
33.746032
130
0.714958
3,528
package edu.central.servicio.bienes.service; import edu.central.servicio.bienes.model.Vivienda; import edu.central.servicio.bienes.exception.NotFoundException; import edu.central.servicio.bienes.repository.ViviendaRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ViviendaServiceImpl implements ViviendaService { @Autowired private ViviendaRepository viviendaRepository; @Override public List<Vivienda> getAllViviendas() { return viviendaRepository.findAll(); } @Override public List<Vivienda> getAllViviendasByContribuyente(String numeroIdentificacion) { return this.viviendaRepository.getAllViviendaContribuyente(numeroIdentificacion); } @Override public Vivienda getViviendaById(String cedulaCatrastal) { Optional<Vivienda> viviendaDB = this.viviendaRepository.findById(cedulaCatrastal); if (viviendaDB.isPresent()) { return viviendaDB.get(); } else { return null; } } @Override public Vivienda crearVivienda(Vivienda vivienda) { return this.viviendaRepository.save(vivienda); } @Override public Vivienda actualizarVivienda(Vivienda vivienda) { Optional<Vivienda> viviendaDB = this.viviendaRepository.findById(vivienda.getCedulaCatrastal()); if (viviendaDB.isPresent()) { return this.viviendaRepository.save(vivienda); } else { throw new NotFoundException("No existe la vivienda con la cédula catrastal Número: " + vivienda.getCedulaCatrastal()); } } @Override public void DeleteVivienda(String cedulaCatrastal) { Optional<Vivienda> viviendaDB = this.viviendaRepository.findById(cedulaCatrastal); if (viviendaDB.isPresent()) { this.viviendaRepository.delete(viviendaDB.get()); } else { throw new NotFoundException("No existe la vivienda con la cédula catrastal Número: " + cedulaCatrastal); } } }
3e08531f06a187b02eea86f74082d80bb7ca496f
2,180
java
Java
plugins/network-elements/ovs/src/main/java/com/cloud/agent/api/OvsCreateTunnelCommand.java
aleskxyz/cloudstack
2700beb4fb1206f93829b8c4085479a8f416833d
[ "Apache-2.0" ]
1,131
2015-01-08T18:59:06.000Z
2022-03-29T11:31:10.000Z
plugins/network-elements/ovs/src/main/java/com/cloud/agent/api/OvsCreateTunnelCommand.java
aleskxyz/cloudstack
2700beb4fb1206f93829b8c4085479a8f416833d
[ "Apache-2.0" ]
5,908
2015-01-13T15:28:37.000Z
2022-03-31T20:31:07.000Z
plugins/network-elements/ovs/src/main/java/com/cloud/agent/api/OvsCreateTunnelCommand.java
Rostov1991/cloudstack
4abe8385e0721793d5dae8f195303d010c8ff8d2
[ "Apache-2.0" ]
1,083
2015-01-05T01:16:52.000Z
2022-03-31T12:14:10.000Z
25.057471
93
0.659174
3,529
// 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 com.cloud.agent.api; public class OvsCreateTunnelCommand extends Command { Integer key; String remoteIp; String networkName; Long from; Long to; long networkId; String networkUuid; // for debug info String fromIp; @Override public boolean executeInSequence() { return true; } public OvsCreateTunnelCommand(String remoteIp, Integer key, Long from, Long to, long networkId, String fromIp, String networkName, String networkUuid) { this.remoteIp = remoteIp; this.key = key; this.from = from; this.to = to; this.networkId = networkId; this.fromIp = fromIp; this.networkName = networkName; this.networkUuid = networkUuid; } public Integer getKey() { return key; } public String getRemoteIp() { return remoteIp; } public Long getFrom() { return from; } public Long getTo() { return to; } public long getNetworkId() { return networkId; } public String getFromIp() { return fromIp; } public String getNetworkName() { return networkName; } public String getNetworkUuid() { return networkUuid; } public void setNetworkUuid(String networkUuid) { this.networkUuid = networkUuid; } }
3e0853418e9d96bc08ddaf31fea4309a3b2eb448
3,538
java
Java
src/test/java/com/elena/trello/tests/TeamCreationTests.java
TayaHatum/trello-selenium-tests-Rochman
9fd7f7fe3cf04cb573966ef39570e52252ee0846
[ "Apache-2.0" ]
null
null
null
src/test/java/com/elena/trello/tests/TeamCreationTests.java
TayaHatum/trello-selenium-tests-Rochman
9fd7f7fe3cf04cb573966ef39570e52252ee0846
[ "Apache-2.0" ]
null
null
null
src/test/java/com/elena/trello/tests/TeamCreationTests.java
TayaHatum/trello-selenium-tests-Rochman
9fd7f7fe3cf04cb573966ef39570e52252ee0846
[ "Apache-2.0" ]
null
null
null
34.349515
115
0.713115
3,530
package com.elena.trello.tests; import com.elena.trello.model.TeamData; import org.openqa.selenium.By; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TeamCreationTests extends TestBase{ @BeforeMethod public void preconditions() throws InterruptedException { if(!app.getSession().isAvatarPresentOnHeader()){ app.getSession().loginAtlassianAcc(); } } @Test(dataProvider = "validTeamsCSV", dataProviderClass = DataProviders.class) public void teamCreationTestFromHeaderCSV(TeamData team) throws InterruptedException { int teamCountBefore = app.getTeam().getTeamsCount(); app.getBoard().clickOnPlusButton(); app.getTeam().selectCreateTeamFromDropDown(); app.getTeam().fillTeamCreationForm(team); app.getTeam().submitTeamCreation(); // if(isElementPresent(By.cssSelector("[name='close']"))){ // closeInviteToTheTeamForm(); // } app.getTeam().clickLaterButton(); app.getHeader().returnToHomePage(); int teamCountAfter = app.getTeam().getTeamsCount(); Assert.assertEquals(teamCountAfter, teamCountBefore+1); } @Test(dataProvider = "validTeams", dataProviderClass = DataProviders.class) public void teamCreationTestFromHeaderWithDP (String teamName, String teamDescr) throws InterruptedException { int teamCountBefore = app.getTeam().getTeamsCount(); app.getBoard().clickOnPlusButton(); app.getTeam().selectCreateTeamFromDropDown(); app.getTeam().fillTeamCreationForm(new TeamData() .withTeamName(teamName) .withTeamDescr(teamDescr)); app.getTeam().submitTeamCreation(); // if(isElementPresent(By.cssSelector("[name='close']"))){ // closeInviteToTheTeamForm(); // } app.getTeam().clickLaterButton(); app.getHeader().returnToHomePage(); int teamCountAfter = app.getTeam().getTeamsCount(); Assert.assertEquals(teamCountAfter, teamCountBefore+1); } @Test public void teamCreationTestFromHeader() throws InterruptedException { int teamCountBefore = app.getTeam().getTeamsCount(); app.getBoard().clickOnPlusButton(); app.getTeam().selectCreateTeamFromDropDown(); app.getTeam().fillTeamCreationForm(new TeamData() .withTeamName("teamName") .withTeamDescr("teamDescr")); app.getTeam().submitTeamCreation(); // if(isElementPresent(By.cssSelector("[name='close']"))){ // closeInviteToTheTeamForm(); // } app.getTeam().clickLaterButton(); app.getHeader().returnToHomePage(); int teamCountAfter = app.getTeam().getTeamsCount(); Assert.assertEquals(teamCountAfter, teamCountBefore+1); } @Test public void teamCreationTestFromHeaderWithNameOnly() throws InterruptedException { int teamCountBefore = app.getTeam().getTeamsCount(); // String teamId = // wd.findElement(By.cssSelector("[data-test-id^=home-team-tab-section]")).getAttribute("data-test-id"); // System.out.println(teamId); app.getBoard().clickOnPlusButton(); app.getTeam().selectCreateTeamFromDropDown(); app.getTeam().fillTeamCreationForm(new TeamData() .withTeamName("teamName")); app.getTeam().submitTeamCreation(); // if(isElementPresent(By.cssSelector("[name='close']"))){ // closeInviteToTheTeamForm(); // } app.getTeam().clickLaterButton(); app.getHeader().returnToHomePage(); int teamCountAfter = app.getTeam().getTeamsCount(); Assert.assertEquals(teamCountAfter, teamCountBefore+1); } }
3e0853f28c617bdfb5533a5508a516d706a276f4
439
java
Java
app/src/main/java/com/coolweather/android/util/HttpUtil.java
oneofnormalprogrammer/CoolWeather
ad985485c6ca0dce283ddc921887a4749e25fbef
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/coolweather/android/util/HttpUtil.java
oneofnormalprogrammer/CoolWeather
ad985485c6ca0dce283ddc921887a4749e25fbef
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/coolweather/android/util/HttpUtil.java
oneofnormalprogrammer/CoolWeather
ad985485c6ca0dce283ddc921887a4749e25fbef
[ "Apache-2.0" ]
null
null
null
21.95
84
0.712984
3,531
package com.coolweather.android.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by Administrator on 2017/5/17/017. */ public class HttpUtil { public static void sendOkHttpRequest(String address, okhttp3.Callback callback){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
3e0854aaf8c57b2a3728e21acfe3dfe96f9acad9
509
java
Java
JVM/chapter02/src/com/learn/java1/ClassLoaderTest1.java
guyi-png/Notes
202cf177577a8f392660797514c539067f4c2893
[ "MIT" ]
2
2020-05-18T07:44:44.000Z
2020-10-12T11:53:11.000Z
JVM/chapter02/src/com/learn/java1/ClassLoaderTest1.java
guyi-png/Notes
202cf177577a8f392660797514c539067f4c2893
[ "MIT" ]
1
2022-03-31T20:57:54.000Z
2022-03-31T20:57:54.000Z
JVM/chapter02/src/com/learn/java1/ClassLoaderTest1.java
guyi-png/Notes
202cf177577a8f392660797514c539067f4c2893
[ "MIT" ]
1
2021-06-29T11:33:22.000Z
2021-06-29T11:33:22.000Z
31.8125
88
0.715128
3,532
package com.learn.java1; public class ClassLoaderTest1 { public static void main(String[] args) { // 获取类加载器的方式 ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); System.out.println(classLoader); System.out.println(contextClassLoader); System.out.println(systemClassLoader); } }
3e08557ce1c720c04725ec8aa14f3fa96b995369
8,595
java
Java
src/main/java/com/nowcoder/community/controller/UserController.java
Wudong-HUST/community
ce5e60c4c88fe648c8813c697234075788a2e936
[ "MIT" ]
null
null
null
src/main/java/com/nowcoder/community/controller/UserController.java
Wudong-HUST/community
ce5e60c4c88fe648c8813c697234075788a2e936
[ "MIT" ]
null
null
null
src/main/java/com/nowcoder/community/controller/UserController.java
Wudong-HUST/community
ce5e60c4c88fe648c8813c697234075788a2e936
[ "MIT" ]
null
null
null
35.962343
111
0.645375
3,533
package com.nowcoder.community.controller; import com.nowcoder.community.annotation.LoginRequired; import com.nowcoder.community.entity.Comment; import com.nowcoder.community.entity.DiscussPost; import com.nowcoder.community.entity.Page; import com.nowcoder.community.entity.User; import com.nowcoder.community.service.*; import com.nowcoder.community.util.CommunityUtil; import com.nowcoder.community.util.HostHolder; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.nowcoder.community.util.CommunityConstant.ENTITY_TYPE_POST; import static com.nowcoder.community.util.CommunityConstant.ENTITY_TYPE_USER; @Controller @RequestMapping("/user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Value("${community.path.upload}") private String uploadPath; @Value("${community.path.domain}") private String domain; @Value("${server.servlet.context-path}") private String contextPath; @Autowired private UserService userService; @Autowired private HostHolder hostHolder; @Autowired private LikeService likeService; @Autowired private FollowService followService; @Autowired private DiscussPostService discussPostService; @Autowired private CommentService commentService; @LoginRequired @RequestMapping(path = "/setting", method = RequestMethod.GET) public String getSettingPage() { return "/site/setting"; } @LoginRequired @RequestMapping(path = "/upload", method = RequestMethod.POST) public String uploadHeader(MultipartFile headerImage, Model model) { if (headerImage == null) { model.addAttribute("error", "您还没有选择图片!"); return "/site/setting"; } // 原始文件名,可能有后缀或者没有 String fileName = headerImage.getOriginalFilename(); // 截取后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); if (StringUtils.isBlank(suffix)) { model.addAttribute("error", "文件的格式不正确!"); return "/site/setting"; } // 生成随机文件名,因为可能上传的名字是重复的 fileName = CommunityUtil.generateUUID() + suffix; // 确定文件存放的路径 File dest = new File(uploadPath + "/" + fileName); try { // 存储文件 headerImage.transferTo(dest); } catch (IOException e) { logger.error("上传文件失败: " + e.getMessage()); throw new RuntimeException("上传文件失败,服务器发生异常!", e); } // 更新当前用户的头像的路径(web访问路径) // http://localhost:8080/community/user/header/xxx.png User user = hostHolder.getUser(); String headerUrl = domain + contextPath + "/user/header/" + fileName; userService.updateHeader(user.getId(), headerUrl); return "redirect:/index"; } @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET) public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) { // 服务器存放路径 fileName = uploadPath + "/" + fileName; // 文件后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); // 响应图片 response.setContentType("image/" + suffix); try ( FileInputStream fis = new FileInputStream(fileName); OutputStream os = response.getOutputStream(); ) { byte[] buffer = new byte[1024]; int b = 0; while ((b = fis.read(buffer)) != -1) { os.write(buffer, 0, b); } } catch (IOException e) { logger.error("读取头像失败: " + e.getMessage()); } } // 修改密码 @RequestMapping(path = "/updatePassword", method = RequestMethod.POST) public String updatePassword(String oldPassword, String newPassword, Model model) { User user = hostHolder.getUser(); Map<String, Object> map = userService.updatePassword(user.getId(), oldPassword, newPassword); if (map == null || map.isEmpty()) { return "redirect:/logout"; } else { model.addAttribute("oldPasswordMsg", map.get("oldPasswordMsg")); model.addAttribute("newPasswordMsg", map.get("newPasswordMsg")); return "/site/setting"; } } // 个人主页,点头像就能看 @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET) public String getProfilePage(@PathVariable("userId") int userId, Model model) { User user = userService.findUserById(userId); if (user == null) { throw new RuntimeException("该用户不存在!"); } // 用户 model.addAttribute("user", user); // 点赞数量 int likeCount = likeService.findUserLikeCount(userId); model.addAttribute("likeCount", likeCount); // 关注的用户数量 long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER); model.addAttribute("followeeCount", followeeCount); // 粉丝数量 long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId); model.addAttribute("followerCount", followerCount); // 是否已关注,当前用户登录才能看自己有没有关注 boolean hasFollowed = false; if (hostHolder.getUser() != null) { hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId); } model.addAttribute("hasFollowed", hasFollowed); return "/site/profile"; } // 我的帖子 @RequestMapping(path = "/mypost/{userId}", method = RequestMethod.GET) public String getMyPost(@PathVariable("userId") int userId, Page page, Model model) { User user = userService.findUserById(userId); if (user == null) { throw new RuntimeException("该用户不存在!"); } model.addAttribute("user", user); // 分页信息 page.setPath("/user/mypost/" + userId); page.setRows(discussPostService.findDiscussPostRows(userId)); // 帖子列表 List<DiscussPost> discussList = discussPostService .findDiscussPosts(userId, page.getOffset(), page.getLimit()); List<Map<String, Object>> discussVOList = new ArrayList<>(); if (discussList != null) { for (DiscussPost post : discussList) { Map<String, Object> map = new HashMap<>(); map.put("discussPost", post); map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId())); discussVOList.add(map); } } model.addAttribute("discussPosts", discussVOList); return "/site/my-post"; } // 我的回复 @RequestMapping(path = "/myreply/{userId}", method = RequestMethod.GET) public String getMyReply(@PathVariable("userId") int userId, Page page, Model model) { User user = userService.findUserById(userId); if (user == null) { throw new RuntimeException("该用户不存在!"); } model.addAttribute("user", user); // 分页信息 page.setPath("/user/myreply/" + userId); page.setRows(commentService.findUserCount(userId)); // 回复列表 List<Comment> commentList = commentService.findUserComments(userId, page.getOffset(), page.getLimit()); List<Map<String, Object>> commentVOList = new ArrayList<>(); if (commentList != null) { for (Comment comment : commentList) { Map<String, Object> map = new HashMap<>(); map.put("comment", comment); DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId()); map.put("discussPost", post); commentVOList.add(map); } } model.addAttribute("comments", commentVOList); return "/site/my-reply"; } }
3e08565489a34dbe7974efce88a2a935a366664a
776
java
Java
src/main/java/com/bdoemu/gameserver/model/items/templates/ItemImprovementSourceT.java
SilenceSu/S7Server491
5646a1f43d9b6383403bae2fd2fce811cad0adae
[ "Apache-2.0" ]
7
2019-04-20T06:08:38.000Z
2021-06-27T09:18:55.000Z
src/main/java/com/bdoemu/gameserver/model/items/templates/ItemImprovementSourceT.java
SilenceSu/S7Server491
5646a1f43d9b6383403bae2fd2fce811cad0adae
[ "Apache-2.0" ]
1
2019-06-29T17:58:36.000Z
2019-06-30T08:58:36.000Z
src/main/java/com/bdoemu/gameserver/model/items/templates/ItemImprovementSourceT.java
jessefjxm/S7Server491
5646a1f43d9b6383403bae2fd2fce811cad0adae
[ "Apache-2.0" ]
12
2019-04-03T11:43:48.000Z
2021-06-27T09:18:57.000Z
22.171429
75
0.630155
3,534
// // Decompiled by Procyon v0.5.30 // package com.bdoemu.gameserver.model.items.templates; import java.sql.ResultSet; import java.sql.SQLException; public class ItemImprovementSourceT { private int sourceItemKey; private int type; private int[] results; public ItemImprovementSourceT(final ResultSet rs) throws SQLException { this.results = new int[5]; this.sourceItemKey = rs.getInt("SourceItemKey"); for (int i = 0; i < this.results.length; ++i) { this.results[i] = rs.getInt("result" + i); } } public int getType() { return this.type; } public int getSourceItemKey() { return this.sourceItemKey; } public int[] getResults() { return this.results; } }
3e085820d58b56ff19d5555cc56c8111fbbcf865
11,214
java
Java
moe.apple/moe.platform.ios/src/main/java/apple/modelio/MDLVoxelArray.java
Berstanio/moe-core
d561df1f6b4f99dc9644227eb8b76e4942abc20a
[ "Apache-2.0" ]
1
2020-05-11T18:36:25.000Z
2020-05-11T18:36:25.000Z
moe.apple/moe.platform.ios/src/main/java/apple/modelio/MDLVoxelArray.java
Berstanio/moe-core
d561df1f6b4f99dc9644227eb8b76e4942abc20a
[ "Apache-2.0" ]
null
null
null
moe.apple/moe.platform.ios/src/main/java/apple/modelio/MDLVoxelArray.java
Berstanio/moe-core
d561df1f6b4f99dc9644227eb8b76e4942abc20a
[ "Apache-2.0" ]
null
null
null
35.827476
123
0.732745
3,535
/* Copyright 2014-2016 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apple.modelio; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSData; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.modelio.protocol.MDLMeshBufferAllocator; import apple.scenekit.SCNNode; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * MDLVoxelArray * [@summary] Voxel data represented on a three dimensional grid. Voxel data can * include voxels considered to be on the surface of an object, and a * series of shells on the outside and inside of the surface. */ @Generated @Library("ModelIO") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class MDLVoxelArray extends MDLObject { static { NatJ.register(); } @Generated protected MDLVoxelArray(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native MDLVoxelArray alloc(); @Generated @Selector("allocWithZone:") @MappedReturn(ObjCObjectMapper.class) public static native Object allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") @MappedReturn(ObjCObjectMapper.class) public static native Object new_objc(); @Generated @Selector("objectWithSCNNode:") public static native MDLVoxelArray objectWithSCNNode(SCNNode scnNode); @Generated @Selector("objectWithSCNNode:bufferAllocator:") public static native MDLVoxelArray objectWithSCNNodeBufferAllocator(SCNNode scnNode, @Mapped(ObjCObjectMapper.class) MDLMeshBufferAllocator bufferAllocator); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); /** * Creates a coarse mesh from the voxel grid */ @Generated @Selector("coarseMesh") public native MDLMesh coarseMesh(); @Generated @Selector("coarseMeshUsingAllocator:") public native MDLMesh coarseMeshUsingAllocator(@Mapped(ObjCObjectMapper.class) MDLMeshBufferAllocator allocator); /** * Converts volume grid into a signed shell field by surrounding the surface voxels, which have shell * level values of zero, by an inner layer of voxels with shell level values of negative one and an * outer layer of voxels with shell level values of positive one. * * The volume model must be closed in order to generate a signed shell field. */ @Generated @Selector("convertToSignedShellField") public native void convertToSignedShellField(); /** * The number of voxels in the grid */ @Generated @Selector("count") @NUInt public native long count(); /** * Difference modifies the voxel grid so that voxels also in the supplied voxel grid are removed. * It is assumed that the spatial voxel extent of one voxel in the supplied grid is the same as that of the voxel grid. * Note that the shell level data will be cleared. */ @Generated @Selector("differenceWithVoxels:") public native void differenceWithVoxels(MDLVoxelArray voxels); @Generated @Selector("init") public native MDLVoxelArray init(); /** * Initialize a voxel grid from an MDLAsset. Attempts to create a closed volume * model by applying "patches" of radius patchRadius to any holes found in the * orginal mesh. Choose a patch radius that will be large enough to fill in the largest * hole in the model. */ @Generated @Selector("initWithAsset:divisions:patchRadius:") public native MDLVoxelArray initWithAssetDivisionsPatchRadius(MDLAsset asset, int divisions, float patchRadius); /** * Intersection modifies the voxel grid so that only voxels that are also in the supplied voxel grid are retained. * It is assumed that the spatial voxel extent of one voxel in the supplied grid is the same as that of the voxel grid. * Note that the shell level data will be cleared. */ @Generated @Selector("intersectWithVoxels:") public native void intersectWithVoxels(MDLVoxelArray voxels); /** * Returns whether or not the volume grid is in a valid signed shell field form. * * This property will be set to YES after calling generateSignedShellField. All other * methods that modify the voxel grid will cause this property to be set to NO. Setting * shellFieldInteriorThickness and shellFieldExteriorThickness will not affect the value * of this property. */ @Generated @Selector("isValidSignedShellField") public native boolean isValidSignedShellField(); /** * Creates a smooth mesh from the voxel grid */ @Generated @Selector("meshUsingAllocator:") public native MDLMesh meshUsingAllocator(@Mapped(ObjCObjectMapper.class) MDLMeshBufferAllocator allocator); /** * If voxel grid is in a valid signed shell field form, sets the exterior thickness to the desired width, * as measured from the model surface. If the voxel grid is not in a valid signed shell field form, the * value of this property is zero. */ @Generated @Selector("setShellFieldExteriorThickness:") public native void setShellFieldExteriorThickness(float value); /** * If voxel grid is in a valid signed shell field form, sets the interior thickness to the desired width, * as measured from the model surface. If the voxel grid is not in a valid signed shell field form, the * value of this property is zero. */ @Generated @Selector("setShellFieldInteriorThickness:") public native void setShellFieldInteriorThickness(float value); /** * Set voxels corresponding to a mesh. * Routine will attempt to create a closed volume model by applying "patches" of * a given radius to any holes it may find in the mesh. */ @Generated @Selector("setVoxelsForMesh:divisions:patchRadius:") public native void setVoxelsForMeshDivisionsPatchRadius(MDLMesh mesh, int divisions, float patchRadius); /** * If voxel grid is in a valid signed shell field form, sets the exterior thickness to the desired width, * as measured from the model surface. If the voxel grid is not in a valid signed shell field form, the * value of this property is zero. */ @Generated @Selector("shellFieldExteriorThickness") public native float shellFieldExteriorThickness(); /** * If voxel grid is in a valid signed shell field form, sets the interior thickness to the desired width, * as measured from the model surface. If the voxel grid is not in a valid signed shell field form, the * value of this property is zero. */ @Generated @Selector("shellFieldInteriorThickness") public native float shellFieldInteriorThickness(); /** * Union modifies the voxel grid to be the merger with the supplied voxel grid. * It is assumed that the spatial voxel extent of one voxel in the supplied grid is the same as that of the voxel grid. * Note that the shell level data will be cleared. */ @Generated @Selector("unionWithVoxels:") public native void unionWithVoxels(MDLVoxelArray voxels); /** * Returns an NSData containing the indices of all voxels in the voxel grid */ @Generated @Selector("voxelIndices") public native NSData voxelIndices(); }
3e08585389a0d28f4729ea2c8e04d20ff78f1f27
313
java
Java
xzazt-config/xzazt-config-core/src/main/java/com/xzazt/annotation/OrderIndex.java
xzzt/xzazt-pom
d86e8f6b9c021ab8c9a91c61546168fada5d216f
[ "MIT" ]
1
2019-03-24T09:32:43.000Z
2019-03-24T09:32:43.000Z
xzazt-config/xzazt-config-core/src/main/java/com/xzazt/annotation/OrderIndex.java
xzzt/xzazt-pom
d86e8f6b9c021ab8c9a91c61546168fada5d216f
[ "MIT" ]
null
null
null
xzazt-config/xzazt-config-core/src/main/java/com/xzazt/annotation/OrderIndex.java
xzzt/xzazt-pom
d86e8f6b9c021ab8c9a91c61546168fada5d216f
[ "MIT" ]
null
null
null
24.076923
44
0.808307
3,536
package com.xzazt.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface OrderIndex { int num() default 0; }
3e0858b8e33189571c46b6039882e58e64dec34f
369
java
Java
src/main/java/com/itcwt/ss/util/ShellUtil.java
itcwt/ss-union
0b4170413e54784d05458bda789e8f865afac34c
[ "MIT" ]
null
null
null
src/main/java/com/itcwt/ss/util/ShellUtil.java
itcwt/ss-union
0b4170413e54784d05458bda789e8f865afac34c
[ "MIT" ]
null
null
null
src/main/java/com/itcwt/ss/util/ShellUtil.java
itcwt/ss-union
0b4170413e54784d05458bda789e8f865afac34c
[ "MIT" ]
null
null
null
16.772727
53
0.569106
3,537
package com.itcwt.ss.util; import java.io.IOException; /** * @author cwt * @create by cwt on 2018-10-18 20:52 */ public class ShellUtil { public void runShell(String shPath){ Process exec = null; try { exec = Runtime.getRuntime().exec(shPath); } catch (IOException e) { e.printStackTrace(); } } }
3e085900dcdf31eb8125353f12475b9df3a3fd10
7,660
java
Java
app/src/main/java/com/challengers/trackmyorder/OrderDetailActivity.java
kalyandechiraju/track-my-order
0b8b35ddc1b16bf4e94cc046ce9f2a2d47dbc10f
[ "MIT" ]
10
2016-09-08T19:08:13.000Z
2021-06-04T02:50:25.000Z
app/src/main/java/com/challengers/trackmyorder/OrderDetailActivity.java
kalyandechiraju/track-my-order
0b8b35ddc1b16bf4e94cc046ce9f2a2d47dbc10f
[ "MIT" ]
1
2018-09-13T20:58:27.000Z
2018-09-13T20:58:27.000Z
app/src/main/java/com/challengers/trackmyorder/OrderDetailActivity.java
kalyandechiraju/track-my-order
0b8b35ddc1b16bf4e94cc046ce9f2a2d47dbc10f
[ "MIT" ]
11
2018-08-22T02:09:40.000Z
2021-07-11T15:45:21.000Z
56.323529
246
0.549869
3,538
package com.challengers.trackmyorder; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.challengers.trackmyorder.util.Constants; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.squareup.picasso.Picasso; public class OrderDetailActivity extends AppCompatActivity { TextView orderIdText, orderDelBoy, orderUser, locationText; TextView itemInOrderText; TextView statusText; ImageView staticUserLocationImage; String orderId, item, status, userId, delBoyId, mapType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_detail); if(getIntent().hasExtra(Constants.ORDER_ID)) { orderId = getIntent().getStringExtra(Constants.ORDER_ID); mapType = getIntent().getStringExtra(Constants.MAPS_TYPE); if(orderId != null) { //Realm realm = Realm.getDefaultInstance(); //Order order = realm.where(Order.class).equalTo("orderId", orderId).findFirst(); //final User user = realm.where(User.class).equalTo("currentOrderId", orderId).findFirst(); orderIdText = (TextView) findViewById(R.id.order_detail_id); itemInOrderText = (TextView) findViewById(R.id.order_detail_item); statusText = (TextView) findViewById(R.id.order_detail_status); staticUserLocationImage = (ImageView) findViewById(R.id.user_location_static_map); orderDelBoy = (TextView) findViewById(R.id.order_delBoy); orderUser = (TextView) findViewById(R.id.order_user); locationText = (TextView) findViewById(R.id.order_details_location_text); Firebase currentOrderRef = Constants.orderRef.child("/" + orderId); currentOrderRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { item = (String) dataSnapshot.child("item").getValue(); status = (String) dataSnapshot.child("status").getValue(); userId = (String) dataSnapshot.child("userId").getValue(); delBoyId = (String) dataSnapshot.child("delBoyId").getValue(); orderIdText.setText(orderId); itemInOrderText.setText(item); if(status.equals(Constants.STATUS_GOING_TO_PICKUP)) { statusText.setText("Going to pickup"); } else if (status.equals(Constants.STATUS_PICKEDUP)) { statusText.setText("Item picked up"); } else if(status.equals(Constants.STATUS_DELIVERED)) { statusText.setText("Item Delivered"); } orderDelBoy.setText(delBoyId); orderUser.setText(userId); if (!status.equals(Constants.STATUS_DELIVERED)) { locationText.setVisibility(View.VISIBLE); if (mapType.equals("D")) { Firebase currentUserRef = Constants.userRef.child("/" + userId); currentUserRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String latLan = (String) dataSnapshot.child("currentLocation").getValue(); String placeUrl = "https://maps.googleapis.com/maps/api/staticmap?center=" + latLan + "&zoom=17&size=1200x250&maptype=roadmap&markers=color:red%7C" + latLan + "&key=AIzaSyBP_hEMi4Pu0VGFRRzeFH4Podfkf2qGEks"; Picasso.with(OrderDetailActivity.this).load(placeUrl).resize(staticUserLocationImage.getWidth(), 300).centerCrop().into(staticUserLocationImage); } @Override public void onCancelled(FirebaseError firebaseError) { Toast.makeText(OrderDetailActivity.this, "Check network connection", Toast.LENGTH_SHORT).show(); } }); } else if (mapType.equals("U")) { Firebase currentDelBoyRef = Constants.delboyRef.child("/" + delBoyId); currentDelBoyRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String latLan = (String) dataSnapshot.child("currentLocation").getValue(); String placeUrl = "https://maps.googleapis.com/maps/api/staticmap?center=" + latLan + "&zoom=17&size=1200x250&maptype=roadmap&markers=color:red%7C" + latLan + "&key=AIzaSyBP_hEMi4Pu0VGFRRzeFH4Podfkf2qGEks"; Picasso.with(OrderDetailActivity.this).load(placeUrl).resize(staticUserLocationImage.getWidth(), 300).centerCrop().into(staticUserLocationImage); } @Override public void onCancelled(FirebaseError firebaseError) { Toast.makeText(OrderDetailActivity.this, "Check network connection", Toast.LENGTH_SHORT).show(); } }); } staticUserLocationImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Go to Map Activity Intent intent = new Intent(OrderDetailActivity.this, MapsActivity.class); intent.putExtra(Constants.MAPS_TYPE, mapType); intent.putExtra(Constants.CURRENT_USER, userId); intent.putExtra(Constants.CURRENT_DELBOY, delBoyId); startActivity(intent); } }); } } @Override public void onCancelled(FirebaseError firebaseError) { Toast.makeText(OrderDetailActivity.this, "Check network connection", Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(this, "Invalid Order", Toast.LENGTH_SHORT).show(); finish(); } } /*@Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, DboyActivity.class); intent.putExtra(Constants.CURRENT_DELBOY, Prefs.getString(Constants.CURRENT_DELBOY, null)); startActivity(intent); }*/ }
3e08590ae88fbe2929dc8efec31e8f36defd14e4
4,021
java
Java
fibonacci-service/src/test/java/com/examples/springcloudstarter/fibonacci/services/SimpleFibonacciServiceImplTest.java
reachpavan/my-spring-cloud-starter
d1d56b3a28662205a542deeb35eb212b9922ee95
[ "MIT" ]
null
null
null
fibonacci-service/src/test/java/com/examples/springcloudstarter/fibonacci/services/SimpleFibonacciServiceImplTest.java
reachpavan/my-spring-cloud-starter
d1d56b3a28662205a542deeb35eb212b9922ee95
[ "MIT" ]
null
null
null
fibonacci-service/src/test/java/com/examples/springcloudstarter/fibonacci/services/SimpleFibonacciServiceImplTest.java
reachpavan/my-spring-cloud-starter
d1d56b3a28662205a542deeb35eb212b9922ee95
[ "MIT" ]
null
null
null
40.21
110
0.694852
3,539
package com.examples.springcloudstarter.fibonacci.services; import com.examples.springcloudstarter.fibonacci.ApplicationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import static java.math.BigInteger.valueOf; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class SimpleFibonacciServiceImplTest { @Autowired SimpleFibonacciServiceImpl service; @Test public void validateCount() throws ApplicationException { assertTrue("when empty create error", service.validateCount(null).isPresent()); assertTrue("when min create error", service.validateCount(-1).isPresent()); assertTrue("when max create error", service.validateCount(100001).isPresent()); assertFalse("when good value shouldn't create error", service.validateCount(10).isPresent()); } @Test public void getFibonacciSeries() throws ApplicationException { ApplicationException exception = null; try { service.getFibonacciSeries(-1); } catch (ApplicationException ex) { exception = ex; } assertNotNull("throw exception for negative cases", exception); assertEquals("count should match series length", 5 , service.getFibonacciSeries(5).size()); assertArrayEquals("series should start with zero", bigIntegerArray(0, 1, 1, 2, 3), service.getFibonacciSeries(5).toArray()); } @Test public void findSeriesInStore() { assertFalse("key is not in store", service.findSeriesInStore(5).isPresent()); BigInteger[] expected = bigIntegerArray(0, 1, 1, 2, 3); service.addSeriesToStore(5, Arrays.asList(expected)); assertArrayEquals("match store values", expected, service.findSeriesInStore(5).get().toArray()); } @Test public void addSeriesToStore() { BigInteger[] expected = bigIntegerArray(0, 1, 1, 2, 3); service.addSeriesToStore(5, Arrays.asList(expected)); assertArrayEquals("match store values", expected, service.findSeriesInStore(5).get().toArray()); } @Test public void generateFibonacciSeries() { assertArrayEquals("test with -1", service.generateFibonacciSeries(-1).toArray(), bigIntegerArray()); assertArrayEquals("test with 0", service.generateFibonacciSeries(0).toArray(), bigIntegerArray()); assertArrayEquals("test with 1", service.generateFibonacciSeries(1).toArray(), bigIntegerArray(0)); assertArrayEquals("test with 2", service.generateFibonacciSeries(2).toArray(), bigIntegerArray(0, 1)); assertArrayEquals("test with 3", service.generateFibonacciSeries(3).toArray(), bigIntegerArray(0, 1, 1)); assertArrayEquals("test with 4", service.generateFibonacciSeries(4).toArray(), bigIntegerArray(0, 1, 1, 2)); assertArrayEquals("test with 5", service.generateFibonacciSeries(5).toArray(), bigIntegerArray(0, 1, 1, 2, 3)); BigInteger actual = new BigInteger("222232244629420445529739893461909967206666939096499764990979600"); assertEquals("test with higher integer value", service.generateFibonacciSeries(301).get(300), actual); } private BigInteger[] bigIntegerArray(long ... args) { return LongStream.of(args).boxed().map(BigInteger::valueOf).toArray(BigInteger[]::new); } }
3e08590df80abb668ab76f2814935396f28d2488
9,074
java
Java
bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/CorrelationKeySetMigration.java
apache/ode
a0c2d1a3c24268523c81b4ddc125eb05d758c6f5
[ "Apache-2.0" ]
20
2015-06-03T05:42:40.000Z
2022-02-15T05:22:13.000Z
bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/CorrelationKeySetMigration.java
apache/attic-ode
a0c2d1a3c24268523c81b4ddc125eb05d758c6f5
[ "Apache-2.0" ]
1
2016-03-10T22:34:09.000Z
2016-03-10T22:34:09.000Z
bpel-runtime/src/main/java/org/apache/ode/bpel/engine/migration/CorrelationKeySetMigration.java
apache/ode
a0c2d1a3c24268523c81b4ddc125eb05d758c6f5
[ "Apache-2.0" ]
57
2015-03-12T12:45:09.000Z
2021-11-10T19:09:27.000Z
45.59799
125
0.62883
3,540
/* * 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.ode.bpel.engine.migration; import org.apache.ode.bpel.engine.BpelProcess; import org.apache.ode.bpel.engine.OutstandingRequestManager; import org.apache.ode.bpel.engine.ReplacementMapImpl; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.ode.bpel.dao.ProcessInstanceDAO; import org.apache.ode.bpel.dao.ProcessDAO; import org.apache.ode.bpel.runtime.Selector; import org.apache.ode.bpel.common.CorrelationKey; import org.apache.ode.bpel.common.CorrelationKeySet; import org.apache.ode.bpel.obj.OProcess; import org.apache.ode.jacob.vpu.ExecutionQueueImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.namespace.QName; import java.util.Set; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.io.ObjectStreamClass; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /** * Migrates the database from using single correlations to multiple correlations support. */ public class CorrelationKeySetMigration implements Migration { private static final Logger __log = LoggerFactory.getLogger(CorrelationKeySetMigration.class); public boolean migrate(Set<BpelProcess> registeredProcesses, BpelDAOConnection connection) { boolean v1First = true; for (BpelProcess process : registeredProcesses) { ProcessDAO processDao = connection.getProcess(process.getConf().getProcessId()); Collection<ProcessInstanceDAO> pis = processDao.getActiveInstances(); // Migrate the correlation key stored in the jacob state of the instance for (ProcessInstanceDAO instance : pis) { __log.debug("Migrating correlation key in jacob for instance " + instance.getInstanceId()); OProcess oproc = findOProcess(registeredProcesses, instance.getProcess().getProcessId()); if (v1First) { if (!updateV1Key(instance, oproc)) { v1First = false; updateV2Key(instance, oproc); } } else { if (!updateV2Key(instance, oproc)) { v1First = true; updateV1Key(instance, oproc); } } } } return true; } private boolean updateV1Key(ProcessInstanceDAO instance, OProcess oproc) { ExecutionQueueImpl soup; try { soup = readOldState(instance, oproc, getClass().getClassLoader(), true); if (soup == null) return false; } catch (Exception e) { __log.debug(" failed to read a v1 state for instance " + instance.getInstanceId()); ExecutionQueueImpl._classDescriptors.clear(); return false; } try { OutstandingRequestManager orm = (OutstandingRequestManager) soup.getGlobalData(); for (OutstandingRequestManager.Entry entry : orm._byChannel.values()) { Selector[] newSelectors = new Selector[entry.selectors.length]; int index = 0; for (Object selector : entry.selectors) { OldSelector sel = (OldSelector)selector; Object selCKey = sel.correlationKey; if (selCKey != null) { OldCorrelationKey old = (OldCorrelationKey) selCKey; __log.debug(" Changing V1 key " + old.toCanonicalString()); CorrelationKeySet newKeySet = new CorrelationKeySet(); newKeySet.add(new CorrelationKey(""+old.getCSetId(), old.getValues())); Selector newSelector = new Selector(sel.idx, sel.plinkInstance, sel.opName, sel.oneWay, sel.messageExchangeId, newKeySet, "one"); newSelector.correlationKey = new CorrelationKey(""+old.getCSetId(), old.getValues()); newSelectors[index++] = newSelector; } } entry.selectors = newSelectors; } writeOldState(instance, soup); } finally { ExecutionQueueImpl._classDescriptors.clear(); } return true; } private boolean updateV2Key(ProcessInstanceDAO instance, OProcess oproc) { ExecutionQueueImpl soup; try { soup = readOldState(instance, oproc, getClass().getClassLoader(), false); if (soup == null) return false; } catch (Exception e) { __log.debug(" failed to read a v2 state for instance " + instance.getInstanceId()); ExecutionQueueImpl._classDescriptors.clear(); return false; } OutstandingRequestManager orm = (OutstandingRequestManager) soup.getGlobalData(); for (OutstandingRequestManager.Entry entry : orm._byChannel.values()) { Selector[] newSelectors = new Selector[entry.selectors.length]; int index = 0; for (Object selector : entry.selectors) { OldSelector sel = (OldSelector)selector; CorrelationKey selCKey = (CorrelationKey) sel.correlationKey; if (selCKey != null) { __log.debug(" Changing V2 key " + selCKey.toCanonicalString()); CorrelationKeySet newKeySet = new CorrelationKeySet(); newKeySet.add(new CorrelationKey(""+selCKey.getCorrelationSetName(), selCKey.getValues())); Selector newSelector = new Selector(sel.idx, sel.plinkInstance, sel.opName, sel.oneWay, sel.messageExchangeId, newKeySet, "one"); newSelector.correlationKey = new CorrelationKey(""+selCKey.getCorrelationSetName(), selCKey.getValues()); newSelectors[index++] = newSelector; } } entry.selectors = newSelectors; } writeOldState(instance, soup); return true; } private ExecutionQueueImpl readOldState(ProcessInstanceDAO instance, OProcess oprocess, ClassLoader cl, boolean changeKey) { if (instance.getExecutionState() == null) return null; try { ExecutionQueueImpl soup = new ExecutionQueueImpl(cl); ObjectStreamClass osc; if (changeKey) { osc = ObjectStreamClass.lookup(Class.forName( "org.apache.ode.bpel.engine.migration.OldCorrelationKey", true, cl)); ExecutionQueueImpl._classDescriptors.put("org.apache.ode.bpel.common.CorrelationKey", osc); } osc = ObjectStreamClass.lookup(Class.forName( "org.apache.ode.bpel.engine.migration.OldSelector", true, cl)); ExecutionQueueImpl._classDescriptors.put("org.apache.ode.bpel.runtime.Selector", osc); osc = ObjectStreamClass.lookup(Class.forName( "[Lorg.apache.ode.bpel.engine.migration.OldSelector;", true, getClass().getClassLoader())); ExecutionQueueImpl._classDescriptors.put("[Lorg.apache.ode.bpel.runtime.Selector;", osc); soup.setReplacementMap(new ReplacementMapImpl(oprocess)); ByteArrayInputStream iis = new ByteArrayInputStream(instance.getExecutionState()); soup.read(iis); return soup; } catch (Exception e) { throw new RuntimeException(e); } } private void writeOldState(ProcessInstanceDAO instance, ExecutionQueueImpl soup) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); soup.write(bos); bos.close(); instance.setExecutionState(bos.toByteArray()); ExecutionQueueImpl._classDescriptors.clear(); } catch (Exception e) { throw new RuntimeException(e); } } private OProcess findOProcess(Set<BpelProcess> registeredProcesses, QName name) { for (BpelProcess process : registeredProcesses) { if (process.getConf().getProcessId().equals(name)) return process.getOProcess(); } return null; } }
3e0859800750dba74a0b2f1ae2f839c70f42c7a2
298
java
Java
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/HttpMvcConfig.java
Hippoom/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
6
2017-08-11T02:50:08.000Z
2018-11-27T06:16:05.000Z
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/HttpMvcConfig.java
tanbinh123/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
1
2017-07-03T13:43:25.000Z
2017-07-03T14:07:43.000Z
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/HttpMvcConfig.java
tanbinh123/wechat-mp-starter
1a12d3d5be2788c9913cd8b423b1756bd5a73f2e
[ "MIT" ]
5
2017-07-03T06:51:02.000Z
2022-02-11T03:29:14.000Z
27.090909
67
0.83557
3,541
package com.github.hippoom.wechat.mp.examples.oauth2.http; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan("com.github.hippoom.wechat.mp.examples.oauth2.http") @Configuration public class HttpMvcConfig { }
3e085bb30519e6e6f1d0437ff155078795273e31
1,485
java
Java
Personal Meteor Fall/src/application/Gravity.java
EudyContreras/Meteor-Fall-FX
4b0432af335e8b3777de6cde5b090265f206263a
[ "MIT" ]
null
null
null
Personal Meteor Fall/src/application/Gravity.java
EudyContreras/Meteor-Fall-FX
4b0432af335e8b3777de6cde5b090265f206263a
[ "MIT" ]
null
null
null
Personal Meteor Fall/src/application/Gravity.java
EudyContreras/Meteor-Fall-FX
4b0432af335e8b3777de6cde5b090265f206263a
[ "MIT" ]
null
null
null
19.285714
66
0.63367
3,542
package application; public class Gravity { private Boolean falling = true; private Boolean notDestroyed = true; private float gravity = 0.4f; private float x,y = 0; private float xVel, yVel = 0; private float maxSpeed = 4; public Gravity(float x, float y, float xVel, float yVel ){ this.x = x; this.y = y; this.xVel = xVel; this.yVel = yVel; } public void GravityG(float x, float y, float xVel, float yVel ){ this.x = x; this.y = y; this.xVel = xVel; this.yVel = yVel; } public Boolean getFalling() { return falling; } public float getGravity() { return gravity; } public void setGravity(float gravity) { this.gravity = gravity; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public float getxVel() { return xVel; } public void setxVel(float xVel) { this.xVel = xVel; } public float getyVel() { return yVel; } public void setyVel(float yVel) { this.yVel = yVel; } public void setFalling(Boolean falling) { this.falling = falling; } public Boolean getNotDestroyed() { return notDestroyed; } public void setNotDestroyed(Boolean notDestroyed) { this.notDestroyed = notDestroyed; } public float getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(float maxSpeed) { this.maxSpeed = maxSpeed; } }
3e085bb72c90f8c8b830baf9e26a692b48b349b7
1,483
java
Java
core/src/java/org/hypergraphdb/transaction/HGTransactionConfig.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
186
2015-07-09T06:00:54.000Z
2022-03-16T01:14:40.000Z
core/src/java/org/hypergraphdb/transaction/HGTransactionConfig.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
27
2015-08-01T20:33:10.000Z
2022-03-08T21:11:23.000Z
core/src/java/org/hypergraphdb/transaction/HGTransactionConfig.java
OpenKGC/hypergraphdb
05073f5082df60577e48af283311172dd3f2f847
[ "Apache-2.0" ]
56
2015-10-15T10:00:14.000Z
2022-03-12T20:56:14.000Z
23.919355
90
0.656777
3,543
package org.hypergraphdb.transaction; /** * * <p> * Encapsulates configuration parameters for a single transaction. * </p> * * @author Borislav Iordanov * */ public class HGTransactionConfig { public static final HGTransactionConfig DEFAULT = new HGTransactionConfig(); public static final HGTransactionConfig NO_STORAGE = new HGTransactionConfig(); public static final HGTransactionConfig READONLY = new HGTransactionConfig(); public static final HGTransactionConfig WRITE_UPGRADABLE = new HGTransactionConfig(); static { NO_STORAGE.setNoStorage(true); READONLY.setReadonly(true); WRITE_UPGRADABLE.setWriteUpgradable(true); } private boolean noStorage = false; private boolean readonly = false; private boolean writeUpgradable = false; public boolean isNoStorage() { return noStorage; } public void setNoStorage(boolean noStorage) { this.noStorage = noStorage; } public boolean isReadonly() { return readonly; } public void setReadonly(boolean readonly) { this.readonly = readonly; writeUpgradable = false; } public boolean isWriteUpgradable() { return writeUpgradable; } public void setWriteUpgradable(boolean writeUpgradable) { this.writeUpgradable = writeUpgradable; if (writeUpgradable) readonly = true; } }
3e085c146987587851124c9f8c9f77aa1d1d8f9c
1,392
java
Java
ml4j-builders-api/src/main/java/org/ml4j/nn/components/builders/axons/UncompletedPoolingAxonsBuilder.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
1
2018-07-24T21:14:28.000Z
2018-07-24T21:14:28.000Z
ml4j-builders-api/src/main/java/org/ml4j/nn/components/builders/axons/UncompletedPoolingAxonsBuilder.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
6
2017-10-24T17:55:47.000Z
2020-01-07T13:19:06.000Z
ml4j-builders-api/src/main/java/org/ml4j/nn/components/builders/axons/UncompletedPoolingAxonsBuilder.java
ml4j/ml4j-api
cbd2db2fcde5d6f9ea87d133eb2c57df8066a241
[ "Apache-2.0" ]
3
2017-09-29T14:44:58.000Z
2018-03-07T07:38:02.000Z
30.26087
100
0.785201
3,544
/* * 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.ml4j.nn.components.builders.axons; import org.ml4j.nn.neurons.Neurons3D; public interface UncompletedPoolingAxonsBuilder<C> extends UncompletedAxonsBuilder<Neurons3D, C> { UncompletedPoolingAxonsBuilder<C> withStride(int widthStride, int heightStride); UncompletedPoolingAxonsBuilder<C> withFilterSize(int width, int height); UncompletedPoolingAxonsBuilder<C> withPadding(int widthPadding, int heightPadding); UncompletedPoolingAxonsBuilder<C> withValidPadding(); UncompletedPoolingAxonsBuilder<C> withSamePadding(); boolean isScaleOutputs(); UncompletedPoolingAxonsBuilder<C> withScaledOutputs(); int getStrideWidth(); int getStrideHeight(); int getPaddingWidth(); int getPaddingHeight(); Integer getFilterHeight(); Integer getFilterWidth(); }
3e085d28b335fdbcb38ea18d337a49a1962c6523
1,453
java
Java
src/main/java/org/tucke/jtt809/packet/common/OuterPacket.java
tucke/java-jtt809-2011
416eed913c646f568d7d3613a7ee626ba8ba68e1
[ "MIT" ]
9
2021-12-01T02:16:24.000Z
2022-01-07T01:38:41.000Z
src/main/java/org/tucke/jtt809/packet/common/OuterPacket.java
tucke/java-jtt809-2011
416eed913c646f568d7d3613a7ee626ba8ba68e1
[ "MIT" ]
null
null
null
src/main/java/org/tucke/jtt809/packet/common/OuterPacket.java
tucke/java-jtt809-2011
416eed913c646f568d7d3613a7ee626ba8ba68e1
[ "MIT" ]
1
2021-12-01T05:59:06.000Z
2021-12-01T05:59:06.000Z
19.635135
68
0.611149
3,545
package org.tucke.jtt809.packet.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author tucke */ @SuppressWarnings("SpellCheckingInspection") @AllArgsConstructor @NoArgsConstructor @Data public class OuterPacket implements Serializable { private static final long serialVersionUID = 1L; /** * 数据长度(包括头标识、数据头、数据体和尾标识) */ private long length; /** * 报文序列号 * 占用四个字节,为发送信息的序列号,用于接收方检测是否有信息的丢失,上级平台和下级平台接自己发送数据包的个数计数,互不影响。 * 程序开始运行时等于零,发送第一帧数据时开始计数,到最大数后自动归零 */ private long sn; /** * 业务数据类型 */ private int id; /** * 下级平台接入码,上级平台给下级平台分配唯一标识码 */ private int gnsscenterId; /** * 协议版本号标识,上下级平台之间采用的标准协议版编号 * 长度为 3 个字节来表示,0x01 0x02 0x0F 表示的版本号是 v1.2.15,以此类推 */ private String version; /** * 报文加密标识位 * 0 - 报文不加密 * 1 - 报文加密, 后继相应业务的数据体采用 ENCRYPT_KEY 对应的密钥进行加密处理 */ private byte encryptFlag; /** * 数据加密解密的密匙,长度为 4 个字节 */ private long encryptKey; /** * 消息体 */ private byte[] body; /** * 数据 CRC 校验码 */ private int crcCode; public OuterPacket(int id, byte[] body) { this.id = id; this.body = body; } public OuterPacket(int id, int gnsscenterId, byte[] body) { this.id = id; this.gnsscenterId = gnsscenterId; this.body = body; } }
3e085df890646cdfa25604ce2a38451779e838e3
1,733
java
Java
hermes-management/src/main/java/pl/allegro/tech/hermes/management/domain/subscription/health/problem/MalfunctioningIndicator.java
bjo2008cnx/mq_on_kafka
25cb580225f2ec56b4b8b48631cb4f9edca57f66
[ "Apache-2.0" ]
null
null
null
hermes-management/src/main/java/pl/allegro/tech/hermes/management/domain/subscription/health/problem/MalfunctioningIndicator.java
bjo2008cnx/mq_on_kafka
25cb580225f2ec56b4b8b48631cb4f9edca57f66
[ "Apache-2.0" ]
null
null
null
hermes-management/src/main/java/pl/allegro/tech/hermes/management/domain/subscription/health/problem/MalfunctioningIndicator.java
bjo2008cnx/mq_on_kafka
25cb580225f2ec56b4b8b48631cb4f9edca57f66
[ "Apache-2.0" ]
null
null
null
44.435897
115
0.807271
3,546
package pl.allegro.tech.hermes.management.domain.subscription.health.problem; import pl.allegro.tech.hermes.api.SubscriptionHealth; import pl.allegro.tech.hermes.management.domain.subscription.health.SubscriptionHealthContext; import pl.allegro.tech.hermes.management.domain.subscription.health.SubscriptionMetrics; import static pl.allegro.tech.hermes.api.SubscriptionHealth.Problem.MALFUNCTIONING; public class MalfunctioningIndicator extends AbstractSubscriptionHealthProblemIndicator { private final double max5xxErrorsRatio; private final double minSubscriptionRateForReliableMetrics; public MalfunctioningIndicator(double max5xxErrorsRatio, double minSubscriptionRateForReliableMetrics) { this.max5xxErrorsRatio = max5xxErrorsRatio; this.minSubscriptionRateForReliableMetrics = minSubscriptionRateForReliableMetrics; } @Override public boolean problemOccurs(SubscriptionHealthContext context) { SubscriptionMetrics subscriptionMetrics = context.getSubscriptionMetrics(); return areSubscriptionMetricsReliable(subscriptionMetrics) && isCode5xxErrorsRateHigh(subscriptionMetrics); } private boolean areSubscriptionMetricsReliable(SubscriptionMetrics subscriptionMetrics) { return subscriptionMetrics.getRate() > minSubscriptionRateForReliableMetrics; } private boolean isCode5xxErrorsRateHigh(SubscriptionMetrics subscriptionMetrics) { double code5xxErrorsRate = subscriptionMetrics.getCode5xxErrorsRate(); double rate = subscriptionMetrics.getRate(); return code5xxErrorsRate > max5xxErrorsRatio * rate; } @Override public SubscriptionHealth.Problem getProblem() { return MALFUNCTIONING; } }
3e085e32a9c7d8979a1d09ff08da1910ac692148
4,712
java
Java
main/boofcv-ip/src/test/java/boofcv/alg/filter/binary/TestThresholdNiblackFamily.java
TheBricktop/BoofCV
3ebe042030d509ea958c6ac90c21f2bfd872c72a
[ "Apache-2.0" ]
782
2015-01-06T03:09:49.000Z
2022-03-31T04:17:26.000Z
main/boofcv-ip/src/test/java/boofcv/alg/filter/binary/TestThresholdNiblackFamily.java
TheBricktop/BoofCV
3ebe042030d509ea958c6ac90c21f2bfd872c72a
[ "Apache-2.0" ]
205
2015-03-19T15:36:02.000Z
2022-03-25T05:48:18.000Z
main/boofcv-ip/src/test/java/boofcv/alg/filter/binary/TestThresholdNiblackFamily.java
TheBricktop/BoofCV
3ebe042030d509ea958c6ac90c21f2bfd872c72a
[ "Apache-2.0" ]
241
2015-01-12T13:23:36.000Z
2022-02-25T07:38:48.000Z
28.385542
101
0.64983
3,547
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.filter.binary; import boofcv.BoofTesting; import boofcv.alg.misc.ImageMiscOps; import boofcv.alg.misc.ImageStatistics; import boofcv.struct.ConfigLength; import boofcv.struct.image.GrayF32; import boofcv.struct.image.GrayU8; import boofcv.testing.BoofStandardJUnit; import org.junit.jupiter.api.Test; /** * @author Peter Abeles */ public class TestThresholdNiblackFamily extends BoofStandardJUnit { /** * Provide it a simple input image with obvious thresholding. There will be regions of white space * which exceed its radius. */ @Test void simple() { // Niblack has issues with this scenario simple(ThresholdNiblackFamily.Variant.SAUVOLA); simple(ThresholdNiblackFamily.Variant.WOLF_JOLION); } void simple(ThresholdNiblackFamily.Variant variant) { int width = 11; GrayU8 expected = new GrayU8(30, 35); for (int y = width/2; y < expected.height - width/2; y++) { expected.set(20, y, 1); expected.set(21, y, 1); expected.set(22, y, 1); } GrayF32 input = new GrayF32(expected.width, expected.height); for (int i = 0; i < input.width*input.height; i++) { input.data[i] = expected.data[i] == 0 ? 255 : 0; } GrayU8 found = new GrayU8(expected.width, expected.height); ConfigLength regionWidth = ConfigLength.fixed(width); int radius = regionWidth.computeI(Math.min(input.width, input.height))/2; var alg = new ThresholdNiblackFamily(regionWidth, 0.5f, true, variant); alg.process(input, found); BoofTesting.assertEqualsInner(expected, found, 0, radius, radius, false); alg.setDown(false); alg.process(input, found); BinaryImageOps.invert(expected, expected); BoofTesting.assertEqualsInner(expected, found, 0, radius, radius, false); } @Test void bruteForce() { int width = 5; float k = 0.5f; checkBruteForce(10, 12, width, k, true); checkBruteForce(10, 12, width, k, false); } private void checkBruteForce( int w, int h, int width, float k, boolean down ) { GrayU8 expected = new GrayU8(w, h); GrayU8 found = new GrayU8(w, h); GrayF32 input = new GrayF32(w, h); ImageMiscOps.fillUniform(input, rand, 0, 200); GrayF32 mean = new GrayF32(w, h); GrayF32 stdev = new GrayF32(w, h); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float m = mean(input, x, y, width/2); mean.set(x, y, m); stdev.set(x, y, stdev(input, m, x, y, width/2)); } } float R = ImageStatistics.max(stdev); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float threshold = mean.get(x, y)*(1.0f + k*(stdev.get(x, y)/R - 1.0f)); int out = down ? (input.get(x, y) <= threshold ? 1 : 0) : (input.get(x, y) >= threshold ? 1 : 0); expected.set(x, y, out); } } ThresholdNiblackFamily alg = new ThresholdNiblackFamily(ConfigLength.fixed(width), k, down, ThresholdNiblackFamily.Variant.SAUVOLA); alg.process(input, found); // expected.printBinary(); // System.out.println(); // found.printBinary(); BoofTesting.assertEquals(expected, found, 0); } private float mean( GrayF32 input, int c_x, int c_y, int radius ) { int x0 = c_x - radius; int x1 = x0 + radius*2 + 1; int y0 = c_y - radius; int y1 = y0 + radius*2 + 1; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 > input.width) x1 = input.width; if (y1 > input.height) y1 = input.height; float total = 0; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { total += input.get(x, y); } } return total/((x1 - x0)*(y1 - y0)); } private float stdev( GrayF32 input, float mean, int c_x, int c_y, int radius ) { int x0 = c_x - radius; int x1 = x0 + radius*2 + 1; int y0 = c_y - radius; int y1 = y0 + radius*2 + 1; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x1 > input.width) x1 = input.width; if (y1 > input.height) y1 = input.height; float total = 0; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { float d = input.get(x, y) - mean; total += d*d; } } return (float)Math.sqrt(total/((x1 - x0)*(y1 - y0))); } }
3e085ea4bbd64a9d6169645bef458c1bf3ebc7d4
1,285
java
Java
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/OneStorageDomainInfoReturnForXmlRpc.java
anjalshireesh/gluster-ovirt-poc
8778ec6809aac91034f1a497383b4ba500f11848
[ "Apache-2.0" ]
1
2019-01-12T06:49:06.000Z
2019-01-12T06:49:06.000Z
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/OneStorageDomainInfoReturnForXmlRpc.java
anjalshireesh/gluster-ovirt-poc
8778ec6809aac91034f1a497383b4ba500f11848
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/OneStorageDomainInfoReturnForXmlRpc.java
anjalshireesh/gluster-ovirt-poc
8778ec6809aac91034f1a497383b4ba500f11848
[ "Apache-2.0" ]
2
2015-01-15T19:06:01.000Z
2015-04-29T08:15:29.000Z
34.72973
86
0.701167
3,548
package org.ovirt.engine.core.vdsbroker.vdsbroker; import java.util.Map; import org.ovirt.engine.core.vdsbroker.irsbroker.*; import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcObjectDescriptor; import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcStruct; public final class OneStorageDomainInfoReturnForXmlRpc extends StatusReturnForXmlRpc { private static final String INFO = "info"; // We are ignoring missing fields after the status, because on failure it is // not sent. // C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to // .NET attributes: // [XmlRpcMissingMapping(MappingAction.Ignore), XmlRpcMember("info")] public XmlRpcStruct mStorageInfo; public OneStorageDomainInfoReturnForXmlRpc(Map<String, Object> innerMap) { super(innerMap); Object temp = innerMap.get(INFO); if (temp != null) { mStorageInfo = new XmlRpcStruct((Map<String, Object>) temp); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append(super.toString()); builder.append("\n"); XmlRpcObjectDescriptor.ToStringBuilder(mStorageInfo, builder); return builder.toString(); } }
3e085f0a80d64e3f65a2418e645219b398a75eaf
756
java
Java
adapter-cqld4/src/main/java/io/nosqlbench/adapter/cqld4/Cqld4ReboundStatement.java
tjake/nosqlbench
d31fbd45fe7627d681624fb94bce763bcac78feb
[ "Apache-2.0" ]
null
null
null
adapter-cqld4/src/main/java/io/nosqlbench/adapter/cqld4/Cqld4ReboundStatement.java
tjake/nosqlbench
d31fbd45fe7627d681624fb94bce763bcac78feb
[ "Apache-2.0" ]
null
null
null
adapter-cqld4/src/main/java/io/nosqlbench/adapter/cqld4/Cqld4ReboundStatement.java
tjake/nosqlbench
d31fbd45fe7627d681624fb94bce763bcac78feb
[ "Apache-2.0" ]
null
null
null
30.24
163
0.739418
3,549
package io.nosqlbench.adapter.cqld4; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.Statement; public class Cqld4ReboundStatement extends Cqld4Op { private final BoundStatement stmt; public Cqld4ReboundStatement(CqlSession session, int maxpages, boolean retryreplace, Cqld4OpMetrics metrics, BoundStatement rebound, RSProcessors processors) { super(session,maxpages,retryreplace,metrics,processors); this.stmt = rebound; } @Override public Statement<?> getStmt() { return stmt; } @Override public String getQueryString() { return stmt.getPreparedStatement().getQuery(); } }
3e085faaa765561359e88422d3f9932b7dcd859b
463
java
Java
mall-coupon/src/main/java/personal/skyxt/mallcoupon/service/MemberPriceService.java
skyxt/skymail
8c8dd874967522eb11bed1572018b0827724d4f2
[ "Apache-2.0" ]
null
null
null
mall-coupon/src/main/java/personal/skyxt/mallcoupon/service/MemberPriceService.java
skyxt/skymail
8c8dd874967522eb11bed1572018b0827724d4f2
[ "Apache-2.0" ]
2
2021-04-22T17:11:48.000Z
2021-09-20T21:01:32.000Z
mall-coupon/src/main/java/personal/skyxt/mallcoupon/service/MemberPriceService.java
skyxt/sky-mall
8c8dd874967522eb11bed1572018b0827724d4f2
[ "Apache-2.0" ]
null
null
null
22.190476
73
0.776824
3,550
package personal.skyxt.mallcoupon.service; import com.baomidou.mybatisplus.extension.service.IService; import personal.skyxt.mallcommon.utils.PageUtils; import personal.skyxt.mallcoupon.entity.MemberPriceEntity; import java.util.Map; /** * 商品会员价格 * * @author skyxt * @email [email protected] * @date 2020-08-06 11:09:18 */ public interface MemberPriceService extends IService<MemberPriceEntity> { PageUtils queryPage(Map<String, Object> params); }
3e086155ea09842fa0f8fcb303a1f252d14097c0
1,261
java
Java
app/src/main/java/com/example/android/quakereport/Earthquake.java
felipeemidio/QuakeReportApp
5ec8e0644be516c12f75e5f9544b50670559c091
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/quakereport/Earthquake.java
felipeemidio/QuakeReportApp
5ec8e0644be516c12f75e5f9544b50670559c091
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/quakereport/Earthquake.java
felipeemidio/QuakeReportApp
5ec8e0644be516c12f75e5f9544b50670559c091
[ "Apache-2.0" ]
null
null
null
26.270833
95
0.643933
3,551
package com.example.android.quakereport; public class Earthquake { double magnitude; String location; private long mTimeInMilliseconds; /** Website URL of the earthquake */ private String mUrl; /** * Constructs a new {@link Earthquake} object. * * @param magnitude is the magnitude (size) of the earthquake * @param location is the location where the earthquake happened * @param timeInMilliseconds is the time in milliseconds (from the Epoch) when the * earthquake happened * @param url is the website URL to find more details about the earthquake */ public Earthquake(double magnitude, String location, long timeInMilliseconds, String url) { this.magnitude = magnitude; this.location = location; mTimeInMilliseconds = timeInMilliseconds; mUrl = url; } public long getTimeInMilliseconds() { return mTimeInMilliseconds; } public double getMagnitude() { return magnitude; } public String getLocation() { return location; } /** * Returns the website URL to find more information about the earthquake. */ public String getUrl() { return mUrl; } }
3e08619a499682d67cd565fe1a69f56d00501f58
6,334
java
Java
unityzarinpaliab/src/main/java/com/zarinpal/ewallets/purchase/ZarinPal.java
IranGameDevelopersCommunity/ZarrinpalUnityPluginAndroidPart
d9f44743f34d1d5c734412b8e71150477b05081b
[ "Unlicense" ]
null
null
null
unityzarinpaliab/src/main/java/com/zarinpal/ewallets/purchase/ZarinPal.java
IranGameDevelopersCommunity/ZarrinpalUnityPluginAndroidPart
d9f44743f34d1d5c734412b8e71150477b05081b
[ "Unlicense" ]
null
null
null
unityzarinpaliab/src/main/java/com/zarinpal/ewallets/purchase/ZarinPal.java
IranGameDevelopersCommunity/ZarrinpalUnityPluginAndroidPart
d9f44743f34d1d5c734412b8e71150477b05081b
[ "Unlicense" ]
null
null
null
46.918519
231
0.573887
3,552
package com.zarinpal.ewallets.purchase; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; @SuppressLint({"StaticFieldLeak"}) public class ZarinPal { private static ZarinPal instance; private Context context; private PaymentRequest paymentRequest; public static ZarinPal getPurchase(Context context) { if (instance == null) { instance = new ZarinPal(context); } return instance; } public static PaymentRequest getPaymentRequest() { return new PaymentRequest(); } public static SandboxPaymentRequest getSandboxPaymentRequest() { return new SandboxPaymentRequest(); } private ZarinPal(Context context) { this.context = context; } public void setPayment(PaymentRequest payment) { paymentRequest = payment; } public void verificationPayment(Uri uri, final OnCallbackVerificationPaymentListener listener) { if (uri == null || this.paymentRequest == null || !uri.isHierarchical()) { Log.d("Zarinpal","can not verify purchase , because paymentrequest is null"); return; } boolean isSuccess = uri.getQueryParameter("Status").equals("OK"); String authority = uri.getQueryParameter("Authority"); if (!authority.equals(this.paymentRequest.getAuthority())) { listener.onCallbackResultVerificationPayment(false, null, this.paymentRequest); } else if (isSuccess) { VerificationPayment verificationPayment = new VerificationPayment(); verificationPayment.setAmount(this.paymentRequest.getAmount()); verificationPayment.setMerchantID(this.paymentRequest.getMerchantID()); verificationPayment.setAuthority(authority); try { new HttpRequest(this.context, this.paymentRequest.getVerificationPaymentURL()).setJson(verificationPayment.getVerificationPaymentAsJson()).setRequestMethod(1).setRequestType((byte) 0).get(new HttpRequestListener() { public void onSuccessResponse(JSONObject jsonObject, String contentResponse) { try { JSONObject error = jsonObject.optJSONObject("errors"); if(error!=null){ listener.onCallbackResultVerificationPayment(false, null, ZarinPal.this.paymentRequest); } else{ JSONObject data = jsonObject.getJSONObject("data"); listener.onCallbackResultVerificationPayment(true, data.getString("ref_id"), ZarinPal.this.paymentRequest); } } catch (JSONException e) { e.printStackTrace(); } } public void onFailureResponse(int httpStatusCode, String dataError) { listener.onCallbackResultVerificationPayment(false, null, ZarinPal.this.paymentRequest); } }); } catch (Exception ex) { ex.printStackTrace(); } } else { listener.onCallbackResultVerificationPayment(false, null, this.paymentRequest); } } public void startPayment(final PaymentRequest paymentRequest, final OnCallbackRequestPaymentListener listener) { this.paymentRequest = paymentRequest; try { Log.d("Zarinpal", "startPayment: here"); new HttpRequest(this.context, paymentRequest.getPaymentRequestURL()).setRequestType((byte) 0).setRequestMethod(1).setJson(paymentRequest.getPaymentRequestAsJson()).get(new HttpRequestListener() { public void onSuccessResponse(JSONObject jsonObject, String contentResponse) { try { Log.d("Zarinpal", "jsonContent:"+jsonObject.toString()); JSONObject error = jsonObject.optJSONObject("errors"); if(error!=null){ listener.onCallbackResultPaymentRequest(error.getInt("code"), null, null, null, error.getString("message")); return; } else { JSONObject data = jsonObject.getJSONObject("data"); int status = data.getInt("code"); String authority = data.getString(Payment.AUTHORITY_PARAMS); paymentRequest.setAuthority(authority); Uri uri = Uri.parse(paymentRequest.getStartPaymentGatewayURL(authority)); listener.onCallbackResultPaymentRequest(status, authority, uri, new Intent("android.intent.action.VIEW", uri), null); } } catch (JSONException e) { e.printStackTrace(); listener.onCallbackResultPaymentRequest(400, null, null, null, "response is not json"); } } public void onFailureResponse(int httpStatusCode, String dataError) { try { JSONObject jsonObject = new JSONObject(dataError); JSONObject error = jsonObject.optJSONObject("errors"); if(error!=null){ listener.onCallbackResultPaymentRequest(error.getInt("code"), null, null, null, error.getString("message")); } else{ listener.onCallbackResultPaymentRequest(httpStatusCode, null, null, null, "http failed, " + dataError); } } catch (JSONException e) { e.printStackTrace(); listener.onCallbackResultPaymentRequest(httpStatusCode, null, null, null, "failed an http request"); } } }); } catch (Exception ex) { ex.printStackTrace(); } } }
3e0863253ef42847f965f35f2fe59ab1f400d35b
110
java
Java
plugins/InspectionGadgets/test/com/siyeh/igfixes/style/inferLambdaParameterType/TwoParams.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
5
2015-12-19T15:27:30.000Z
2019-08-17T10:07:23.000Z
plugins/InspectionGadgets/test/com/siyeh/igfixes/style/inferLambdaParameterType/TwoParams.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
plugins/InspectionGadgets/test/com/siyeh/igfixes/style/inferLambdaParameterType/TwoParams.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
12.222222
40
0.427273
3,553
class X { interface I<A> { void foo(A a1, A a2); } { I<String> c = (<caret>o1, o2) -> {}; } }
3e0863340474a24d8a0f5d14bd2036853e37b867
879
java
Java
src/main/java/com/intershop/oms/test/servicehandler/transmissionservice/v1_1/mapping/SortableTransmissionAttributeMapper.java
intershop/iom-test-framework
fcc98d475135ed3488449fc298363181c66358f8
[ "MIT" ]
null
null
null
src/main/java/com/intershop/oms/test/servicehandler/transmissionservice/v1_1/mapping/SortableTransmissionAttributeMapper.java
intershop/iom-test-framework
fcc98d475135ed3488449fc298363181c66358f8
[ "MIT" ]
null
null
null
src/main/java/com/intershop/oms/test/servicehandler/transmissionservice/v1_1/mapping/SortableTransmissionAttributeMapper.java
intershop/iom-test-framework
fcc98d475135ed3488449fc298363181c66358f8
[ "MIT" ]
null
null
null
43.95
152
0.885097
3,554
package com.intershop.oms.test.servicehandler.transmissionservice.v1_1.mapping; import org.mapstruct.InheritInverseConfiguration; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import com.intershop.oms.rest.transmission.v1_1.model.SortableTransmissionAttribute; import com.intershop.oms.test.businessobject.transmission.OMSSortableTransmissionAttribute; @Mapper public interface SortableTransmissionAttributeMapper { SortableTransmissionAttributeMapper INSTANCE = Mappers.getMapper(SortableTransmissionAttributeMapper.class); OMSSortableTransmissionAttribute fromApiSortableTransmissionAttribute(SortableTransmissionAttribute sortableTransmissionAttribute); @InheritInverseConfiguration public abstract SortableTransmissionAttribute toApiSortableTransmissionAttribute(OMSSortableTransmissionAttribute omsSortableTransmissionAttribute); }
3e0865c59c10c1dd08152f12825ad8b7605574cb
359
java
Java
src/main/java/at/gepardec/training/cdi/advanced/specializes/ServiceOriginal.java
Gepardec/cdi-training
b1ff740577b1fdfd4f4ead7952a830358b11b58c
[ "Apache-2.0" ]
2
2021-01-30T15:02:50.000Z
2021-12-10T08:35:51.000Z
src/main/java/at/gepardec/training/cdi/advanced/specializes/ServiceOriginal.java
Gepardec/cdi-training
b1ff740577b1fdfd4f4ead7952a830358b11b58c
[ "Apache-2.0" ]
6
2021-03-22T17:57:29.000Z
2021-12-10T08:34:26.000Z
src/main/java/at/gepardec/training/cdi/advanced/specializes/ServiceOriginal.java
Gepardec/cdi-training
b1ff740577b1fdfd4f4ead7952a830358b11b58c
[ "Apache-2.0" ]
1
2021-07-13T08:30:39.000Z
2021-07-13T08:30:39.000Z
19.944444
54
0.749304
3,555
package at.gepardec.training.cdi.advanced.specializes; import at.gepardec.training.cdi.Util; import javax.enterprise.context.RequestScoped; /** * That is the implementation we specialize */ @RequestScoped public class ServiceOriginal implements Service { @Override public String execute() { return Util.nameWithInstanceId(this); } }
3e08662d4f3c886e6edc9f4b651d5d9729b33d2d
551
java
Java
qa/src/main/java/com/salton123/qa/config/GpsMockConfig.java
LiveSalton/fundationholding
212a66560eef495140a4a522c8bb95ebb3ac8dab
[ "Apache-2.0" ]
6
2020-12-13T03:16:46.000Z
2021-11-02T06:36:43.000Z
qa/src/main/java/com/salton123/qa/config/GpsMockConfig.java
LiveSalton/fundationholding
212a66560eef495140a4a522c8bb95ebb3ac8dab
[ "Apache-2.0" ]
1
2021-08-13T07:55:33.000Z
2021-08-13T07:55:33.000Z
qa/src/main/java/com/salton123/qa/config/GpsMockConfig.java
LiveSalton/fundationholding
212a66560eef495140a4a522c8bb95ebb3ac8dab
[ "Apache-2.0" ]
4
2020-09-19T19:07:20.000Z
2021-09-22T07:55:08.000Z
27.55
88
0.760436
3,556
package com.salton123.qa.config; import android.content.Context; import com.salton123.qa.constant.SharedPrefsKey; import com.salton123.utils.SharedPrefsUtil; /** * Created by wanglikun on 2018/9/20. */ public class GpsMockConfig { public static boolean isGPSMockOpen(Context context) { return SharedPrefsUtil.getBoolean(context, SharedPrefsKey.GPS_MOCK_OPEN, false); } public static void setGPSMockOpen(Context context, boolean open) { SharedPrefsUtil.putBoolean(context, SharedPrefsKey.GPS_MOCK_OPEN, open); } }
3e086783e8df41ece0d6f8f9510d4eda2aae61d0
3,387
java
Java
src/main/java/com/romanceabroad/ui/LeftCornerMenuPage.java
shsmith11/romanceWeb
b38ed441a5d5a647a4b861338ce4b962676ac85e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/romanceabroad/ui/LeftCornerMenuPage.java
shsmith11/romanceWeb
b38ed441a5d5a647a4b861338ce4b962676ac85e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/romanceabroad/ui/LeftCornerMenuPage.java
shsmith11/romanceWeb
b38ed441a5d5a647a4b861338ce4b962676ac85e
[ "Apache-2.0" ]
null
null
null
42.3375
115
0.611456
3,557
package com.romanceabroad.ui; import data.Data; import data.Locators; import data.PagesLinks; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class LeftCornerMenuPage extends BasePage{ public LeftCornerMenuPage(WebDriver driver) { super(driver, explicitWait); } public List<WebElement> navMenuItemsList(){ openPage(PagesLinks.mainUrl); return driver.findElements(By.xpath(Locators.navMenuItems)); } public WebElement headersPages(){return driver.findElement(By.xpath("//h1"));} ArrayList<String> actualTitles; ArrayList<String> actualUrl; ArrayList<String> actualH1; HashMap<String, ArrayList<String>> navMenuData = new HashMap<>(); ; public boolean checkAllNavMenuItems(Enum pageKey){ int assertState = 0; for (int i = 0; i < navMenuItemsList().size(); i++) { if (navMenuData.get("titles").get(i).contains(Data.getExpectedTitles().get(pageKey))) {assertState++;} if (navMenuData.get("h1").get(i).contains(Data.getExpectedH1().get(pageKey))) {assertState++;} if (navMenuData.get("urls").get(i).contains(PagesLinks.getNavMenuLinks().get(pageKey))){assertState++;} if (assertState>0) { System.out.println("iteration " + i + ", assertState: " + assertState); System.out.println("Expected titles- " + Data.getExpectedTitles().get(pageKey)); System.out.println("Actual titles- " + navMenuData.get("titles").get(i)); System.out.println("Expected h1- " + Data.getExpectedH1().get(pageKey)); System.out.println("Actual h1- " + navMenuData.get("h1").get(i)); System.out.println("Expected urls- " + PagesLinks.getNavMenuLinks().get(pageKey)); System.out.println("Actual urls- " + navMenuData.get("urls").get(i)); System.out.println("________________________"); } if (assertState <2) {assertState = 0;} else break; } return (assertState>=2); } public void getAllNavMenuItems() { navMenuItemsList(); actualTitles = new ArrayList<>(); actualUrl = new ArrayList<>(); actualH1 = new ArrayList<>(); for (int i = 0; i < navMenuItemsList().size(); i++) { System.out.println(i + "/" + navMenuItemsList().size() + " - " + navMenuItemsList().get(i).getText()); navMenuItemsList().get(i).click(); actualTitles.add(driver.getTitle()); actualUrl.add(driver.getCurrentUrl()); try { fluentWait.until(x->x.findElement(By.xpath("//h1")).isDisplayed()); actualH1.add(headersPages().getText()); } catch (NoSuchElementException e){ actualH1.add(""); } navMenuItemsList(); } navMenuData.put("titles", actualTitles); navMenuData.put("urls", actualUrl); navMenuData.put("h1", actualH1); for(String key: navMenuData.keySet()){ System.out.println(key +" :: "+ navMenuData.get(key)); } //fluentWait.until(x->x.findElement(By.xpath("//h1"))); } }
3e0867d0e992a52619935b59b8e7dbc9c3b25e1d
3,836
java
Java
src/main/java/com/qa/ims/persistence/dao/OrderDAO.java
variskhan98/Varis-IMS
3670bf7d32a284eebb1a8db64395ce0040e2cb44
[ "MIT" ]
null
null
null
src/main/java/com/qa/ims/persistence/dao/OrderDAO.java
variskhan98/Varis-IMS
3670bf7d32a284eebb1a8db64395ce0040e2cb44
[ "MIT" ]
null
null
null
src/main/java/com/qa/ims/persistence/dao/OrderDAO.java
variskhan98/Varis-IMS
3670bf7d32a284eebb1a8db64395ce0040e2cb44
[ "MIT" ]
null
null
null
29.507692
102
0.702033
3,558
package com.qa.ims.persistence.dao; import com.qa.ims.persistence.domain.Customer; import com.qa.ims.persistence.domain.Item; import com.qa.ims.persistence.domain.Order; import com.qa.ims.utils.DBUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Random; public class OrderDAO implements Dao<Order> { public static final Logger LOGGER = LogManager.getLogger(); @Override public Order modelFromResultSet(ResultSet resultSet) throws SQLException { Long id = resultSet.getLong("id"); int orderId = resultSet.getInt("orderid"); int customerId = resultSet.getInt("customerid"); int itemId = resultSet.getInt("itemid"); return new Order(id,orderId, customerId, itemId); } @Override public List<Order> readAll() { try (Connection connection = DBUtils.getInstance().getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM orders");) { List<Order> orders = new ArrayList<>(); while (resultSet.next()) { orders.add(modelFromResultSet(resultSet)); } return orders; } catch (SQLException e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } return new ArrayList<>(); } public Order readLatest() { try (Connection connection = DBUtils.getInstance().getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM orders ORDER BY id DESC LIMIT 1");) { resultSet.next(); return modelFromResultSet(resultSet); } catch (Exception e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } return null; } @Override public Order create(Order order) { Random rand = new Random(); int orderId = rand.nextInt(1000); int count=order.getItemIDs().size(); for(int x=0;x<count;x++) { try (Connection connection = DBUtils.getInstance().getConnection(); PreparedStatement statement = connection .prepareStatement("INSERT INTO orders(orderid,customerid,itemid) VALUES (?, ?,?)");) { statement.setInt(1,orderId); ; statement.setInt(2, order.getCustomerId()); statement.setLong(3,Long.parseLong(order.getItemIDs().get(x))); statement.executeUpdate(); } catch (Exception e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } } return readLatest(); } @Override public Order read(Long id) { try (Connection connection = DBUtils.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM orders WHERE id = ?");) { statement.setLong(1, id); try (ResultSet resultSet = statement.executeQuery();) { resultSet.next(); return modelFromResultSet(resultSet); } } catch (Exception e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } return null; } @Override public Order update(Order order) { try (Connection connection = DBUtils.getInstance().getConnection(); PreparedStatement statement = connection .prepareStatement("UPDATE orders SET customerid = ?, itemid = ? WHERE id = ?");) { statement.setInt(1, order.getCustomerId()); statement.setInt(2, order.getItemId()); statement.setLong(3, order.getId()); statement.executeUpdate(); return read(order.getId()); } catch (Exception e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } return null; } @Override public int delete(long id) { try (Connection connection = DBUtils.getInstance().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM orders WHERE id = ?");) { statement.setLong(1, id); return statement.executeUpdate(); } catch (Exception e) { LOGGER.debug(e); LOGGER.error(e.getMessage()); } return 0; } }
3e08688ff01ba1b76d7b8f479dc909f350738080
6,502
java
Java
service/src/main/java/com/huotu/hotcms/service/service/impl/LinkServiceImpl.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
null
null
null
service/src/main/java/com/huotu/hotcms/service/service/impl/LinkServiceImpl.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
2
2021-04-07T18:44:39.000Z
2022-01-21T23:47:13.000Z
service/src/main/java/com/huotu/hotcms/service/service/impl/LinkServiceImpl.java
tomkay1/cms
56e1bea259123d2e8111e9d808d20900fd76332b
[ "Apache-2.0" ]
null
null
null
41.679487
142
0.686712
3,559
/* * 版权所有:杭州火图科技有限公司 * 地址:浙江省杭州市滨江区西兴街道阡陌路智慧E谷B幢4楼 * * (c) Copyright Hangzhou Hot Technology Co., Ltd. * Floor 4,Block B,Wisdom E Valley,Qianmo Road,Binjiang District * 2013-2016. All rights reserved. */ package com.huotu.hotcms.service.service.impl; import com.huotu.hotcms.service.entity.AbstractContent; import com.huotu.hotcms.service.entity.Category; import com.huotu.hotcms.service.entity.Link; import com.huotu.hotcms.service.model.LinkCategory; import com.huotu.hotcms.service.model.thymeleaf.foreach.NormalForeachParam; import com.huotu.hotcms.service.repository.LinkRepository; import com.huotu.hotcms.service.service.CategoryService; import com.huotu.hotcms.service.service.LinkService; import com.huotu.hotcms.service.util.PageData; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by chendeyu on 2016/1/6. */ @Service public class LinkServiceImpl implements LinkService { private static Log log = LogFactory.getLog(LinkServiceImpl.class); @Autowired LinkRepository linkRepository; @Autowired CategoryService categoryService; @Override public Link save(Link link) { return linkRepository.save(link); } @Override public PageData<LinkCategory> getPage(long ownerId, String title, int page, int pageSize) { PageData<LinkCategory> data = null; Specification<Link> specification = AbstractContent.Specification(ownerId, title, false); Page<Link> pageData = linkRepository.findAll(specification,new PageRequest(page - 1, pageSize)); if (pageData != null) { List<Link> links =pageData.getContent(); List<LinkCategory> linkCategoryList =new ArrayList<>(); for(Link link : links){ LinkCategory linkCategory = new LinkCategory(); linkCategory.setCategoryName(link.getCategory().getName()); linkCategory.setCreateTime(link.getCreateTime()); linkCategory.setId(link.getId()); linkCategory.setDescription(link.getDescription()); linkCategory.setTitle(link.getTitle()); linkCategoryList.add(linkCategory); } data = new PageData<>(); data.setPageCount(pageData.getTotalPages()); data.setPageIndex(pageData.getNumber()); data.setPageSize(pageData.getSize()); data.setTotal(pageData.getTotalElements()); data.setRows(linkCategoryList.toArray(new LinkCategory[linkCategoryList.size()])); } return data; } @Override public Boolean saveLink(Link link) { linkRepository.save(link); return true; } @Override public Link findById(Long id) { return linkRepository.findOne(id); } @Override public List<Link> getSpecifyLinks(String[] specifyIds) { List<String> ids = Arrays.asList(specifyIds); List<Long> linkIds = ids.stream().map(Long::parseLong).collect(Collectors.toList()); Specification<Link> specification = (root, query, cb) -> { List<Predicate> predicates = linkIds.stream().map(id -> cb.equal(root.get("id").as(Long.class),id)).collect(Collectors.toList()); return cb.or(predicates.toArray(new Predicate[predicates.size()])); }; return linkRepository.findAll(specification, new Sort(Sort.Direction.DESC,"orderWeight")); } @Override public Page<Link> getLinkList(NormalForeachParam normalForeachParam) throws Exception { int pageIndex = normalForeachParam.getPageNo() - 1; int pageSize = normalForeachParam.getPageSize(); if(normalForeachParam.getSize()!=null){ pageSize=normalForeachParam.getSize(); } Sort sort = new Sort(Sort.Direction.DESC, "orderWeight"); if (!StringUtils.isEmpty(normalForeachParam.getSpecifyIds())) { return getSpecifyLinks(normalForeachParam.getSpecifyIds(), pageIndex, pageSize, sort); } if (!StringUtils.isEmpty(normalForeachParam.getCategoryId())) { return getLinks(normalForeachParam, pageIndex, pageSize, sort); } else { return getAllArticle(normalForeachParam, pageIndex, pageSize, sort); } } private Page<Link> getSpecifyLinks(String[] specifyIds, int pageIndex, int pageSize, Sort sort) { List<String> ids = Arrays.asList(specifyIds); List<Long> linkIds = ids.stream().map(Long::parseLong).collect(Collectors.toList()); Specification<Link> specification = (root, criteriaQuery, cb) -> { List<Predicate> predicates = linkIds.stream().map(id -> cb.equal(root.get("id").as(Long.class), id)).collect(Collectors.toList()); return cb.or(predicates.toArray(new Predicate[predicates.size()])); }; return linkRepository.findAll(specification, new PageRequest(pageIndex, pageSize, sort)); } private Page<Link> getLinks(NormalForeachParam params, int pageIndex, int pageSize, Sort sort) throws Exception { try { Specification<Link> specification = AbstractContent.Specification(params); return linkRepository.findAll(specification, new PageRequest(pageIndex, pageSize, sort)); } catch (Exception ex) { throw new Exception("获得文章列表出现错误"); } } private Page<Link> getAllArticle(NormalForeachParam params, int pageIndex, int pageSize, Sort sort) { List<Category> subCategories = categoryService.getSubCategories(params.getParentcId()); if (subCategories.size() == 0) { try { throw new Exception("父栏目节点没有子栏目"); } catch (Exception e) { log.error(e.getMessage()); } } Specification<Link> specification = AbstractContent.Specification(params, subCategories); return linkRepository.findAll(specification, new PageRequest(pageIndex, pageSize, sort)); } }
3e08698e7240eb34daaf56f07ce8c02585e9070a
719
java
Java
spring/src/main/java/com/example/kafka/KafkaListenerService.java
ns3154/learn
887e57e116985b5f530c4593ec1f2d037298de6b
[ "MIT" ]
null
null
null
spring/src/main/java/com/example/kafka/KafkaListenerService.java
ns3154/learn
887e57e116985b5f530c4593ec1f2d037298de6b
[ "MIT" ]
3
2021-12-09T15:28:51.000Z
2022-01-12T23:04:53.000Z
spring/src/main/java/com/example/kafka/KafkaListenerService.java
ns3154/learn
887e57e116985b5f530c4593ec1f2d037298de6b
[ "MIT" ]
null
null
null
23.966667
74
0.721836
3,560
package com.example.kafka; import com.example.utils.TrackUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; /** * <pre> * * </pre> * @author 杨帮东 * @since 1.0 * @date 2020/04/17 19:13 **/ @Component public class KafkaListenerService { private final Logger logger = LoggerFactory.getLogger(getClass()); @KafkaListener(topics = "TEST") private void listener(ConsumerRecord<String, String> consumerRecord) { TrackUtils.printTrack("listener"); logger.error("**** listener:{}****", consumerRecord); } }
3e08699b099d8f82e3d3f991fa72fbd74306b50c
433
java
Java
backend/src/main/java/net/kalars/rest/restfulws/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtTokenResponse.java
larsreed/training-react
919b2b5d6afcb5fa234446b5ed4dcdc09e1a0b13
[ "MIT" ]
null
null
null
backend/src/main/java/net/kalars/rest/restfulws/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtTokenResponse.java
larsreed/training-react
919b2b5d6afcb5fa234446b5ed4dcdc09e1a0b13
[ "MIT" ]
null
null
null
backend/src/main/java/net/kalars/rest/restfulws/com/in28minutes/rest/webservices/restfulwebservices/jwt/resource/JwtTokenResponse.java
larsreed/training-react
919b2b5d6afcb5fa234446b5ed4dcdc09e1a0b13
[ "MIT" ]
null
null
null
24.055556
99
0.745958
3,561
package net.kalars.rest.restfulws.com.in28minutes.rest.webservices.restfulwebservices.jwt.resource; import java.io.Serializable; public class JwtTokenResponse implements Serializable { private static final long serialVersionUID = 8317676219297719109L; private final String token; public JwtTokenResponse(String token) { this.token = token; } public String getToken() { return this.token; } }
3e0869ac25cd9714b83cee8fd78d91516820bd71
33,246
java
Java
app/src/main/java/xyz/zzyitj/qbremote/MainActivity.java
zzyandzzy/qBRemote
f2be6dab0a87113218c2ff51f2d80a0b8b854b46
[ "MIT" ]
5
2020-04-04T01:31:42.000Z
2021-08-20T03:29:42.000Z
app/src/main/java/xyz/zzyitj/qbremote/MainActivity.java
zzyandzzy/qBRemote
f2be6dab0a87113218c2ff51f2d80a0b8b854b46
[ "MIT" ]
null
null
null
app/src/main/java/xyz/zzyitj/qbremote/MainActivity.java
zzyandzzy/qBRemote
f2be6dab0a87113218c2ff51f2d80a0b8b854b46
[ "MIT" ]
1
2021-08-20T03:29:52.000Z
2021-08-20T03:29:52.000Z
49.180473
152
0.57243
3,562
package xyz.zzyitj.qbremote; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.OpenableColumns; import android.text.TextUtils; import android.util.Log; import android.view.*; import android.widget.*; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.mikepenz.fontawesome_typeface_library.FontAwesome; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.*; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import xyz.zzyitj.qbremote.activity.AddServerActivity; import xyz.zzyitj.qbremote.activity.DonationActivity; import xyz.zzyitj.qbremote.adapter.TorrentInfoAdapter; import xyz.zzyitj.qbremote.api.AuthService; import xyz.zzyitj.qbremote.api.SyncService; import xyz.zzyitj.qbremote.api.TorrentsService; import xyz.zzyitj.qbremote.drawer.SortDrawerItem; import xyz.zzyitj.qbremote.enums.InfoTorrentsVoFilter; import xyz.zzyitj.qbremote.enums.SortOrder; import xyz.zzyitj.qbremote.enums.SortedBy; import xyz.zzyitj.qbremote.model.InfoTorrentFilter; import xyz.zzyitj.qbremote.model.TorrentInfo; import xyz.zzyitj.qbremote.model.vo.AddTorrentsVo; import xyz.zzyitj.qbremote.model.vo.InfoTorrentsVo; import xyz.zzyitj.qbremote.util.IconUtils; import xyz.zzyitj.qbremote.util.ThemeUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.*; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int DRAWER_ITEM_ID_SETTINGS = 1; private static final int DRAWER_ITEM_ID_DONATION = 2; private static final int REQUEST_CODE_CHOOSE_TORRENT = 102; private static final int REQUEST_READ_PERMISSIONS = 103; private static final String MIME_TYPE_TORRENT = "application/x-bittorrent"; private boolean isSelect = false; private MyApplication myApplication; private Drawer drawer; private FloatingActionButton fab; private ProgressBar progressBar; private RecyclerView recyclerView; private TorrentInfoAdapter torrentInfoAdapter; private List<TorrentInfo> torrentInfoList = new ArrayList<>(); private MyApplication.OnSortingChangedListener sortingListener = comparator -> updateTorrentList(); private Handler handler = new Handler(); private Runnable task = new Runnable() { public void run() { handler.postDelayed(this, 3 * 1000); syncMainData(); } }; public ActionMode actionMode; public MenuItem removeMenuItem; public MenuItem pauseMenuItem; public MenuItem startMenuItem; public MenuItem renameMenuItem; public MenuItem setLocationMenuItem; public ActionMode.Callback actionModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.context_torrent_list_menu, menu); inflater.inflate(R.menu.torrent_actions_menu, menu); IconUtils.setMenuIcon(MyApplication.instance.getContext(), menu, R.id.action_select_all, GoogleMaterial.Icon.gmd_select_all); IconUtils.setMenuIcon(MyApplication.instance.getContext(), menu, R.id.action_remove_torrents, GoogleMaterial.Icon.gmd_delete); IconUtils.setMenuIcon(MyApplication.instance.getContext(), menu, R.id.action_pause, FontAwesome.Icon.faw_pause); IconUtils.setMenuIcon(MyApplication.instance.getContext(), menu, R.id.action_start, FontAwesome.Icon.faw_play); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { removeMenuItem = menu.findItem(R.id.action_remove_torrents); pauseMenuItem = menu.findItem(R.id.action_pause); startMenuItem = menu.findItem(R.id.action_start); renameMenuItem = menu.findItem(R.id.action_rename); setLocationMenuItem = menu.findItem(R.id.action_set_location); return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { String[] hashes = new String[torrentInfoAdapter.getSelectedItemsCount()]; int i = 0; for (Integer key : torrentInfoAdapter.getSelectedItemsHashes().keySet()) { hashes[i] = torrentInfoAdapter.getSelectedItemsHashes().get(key); i++; } switch (item.getItemId()) { case R.id.action_select_all: if (torrentInfoAdapter.getSelectedItemsCount() < torrentInfoAdapter.getItemCount()) { torrentInfoAdapter.selectAll(); } else { torrentInfoAdapter.clearSelection(); } return true; case R.id.action_remove_torrents: showDeleteDialog(mode, hashes); return true; case R.id.action_pause: TorrentsService.pause(MyApplication.instance.getServer(), hashes) .subscribe(responseBody -> { }, throwable -> { Toast.makeText(MyApplication.instance.getContext(), "Error", Toast.LENGTH_SHORT).show(); }); mode.finish(); return true; case R.id.action_start: TorrentsService.resume(MyApplication.instance.getServer(), hashes) .subscribe(responseBody -> { }, throwable -> { Toast.makeText(MyApplication.instance.getContext(), "Error", Toast.LENGTH_SHORT).show(); }); mode.finish(); return true; case R.id.action_rename: if (torrentInfoAdapter.getSelectedItemsCount() == 1) { String hash = hashes[0]; showRenameDialog(mode, hash); } return true; case R.id.action_set_location: showChooseLocationDialog(mode, hashes); return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { torrentInfoAdapter.clearSelection(); actionMode = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { MainActivity.this.getWindow().setStatusBarColor(Color.TRANSPARENT); } } }; private void showRenameDialog(ActionMode mode, String hash) { View rootView = LayoutInflater.from(this).inflate(R.layout.torrent_location_dialog, null); EditText locationEdit = rootView.findViewById(R.id.location_edit); Integer pos = torrentInfoAdapter.getSelectedItemsHashes().keySet().iterator().next(); TorrentInfo torrentInfo = torrentInfoList.get(pos); locationEdit.setText(torrentInfo.getName()); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.action_rename).setView(rootView) .setNegativeButton(Resources.getSystem().getIdentifier("cancel", "string", "android"), null) .setPositiveButton(Resources.getSystem().getIdentifier("ok", "string", "android"), (dialog1, which) -> { if (TextUtils.isEmpty(locationEdit.getText())) { Toast.makeText(MyApplication.instance.getContext(), "edit text not empty!", Toast.LENGTH_SHORT).show(); } else { TorrentsService.rename(MyApplication.instance.getServer(), locationEdit.getText().toString(), hash) .subscribe(responseBody -> { Toast.makeText(MyApplication.instance.getContext(), "Ok", Toast.LENGTH_SHORT).show(); mode.finish(); }, throwable -> { Toast.makeText(MyApplication.instance.getContext(), "Error", Toast.LENGTH_SHORT).show(); }); } }) .create(); dialog.show(); } private void showChooseLocationDialog(ActionMode mode, String[] hashes) { View rootView = LayoutInflater.from(this).inflate(R.layout.torrent_location_dialog, null); EditText locationEdit = rootView.findViewById(R.id.location_edit); Integer pos = torrentInfoAdapter.getSelectedItemsHashes().keySet().iterator().next(); TorrentInfo torrentInfo = torrentInfoList.get(pos); locationEdit.setText(torrentInfo.getSave_path()); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.action_set_location).setView(rootView) .setNegativeButton(Resources.getSystem().getIdentifier("cancel", "string", "android"), null) .setPositiveButton(Resources.getSystem().getIdentifier("ok", "string", "android"), (dialog1, which) -> { if (TextUtils.isEmpty(locationEdit.getText())) { Toast.makeText(MyApplication.instance.getContext(), "edit text not empty!", Toast.LENGTH_SHORT).show(); } else { TorrentsService.location(MyApplication.instance.getServer(), locationEdit.getText().toString(), hashes) .subscribe(responseBody -> { Toast.makeText(MyApplication.instance.getContext(), "Ok", Toast.LENGTH_SHORT).show(); mode.finish(); }, throwable -> { Toast.makeText(MyApplication.instance.getContext(), "Error", Toast.LENGTH_SHORT).show(); }); } }) .create(); dialog.show(); } private void showDeleteDialog(ActionMode mode, String[] hashes) { View rootView = LayoutInflater.from(this).inflate(R.layout.torrent_delete_dialog, null); CheckBox deleteFilesCheckbox = rootView.findViewById(R.id.delete_files_checkbox); AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(R.string.action_remove_torrents).setView(rootView) .setNegativeButton(Resources.getSystem().getIdentifier("cancel", "string", "android"), null) .setPositiveButton(Resources.getSystem().getIdentifier("ok", "string", "android"), (dialog1, which) -> TorrentsService.delete(MyApplication.instance.getServer(), deleteFilesCheckbox.isChecked(), hashes) .subscribe(responseBody -> { for (int i = 0; i < torrentInfoList.size(); i++) { for (String s : hashes) { if (torrentInfoList.get(i).getHash().equals(s)) { torrentInfoList.remove(i); torrentInfoAdapter.notifyItemRemoved(i); } } } Toast.makeText(MyApplication.instance.getContext(), "Ok", Toast.LENGTH_SHORT).show(); mode.finish(); }, throwable -> { Toast.makeText(MyApplication.instance.getContext(), "Error", Toast.LENGTH_SHORT).show(); })) .create(); dialog.show(); } private void updateTorrentList() { Comparator<TorrentInfo> comparator = myApplication.getSortComparator(); if (comparator != null) { Collections.sort(torrentInfoList, comparator); } torrentInfoAdapter.notifyDataSetChanged(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); if (myApplication.getServer() == null) { Intent intent = new Intent(this, AddServerActivity.class); startActivity(intent); } else { initViews(); initDatas(); handler.postDelayed(task, 3000); } } @SuppressLint("CheckResult") private void syncMainData() { SyncService.mainData(myApplication.getServer(), myApplication.getRid()) .subscribe(syncMainData -> { // Log.i(TAG, "syncMainData: " + myApplication.getRid()); if (myApplication.getRid() != 0) { for (String key : syncMainData.getTorrents().keySet()) { for (int i = 0; i < torrentInfoList.size(); i++) { if (key.equals(torrentInfoList.get(i).getHash())) { TorrentInfo modifyTorrentInfo = syncMainData.getTorrents().get(key); TorrentInfo torrentInfo = torrentInfoList.get(i); // state if (modifyTorrentInfo.getState() != null) { torrentInfo.setState(modifyTorrentInfo.getState()); } // download speed if (modifyTorrentInfo.getDlspeed() != null) { torrentInfo.setDlspeed(modifyTorrentInfo.getDlspeed()); } // download size if (modifyTorrentInfo.getDownloaded() != null) { torrentInfo.setDownloaded(modifyTorrentInfo.getDownloaded()); } // upload speed if (modifyTorrentInfo.getUpspeed() != null) { torrentInfo.setUpspeed(modifyTorrentInfo.getUpspeed()); } // upload size if (modifyTorrentInfo.getDownloaded() != null) { torrentInfo.setUploaded(modifyTorrentInfo.getUploaded()); } // progress if (modifyTorrentInfo.getProgress() != null) { torrentInfo.setProgress(modifyTorrentInfo.getProgress()); } // eta if (modifyTorrentInfo.getEta() != null) { torrentInfo.setEta(modifyTorrentInfo.getEta()); } // radio if (modifyTorrentInfo.getRatio() != null) { // Log.i(TAG, "syncMainData: radio: " + modifyTorrentInfo.getRatio()); torrentInfo.setRatio(modifyTorrentInfo.getRatio()); } // name if (modifyTorrentInfo.getName() != null) { torrentInfo.setName(modifyTorrentInfo.getName()); } torrentInfoList.set(i, torrentInfo); torrentInfoAdapter.notifyItemChanged(i); } } } } myApplication.setRid(syncMainData.getRid()); }, throwable -> { Log.e(TAG, "syncMainData: ", throwable); }); } @SuppressLint("CheckResult") private void initDatas() { torrentInfoAdapter = new TorrentInfoAdapter(torrentInfoList); recyclerView.setAdapter(torrentInfoAdapter); recyclerView.getItemAnimator().setChangeDuration(0); AuthService.login(myApplication.getServer()) .subscribe(responseBody -> { Log.v(TAG, responseBody.string()); InfoTorrentsVo infoTorrentsVo = new InfoTorrentsVo(); infoTorrentsVo.setFilter(myApplication.getFilter().getValue()); TorrentsService.info(myApplication.getServer(), infoTorrentsVo) .subscribe(this::initAdapter, throwable -> { Log.e(TAG, "Connection error.", throwable); Toast.makeText(this, "Connection error.", Toast.LENGTH_SHORT).show(); }); }, throwable -> { Log.e(TAG, "Connection error.", throwable); Toast.makeText(this, "Connection error.", Toast.LENGTH_SHORT).show(); }); fab.setOnClickListener(view -> { checkPermissionAndSelectTorrent(); }); } private void checkPermissionAndSelectTorrent() { int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); if (permissionCheck == PackageManager.PERMISSION_GRANTED) { showFileChooser(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_PERMISSIONS); } } private void initAdapter(List<TorrentInfo> torrentInfoList) { progressBar.setVisibility(View.GONE); this.torrentInfoList = torrentInfoList; Log.i(TAG, "initAdapter: " + torrentInfoList.size()); // for (TorrentInfo torrentInfo : torrentInfoList) { // Log.i(TAG, "initAdapter: " + torrentInfo.getSave_path()); // } torrentInfoAdapter = new TorrentInfoAdapter(this.torrentInfoList); recyclerView.setAdapter(torrentInfoAdapter); updateTorrentList(); } private void initViews() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.filter_spinner, R.layout.toolbar_spinner_item); Spinner filterSpinner = new Spinner(getSupportActionBar().getThemedContext()); filterSpinner.setAdapter(spinnerAdapter); String[] filterArr = getResources().getStringArray(R.array.filter_spinner); InfoTorrentFilter filter = myApplication.getFilters(); for (int i = 0; i < filterArr.length; i++) { if (filterArr[i].equals(filter.getName())) { filterSpinner.setSelection(i); } } filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String filterName = (String) parent.getItemAtPosition(position); String filter = InfoTorrentsVoFilter.ALL.getName(); if (position == 1) { filter = InfoTorrentsVoFilter.DOWNLOADING.getName(); } else if (position == 2) { filter = InfoTorrentsVoFilter.COMPLETED.getName(); } else if (position == 3) { filter = InfoTorrentsVoFilter.PAUSED.getName(); } else if (position == 4) { filter = InfoTorrentsVoFilter.ACTIVE.getName(); } else if (position == 5) { filter = InfoTorrentsVoFilter.INACTIVE.getName(); } else if (position == 6) { filter = InfoTorrentsVoFilter.RESUMED.getName(); } myApplication.saveFilter(filterName, filter); InfoTorrentsVo infoTorrentsVo = new InfoTorrentsVo(); infoTorrentsVo.setFilter(filter); if (isSelect) { TorrentsService.info(myApplication.getServer(), infoTorrentsVo) .subscribe(torrentInfoList -> MainActivity.this.initAdapter(torrentInfoList), throwable -> { Log.e(TAG, "Connection error.", throwable); Toast.makeText(MainActivity.this, "Connection error.", Toast.LENGTH_SHORT).show(); }); } isSelect = true; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); toolbar.addView(filterSpinner, 0); fab = findViewById(R.id.fab); PrimaryDrawerItem settingsItem = new PrimaryDrawerItem().withName(R.string.action_settings) .withIdentifier(DRAWER_ITEM_ID_SETTINGS) .withIcon(R.drawable.ic_settings) .withSelectable(false); PrimaryDrawerItem donationItem = new PrimaryDrawerItem().withName(R.string.donation) .withIdentifier(DRAWER_ITEM_ID_DONATION) .withIcon(R.drawable.ic_thumb_up) .withSelectable(false); SwitchDrawerItem nightModeItem = new SwitchDrawerItem().withName(R.string.night_mode) .withIcon(R.drawable.ic_brightness) .withSelectable(false) .withChecked(ThemeUtils.isInNightMode(this)) .withOnCheckedChangeListener((drawerItem, buttonView, isChecked) -> switchTheme(isChecked)); final SortDrawerItem[] sortItems = new SortDrawerItem[]{ new SortDrawerItem(SortedBy.NAME).withName(R.string.drawer_sort_by_name), new SortDrawerItem(SortedBy.DATE_ADDED).withName(R.string.drawer_sort_by_date_added), new SortDrawerItem(SortedBy.SIZE).withName(R.string.drawer_sort_by_size), new SortDrawerItem(SortedBy.TIME_REMAINING).withName(R.string.drawer_sort_by_time_remaining), new SortDrawerItem(SortedBy.PROGRESS).withName(R.string.drawer_sort_by_progress), new SortDrawerItem(SortedBy.UPLOAD_RATIO).withName(R.string.drawer_sort_by_upload_ratio) }; drawer = new DrawerBuilder() .withActivity(this) .withToolbar(toolbar) .addDrawerItems(new SectionDrawerItem().withName(R.string.drawer_sort_by).withDivider(false)) .addDrawerItems(sortItems) .addStickyDrawerItems(nightModeItem, donationItem, settingsItem) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { if (drawerItem instanceof SortDrawerItem) { handleSortItemClick((SortDrawerItem) drawerItem); return true; } else if (drawerItem.getIdentifier() == DRAWER_ITEM_ID_SETTINGS) { Toast.makeText(MainActivity.this, "暂未开发!", Toast.LENGTH_SHORT).show(); } else if (drawerItem.getIdentifier() == DRAWER_ITEM_ID_DONATION) { startActivity(new Intent(MainActivity.this, DonationActivity.class)); } else { Toast.makeText(MainActivity.this, "pos: " + position, Toast.LENGTH_SHORT).show(); } return false; } private void handleSortItemClick(SortDrawerItem selectedItem) { SortOrder prevSortOrder = selectedItem.getSortOrder(); SortOrder sortOrder; if (prevSortOrder == null) sortOrder = SortOrder.ASCENDING; else sortOrder = prevSortOrder == SortOrder.ASCENDING ? SortOrder.DESCENDING : SortOrder.ASCENDING; for (SortDrawerItem item : sortItems) { if (item != selectedItem) { item.setSortOrder(null); item.withSetSelected(false); drawer.updateItem(item); } } selectedItem.setSortOrder(sortOrder); drawer.updateItem(selectedItem); myApplication.setSorting(selectedItem.getSortedBy(), sortOrder); } }) .build(); SortedBy persistedSortedBy = myApplication.getSortedBy(); SortOrder persistedSortOrder = myApplication.getSortOrder(); for (SortDrawerItem item : sortItems) { if (item.getSortedBy() == persistedSortedBy) { item.setSortOrder(persistedSortOrder); item.withSetSelected(true); break; } } progressBar = findViewById(R.id.progress); recyclerView = findViewById(R.id.recycler_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); } private void init() { myApplication = new MyApplication(this); myApplication.addOnSortingChangedListeners(sortingListener); if (ThemeUtils.isInNightMode(this)) { ThemeUtils.setIsInNightMode(this, true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_open_torrent: checkPermissionAndSelectTorrent(); break; } return super.onOptionsItemSelected(item); } private void switchTheme(boolean nightMode) { ThemeUtils.setIsInNightMode(this, nightMode); recreate(); } @Override protected void onResume() { super.onResume(); if (myApplication.getServer() == null) { Intent intent = new Intent(this, AddServerActivity.class); startActivity(intent); } } @Override protected void onPause() { super.onPause(); myApplication.persist(); } @Override protected void onDestroy() { myApplication.removeOnSortingChangedListener(sortingListener); super.onDestroy(); } private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(MIME_TYPE_TORRENT); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent, getResources().getString(R.string.select_torrent_file)), MainActivity.REQUEST_CODE_CHOOSE_TORRENT); } catch (ActivityNotFoundException ex) { Toast.makeText(this, getResources().getString(R.string.error_install_file_manager_msg), Toast.LENGTH_LONG).show(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_READ_PERMISSIONS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showFileChooser(); } else { Toast.makeText(MainActivity.this, "Please get this app read permission", Toast.LENGTH_SHORT).show(); } } } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_CHOOSE_TORRENT) { if (resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); if (uri != null) { getFileInputStream(uri); } } } } private void getFileInputStream(Uri uri) { try { openTorrentByLocalFile(getContentResolver().openInputStream(uri)); } catch (IOException ex) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); if (cursor == null) { String msg = getString(R.string.error_file_does_not_exists_msg, uri.toString()); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); return; } int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); cursor.moveToFirst(); String fileName = cursor.getString(nameIndex); cursor.close(); String extension = FilenameUtils.getExtension(fileName); if (!"torrent".equals(extension)) { String msg = getResources().getString(R.string.error_wrong_file_extension_msg, extension); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); return; } try { openTorrentByLocalFile(getContentResolver().openInputStream(Uri.parse(fileName))); } catch (FileNotFoundException e) { String msg = getResources().getString(R.string.error_file_does_not_exists_msg, fileName); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } } } @SuppressLint("CheckResult") private void openTorrentByLocalFile(InputStream inputStream) { try { AddTorrentsVo addTorrentsVo = new AddTorrentsVo(); addTorrentsVo.setTorrents(IOUtils.toByteArray(inputStream)); TorrentsService.add(myApplication.getServer(), addTorrentsVo) .subscribe(responseBody -> { String body = responseBody.string(); Log.i(TAG, "onActivityResult: " + body); if (body.contains("Fails")) { Toast.makeText(MainActivity.this, R.string.torrent_added_fail, Toast.LENGTH_SHORT).show(); } else if (body.contains("Ok")) { Toast.makeText(MainActivity.this, R.string.torrent_added_successfully, Toast.LENGTH_SHORT).show(); } }, throwable -> { Log.e(TAG, "onActivityResult: ", throwable); Toast.makeText(MainActivity.this, R.string.torrent_added_fail, Toast.LENGTH_SHORT).show(); }); } catch (IOException e) { Log.e(TAG, "Failed to read file stream", e); Toast.makeText(MainActivity.this, getString(R.string.error_cannot_read_file_msg), Toast.LENGTH_SHORT).show(); return; } finally { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "Failed to close input stream", e); } } } }
3e086a07a70bd46c692352341e1d5cc4723bacd1
472
java
Java
excode-generator/src/main/java/com/vancone/excode/generator/constant/UrlPath.java
mekcone/mekcone-studio
93e845fb7e7b99eb343b91d52edd14057acd88c2
[ "MIT" ]
null
null
null
excode-generator/src/main/java/com/vancone/excode/generator/constant/UrlPath.java
mekcone/mekcone-studio
93e845fb7e7b99eb343b91d52edd14057acd88c2
[ "MIT" ]
null
null
null
excode-generator/src/main/java/com/vancone/excode/generator/constant/UrlPath.java
mekcone/mekcone-studio
93e845fb7e7b99eb343b91d52edd14057acd88c2
[ "MIT" ]
null
null
null
33.714286
93
0.745763
3,563
package com.vancone.excode.generator.constant; import java.io.File; /** * @author Tenton Lien */ public interface UrlPath { String VANCONE_STUDIO_HOME = System.getenv("VANCONE_STUDIO_HOME") + File.separator; String EXAMPLE_PATH = VANCONE_STUDIO_HOME + File.separator + "examples" + File.separator; String GEN_PATH = VANCONE_STUDIO_HOME + File.separator + "gen" + File.separator; String MODULE_PATH = VANCONE_STUDIO_HOME + "modules" + File.separator; }
3e086c0f945c8ecedc3b3a950942d54ecff4b354
353
java
Java
src/main/java/linkedlist/SinglyNode.java
chinhung/data-structures-and-algorithms
1720fa4f62e36943fe11428a2f29fc592dedd6c5
[ "MIT" ]
null
null
null
src/main/java/linkedlist/SinglyNode.java
chinhung/data-structures-and-algorithms
1720fa4f62e36943fe11428a2f29fc592dedd6c5
[ "MIT" ]
null
null
null
src/main/java/linkedlist/SinglyNode.java
chinhung/data-structures-and-algorithms
1720fa4f62e36943fe11428a2f29fc592dedd6c5
[ "MIT" ]
null
null
null
14.708333
41
0.563739
3,564
package linkedlist; class SinglyNode<Data> { private Data data; private SinglyNode<Data> next; SinglyNode(Data data) { this.data = data; } Data getData() { return data; } SinglyNode<Data> getNext() { return next; } void setNext(SinglyNode<Data> next) { this.next = next; } }
3e086c17034ebf225f4917c24a726e62d3e456ec
920
java
Java
Gallery/gallery/src/main/java/com/ptrprograms/gallery/util/SquareImageView.java
puru2u/NavDrawer
97861bd443099ed6e3a1794c743e32b5399c9b40
[ "Apache-2.0" ]
486
2015-01-04T02:47:46.000Z
2022-03-01T13:09:48.000Z
Gallery/gallery/src/main/java/com/ptrprograms/gallery/util/SquareImageView.java
pnlwlust/AndroidDemoProjects
b140c23118258371d99a186a4c2480e963de9d73
[ "Apache-2.0" ]
8
2015-02-04T09:44:06.000Z
2020-10-27T22:27:18.000Z
Gallery/gallery/src/main/java/com/ptrprograms/gallery/util/SquareImageView.java
pnlwlust/AndroidDemoProjects
b140c23118258371d99a186a4c2480e963de9d73
[ "Apache-2.0" ]
505
2015-01-05T14:29:28.000Z
2022-02-16T05:49:20.000Z
29.677419
99
0.705435
3,565
package com.ptrprograms.gallery.util; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; public class SquareImageView extends ImageView { public SquareImageView( final Context context ) { super( context ); } public SquareImageView( final Context context, final AttributeSet attrs ) { super( context, attrs ); } public SquareImageView( final Context context, final AttributeSet attrs, final int defStyle ) { super( context, attrs, defStyle ); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int dimension = getDefaultSize( getSuggestedMinimumWidth(), widthMeasureSpec ); setMeasuredDimension(dimension, dimension); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, w, oldw, oldh); } }
3e086d798d47cf0b708ab8fe17289292f67869d7
2,492
java
Java
src/test/java/com/launchdarkly/sdk/server/LDClientExternalUpdatesOnlyTest.java
driverpt/java-server-sdk
5c90bd5dd80d5a1c940cfa5673d3fc9f721358f1
[ "Apache-2.0" ]
44
2019-04-29T15:31:26.000Z
2022-03-09T18:28:34.000Z
src/test/java/com/launchdarkly/sdk/server/LDClientExternalUpdatesOnlyTest.java
driverpt/java-server-sdk
5c90bd5dd80d5a1c940cfa5673d3fc9f721358f1
[ "Apache-2.0" ]
48
2019-05-10T04:07:38.000Z
2022-02-25T01:10:50.000Z
src/test/java/com/launchdarkly/sdk/server/LDClientExternalUpdatesOnlyTest.java
driverpt/java-server-sdk
5c90bd5dd80d5a1c940cfa5673d3fc9f721358f1
[ "Apache-2.0" ]
30
2019-05-04T01:59:38.000Z
2021-12-31T20:18:26.000Z
37.757576
118
0.746388
3,566
package com.launchdarkly.sdk.server; import com.launchdarkly.sdk.LDUser; import com.launchdarkly.sdk.LDValue; import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider; import com.launchdarkly.sdk.server.interfaces.DataStore; import org.junit.Test; import java.io.IOException; import static com.launchdarkly.sdk.server.ModelBuilders.flagWithValue; import static com.launchdarkly.sdk.server.TestComponents.initedDataStore; import static com.launchdarkly.sdk.server.TestComponents.specificDataStore; import static com.launchdarkly.sdk.server.TestUtil.upsertFlag; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @SuppressWarnings("javadoc") public class LDClientExternalUpdatesOnlyTest { @Test public void externalUpdatesOnlyClientHasNullDataSource() throws Exception { LDConfig config = new LDConfig.Builder() .dataSource(Components.externalUpdatesOnly()) .build(); try (LDClient client = new LDClient("SDK_KEY", config)) { assertEquals(ComponentsImpl.NullDataSource.class, client.dataSource.getClass()); } } @Test public void externalUpdatesOnlyClientHasDefaultEventProcessor() throws Exception { LDConfig config = new LDConfig.Builder() .dataSource(Components.externalUpdatesOnly()) .build(); try (LDClient client = new LDClient("SDK_KEY", config)) { assertEquals(DefaultEventProcessor.class, client.eventProcessor.getClass()); } } @Test public void externalUpdatesOnlyClientIsInitialized() throws Exception { LDConfig config = new LDConfig.Builder() .dataSource(Components.externalUpdatesOnly()) .build(); try (LDClient client = new LDClient("SDK_KEY", config)) { assertTrue(client.isInitialized()); assertEquals(DataSourceStatusProvider.State.VALID, client.getDataSourceStatusProvider().getStatus().getState()); } } @Test public void externalUpdatesOnlyClientGetsFlagFromDataStore() throws IOException { DataStore testDataStore = initedDataStore(); LDConfig config = new LDConfig.Builder() .dataSource(Components.externalUpdatesOnly()) .dataStore(specificDataStore(testDataStore)) .build(); DataModel.FeatureFlag flag = flagWithValue("key", LDValue.of(true)); upsertFlag(testDataStore, flag); try (LDClient client = new LDClient("SDK_KEY", config)) { assertTrue(client.boolVariation("key", new LDUser("user"), false)); } } }
3e086da85334d659119989edc31b2698571ed1f3
2,033
java
Java
nio/src/main/java/jlibs/nio/http/filters/ParseJAXB.java
vvasianovych/jlibs
9eaf68928f10f1d73ebb7b71761a8ec90caad1ac
[ "Apache-2.0" ]
59
2015-06-01T22:02:06.000Z
2022-03-02T14:46:08.000Z
nio/src/main/java/jlibs/nio/http/filters/ParseJAXB.java
vvasianovych/jlibs
9eaf68928f10f1d73ebb7b71761a8ec90caad1ac
[ "Apache-2.0" ]
48
2015-06-01T21:57:16.000Z
2022-02-28T07:14:58.000Z
nio/src/main/java/jlibs/nio/http/filters/ParseJAXB.java
vvasianovych/jlibs
9eaf68928f10f1d73ebb7b71761a8ec90caad1ac
[ "Apache-2.0" ]
31
2015-06-12T06:40:54.000Z
2020-09-14T04:38:40.000Z
34.016667
109
0.728564
3,567
/* * JLibs: Common Utilities for Java * Copyright (C) 2009 Santhosh Kumar T <[email protected]> * * 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. */ package jlibs.nio.http.filters; import jlibs.core.io.IOUtil; import jlibs.nio.http.Exchange; import jlibs.nio.http.SocketPayload; import jlibs.nio.http.msg.JAXBPayload; import jlibs.nio.http.msg.Message; import jlibs.xml.sax.async.AsyncXMLReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.UnmarshallerHandler; /** * @author Santhosh Kumar Tekuri */ public class ParseJAXB extends ParseXML{ public final JAXBContext jaxbContext; public ParseJAXB(JAXBContext jaxbContext){ this.jaxbContext = jaxbContext; } @Override protected boolean retain(SocketPayload payload){ return false; } @Override protected void addHandlers(AsyncXMLReader xmlReader) throws Exception{ xmlReader.setContentHandler(jaxbContext.createUnmarshaller().getUnmarshallerHandler()); } @Override protected void parsingCompleted(Exchange exchange, Message msg, AsyncXMLReader xmlReader){ UnmarshallerHandler handler = (UnmarshallerHandler)xmlReader.getContentHandler(); try{ String contentType = msg.getPayload().getMediaType().withCharset(IOUtil.UTF_8.name()).toString(); msg.setPayload(new JAXBPayload(contentType, handler.getResult(), jaxbContext)); }catch(Throwable thr){ exchange.resume(thr); return; } super.parsingCompleted(exchange, msg, xmlReader); } }
3e086dce8681c1cd3beb053f73f68d883f34ceca
1,486
java
Java
modules/flowable-engine/src/test/java/org/flowable/engine/test/api/runtime/migration/ConvertProcessVariable.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
5,250
2016-10-13T08:15:16.000Z
2022-03-31T13:53:26.000Z
modules/flowable-engine/src/test/java/org/flowable/engine/test/api/runtime/migration/ConvertProcessVariable.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
1,736
2016-10-13T17:03:10.000Z
2022-03-31T19:27:39.000Z
modules/flowable-engine/src/test/java/org/flowable/engine/test/api/runtime/migration/ConvertProcessVariable.java
le-shi/flowable-engine
0b610fd04b23769212f328cee330a65991fa7683
[ "Apache-2.0" ]
2,271
2016-10-13T08:27:26.000Z
2022-03-31T15:36:02.000Z
38.102564
92
0.746299
3,568
/* 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.flowable.engine.test.api.runtime.migration; import java.io.Serializable; import java.util.List; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.JavaDelegate; import org.flowable.engine.impl.context.Context; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; /** * @author martin.grofcik */ public class ConvertProcessVariable implements JavaDelegate, Serializable { @Override public void execute(DelegateExecution execution) { List<String> list = (List<String>) execution.getVariable("listVariable"); ObjectMapper mapper = Context.getProcessEngineConfiguration().getObjectMapper(); ArrayNode jsonArray = mapper.createArrayNode(); list.forEach(listItem -> jsonArray.add(listItem)); execution.setVariable("listVariable", jsonArray); } }
3e086e7e23c3e23bbe1b1a67630c4309b2a50b3b
2,469
java
Java
starter-core/src/main/java/io/micronaut/starter/feature/kotlin/Ktor.java
grimmjo/micronaut-starter
ff98bc1af4d8d1a42555c86fc69e472cff779b13
[ "Apache-2.0" ]
1
2020-05-08T14:45:27.000Z
2020-05-08T14:45:27.000Z
starter-core/src/main/java/io/micronaut/starter/feature/kotlin/Ktor.java
alexismp/micronaut-starter
17b0384dd5bba93c8a3920e719b56f73e9099998
[ "Apache-2.0" ]
null
null
null
starter-core/src/main/java/io/micronaut/starter/feature/kotlin/Ktor.java
alexismp/micronaut-starter
17b0384dd5bba93c8a3920e719b56f73e9099998
[ "Apache-2.0" ]
null
null
null
30.481481
96
0.690563
3,569
/* * Copyright 2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.starter.feature.kotlin; import edu.umd.cs.findbugs.annotations.NonNull; import io.micronaut.starter.application.ApplicationType; import io.micronaut.starter.feature.Category; import io.micronaut.starter.feature.Feature; import io.micronaut.starter.feature.FeatureContext; import io.micronaut.starter.feature.FeaturePredicate; import io.micronaut.starter.feature.LanguageSpecificFeature; import io.micronaut.starter.feature.server.ServerFeature; import io.micronaut.starter.options.Language; import javax.inject.Singleton; import java.util.Optional; @Singleton public class Ktor implements ServerFeature, LanguageSpecificFeature { @Override public boolean supports(ApplicationType applicationType) { return applicationType == ApplicationType.DEFAULT; } @Override public void processSelectedFeatures(FeatureContext featureContext) { if (featureContext.getLanguage() != Language.KOTLIN) { featureContext.exclude(new FeaturePredicate() { @Override public boolean test(Feature feature) { return feature instanceof Ktor; } @Override public Optional<String> getWarning() { return Optional.of("Ktor feature only supports Kotlin"); } }); } } @NonNull @Override public String getName() { return "ktor"; } @Override public String getDescription() { return "Support for using Ktor as the server instead of Micronaut’s native HTTP server"; } @Override public String getTitle() { return "Ktor"; } @Override public String getCategory() { return Category.LANGUAGES; } @Override public Language getRequiredLanguage() { return Language.KOTLIN; } }
3e086eafe6e7b1efc8eca07ee84e59f3d1e3a516
4,373
java
Java
clients/google-api-services-dialogflow/v2beta1/1.31.0/com/google/api/services/dialogflow/v2beta1/model/GoogleCloudDialogflowV2HumanAgentAssistantEvent.java
yoshi-code-bot/google-api-java-client-services
9f5e3b6073c822db4078d638c980b11a0effc686
[ "Apache-2.0" ]
372
2018-09-05T21:06:51.000Z
2022-03-31T09:22:03.000Z
clients/google-api-services-dialogflow/v2beta1/1.31.0/com/google/api/services/dialogflow/v2beta1/model/GoogleCloudDialogflowV2HumanAgentAssistantEvent.java
yoshi-code-bot/google-api-java-client-services
9f5e3b6073c822db4078d638c980b11a0effc686
[ "Apache-2.0" ]
1,351
2018-10-12T23:07:12.000Z
2022-03-05T09:25:29.000Z
clients/google-api-services-dialogflow/v2beta1/1.31.0/com/google/api/services/dialogflow/v2beta1/model/GoogleCloudDialogflowV2HumanAgentAssistantEvent.java
yoshi-code-bot/google-api-java-client-services
9f5e3b6073c822db4078d638c980b11a0effc686
[ "Apache-2.0" ]
307
2018-09-04T20:15:31.000Z
2022-03-31T09:42:39.000Z
36.747899
182
0.743883
3,570
/* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v2beta1.model; /** * Represents a notification sent to Cloud Pub/Sub subscribers for human agent assistant events in a * specific conversation. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2HumanAgentAssistantEvent extends com.google.api.client.json.GenericJson { /** * The conversation this notification refers to. Format: `projects//conversations/`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String conversation; /** * The participant that the suggestion is compiled for. Format: * `projects//conversations//participants/`. It will not be set in legacy workflow. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String participant; /** * The suggestion results payload that this notification refers to. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowV2SuggestionResult> suggestionResults; /** * The conversation this notification refers to. Format: `projects//conversations/`. * @return value or {@code null} for none */ public java.lang.String getConversation() { return conversation; } /** * The conversation this notification refers to. Format: `projects//conversations/`. * @param conversation conversation or {@code null} for none */ public GoogleCloudDialogflowV2HumanAgentAssistantEvent setConversation(java.lang.String conversation) { this.conversation = conversation; return this; } /** * The participant that the suggestion is compiled for. Format: * `projects//conversations//participants/`. It will not be set in legacy workflow. * @return value or {@code null} for none */ public java.lang.String getParticipant() { return participant; } /** * The participant that the suggestion is compiled for. Format: * `projects//conversations//participants/`. It will not be set in legacy workflow. * @param participant participant or {@code null} for none */ public GoogleCloudDialogflowV2HumanAgentAssistantEvent setParticipant(java.lang.String participant) { this.participant = participant; return this; } /** * The suggestion results payload that this notification refers to. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowV2SuggestionResult> getSuggestionResults() { return suggestionResults; } /** * The suggestion results payload that this notification refers to. * @param suggestionResults suggestionResults or {@code null} for none */ public GoogleCloudDialogflowV2HumanAgentAssistantEvent setSuggestionResults(java.util.List<GoogleCloudDialogflowV2SuggestionResult> suggestionResults) { this.suggestionResults = suggestionResults; return this; } @Override public GoogleCloudDialogflowV2HumanAgentAssistantEvent set(String fieldName, Object value) { return (GoogleCloudDialogflowV2HumanAgentAssistantEvent) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2HumanAgentAssistantEvent clone() { return (GoogleCloudDialogflowV2HumanAgentAssistantEvent) super.clone(); } }
3e086fce4c0df98374d787aa7fe654d1542048fd
22,201
java
Java
apis/api-web/api-web-bo-business/src/main/java/org/hoteia/qalingo/web/mvc/controller/ajax/CatalogAjaxController.java
AppSecAI-TEST/qalingo-engine
7380084369034012d9ad6cb1ab4973ce7960aa2d
[ "Apache-2.0" ]
321
2015-01-04T08:13:13.000Z
2021-12-29T02:27:29.000Z
apis/api-web/api-web-bo-business/src/main/java/org/hoteia/qalingo/web/mvc/controller/ajax/CatalogAjaxController.java
AppSecAI-TEST/qalingo-engine
7380084369034012d9ad6cb1ab4973ce7960aa2d
[ "Apache-2.0" ]
24
2021-04-02T13:21:00.000Z
2022-02-10T09:22:15.000Z
apis/api-web/api-web-bo-business/src/main/java/org/hoteia/qalingo/web/mvc/controller/ajax/CatalogAjaxController.java
Rostov1991/qalingo-engine
cd48ffe14fe2a6a14e3fbb777b3e2ce6a7454621
[ "Apache-2.0" ]
220
2015-01-04T08:04:53.000Z
2022-01-25T06:46:44.000Z
67.075529
298
0.724709
3,571
/** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - [email protected] * */ package org.hoteia.qalingo.web.mvc.controller.ajax; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.hoteia.qalingo.core.RequestConstants; import org.hoteia.qalingo.core.domain.CatalogCategoryMaster; import org.hoteia.qalingo.core.domain.CatalogCategoryMasterProductSkuRel; import org.hoteia.qalingo.core.domain.CatalogCategoryMaster_; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuRel; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuRel_; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual_; import org.hoteia.qalingo.core.domain.CatalogMaster; import org.hoteia.qalingo.core.domain.CatalogVirtual; import org.hoteia.qalingo.core.domain.MarketArea; import org.hoteia.qalingo.core.domain.ProductMarketing; import org.hoteia.qalingo.core.domain.ProductMarketing_; import org.hoteia.qalingo.core.domain.ProductSku; import org.hoteia.qalingo.core.domain.ProductSkuStorePrice_; import org.hoteia.qalingo.core.domain.ProductSku_; import org.hoteia.qalingo.core.domain.enumtype.BoUrls; import org.hoteia.qalingo.core.fetchplan.FetchPlan; import org.hoteia.qalingo.core.fetchplan.SpecificFetchMode; import org.hoteia.qalingo.core.pojo.catalog.BoCatalogCategoryPojo; import org.hoteia.qalingo.core.pojo.catalog.CatalogPojo; import org.hoteia.qalingo.core.pojo.product.ProductMarketingPojo; import org.hoteia.qalingo.core.pojo.product.ProductSkuPojo; import org.hoteia.qalingo.core.service.CatalogCategoryService; import org.hoteia.qalingo.core.service.CatalogService; import org.hoteia.qalingo.core.service.ProductService; import org.hoteia.qalingo.core.service.pojo.CatalogPojoService; import org.hoteia.qalingo.core.web.resolver.RequestData; import org.hoteia.qalingo.web.mvc.controller.AbstractBusinessBackofficeController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * */ @Controller("catalogAjaxController") public class CatalogAjaxController extends AbstractBusinessBackofficeController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected CatalogService catalogService; @Autowired private CatalogPojoService catalogPojoService; @Autowired protected ProductService productService; @Autowired protected CatalogCategoryService catalogCategoryService; protected List<SpecificFetchMode> categoryMasterFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> categoryVirtualFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> productMarketingFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> productSkuFetchPlans = new ArrayList<SpecificFetchMode>(); public CatalogAjaxController() { categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.catalogCategories.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.parentCatalogCategory.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.attributes.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.catalogCategoryType.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategories.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.parentCatalogCategory.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.attributes.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.categoryMaster.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.parentCatalogCategory.getName() + "." + CatalogCategoryVirtual_.categoryMaster.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.categoryMaster.getName() + "." + CatalogCategoryMaster_.catalogCategoryType.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productBrand.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productMarketingType.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.attributes.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName() + "." + ProductSku_.prices.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName() + "." + ProductSku_.prices.getName() + "." + ProductSkuStorePrice_.currency.getName())); productSkuFetchPlans.add(new SpecificFetchMode(ProductSku_.productMarketing.getName())); productSkuFetchPlans.add(new SpecificFetchMode(ProductSku_.attributes.getName())); } @RequestMapping(value = BoUrls.GET_CATALOG_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public CatalogPojo getCatalog(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final MarketArea currentMarketArea = requestData.getMarketArea(); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); CatalogPojo catalogPojo = new CatalogPojo(); if("master".equals(catalogType)){ final CatalogMaster catalogMaster = catalogService.getMasterCatalogById(currentMarketArea.getCatalog().getCatalogMaster().getId()); Set<CatalogCategoryMaster> catalogCategories = new HashSet<CatalogCategoryMaster>(); if(catalogMaster.getCatalogCategories() != null){ for (Iterator<CatalogCategoryMaster> iterator = catalogMaster.getCatalogCategories().iterator(); iterator.hasNext();) { CatalogCategoryMaster categoryMaster = (CatalogCategoryMaster) iterator.next(); CatalogCategoryMaster reloadedCategoryMaster = catalogCategoryService.getMasterCatalogCategoryById(categoryMaster.getId(), new FetchPlan(categoryMasterFetchPlans)); Set<CatalogCategoryMaster> reloadedSubCategories = new HashSet<CatalogCategoryMaster>(); if(reloadedCategoryMaster.getSortedChildCatalogCategories() != null){ for (Iterator<CatalogCategoryMaster> iteratorSubCategories = reloadedCategoryMaster.getSortedChildCatalogCategories().iterator(); iteratorSubCategories.hasNext();) { CatalogCategoryMaster subCategory = (CatalogCategoryMaster) iteratorSubCategories.next(); CatalogCategoryMaster reloadedSubCategory = catalogCategoryService.getMasterCatalogCategoryById(subCategory.getId(), new FetchPlan(categoryMasterFetchPlans)); reloadedSubCategories.add(reloadedSubCategory); } } reloadedCategoryMaster.setCatalogCategories(reloadedSubCategories); catalogCategories.add(reloadedCategoryMaster); } } catalogMaster.setCatalogCategories(new HashSet<CatalogCategoryMaster>(catalogCategories)); try { catalogPojo = (CatalogPojo) catalogPojoService.buildMasterCatalog(catalogMaster); } catch (Exception e) { logger.error("", e); } } else if("virtual".equals(catalogType)){ final CatalogVirtual catalogVirtual = catalogService.getVirtualCatalogById(currentMarketArea.getCatalog().getId()); Set<CatalogCategoryVirtual> catalogCategories = new HashSet<CatalogCategoryVirtual>(); if(catalogVirtual.getCatalogCategories() != null){ for (Iterator<CatalogCategoryVirtual> iterator = catalogVirtual.getCatalogCategories().iterator(); iterator.hasNext();) { CatalogCategoryVirtual categoryVirtual = (CatalogCategoryVirtual) iterator.next(); CatalogCategoryVirtual reloadedCategoryVirtual = catalogCategoryService.getVirtualCatalogCategoryById(categoryVirtual.getId(), new FetchPlan(categoryVirtualFetchPlans)); Set<CatalogCategoryVirtual> reloadedSubCategories = new HashSet<CatalogCategoryVirtual>(); if(reloadedCategoryVirtual.getSortedChildCatalogCategories() != null){ for (Iterator<CatalogCategoryVirtual> iteratorSubCategories = reloadedCategoryVirtual.getSortedChildCatalogCategories().iterator(); iteratorSubCategories.hasNext();) { CatalogCategoryVirtual subCategory = (CatalogCategoryVirtual) iteratorSubCategories.next(); CatalogCategoryVirtual reloadedSubCategory = catalogCategoryService.getVirtualCatalogCategoryById(subCategory.getId(), new FetchPlan(categoryVirtualFetchPlans)); reloadedSubCategories.add(reloadedSubCategory); } } reloadedCategoryVirtual.setCatalogCategories(reloadedSubCategories); catalogCategories.add(reloadedCategoryVirtual); } } catalogVirtual.setCatalogCategories(new HashSet<CatalogCategoryVirtual>(catalogCategories)); try { catalogPojo = (CatalogPojo) catalogPojoService.buildVirtualCatalog(catalogVirtual); } catch (Exception e) { logger.error("", e); } } return catalogPojo; } @RequestMapping(value = BoUrls.GET_PRODUCT_LIST_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo getProductListByCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ FetchPlan fetchPlanWithProducts = new FetchPlan(categoryMasterFetchPlans); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName())); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode("catalogCategoryProductSkuRels.pk.productSku")); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.assets.getName())); CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), fetchPlanWithProducts); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); final List<ProductSku> productSkus = reloadedCategory.getSortedProductSkus(); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } else if("virtual".equals(catalogType)){ FetchPlan fetchPlanWithProducts = new FetchPlan(categoryVirtualFetchPlans); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName())); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName() + "." + CatalogCategoryVirtualProductSkuRel_.pk.getName() + "." + org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuPk_.productSku.getName())); CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), fetchPlanWithProducts); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); final List<ProductSku> productSkus = reloadedCategory.getSortedProductSkus(); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } return catalogCategoryPojo; } @RequestMapping(value = BoUrls.GET_PRODUCT_LIST_FOR_CATALOG_CATEGORY_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo getProductListForCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), new FetchPlan(categoryMasterFetchPlans)); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); List<ProductSku> productSkus = productService.findProductSkusNotInThisMasterCatalogCategoryId(reloadedCategory.getId(), new FetchPlan(productSkuFetchPlans)); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } else if("virtual".equals(catalogType)){ CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), new FetchPlan(categoryVirtualFetchPlans)); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); List<ProductSku> productSkus = productService.findProductSkusNotInThisVirtualCatalogCategoryId(reloadedCategory.getId(), new FetchPlan(productSkuFetchPlans)); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } return catalogCategoryPojo; } @RequestMapping(value = BoUrls.SET_PRODUCT_LIST_FOR_CATALOG_CATEGORY_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo setProductListForCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); final String skuCodes = request.getParameter(RequestConstants.REQUEST_PARAMETER_SKU_CODE_LIST); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), new FetchPlan(categoryMasterFetchPlans)); if(StringUtils.isNotEmpty(skuCodes)){ List<String> productSkuCodes = reloadedCategory.getProductSkuCodes(); String[] skuCodesSplit = skuCodes.split(";"); for (int i = 0; i < skuCodesSplit.length; i++) { String skuCode = skuCodesSplit[i]; if(productSkuCodes != null && !productSkuCodes.contains(skuCode)){ final ProductSku reloadedProductSku = productService.getProductSkuByCode(skuCode, new FetchPlan(productSkuFetchPlans)); if(reloadedProductSku != null){ reloadedCategory.getCatalogCategoryProductSkuRels().add(new CatalogCategoryMasterProductSkuRel(reloadedCategory, reloadedProductSku)); reloadedCategory = catalogCategoryService.saveOrUpdateCatalogCategory(reloadedCategory); } } } } catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); } else if("virtual".equals(catalogType)){ CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), new FetchPlan(categoryVirtualFetchPlans)); if(StringUtils.isNotEmpty(skuCodes)){ List<String> productSkuCodes = reloadedCategory.getProductSkuCodes(); String[] skuCodesSplit = skuCodes.split(";"); for (int i = 0; i < skuCodesSplit.length; i++) { String skuCode = skuCodesSplit[i]; if(productSkuCodes != null && !productSkuCodes.contains(skuCode)){ final ProductSku reloadedProductSku = productService.getProductSkuByCode(skuCode, new FetchPlan(productSkuFetchPlans)); if(reloadedProductSku != null){ reloadedCategory.getCatalogCategoryProductSkuRels().add(new CatalogCategoryVirtualProductSkuRel(reloadedCategory, reloadedProductSku)); reloadedCategory = catalogCategoryService.saveOrUpdateCatalogCategory(reloadedCategory); } } } } catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); } return catalogCategoryPojo; } protected List<ProductMarketingPojo> buildSortedProduct(List<ProductSku> productSkus){ List<Long> productSkuIds = new ArrayList<Long>(); for (Iterator<ProductSku> iterator = productSkus.iterator(); iterator.hasNext();) { ProductSku productSku = (ProductSku) iterator.next(); productSkuIds.add(productSku.getId()); } Map<String, ProductMarketingPojo> productMarketingMap = new HashMap<String, ProductMarketingPojo>(); for (Iterator<ProductSku> iteratorProductSku = productSkus.iterator(); iteratorProductSku.hasNext();) { final ProductSku productSku = (ProductSku) iteratorProductSku.next(); final ProductSku reloadedProductSku = productService.getProductSkuByCode(productSku.getCode(), new FetchPlan(productSkuFetchPlans)); final ProductMarketing reloadedProductMarketing = productService.getProductMarketingById(reloadedProductSku.getProductMarketing().getId(), new FetchPlan(productMarketingFetchPlans)); ProductMarketingPojo productMarketingPojo = catalogPojoService.buildProductMarketing(reloadedProductMarketing); // CLEAN NOT AVAILABLE SKU List<ProductSkuPojo> productSkuPojos = new ArrayList<ProductSkuPojo>(productMarketingPojo.getProductSkus()); for (Iterator<ProductSkuPojo> iterator = productSkuPojos.iterator(); iterator.hasNext();) { ProductSkuPojo productSkuPojo = (ProductSkuPojo) iterator.next(); if(!productSkuIds.contains(productSkuPojo.getId())){ productMarketingPojo.getProductSkus().remove(productSkuPojo); } } productMarketingMap.put(productMarketingPojo.getCode(), productMarketingPojo); } List<ProductMarketingPojo> sortedProductMarketings = new LinkedList<ProductMarketingPojo>(productMarketingMap.values()); Collections.sort(sortedProductMarketings, new Comparator<ProductMarketingPojo>() { @Override public int compare(ProductMarketingPojo o1, ProductMarketingPojo o2) { if (o1 != null && o2 != null) { return o1.getCode().compareTo(o2.getCode()); } return 0; } }); return sortedProductMarketings; } }
3e086fe943271bdef6bf11bbeea8ee89a6306d8a
724
java
Java
src/main/java/com/aiw/bdzb/entity/Subject.java
yolo3a525/AiwSM
e56ed9931e525af2ef89dbe1882dddfa172f747d
[ "MIT" ]
null
null
null
src/main/java/com/aiw/bdzb/entity/Subject.java
yolo3a525/AiwSM
e56ed9931e525af2ef89dbe1882dddfa172f747d
[ "MIT" ]
4
2020-05-15T19:42:16.000Z
2021-09-20T20:33:51.000Z
src/main/java/com/aiw/bdzb/entity/Subject.java
yolo3a525/AiwSM
e56ed9931e525af2ef89dbe1882dddfa172f747d
[ "MIT" ]
null
null
null
19.052632
43
0.689227
3,572
package com.aiw.bdzb.entity; import com.aiw.base.entity.BaseEntity; public class Subject extends BaseEntity { private String content; private String title; private Integer imgFlag; private Integer status; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getImgFlag() { return imgFlag; } public void setImgFlag(Integer imgFlag) { this.imgFlag = imgFlag; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
3e086ff823d550c3c05c54a9e441981392a26ce4
2,030
java
Java
flink-core/src/test/java/org/apache/flink/types/BasicArrayTypeInfoTest.java
TU-Berlin-DIMA/sage-flink
7439cc4e57889e752fd3da71e16696af1baf82ce
[ "BSD-3-Clause" ]
80
2016-08-11T03:07:28.000Z
2022-03-27T06:47:09.000Z
flink-core/src/test/java/org/apache/flink/types/BasicArrayTypeInfoTest.java
TU-Berlin-DIMA/sage-flink
7439cc4e57889e752fd3da71e16696af1baf82ce
[ "BSD-3-Clause" ]
6
2019-11-13T04:08:37.000Z
2021-08-09T20:46:08.000Z
flink-core/src/test/java/org/apache/flink/types/BasicArrayTypeInfoTest.java
TU-Berlin-DIMA/sage-flink
7439cc4e57889e752fd3da71e16696af1baf82ce
[ "BSD-3-Clause" ]
40
2016-08-12T05:40:51.000Z
2022-01-11T08:01:04.000Z
35.614035
93
0.737931
3,573
/* * 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.flink.types; import org.apache.flink.api.common.typeinfo.BasicArrayTypeInfo; import org.apache.flink.util.TestLogger; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class BasicArrayTypeInfoTest extends TestLogger { static Class<?>[] classes = {String[].class, Integer[].class, Boolean[].class, Byte[].class, Short[].class, Long[].class, Float[].class, Double[].class, Character[].class}; @Test public void testBasicArrayTypeInfoEquality() { for (Class<?> clazz: classes) { BasicArrayTypeInfo<?, ?> tpeInfo1 = BasicArrayTypeInfo.getInfoFor(clazz); BasicArrayTypeInfo<?, ?> tpeInfo2 = BasicArrayTypeInfo.getInfoFor(clazz); assertEquals(tpeInfo1, tpeInfo2); assertEquals(tpeInfo1.hashCode(), tpeInfo2.hashCode()); } } @Test public void testBasicArrayTypeInfoInequality() { for (Class<?> clazz1: classes) { for (Class<?> clazz2: classes) { if (!clazz1.equals(clazz2)) { BasicArrayTypeInfo<?, ?> tpeInfo1 = BasicArrayTypeInfo.getInfoFor(clazz1); BasicArrayTypeInfo<?, ?> tpeInfo2 = BasicArrayTypeInfo.getInfoFor(clazz2); assertNotEquals(tpeInfo1, tpeInfo2); } } } } }
3e0870e91cf7fc76358cc947813d63b807523008
1,369
java
Java
Data/Juliet-Java/Juliet-Java-v103/000/132/789/CWE197_Numeric_Truncation_Error__int_Environment_to_byte_72b.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/132/789/CWE197_Numeric_Truncation_Error__int_Environment_to_byte_72b.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/132/789/CWE197_Numeric_Truncation_Error__int_Environment_to_byte_72b.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
29.76087
128
0.672754
3,574
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE197_Numeric_Truncation_Error__int_Environment_to_byte_72b.java Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml Template File: sources-sink-72b.tmpl.java */ /* * @description * CWE: 197 Numeric Truncation Error * BadSource: Environment Read data from an environment variable * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: to_byte * BadSink : Convert data to a byte * Flow Variant: 72 Data flow: data passed in a Vector from one method to another in different source files in the same package * * */ import java.util.Vector; public class CWE197_Numeric_Truncation_Error__int_Environment_to_byte_72b { public void badSink(Vector<Integer> dataVector ) throws Throwable { int data = dataVector.remove(2); { /* POTENTIAL FLAW: Convert data to a byte, possibly causing a truncation error */ IO.writeLine((byte)data); } } /* goodG2B() - use goodsource and badsink */ public void goodG2BSink(Vector<Integer> dataVector ) throws Throwable { int data = dataVector.remove(2); { /* POTENTIAL FLAW: Convert data to a byte, possibly causing a truncation error */ IO.writeLine((byte)data); } } }
3e0871431f72314c51326453c92485377a2b9739
6,783
java
Java
MatisseLib/src/org/specs/matisselib/ssa/SsaBlock.java
specs-feup/matisse
8e0838e3f42cac0a5f5be8979a3444231b9ba944
[ "Apache-2.0" ]
null
null
null
MatisseLib/src/org/specs/matisselib/ssa/SsaBlock.java
specs-feup/matisse
8e0838e3f42cac0a5f5be8979a3444231b9ba944
[ "Apache-2.0" ]
null
null
null
MatisseLib/src/org/specs/matisselib/ssa/SsaBlock.java
specs-feup/matisse
8e0838e3f42cac0a5f5be8979a3444231b9ba944
[ "Apache-2.0" ]
null
null
null
33.746269
118
0.679493
3,575
/** * Copyright 2015 SPeCS. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. under the License. */ package org.specs.matisselib.ssa; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.specs.matisselib.ssa.instructions.AssignmentInstruction; import org.specs.matisselib.ssa.instructions.CommentInstruction; import org.specs.matisselib.ssa.instructions.SsaInstruction; import com.google.common.base.Preconditions; public class SsaBlock { private final List<SsaInstruction> instructions = new ArrayList<>(); public void addInstruction(SsaInstruction instruction) { Preconditions.checkArgument(instruction != null); this.instructions.add(instruction); } public void addInstructions(List<SsaInstruction> instructions) { Preconditions.checkArgument(instructions != null); this.instructions.addAll(instructions); } public void prependInstruction(SsaInstruction instruction) { Preconditions.checkArgument(instruction != null); this.instructions.add(0, instruction); } public void prependInstructions(List<SsaInstruction> instructions) { Preconditions.checkArgument(instructions != null); this.instructions.addAll(0, instructions); } public void insertInstruction(int index, SsaInstruction instruction) { Preconditions.checkArgument(index >= 0 && index <= this.instructions.size()); Preconditions.checkArgument(instruction != null); this.instructions.add(index, instruction); } public void insertInstructions(int index, List<SsaInstruction> instructions) { Preconditions.checkArgument(index >= 0 && index <= this.instructions.size()); Preconditions.checkArgument(instructions != null); this.instructions.addAll(index, instructions); } public List<SsaInstruction> getInstructions() { return this.instructions; } public boolean isEmpty() { return this.instructions.isEmpty(); } @Override public String toString() { return this.instructions .stream() .map(instruction -> instruction.toString()) .collect(Collectors.joining("\n")); } public void renameVariables(Map<String, String> newNames) { Preconditions.checkArgument(newNames != null); for (SsaInstruction instruction : getInstructions()) { instruction.renameVariables(newNames); } } public void replaceInstructionAt(int instructionId, List<SsaInstruction> instructionsToInsert) { this.instructions.remove(instructionId); this.instructions.addAll(instructionId, instructionsToInsert); } public void replaceInstructionAt(int instructionId, SsaInstruction newInstruction) { this.instructions.set(instructionId, newInstruction); } public SsaInstruction removeLastInstruction() { Preconditions.checkState(this.instructions.size() > 0); return this.instructions.remove(this.instructions.size() - 1); } public void removeInstructionsFrom(int instructionId) { Preconditions.checkArgument(instructionId >= 0); Preconditions.checkArgument(instructionId < this.instructions.size()); while (this.instructions.size() > instructionId) { this.instructions.remove(this.instructions.size() - 1); } } /** * Gets the "ending instruction" of the block. An instruction is "ending" if it can only appear as the last * instruction of a block. For instance, sets are not ending instructions, but branches and breaks are. * * @return The ending instruction of the block, or empty if there isn't any. * @see SsaInstruction#isEndingInstruction() */ public Optional<SsaInstruction> getEndingInstruction() { if (this.instructions.size() == 0) { return Optional.empty(); } SsaInstruction lastInstruction = this.instructions.get(this.instructions.size() - 1); if (lastInstruction.isEndingInstruction()) { return Optional.of(lastInstruction); } return Optional.empty(); } public boolean hasSideEffects() { return this.instructions .stream() .map(instruction -> instruction.getInstructionType()) .anyMatch( type -> type == InstructionType.HAS_SIDE_EFFECT || type == InstructionType.HAS_VALIDATION_SIDE_EFFECT); } public boolean usesVariable(String variable) { Preconditions.checkArgument(variable != null); for (SsaInstruction instruction : this.instructions) { if (instruction.getInputVariables().contains(variable)) { return true; } } return false; } public SsaBlock copy() { SsaBlock newBlock = new SsaBlock(); for (SsaInstruction instruction : getInstructions()) { newBlock.addInstruction(instruction.copy()); } return newBlock; } public void removeInstructionAt(int instructionId) { this.instructions.remove(instructionId); } // Helper operations public void addAssignment(String variable, int value) { addInstruction(AssignmentInstruction.fromInteger(variable, value)); } public void addAssignment(String out, String in) { addInstruction(AssignmentInstruction.fromVariable(out, in)); } public void addComment(String content) { addInstruction(new CommentInstruction(content)); } public void breakBlock(int originalBlock, int startBlock, int endBlock) { for (SsaInstruction instruction : this.instructions) { instruction.breakBlock(originalBlock, startBlock, endBlock); } } public void renameBlocks(List<Integer> oldNames, List<Integer> newNames) { for (SsaInstruction instruction : this.instructions) { instruction.renameBlocks(oldNames, newNames); } } public void removeInstructions(List<SsaInstruction> instructionsToRemove) { instructions.removeAll(instructionsToRemove); } }
3e087211ca2abe3bda833099ee9d7406b2dc5a80
3,433
java
Java
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/schedule/WeeklyScheduleOnDayCalculator.java
emcleod/OG-Platform
dbd4e1c64907f6a2dd27a62d252e9c61e609f779
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/schedule/WeeklyScheduleOnDayCalculator.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
10
2017-01-19T13:32:36.000Z
2021-09-20T20:41:48.000Z
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/schedule/WeeklyScheduleOnDayCalculator.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
33.990099
154
0.715118
3,576
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.schedule; import java.util.ArrayList; import java.util.List; import org.threeten.bp.DayOfWeek; import org.threeten.bp.LocalDate; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.temporal.TemporalAdjusters; import com.opengamma.util.ArgumentChecker; /** * */ public class WeeklyScheduleOnDayCalculator extends Schedule { private final DayOfWeek _dayOfWeek; public WeeklyScheduleOnDayCalculator(final DayOfWeek dayOfWeek) { _dayOfWeek = dayOfWeek; } @Override public LocalDate[] getSchedule(final LocalDate startDate, final LocalDate endDate, final boolean fromEnd, final boolean generateRecursive) { return getSchedule(startDate, endDate); } public LocalDate[] getSchedule(final LocalDate startDate, final LocalDate endDate) { ArgumentChecker.notNull(startDate, "start date"); ArgumentChecker.notNull(endDate, "end date"); ArgumentChecker.isFalse(startDate.isAfter(endDate), "start date must not be after end date"); if (startDate.equals(endDate)) { if (startDate.getDayOfWeek() == _dayOfWeek) { return new LocalDate[] {startDate}; } throw new IllegalArgumentException("Start date and end date were the same but their day of week was not the same as that required"); } final List<LocalDate> dates = new ArrayList<>(); LocalDate date = startDate; date = date.with(TemporalAdjusters.nextOrSame(_dayOfWeek)); while (!date.isAfter(endDate)) { dates.add(date); date = date.with(TemporalAdjusters.next(_dayOfWeek)); } return dates.toArray(EMPTY_LOCAL_DATE_ARRAY); } @Override public ZonedDateTime[] getSchedule(final ZonedDateTime startDate, final ZonedDateTime endDate, final boolean fromEnd, final boolean generateRecursive) { return getSchedule(startDate, endDate); } public ZonedDateTime[] getSchedule(final ZonedDateTime startDate, final ZonedDateTime endDate) { ArgumentChecker.notNull(startDate, "start date"); ArgumentChecker.notNull(endDate, "end date"); ArgumentChecker.isFalse(startDate.isAfter(endDate), "start date must not be after end date"); if (startDate.equals(endDate)) { if (startDate.getDayOfWeek() == _dayOfWeek) { return new ZonedDateTime[] {startDate}; } throw new IllegalArgumentException("Start date and end date were the same but their day of week was not the same as that required"); } final List<ZonedDateTime> dates = new ArrayList<>(); ZonedDateTime date = startDate; date = date.with(TemporalAdjusters.nextOrSame(_dayOfWeek)); while (!date.isAfter(endDate)) { dates.add(date); date = date.with(TemporalAdjusters.next(_dayOfWeek)); } return dates.toArray(EMPTY_ZONED_DATE_TIME_ARRAY); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _dayOfWeek.hashCode(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WeeklyScheduleOnDayCalculator other = (WeeklyScheduleOnDayCalculator) obj; return _dayOfWeek == other._dayOfWeek; } }
3e0873850623f7b32c7998e7ddf2075cecb109eb
8,155
java
Java
depclean-gradle-plugin/src/main/java/se/kth/depclean/gradle/task/DepCleanTask.java
jfneis/depclean
d128463d36bd74caa4fe4b4b1c4ec92f4a3d1536
[ "MIT" ]
null
null
null
depclean-gradle-plugin/src/main/java/se/kth/depclean/gradle/task/DepCleanTask.java
jfneis/depclean
d128463d36bd74caa4fe4b4b1c4ec92f4a3d1536
[ "MIT" ]
null
null
null
depclean-gradle-plugin/src/main/java/se/kth/depclean/gradle/task/DepCleanTask.java
jfneis/depclean
d128463d36bd74caa4fe4b4b1c4ec92f4a3d1536
[ "MIT" ]
null
null
null
46.335227
167
0.678479
3,577
package se.kth.depclean.gradle.task; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.TaskAction; import se.kth.depclean.core.analysis.ProjectDependencyAnalysis; import se.kth.depclean.core.analysis.ProjectDependencyAnalyzer; import se.kth.depclean.core.analysis.ProjectDependencyAnalyzerException; import se.kth.depclean.gradle.DepCleanExtension; import se.kth.depclean.gradle.analysis.GradleDependencyAnalyzer; import se.kth.depclean.gradle.dt.InputType; import se.kth.depclean.gradle.dt.Node; import se.kth.depclean.gradle.dt.ParseException; import se.kth.depclean.gradle.dt.Parser; import se.kth.depclean.gradle.util.JarUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class DepCleanTask extends DefaultTask { @TaskAction public void depcleanAction() throws FileNotFoundException, UnsupportedEncodingException { DepCleanExtension extension = getProject().getExtensions().findByType(DepCleanExtension.class); if (extension == null) { extension = new DepCleanExtension(); } String message = extension.getMessage(); HelloWorld helloWorld = new HelloWorld(message); System.out.println(helloWorld.greet()); System.out.println("-------------------------------------------------------"); /* Initialize the Gradle connector */ GradleConnector connector = new GradleConnector(getProject().getGradle().getGradleHomeDir().getAbsolutePath(), getProject().getProjectDir().getAbsolutePath()); /* Copy direct dependencies locally */ connector.executeTask("copyDependencies"); /* Decompress dependencies */ JarUtils.decompressJars(getProject().getBuildDir().getAbsolutePath() + "/dependencies"); /* Generate a model */ connector.executeTask("install"); Model model = null; FileReader pomReader = null; MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader(); try { pomReader = new FileReader(getProject().getBuildDir().getAbsolutePath() + "/poms/pom-default.xml"); model = mavenXpp3Reader.read(pomReader); model.setPomFile(new File(getProject().getBuildDir().getAbsolutePath() + "/poms/pom-default.xml")); } catch (Exception ex) { } MavenProject project = new MavenProject(model); Build build = new Build(); build.setDirectory(getProject().getBuildDir().getAbsolutePath()); project.setBuild(build); /* Analyze dependencies usage status */ ProjectDependencyAnalysis projectDependencyAnalysis; try { ProjectDependencyAnalyzer dependencyAnalyzer = new GradleDependencyAnalyzer(); projectDependencyAnalysis = dependencyAnalyzer.analyze(project); } catch (ProjectDependencyAnalyzerException e) { getLogger().error("Unable to analyze dependencies."); return; } printAnalysisResults(project, projectDependencyAnalysis); connector.executeTask("dependencyReportFile"); String pathToDependencyTree = getProject().getBuildDir().getAbsolutePath() + "/dependencies/dependencies.txt"; removeBlankLines(pathToDependencyTree); // parsing the dependency tree InputType type = InputType.TEXT; Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pathToDependencyTree), StandardCharsets.UTF_8)); Parser parser = type.newParser(); try { Node tree = parser.parse(reader); System.out.println("direct dependencies: "); for (Node childNode : tree.getChildNodes()) { System.out.println("\t" + childNode.getArtifactCanonicalForm()); } } catch (ParseException e) { System.out.println("Unable to parse the dependency tree file."); } } private void printAnalysisResults(MavenProject project, ProjectDependencyAnalysis projectDependencyAnalysis) { Set<Artifact> usedUndeclaredArtifacts = projectDependencyAnalysis.getUsedUndeclaredArtifacts(); Set<Artifact> usedDeclaredArtifacts = projectDependencyAnalysis.getUsedDeclaredArtifacts(); Set<Artifact> unusedDeclaredArtifacts = projectDependencyAnalysis.getUnusedDeclaredArtifacts(); Set<Artifact> unusedUndeclaredArtifacts = project.getArtifacts(); unusedUndeclaredArtifacts.removeAll(usedDeclaredArtifacts); unusedUndeclaredArtifacts.removeAll(usedUndeclaredArtifacts); unusedUndeclaredArtifacts.removeAll(unusedDeclaredArtifacts); /* Use artifacts coordinates for the report instead of the Artifact object */ Set<String> usedDeclaredArtifactsCoordinates = new HashSet<>(); usedDeclaredArtifacts.forEach(s -> usedDeclaredArtifactsCoordinates.add(s.getGroupId() + ":" + s.getArtifactId() + ":" + s.getVersion())); Set<String> usedUndeclaredArtifactsCoordinates = new HashSet<>(); usedUndeclaredArtifacts.forEach(s -> usedUndeclaredArtifactsCoordinates.add(s.getGroupId() + ":" + s.getArtifactId() + ":" + s.getVersion())); Set<String> unusedDeclaredArtifactsCoordinates = new HashSet<>(); unusedDeclaredArtifacts.forEach(s -> unusedDeclaredArtifactsCoordinates.add(s.getGroupId() + ":" + s.getArtifactId() + ":" + s.getVersion())); Set<String> unusedUndeclaredArtifactsCoordinates = new HashSet<>(); unusedUndeclaredArtifacts.forEach(s -> unusedUndeclaredArtifactsCoordinates.add(s.getGroupId() + ":" + s.getArtifactId() + ":" + s.getVersion())); /* Printing the results to the console */ System.out.println(" D E P C L E A N A N A L Y S I S R E S U L T S"); System.out.println("-------------------------------------------------------"); System.out.println("Used direct dependencies" + " [" + usedDeclaredArtifactsCoordinates.size() + "]" + ": "); usedDeclaredArtifactsCoordinates.stream().forEach(s -> System.out.println("\t" + s)); System.out.println("Used transitive dependencies" + " [" + usedUndeclaredArtifactsCoordinates.size() + "]" + ": "); usedUndeclaredArtifactsCoordinates.stream().forEach(s -> System.out.println("\t" + s)); System.out.println("Potentially unused direct dependencies" + " [" + unusedDeclaredArtifactsCoordinates.size() + "]" + ": "); unusedDeclaredArtifactsCoordinates.stream().forEach(s -> System.out.println("\t" + s)); System.out.println("Potentially unused transitive dependencies" + " [" + unusedUndeclaredArtifactsCoordinates.size() + "]" + ": "); unusedUndeclaredArtifactsCoordinates.stream().forEach(s -> System.out.println("\t" + s)); } private void removeBlankLines(String filePath) throws FileNotFoundException { Scanner file; PrintWriter writer; file = new Scanner(new File(filePath)); writer = new PrintWriter(filePath + "_old"); while (file.hasNext()) { String line = file.nextLine(); if (!line.isEmpty() && !line.startsWith("\n") && (line.startsWith(" ") || line.startsWith("|") || line.startsWith("+") || line.startsWith("\\") || line.startsWith("³") || line.startsWith("Ã") || line.startsWith("Ä") || line.startsWith("À"))) { writer.write(line); writer.write("\n"); } } file.close(); writer.close(); File file1 = new File(filePath); File file2 = new File(filePath + "_old"); file1.delete(); file2.renameTo(file1); } }
3e0873a04c824075a3880f4a285ab0cb6b87df29
1,175
java
Java
src/main/java/com/nike/cerberus/service/JobCoordinatorService.java
seclib/cerberus_scripts
0c1dec4c1745ad1ddcffb74a75842befa364d077
[ "Apache-2.0" ]
2
2018-04-14T00:07:35.000Z
2018-04-15T05:55:57.000Z
src/main/java/com/nike/cerberus/service/JobCoordinatorService.java
seclib/cerberus_scripts
0c1dec4c1745ad1ddcffb74a75842befa364d077
[ "Apache-2.0" ]
27
2018-09-06T00:46:18.000Z
2018-09-06T23:12:45.000Z
src/main/java/com/nike/cerberus/service/JobCoordinatorService.java
TomMD/cerberus-management-service
3bc2f37ab0409bfe6da435be81def147919abc2c
[ "Apache-2.0" ]
null
null
null
27.325581
75
0.723404
3,578
/* * Copyright (c) 2017 Nike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nike.cerberus.service; import com.nike.cerberus.dao.LockDao; import org.mybatis.guice.transactional.Transactional; import javax.inject.Inject; public class JobCoordinatorService { private final LockDao lockDao; @Inject public JobCoordinatorService(LockDao lockDao) { this.lockDao = lockDao; } @Transactional public boolean acquireLockToRunJob(String job) { return lockDao.getLock(job) > 0; } @Transactional public boolean releaseLock(String jobName) { return lockDao.releaseLock(jobName) > 0; } }
3e0873b9d11a771ded939eabcf7db577bf69fa9f
3,017
java
Java
teammanager/src/main/java/com/publicuhc/uhcaddons/teammanager/commands/NoTeamCommand.java
Eluinhost/UHC-Addons
08bf35dcf887f6d7b0e71aea761188531f753b06
[ "MIT" ]
null
null
null
teammanager/src/main/java/com/publicuhc/uhcaddons/teammanager/commands/NoTeamCommand.java
Eluinhost/UHC-Addons
08bf35dcf887f6d7b0e71aea761188531f753b06
[ "MIT" ]
2
2016-04-26T11:03:12.000Z
2016-04-26T11:03:16.000Z
teammanager/src/main/java/com/publicuhc/uhcaddons/teammanager/commands/NoTeamCommand.java
Eluinhost/UHC-Addons
08bf35dcf887f6d7b0e71aea761188531f753b06
[ "MIT" ]
null
null
null
35.916667
86
0.727212
3,579
/* * NoTeamCommand.java * * The MIT License (MIT) * * Copyright (c) 2014 Graham Howden <graham_howden1 at yahoo.co.uk>. * * 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.publicuhc.uhcaddons.teammanager.commands; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.publicuhc.ultrahardcore.api.Command; import com.publicuhc.ultrahardcore.framework.routing.annotation.CommandMethod; import com.publicuhc.ultrahardcore.framework.routing.annotation.PermissionRestriction; import com.publicuhc.ultrahardcore.framework.shaded.joptsimple.OptionSet; import com.publicuhc.ultrahardcore.framework.translate.Translate; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; import java.util.Collection; import java.util.List; public class NoTeamCommand implements Command { public static final String NO_TEAM_PERMISSION = "UHC.teams.noteam"; private final Translate translate; private final Scoreboard scoreboard; protected NoTeamCommand(Translate translate, Scoreboard scoreboard) { this.translate = translate; this.scoreboard = scoreboard; } @CommandMethod("noteam") @PermissionRestriction(NO_TEAM_PERMISSION) public void noteam(OptionSet set, CommandSender sender) { Player[] online = Bukkit.getOnlinePlayers(); List<Player> noteam = Lists.newArrayList(); for(Player player : online) { if(scoreboard.getPlayerTeam(player) == null) { noteam.add(player); } } if(noteam.isEmpty()) { translate.sendMessage("all in teams", sender); return; } Collection<String> playerNames = Lists.newArrayList(); for(Player p : noteam) { playerNames.add(p.getName()); } translate.sendMessage("no team", sender, Joiner.on(",").join(playerNames)); } }
3e0873c4c27b7a98833a5e07f5fcd517ec943c92
509
java
Java
daikon-audit/audit-common/src/main/java/org/talend/logging/audit/AuditAppenderException.java
jmfrancois/daikon
f7bb5bba45ec8b541c1c4845a63e3f0e0123956b
[ "Apache-2.0" ]
14
2016-02-02T11:20:49.000Z
2021-12-02T01:08:40.000Z
daikon-audit/audit-common/src/main/java/org/talend/logging/audit/AuditAppenderException.java
jmfrancois/daikon
f7bb5bba45ec8b541c1c4845a63e3f0e0123956b
[ "Apache-2.0" ]
488
2015-12-14T07:54:38.000Z
2022-03-11T15:29:45.000Z
daikon-audit/audit-common/src/main/java/org/talend/logging/audit/AuditAppenderException.java
jmfrancois/daikon
f7bb5bba45ec8b541c1c4845a63e3f0e0123956b
[ "Apache-2.0" ]
82
2015-11-29T22:24:42.000Z
2022-02-25T17:17:58.000Z
21.208333
75
0.685658
3,580
package org.talend.logging.audit; /** * */ public class AuditAppenderException extends AuditLoggingException { private final LogAppenders appender; public AuditAppenderException(LogAppenders appender, String message) { super(message); this.appender = appender; } public AuditAppenderException(LogAppenders appender, Throwable cause) { super(cause); this.appender = appender; } public LogAppenders getAppender() { return appender; } }
3e08740bf274cbbb3b202ad42ba42b8fb7e44116
24,089
java
Java
lens-cube/src/test/java/org/apache/lens/cube/parse/TestAggregateResolver.java
ankitkailaswar/grill
884595250a0a6f2a82d6e46a2f0f213536b0a52e
[ "Apache-2.0", "BSD-3-Clause" ]
59
2015-08-31T17:03:10.000Z
2021-11-10T19:01:30.000Z
lens-cube/src/test/java/org/apache/lens/cube/parse/TestAggregateResolver.java
ankitkailaswar/grill
884595250a0a6f2a82d6e46a2f0f213536b0a52e
[ "Apache-2.0", "BSD-3-Clause" ]
3
2019-04-24T12:47:39.000Z
2019-08-19T15:17:27.000Z
lens-cube/src/test/java/org/apache/lens/cube/parse/TestAggregateResolver.java
ankitkailaswar/grill
884595250a0a6f2a82d6e46a2f0f213536b0a52e
[ "Apache-2.0", "BSD-3-Clause" ]
91
2015-09-11T19:27:58.000Z
2022-01-31T12:13:08.000Z
51.362473
118
0.70746
3,581
/** * 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.lens.cube.parse; import static org.apache.lens.cube.metadata.DateFactory.*; import static org.apache.lens.cube.parse.CubeTestSetup.*; import static org.apache.lens.cube.parse.TestCubeRewriter.compareQueries; import org.apache.lens.server.api.error.LensException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.ql.parse.ParseException; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import lombok.Getter; public class TestAggregateResolver extends TestQueryRewrite { @Getter private Configuration conf; private final String cubeName = CubeTestSetup.TEST_CUBE_NAME; @BeforeTest public void setupDriver() throws Exception { conf = new Configuration(); conf.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C2"); conf.setBoolean(CubeQueryConfUtil.DISABLE_AUTO_JOINS, true); conf.setBoolean(CubeQueryConfUtil.ENABLE_SELECT_TO_GROUPBY, true); conf.setBoolean(CubeQueryConfUtil.ENABLE_GROUP_BY_TO_SELECT, true); } private CubeQueryContext rewrittenQuery; @Test public void testAggregateResolver() throws Exception { conf.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, false); // pass String q1 = "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE; // pass String q2 = "SELECT cityid, testCube.msr2 * testCube.msr3 from testCube where " + TWO_DAYS_RANGE; // pass String q3 = "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE; // pass String q4 = "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE + " having testCube.msr2 > 100"; // pass String q5 = "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE + " having testCube.msr2 + testCube.msr3 > 100"; // pass String q6 = "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE + " having testCube.msr2 > 100 AND testCube.msr2 < 1000"; // pass String q7 = "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE + " having (testCube.msr2 > 100) OR (testcube.msr2 < 100 AND max(testcube.msr3) > 1000)"; // pass String q8 = "SELECT cityid, sum(testCube.msr2) * max(testCube.msr3) from testCube where " + TWO_DAYS_RANGE; // pass String q9 = "SELECT cityid c1, max(msr3) m3 from testCube where c1 > 100 and " + TWO_DAYS_RANGE + " having (msr2 < 100" + " AND m3 > 1000)"; String q10 = "SELECT cityid, round(testCube.msr2) from testCube where " + TWO_DAYS_RANGE; //dimension selected with having String q11 = "SELECT cityid from testCube where " + TWO_DAYS_RANGE + " having (testCube.msr2 > 100)"; String expectedq1 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `msr2` from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq2 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) * max(testCube.msr3) " + "as `testCube.msr2 * testCube.msr3` from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq3 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq4 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid having" + " sum(testCube.msr2) > 100", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq5 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `msr2` from ", null, "group by testcube.cityid having" + " sum(testCube.msr2) + max(testCube.msr3) > 100", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq6 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `msr2`from ", null, "group by testcube.cityid having" + " sum(testCube.msr2) > 100 and sum(testCube.msr2) < 1000", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq7 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid having" + " sum(testCube.msr2) > 100 OR (sum(testCube.msr2) < 100 AND" + " max(testcube.msr3) > 1000)", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq8 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) * max(testCube.msr3) " + "as `sum(testCube.msr2) * max(testCube.msr3)` from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq9 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `c1`, max(testCube.msr3) as `m3` from ", "c1 > 100", "group by testcube.cityid" + " having sum(testCube.msr2) < 100 AND (m3 > 1000)", getWhereForDailyAndHourly2days(cubeName, "c2_testfact")); String expectedq10 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, round(sum(testCube.msr2)) " + "as `round(testCube.msr2)` from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String expectedq11 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`from ", null, "group by testcube.cityid" + "having sum(testCube.msr2) > 100", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); String[] tests = { q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, }; String[] expected = { expectedq1, expectedq2, expectedq3, expectedq4, expectedq5, expectedq6, expectedq7, expectedq8, expectedq9, expectedq10, expectedq11, }; for (int i = 0; i < tests.length; i++) { String hql = rewrite(tests[i], conf); System.out.println("hql[" + i + "]:" + hql); compareQueries(hql, expected[i]); } aggregateFactSelectionTests(conf); rawFactSelectionTests(getConfWithStorages("C1,C2")); } @Test public void testDimOnlyDistinctQuery() throws ParseException, LensException { conf.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, false); //Add distinct String query1 = "SELECT testcube.cityid,testcube.zipcode,testcube.stateid from testCube where " + TWO_DAYS_RANGE; String hQL1 = rewrite(query1, conf); String expectedQL1 = getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, testcube.zipcode as `zipcode`, " + "testcube.stateid as `stateid`" + " from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL1, expectedQL1); //Don't add distinct String query2 = "SELECT count (distinct testcube.cityid) from testcube where " + TWO_DAYS_RANGE; String hQL2 = rewrite(query2, conf); String expectedQL2 = getExpectedQuery(cubeName, "SELECT count (distinct testcube.cityid) as `count(distinct testcube.cityid)`" + " from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL2, expectedQL2); //Don't add distinct String query3 = "SELECT testcube.cityid, count(distinct testcube.stateid) from testcube where " + TWO_DAYS_RANGE; String hQL3 = rewrite(query3, conf); String expectedQL3 = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testcube.stateid) " + "as `count(distinct testcube.stateid)` " + " from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL3, expectedQL3); //Don't add distinct String query4 = "SELECT count(testcube.stateid) from testcube where " + TWO_DAYS_RANGE; String hQL4 = rewrite(query4, conf); String expectedQL4 = getExpectedQuery(cubeName, "SELECT count(testcube.stateid) as `count(testcube.stateid)`" + " from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL4, expectedQL4); //Don't add distinct, by setting the flag false conf.setBoolean(CubeQueryConfUtil.ENABLE_ATTRFIELDS_ADD_DISTINCT, false); String query5 = "SELECT testcube.stateid from testcube where " + TWO_DAYS_RANGE; String hQL5 = rewrite(query5, conf); String expectedQL5 = getExpectedQuery(cubeName, "SELECT testcube.stateid as `stateid`" + " from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL5, expectedQL5); } @Test public void testAggregateResolverOff() throws ParseException, LensException { Configuration conf2 = getConfWithStorages("C1,C2"); conf2.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, true); // Test if raw fact is selected for query with no aggregate function on a // measure, with aggregate resolver disabled String query = "SELECT cityid, testCube.msr2 FROM testCube WHERE " + TWO_DAYS_RANGE; CubeQueryContext cubeql = rewriteCtx(query, conf2); String hQL = cubeql.toHQL(); Assert.assertEquals(1, cubeql.getCandidates().size()); Candidate candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate).getStorageTable().toLowerCase()); String expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, testCube.msr2 as `msr2` from ", null, null, getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); conf2.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C2"); aggregateFactSelectionTests(conf2); conf2.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C1,C2"); rawFactSelectionTests(conf2); } private void aggregateFactSelectionTests(Configuration conf) throws ParseException, LensException { String query = "SELECT count(distinct cityid) from testcube where " + TWO_DAYS_RANGE; CubeQueryContext cubeql = rewriteCtx(query, conf); String hQL = cubeql.toHQL(); String expectedQL = getExpectedQuery(cubeName, "SELECT count(distinct testcube.cityid) as `count( distinct cityid)` from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL, expectedQL); query = "SELECT distinct cityid from testcube where " + TWO_DAYS_RANGE; hQL = rewrite(query, conf); expectedQL = getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid` from ", null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL, expectedQL); // with aggregate resolver on/off, msr with its default aggregate around it // should pick up aggregated fact query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) m2 FROM testCube WHERE " + TWO_DAYS_RANGE + " order by m2"; cubeql = rewriteCtx(query, conf); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `m2` from ", null, "group by testcube.cityid order by m2 asc", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " having max(msr3) > 100"; cubeql = rewriteCtx(query, conf); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid having max(testcube.msr3) > 100", getWhereForDailyAndHourly2days(cubeName, "C2_testfact")); compareQueries(hQL, expectedQL); } private void rawFactSelectionTests(Configuration conf) throws ParseException, LensException { // Check a query with non default aggregate function String query = "SELECT cityid, avg(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE; CubeQueryContext cubeql = rewriteCtx(query, conf); String hQL = cubeql.toHQL(); Assert.assertEquals(1, cubeql.getCandidates().size()); Candidate candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); String expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, avg(testCube.msr2) as `avg(testCube.msr2)` " + "from ", null, "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); // query with measure in a where clause query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE testCube.msr1 < 100 and " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", "testcube.msr1 < 100", "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, testCube.msr2 FROM testCube WHERE testCube.msr2 < 100 and " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, testCube.msr2 as `msr2` from ", "testcube.msr2 < 100", null, getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " group by testCube.msr1"; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, " group by testCube.msr1", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " group by testCube.msr3"; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, " group by testCube.msr3", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " order by testCube.msr1"; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, " group by testcube.cityid order by testcube.msr1 asc", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " order by testCube.msr3"; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, " group by testcube.cityid order by testcube.msr3 asc", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT distinct cityid, round(testCube.msr2) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, round(testCube.msr2) " + "as `round(testCube.msr2)` from ", null, null, getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, count(distinct(testCube.msr2)) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testCube.msr2) " + "as `count(distinct(testCube.msr2))` from ", null, "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); // query with no default aggregate measure query = "SELECT cityid, round(testCube.msr1) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, round(testCube.msr1) as `round(testCube.msr1)` " + "from ", null, null, getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT distinct cityid, round(testCube.msr1) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, round(testCube.msr1) " + "as `round(testCube.msr1)` from ", null, null, getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, count(distinct(testCube.msr1)) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testCube.msr1) " + "as ` count(distinct testCube.msr1)` from ", null, "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr1) from testCube where " + TWO_DAYS_RANGE; cubeql = rewriteCtx(query, conf); Assert.assertEquals(1, cubeql.getCandidates().size()); candidate = cubeql.getCandidates().iterator().next(); Assert.assertTrue(candidate instanceof StorageCandidate); Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate) .getStorageTable().toLowerCase()); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr1) as `sum(testCube.msr1)` " + "from ", null, "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " having max(msr1) > 100"; cubeql = rewriteCtx(query, conf); hQL = cubeql.toHQL(); expectedQL = getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` " + "from ", null, "group by testcube.cityid having max(testcube.msr1) > 100", getWhereForHourly2days("c1_testfact2_raw")); compareQueries(hQL, expectedQL); } }
3e08740d80e54695f3383c3c172bcca33300d1a0
7,504
java
Java
tasks/Task2/ServerThread.java
Chen-Zidi/ID1212
57b16b046a142b2c6755ab4d8439fba31dffd7a0
[ "MIT" ]
1
2020-10-29T22:06:59.000Z
2020-10-29T22:06:59.000Z
tasks/Task2/ServerThread.java
Chen-Zidi/ChatApplication
57b16b046a142b2c6755ab4d8439fba31dffd7a0
[ "MIT" ]
null
null
null
tasks/Task2/ServerThread.java
Chen-Zidi/ChatApplication
57b16b046a142b2c6755ab4d8439fba31dffd7a0
[ "MIT" ]
null
null
null
39.914894
155
0.513726
3,582
import java.io.*; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.StringTokenizer; public class ServerThread extends Thread { Socket socket; Guess guess; BufferedReader request; int count = -1; int number = -1; int contentLength = -1; int guessNumber = -1; String method = ""; String htmlContent = ""; String requestedDocument = ""; int id; public ServerThread(Socket socket, int id) { this.socket = socket; this.id = id; } @Override public void run() { try { //receive http request OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); request = new BufferedReader(new InputStreamReader(inputStream)); String str = request.readLine(); // If this is a favicon request from browser if (str.contains("favicon.ico")) { //Read favicon.ico to bytes byte[] favicon = Files.readAllBytes(Paths.get("tasks", "Task2", "favicon.ico")); String header = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nContent-Type: image/ico\nContent-Length: " + favicon.length + "\r\n\r\n"; outputStream.write(header.getBytes(StandardCharsets.UTF_8)); outputStream.write(favicon); } System.out.println("str: " + str); //print the received http request StringTokenizer tokens = new StringTokenizer(str, " ?"); method = tokens.nextToken(); System.out.println("token: " + method); // The word GET/POST //identify whether a icon is needed or html is needed requestedDocument = tokens.nextToken(); System.out.println(requestedDocument); //read http request do { str = request.readLine(); System.out.println("str: " + str); //find out the content length when is it a post request if (str.startsWith("Content-Length: ")) { contentLength = Integer.parseInt(str.substring("Content-Length: ".length())); } //to get cookie values if (str.contains("Cookie")) { String[] cInfo = str.split(":|;"); for (String s : cInfo) { //get count value if (s.contains("count")) { count = Integer.parseInt(s.replaceAll("count=", "").trim()); //System.out.println("count"+count); } //get number value if (s.contains("number")) { number = Integer.parseInt(s.replaceAll("number=", "").trim()); //System.out.println("number"+number); } } } } while (str.length() != 0); //if method is post, then find the submitted value in the http body //the while loop always results in print an empty line //this empty line is the line between http header and http body if (method.equals("POST") && contentLength > 0) { System.out.println("POST received"); char[] content = new char[contentLength]; request.read(content); String temp = new String(content); guessNumber = Integer.parseInt(temp.substring("number=".length())); } //check if the browser already visited the url if ((count >= 0) && number >= 0) { guess = new Guess(number, count); } else { guess = new Guess(); } //if it is a get request, give the start page if (method.equals("GET")) { //read the html file FileReader fileReader = new FileReader("./tasks/Task2/GuessGamePage.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); while (bufferedReader.ready()) { htmlContent += bufferedReader.readLine(); } System.out.println(guess.getNumber()); //inject the number to the html htmlContent = String.format(htmlContent, guess.getNumber()); //System.out.println(htmlContent); fileReader.close(); } else if (method.equals("POST")) {//if it is a post request FileReader fileReader; String result = guess.compare(guessNumber); if (result.equals("equal")) {//if the guess number is right fileReader = new FileReader("./tasks/Task2/GuessRight.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); while (bufferedReader.ready()) { htmlContent += bufferedReader.readLine(); } //inject the number to the html htmlContent = String.format(htmlContent, guess.getCounter(), guess.getNumber()); fileReader.close(); //reset the guess number and counter guess = new Guess(); } else if (result.equals("higher")) {//if the gues number is higher fileReader = new FileReader("./tasks/Task2/GuessHigher.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); while (bufferedReader.ready()) { htmlContent += bufferedReader.readLine(); } //inject the number to the html htmlContent = String.format(htmlContent, guess.getCounter(), guess.getNumber()); fileReader.close(); } else {//if the guess number is lower fileReader = new FileReader("./tasks/Task2/GuessLower.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); while (bufferedReader.ready()) { htmlContent += bufferedReader.readLine(); } //inject the number to the html htmlContent = String.format(htmlContent, guess.getCounter(), guess.getNumber()); fileReader.close(); } } //write the response to the client with cookie number and count String page = "HTTP/1.1 200 OK\r\n" + "Content-Length: " + htmlContent.getBytes().length + "\r\n" + "Content-Type: text/html; charset-utf-8\r\n" + "Set-Cookie: number=" + guess.getNumber() + "\r\n" + "Set-Cookie: count=" + guess.getCounter() + "\r\n" + "Set-Cookie: id=" + id + "\r\n" + "\r\n" + htmlContent + "\r\n"; //send the response outputStream.write(page.getBytes()); outputStream.flush(); socket.shutdownInput(); socket.shutdownOutput(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
3e08746cb8f1ca89aec0180a3dc26380a277d7aa
2,462
java
Java
src/main/java/org/subethamail/plugin/blueprint/AnnounceOnlyBlueprint.java
stickfigure/subetha
f3130ad16360724a12d4e33bccaaaa07c4b246d6
[ "BSD-3-Clause" ]
14
2015-05-15T20:58:17.000Z
2021-04-27T02:57:56.000Z
src/main/java/org/subethamail/plugin/blueprint/AnnounceOnlyBlueprint.java
stickfigure/subetha
f3130ad16360724a12d4e33bccaaaa07c4b246d6
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/subethamail/plugin/blueprint/AnnounceOnlyBlueprint.java
stickfigure/subetha
f3130ad16360724a12d4e33bccaaaa07c4b246d6
[ "BSD-3-Clause" ]
9
2015-05-17T19:33:25.000Z
2020-09-29T13:01:24.000Z
27.054945
89
0.712429
3,583
/* * $Id$ * $URL$ */ package org.subethamail.plugin.blueprint; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import org.subethamail.common.NotFoundException; import org.subethamail.core.lists.i.ListMgr; import org.subethamail.core.plugin.i.Blueprint; import org.subethamail.entity.i.Permission; import org.subethamail.entity.i.PermissionException; import org.subethamail.plugin.filter.AppendFooterFilter; import org.subethamail.plugin.filter.HoldEverythingFilter; import org.subethamail.plugin.filter.ListHeaderFilter; /** * Creates an announce-only list. * * @author Jeff Schnitzer * @author Jon Stevens * @author Scott Hernandez */ @Singleton public class AnnounceOnlyBlueprint implements Blueprint { @Inject ListMgr listMgr; /** */ public String getName() { return "Announce-Only List"; } /** */ public String getDescription() { return "Create a list which allows only moderators to post and view the subscriber list. " + "All messages are held for manual approval to prevent spoofing. " + "Subscribers can read the archives."; } /** */ public void configureMailingList(Long listId) { try { // Subscriber Set<Permission> perms = new HashSet<Permission>(); perms.add(Permission.VIEW_ARCHIVES); Long roleId = listMgr.addRole(listId, "Subscriber", perms); listMgr.setDefaultRole(listId, roleId); // Guest perms = new HashSet<Permission>(); roleId = listMgr.addRole(listId, "Guest", perms); listMgr.setAnonymousRole(listId, roleId); // Moderator perms = new HashSet<Permission>(); perms.add(Permission.POST); perms.add(Permission.VIEW_ARCHIVES); perms.add(Permission.VIEW_ADDRESSES); perms.add(Permission.VIEW_SUBSCRIBERS); perms.add(Permission.APPROVE_MESSAGES); perms.add(Permission.APPROVE_SUBSCRIPTIONS); perms.add(Permission.VIEW_ROLES); listMgr.addRole(listId, "Moderator", perms); // Add a couple useful filters listMgr.setFilterDefault(listId, AppendFooterFilter.class.getName()); listMgr.setFilterDefault(listId, ListHeaderFilter.class.getName()); listMgr.setFilterDefault(listId, HoldEverythingFilter.class.getName()); } catch (PermissionException pe) { throw new RuntimeException(pe); } catch (NotFoundException nfe) { throw new RuntimeException(nfe); } } }
3e0874f549483db937aa16aada820e73a72cf258
4,174
java
Java
src/main/java/com/github/wihoho/training/PCA.java
wihoho/FaceRecognition
df9471c04d6ee1aa990fb97dd7352be8ab59e6d4
[ "Unlicense" ]
228
2015-01-04T04:53:44.000Z
2022-03-26T02:53:56.000Z
src/main/java/com/github/wihoho/training/PCA.java
wihoho/FaceRecognition
df9471c04d6ee1aa990fb97dd7352be8ab59e6d4
[ "Unlicense" ]
12
2015-01-22T15:15:44.000Z
2020-01-28T14:08:37.000Z
src/main/java/com/github/wihoho/training/PCA.java
wihoho/FaceRecognition
df9471c04d6ee1aa990fb97dd7352be8ab59e6d4
[ "Unlicense" ]
129
2015-02-04T12:20:45.000Z
2021-04-03T00:25:42.000Z
25.45122
102
0.684715
3,584
package com.github.wihoho.training; import com.github.wihoho.jama.EigenvalueDecomposition; import com.github.wihoho.jama.Matrix; import java.util.ArrayList; import java.util.Arrays; public class PCA extends FeatureExtraction { public PCA(ArrayList<Matrix> trainingSet, ArrayList<String> labels, int numOfComponents) throws Exception { if(numOfComponents >= trainingSet.size()){ throw new Exception("the expected dimensions could not be achieved!"); } this.trainingSet = trainingSet; this.labels = labels; this.numOfComponents = numOfComponents; this.meanMatrix = getMean(this.trainingSet); this.W = getFeature(this.trainingSet, this.numOfComponents); // Construct projectedTrainingMatrix this.projectedTrainingSet = new ArrayList<ProjectedTrainingMatrix>(); for (int i = 0; i < trainingSet.size(); i++) { ProjectedTrainingMatrix ptm = new ProjectedTrainingMatrix(this.W .transpose().times(trainingSet.get(i).minus(meanMatrix)), labels.get(i)); this.projectedTrainingSet.add(ptm); } } // extract features, namely W private Matrix getFeature(ArrayList<Matrix> input, int K) { int i, j; int row = input.get(0).getRowDimension(); int column = input.size(); Matrix X = new Matrix(row, column); for (i = 0; i < column; i++) { X.setMatrix(0, row - 1, i, i, input.get(i).minus(this.meanMatrix)); } // get eigenvalues and eigenvectors Matrix XT = X.transpose(); Matrix XTX = XT.times(X); EigenvalueDecomposition feature = XTX.eig(); double[] d = feature.getd(); assert d.length >= K : "number of eigenvalues is less than K"; int[] indexes = this.getIndexesOfKEigenvalues(d, K); Matrix eigenVectors = X.times(feature.getV()); Matrix selectedEigenVectors = eigenVectors.getMatrix(0, eigenVectors.getRowDimension() - 1, indexes); // normalize the eigenvectors row = selectedEigenVectors.getRowDimension(); column = selectedEigenVectors.getColumnDimension(); for (i = 0; i < column; i++) { double temp = 0; for (j = 0; j < row; j++) temp += Math.pow(selectedEigenVectors.get(j, i), 2); temp = Math.sqrt(temp); for (j = 0; j < row; j++) { selectedEigenVectors.set(j, i, selectedEigenVectors.get(j, i) / temp); } } return selectedEigenVectors; } // get the first K indexes with the highest eigenValues private class mix implements Comparable { int index; double value; mix(int i, double v) { index = i; value = v; } public int compareTo(Object o) { double target = ((mix) o).value; if (value > target) return -1; else if (value < target) return 1; return 0; } } private int[] getIndexesOfKEigenvalues(double[] d, int k) { mix[] mixes = new mix[d.length]; int i; for (i = 0; i < d.length; i++) mixes[i] = new mix(i, d[i]); Arrays.sort(mixes); int[] result = new int[k]; for (i = 0; i < k; i++) result[i] = mixes[i].index; return result; } // The matrix has already been vectorized private static Matrix getMean(ArrayList<Matrix> input) { int rows = input.get(0).getRowDimension(); int length = input.size(); Matrix all = new Matrix(rows, 1); for (int i = 0; i < length; i++) { all.plusEquals(input.get(i)); } return all.times((double) 1 / length); } @Override public Matrix getW() { return this.W; } @Override public ArrayList<ProjectedTrainingMatrix> getProjectedTrainingSet() { return this.projectedTrainingSet; } @Override public Matrix getMeanMatrix() { // TODO Auto-generated method stub return meanMatrix; } @Override public int addFace(Matrix face, String label) { // to be done return 0; } public ArrayList<Matrix> getTrainingSet(){ return this.trainingSet; } public Matrix reconstruct(int whichImage, int dimensions) throws Exception{ if(dimensions > this.numOfComponents) throw new Exception("dimensions should be smaller than the number of components"); Matrix afterPCA = this.projectedTrainingSet.get(whichImage).matrix.getMatrix(0, dimensions-1, 0, 0); Matrix eigen = this.getW().getMatrix(0, 10304-1, 0, dimensions - 1); return eigen.times(afterPCA).plus(this.getMeanMatrix()); } }
3e0874fd91f288f3b5275ad9b1748524dd675475
27,622
java
Java
community/kernel/src/test/java/org/neo4j/kernel/impl/traversal/TestTraversal.java
jexp/neo4j
fcc121f9f0456e21f609f3f8e895255052242ff1
[ "CNRI-Python", "Apache-1.1" ]
1
2015-12-14T07:35:29.000Z
2015-12-14T07:35:29.000Z
community/kernel/src/test/java/org/neo4j/kernel/impl/traversal/TestTraversal.java
jexp/neo4j
fcc121f9f0456e21f609f3f8e895255052242ff1
[ "CNRI-Python", "Apache-1.1" ]
null
null
null
community/kernel/src/test/java/org/neo4j/kernel/impl/traversal/TestTraversal.java
jexp/neo4j
fcc121f9f0456e21f609f3f8e895255052242ff1
[ "CNRI-Python", "Apache-1.1" ]
null
null
null
37.126344
91
0.574325
3,585
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.traversal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.neo4j.graphdb.Traverser.Order.BREADTH_FIRST; import static org.neo4j.graphdb.Traverser.Order.DEPTH_FIRST; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Test; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.ReturnableEvaluator; import org.neo4j.graphdb.StopEvaluator; import org.neo4j.graphdb.TraversalPosition; import org.neo4j.graphdb.Traverser; import org.neo4j.graphdb.Traverser.Order; import org.neo4j.kernel.impl.AbstractNeo4jTestCase; import org.neo4j.kernel.impl.MyRelTypes; public class TestTraversal extends AbstractNeo4jTestCase { // Tests the traverser factory for sanity checks with corrupted input @Test public void testSanityChecks1() throws Exception { // Valid data Node root = getGraphDb().createNode(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, }; // Null traversable relationships this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, Direction.OUTGOING, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null stop evaluator this.sanityCheckTraverser( "Sanity check failed: null stop eval " + "should throw an IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], Direction.OUTGOING, null, ReturnableEvaluator.ALL ); // Null returnable evaluator this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], Direction.OUTGOING, StopEvaluator.END_OF_GRAPH, null ); root.delete(); } @Test public void testSanityChecks2() throws Exception { // ------------- with traverser direction ------------- // Valid data Node root = getGraphDb().createNode(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, }; Direction[] traversableDirs = new Direction[] { Direction.OUTGOING }; // Null traversable relationships this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, traversableDirs[0], StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null traversable directions this.sanityCheckTraverser( "Sanity check failed: null traversable " + "rels should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], null, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL ); // Null stop evaluator this.sanityCheckTraverser( "Sanity check failed: null stop eval " + "should throw an IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], traversableDirs[0], null, ReturnableEvaluator.ALL ); // Null returnable evaluator this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], traversableDirs[0], StopEvaluator.END_OF_GRAPH, null ); // traversable relationships length not equal to traversable directions // length this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, traversableRels[0], null, StopEvaluator.END_OF_GRAPH, null ); this.sanityCheckTraverser( "Sanity check failed: null returnable " + "evaluator should throw an " + "IllegalArgumentException", BREADTH_FIRST, root, null, traversableDirs[0], StopEvaluator.END_OF_GRAPH, null ); root.delete(); } // Tests the traverser factory for simple corrupted (null) input, used // by testSanityChecks() private void sanityCheckTraverser( String failMessage, Order type, Node startNode, RelationshipType traversableRel, Direction direction, StopEvaluator stopEval, ReturnableEvaluator retEval ) { try { startNode.traverse( type, stopEval, retEval, traversableRel, direction ); fail( failMessage ); } catch ( IllegalArgumentException iae ) { // This is ok } } // Traverses the full test "ise-tree-like" population breadth first // and verifies that it is returned in correct order @Test public void testBruteBreadthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; Traverser traverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7", "8", "9" }, new String[] { "10", "11", "12", "13", "14" } } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } private void assertNodes( Traverser traverser, String... expectedNodes ) { Set<String> set = new HashSet<String>( Arrays.asList( expectedNodes ) ); for ( Node node : traverser ) { assertTrue( set.remove( node.getProperty( "node.test.id" ) ) ); } assertTrue( set.isEmpty() ); } private void assertLevelsOfNodes( Traverser traverser, String[][] nodes ) { Map<Integer, Collection<String>> map = new HashMap<Integer, Collection<String>>(); for ( Node node : traverser ) { Collection<String> collection = map.get( traverser.currentPosition().depth() ); if ( collection == null ) { collection = new ArrayList<String>(); map.put( traverser.currentPosition().depth(), collection ); } String name = (String) node.getProperty( "node.test.id" ); collection.add( name ); } for ( int i = 0; i < nodes.length; i++ ) { Collection<String> expected = Arrays.asList( nodes[i] ); assertEquals( expected, map.get( i ) ); } } // Traverses the test "ise-tree-like" population breadth first, // but only traverses "ise" (TEST) relationships (the population also // contains // "ise_clone" (TEST_TRAVERSAL) rels) @Test public void testMultiRelBreadthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; Traverser traverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7" }, new String[] { "10", "11", "12", "13" }, } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the test "ise-tree-like" population breadth first, // starting in the middle of the tree and traversing only in the // "forward" direction @Test public void testDirectedBreadthTraversal() throws Exception { // Build test population Node root = this.buildIseTreePopulation(); Node startNode = null; // Get a node in the middle of the tree: try { // a) Construct a returnable evaluator that returns node 2 ReturnableEvaluator returnEvaluator = new ReturnableEvaluator() { public boolean isReturnableNode( TraversalPosition pos ) { try { Node node = pos.currentNode(); String key = "node.test.id"; String nodeId = (String) node.getProperty( key ); return nodeId.equals( "2" ); } catch ( Exception e ) { return false; } } }; // b) create a traverser Traverser toTheMiddleTraverser = root.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, returnEvaluator, MyRelTypes.TEST, Direction.BOTH ); // c) get the first node it returns startNode = toTheMiddleTraverser.iterator().next(); assertEquals( "2", startNode.getProperty( "node.test.id" ) ); } catch ( Exception e ) { e.printStackTrace(); fail( "Something went wrong when trying to get a start node " + "in the middle of the tree: " + e ); } // Construct the real traverser Traverser traverser = startNode.traverse( BREADTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, MyRelTypes.TEST, Direction.OUTGOING ); try { this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); this.assertNextNodeId( traverser, "10" ); this.assertNextNodeId( traverser, "11" ); this.assertNextNodeId( traverser, "12" ); this.assertNextNodeId( traverser, "13" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { nsee.printStackTrace(); fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the full test "ise-tree-like" population depth first // and verifies that it is returned in correct order @Test public void testBruteDepthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; Traverser traverser = root.traverse( DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertNodes( traverser, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Traverses the test "ise-tree-like" population depth first, // but only traverses "ise" relationships (the population also contains // "ise_clone" rels) @Test public void testMultiRelDepthTraversal() throws Exception { Node root = this.buildIseTreePopulation(); RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; Traverser traverser = root.traverse( DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { assertNodes( traverser, "1", "2", "3", "4", "5", "6", "7", "10", "11", "12", "13" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the current node @Test public void testStopOnCurrentNode() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on nodes 5, 6, 3 and 4 StopEvaluator stopEvaluator = new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { try { Node node = position.currentNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "5" ) || nodeId.equals( "6" ) || nodeId.equals( "3" ) || nodeId.equals( "4" ); } catch ( Exception e ) { return false; } } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the previous node @Test public void testStopOnPreviousNode() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on nodes 2, 3, and 4 // (ie root's children) StopEvaluator stopEvaluator = new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { try { Node node = position.previousNode(); String nodeId = (String) node.getProperty( "node.test.id" ); return nodeId.equals( "1" ); } catch ( Exception e ) { return false; } } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the current depth @Test public void testStopOnDepth() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct a stop evaluator that stops on depth 2 StopEvaluator stopEvaluator = new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { return position.depth() >= 2; } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH ); try { this.assertNextNodeId( traverser, "1" ); this.assertNextNodeId( traverser, "2" ); this.assertNextNodeId( traverser, "3" ); this.assertNextNodeId( traverser, "4" ); this.assertNextNodeId( traverser, "5" ); this.assertNextNodeId( traverser, "6" ); this.assertNextNodeId( traverser, "7" ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the amount of // returned nodes @Test public void testStopOnReturnedNodes() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST }; // Construct stop- and returnable evaluators that return 5 nodes StopEvaluator stopEvaluator = new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { // Stop traversing when we've returned 5 nodes return position.returnedNodesCount() >= 5; } }; ReturnableEvaluator returnEvaluator = new ReturnableEvaluator() { public boolean isReturnableNode( TraversalPosition position ) { // Return nodes until we've reached 5 nodes or end of graph return position.returnedNodesCount() < 5; } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, returnEvaluator, traversableRels[0], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5" }, } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // Verifies that the stop evaluator can stop based on the last // traversed relationship @Test public void testStopOnLastRelationship() throws Exception { // Build ise tree Node root = this.buildIseTreePopulation(); // Traverse only ISE relationships RelationshipType[] traversableRels = new RelationshipType[] { MyRelTypes.TEST, MyRelTypes.TEST_TRAVERSAL }; // Construct stop- and returnable evaluators that return 5 nodes StopEvaluator stopEvaluator = new StopEvaluator() { public boolean isStopNode( TraversalPosition position ) { // Stop when we got here by traversing a clone relationship Relationship rel = position.lastRelationshipTraversed(); return rel != null && rel.isType( MyRelTypes.TEST_TRAVERSAL ); } }; // Create a traverser Traverser traverser = root.traverse( BREADTH_FIRST, stopEvaluator, ReturnableEvaluator.ALL, traversableRels[0], Direction.BOTH, traversableRels[1], Direction.BOTH ); try { this.assertLevelsOfNodes( traverser, new String[][] { new String[] { "1" }, new String[] { "2", "3", "4" }, new String[] { "5", "6", "7", "8", "9" }, new String[] { "10", "11", "12", "13" } } ); assertTrue( "Too many nodes returned from traversal", traverser .iterator().hasNext() == false ); } catch ( java.util.NoSuchElementException nsee ) { fail( "Too few nodes returned from traversal" ); } finally { // Delete ise tree and commmit work this.deleteNodeTreeRecursively( root, 0 ); } } // -- Utility operations private Node buildIseTreePopulation() throws Exception { // Create population Node[] nodeSpace = new Node[] { null, // empty getGraphDb().createNode(), // 1 [root] getGraphDb().createNode(), // 2 getGraphDb().createNode(), // 3 getGraphDb().createNode(), // 4 getGraphDb().createNode(), // 5 getGraphDb().createNode(), // 6 getGraphDb().createNode(), // 7 getGraphDb().createNode(), // 8 getGraphDb().createNode(), // 9 getGraphDb().createNode(), // 10 getGraphDb().createNode(), // 11 getGraphDb().createNode(), // 12 getGraphDb().createNode(), // 13 getGraphDb().createNode(), // 14 }; String key = "node.test.id"; for ( int i = 1; i < nodeSpace.length; i++ ) { nodeSpace[i].setProperty( key, "" + i ); } RelationshipType ise = MyRelTypes.TEST; RelationshipType clone = MyRelTypes.TEST_TRAVERSAL; // Bind it together // // ----(1)------- // / \ \ // --(2)-- (3) (4)-- // / \ \ | \ // --(5)----- (6)---(7) (8) (9) // / | \ \ | // (10) (11)(12)(13) (14) // nodeSpace[1].createRelationshipTo( nodeSpace[2], ise ); nodeSpace[2].createRelationshipTo( nodeSpace[5], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[10], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[11], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[12], ise ); nodeSpace[5].createRelationshipTo( nodeSpace[13], ise ); nodeSpace[2].createRelationshipTo( nodeSpace[6], ise ); nodeSpace[1].createRelationshipTo( nodeSpace[3], ise ); nodeSpace[1].createRelationshipTo( nodeSpace[4], ise ); nodeSpace[3].createRelationshipTo( nodeSpace[7], ise ); nodeSpace[6].createRelationshipTo( nodeSpace[7], clone ); nodeSpace[4].createRelationshipTo( nodeSpace[8], clone ); nodeSpace[4].createRelationshipTo( nodeSpace[9], clone ); nodeSpace[9].createRelationshipTo( nodeSpace[14], clone ); return nodeSpace[1]; // root } // Deletes a tree-like structure of nodes, starting with 'currentNode'. // Works fine with trees, dies horribly on cyclic structures. private void deleteNodeTreeRecursively( Node currentNode, int depth ) { if ( depth > 100 ) { throw new RuntimeException( "Recursive guard: depth = " + depth ); } if ( currentNode == null ) { return; } Iterable<Relationship> rels = currentNode.getRelationships(); for ( Relationship rel : rels ) { if ( !rel.getStartNode().equals( currentNode ) ) { continue; } Node endNode = rel.getEndNode(); rel.delete(); this.deleteNodeTreeRecursively( endNode, depth + 1 ); } String msg = "Deleting " + currentNode + "\t["; String id = (String) currentNode.getProperty( "node.test.id" ); msg += id + "]"; Iterable<Relationship> allRels = currentNode.getRelationships(); for ( Relationship rel : allRels ) { rel.delete(); } currentNode.delete(); } private void assertNextNodeId( Traverser traverser, String property ) throws NotFoundException { Node node = traverser.iterator().next(); assertEquals( property, node.getProperty( "node.test.id" ) ); } }
3e087612f9e2ec7d9d5052ebc9b107a27e29a26a
2,204
java
Java
jinx-com4j/src/main/java/com/exceljava/com4j/JinxBridge.java
exceljava/jinx-com4j
41a3eaf71c073f1282c2ab57a1c91986ed92e140
[ "MIT" ]
11
2018-06-04T19:49:44.000Z
2021-12-26T23:41:17.000Z
jinx-com4j/src/main/java/com/exceljava/com4j/JinxBridge.java
exceljava/jinx-com4j
41a3eaf71c073f1282c2ab57a1c91986ed92e140
[ "MIT" ]
1
2019-11-22T14:53:05.000Z
2019-11-25T12:53:56.000Z
jinx-com4j/src/main/java/com/exceljava/com4j/JinxBridge.java
exceljava/jinx-com4j
41a3eaf71c073f1282c2ab57a1c91986ed92e140
[ "MIT" ]
null
null
null
33.907692
89
0.690109
3,586
package com.exceljava.com4j; import com.exceljava.jinx.ExcelAddIn; import com.exceljava.jinx.ExcelArgumentConverter; import com.exceljava.jinx.IUnknown; import com.exceljava.com4j.excel._Application; import com4j.COM4J; import com4j.Com4jObject; /** * Bridge between the Jinx add-in and com4j. * Used for obtaining com4j COM wrappers from code running in Excel using Jinx. */ public class JinxBridge { /** * Gets the Excel Application object for the current Excel process. * * This can then be used to call back into Excel using the Excel * automation API, in the same way as VBA can be used to automate * Excel. * * The _Application object and objects obtained from it should only * be used from the same thread as it was obtained on. Sharing it * between threads will cause issues, and may cause Excel to crash. * * @param xl The ExcelAddIn object obtained from Jinx. * @return An Excel Application instance. */ public static _Application getApplication(ExcelAddIn xl) { return xl.getExcelApplication(_Application.class); } /** * Return an IUnknown instance that wraps a Com4jObject. * * This can be used for passing Com4jObjects back to Jinx * methods requiring an IUnknown instance. * * @param object COM object to be wrapped as an IUnknown. * @return Instance implementing IUnknown. */ public static IUnknown getIUnknown(Com4jObject object) { return new IUnknownAdaptor(object); } /** * Converts IUnknown to any Com4jObject type. * * This allows Com4jObjects to be used as method arguments where * an IUnknown would be passed by Jinx. For example, in the * ribbon actions. * * @param unk IUnknown instance. * @param cls Class of type to cast to. * @param <T> Type to cast to. * @return IUnknown instance cast to a Com4jObject instance. */ @ExcelArgumentConverter public static <T extends Com4jObject> T convertIUnknown(IUnknown unk, Class<T> cls) { Com4jObject obj = COM4J.wrapSta(Com4jObject.class, unk.getPointer(true)); return obj.queryInterface(cls); } }
3e087675b6933a4cadfcaa4ceb8f1d5720b752d0
1,905
java
Java
lib/test/co/edu/eafit/solver/lib/test/interpolation/SystemInterpolationTest.java
halzate93/solver
1adc9b01e6f091295f13214567e295a8a7d8cf7b
[ "MIT" ]
null
null
null
lib/test/co/edu/eafit/solver/lib/test/interpolation/SystemInterpolationTest.java
halzate93/solver
1adc9b01e6f091295f13214567e295a8a7d8cf7b
[ "MIT" ]
null
null
null
lib/test/co/edu/eafit/solver/lib/test/interpolation/SystemInterpolationTest.java
halzate93/solver
1adc9b01e6f091295f13214567e295a8a7d8cf7b
[ "MIT" ]
null
null
null
26.830986
83
0.703412
3,587
package co.edu.eafit.solver.lib.test.interpolation; import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import co.edu.eafit.solver.lib.interpolation.EInterpolationParameter; import co.edu.eafit.solver.lib.interpolation.function.EFunctionInterpolationResult; import co.edu.eafit.solver.lib.interpolation.function.SystemInterpolation; import co.edu.eafit.solver.lib.systemsolver.MatrixUtility; public class SystemInterpolationTest { private static double[][] points = {{-2, 12.13533528}, {-1, 6.367879441}, {2, -4.610943901}, {3, 2.085536923}}; private static double x = 0; private static double[][] A = {{-8, 4, -2, 1}, {-1, 1, -1, 1}, {8, 4, 2, 1}, {27, 9, 3, 1}}; private static double y = 0.0046995; private static double[] p = {0.412412, 0.939374, -5.836218, 0.004700}; private SystemInterpolation sys; @Before public void setUp() throws Exception { JSONObject parameters = new JSONObject(); parameters.put(EInterpolationParameter.Points.toString(), MatrixUtility.matrix2Json(points)); parameters.put(EInterpolationParameter.X.toString(), x); sys = new SystemInterpolation(); sys.setParameters(parameters); } @Test public void testRun() throws Exception { sys.interpolate(); } @Test public void testA() throws Exception{ sys.interpolate(); assertTrue(MatrixUtility.compareMatrix(A, sys.getA(), 0)); } @Test public void testSolution() throws Exception { sys.interpolate(); assertEquals(y, sys.getY(), 0.0000001); } @Test public void testP() throws Exception{ sys.interpolate(); assertTrue(MatrixUtility.compareVector(p, sys.getP(), 0.000001)); } @Test public void testJSON() throws Exception{ JSONObject result = sys.interpolate(); assertTrue(result.has(EFunctionInterpolationResult.A.toString())); } }
3e08769361174b1f25842b6871cae642acb33ce2
324
java
Java
src/main/java/com/lzhlyle/leetcode/recite/no470/ImplementRand10UsingRand7.java
lzhlyle/leetcode
8f053128ed7917c231fd24cfe82552d9c599dc16
[ "MIT" ]
2
2020-04-24T16:52:55.000Z
2020-04-24T16:53:10.000Z
src/main/java/com/lzhlyle/leetcode/recite/no470/ImplementRand10UsingRand7.java
lzhlyle/leetcode
8f053128ed7917c231fd24cfe82552d9c599dc16
[ "MIT" ]
null
null
null
src/main/java/com/lzhlyle/leetcode/recite/no470/ImplementRand10UsingRand7.java
lzhlyle/leetcode
8f053128ed7917c231fd24cfe82552d9c599dc16
[ "MIT" ]
null
null
null
20.25
47
0.478395
3,588
package com.lzhlyle.leetcode.recite.no470; public class ImplementRand10UsingRand7 { public int rand10() { int res = 0; do { res = (rand7() - 1) * 7 + rand7(); } while (res > 40); return res % 10 + 1; } private int rand7() { return -1; } }
3e0876ba1be2e168c382877e0b563d6232929705
1,713
java
Java
smilcool-server/src/main/java/com/smilcool/server/common/util/validation/anno/CheckEnum.java
Angus-Liu/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
70
2020-03-06T03:20:13.000Z
2022-03-31T08:19:50.000Z
smilcool-server/src/main/java/com/smilcool/server/common/util/validation/anno/CheckEnum.java
calokkk/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
8
2020-04-08T11:01:01.000Z
2022-02-26T20:19:45.000Z
smilcool-server/src/main/java/com/smilcool/server/common/util/validation/anno/CheckEnum.java
calokkk/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
12
2020-07-07T15:16:19.000Z
2022-03-23T16:48:08.000Z
27.629032
79
0.683012
3,589
package com.smilcool.server.common.util.validation.anno; import com.smilcool.server.common.enums.CommonState; import com.smilcool.server.common.enums.PermissionType; import com.smilcool.server.common.enums.UserState; import com.smilcool.server.common.util.validation.validator.CheckEnumValidator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.HashSet; import java.util.Set; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * @author Angus * @date 2019/4/1 */ @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = {CheckEnumValidator.class}) public @interface CheckEnum { /** * 添加枚举的原因在于,注解的属性不支持变量,原本的想法是让 CheckEnum 的 value 为 int[] 型, * 但在使用时 @CheckEnum(value = CommonState.enums(),...) 会报错,故而设置一个枚举作为中专站 */ enum EnumType { EMPTY(new HashSet<>(), "枚举字段非法"), COMMON_STATE(CommonState.enums(), "状态取值为[0-停用,1-启用]"), USER_STATE(UserState.enums(), "状态取值为[0-停用,1-启用,2-未激活]"), PERMISSION_TYPE(PermissionType.enums(), "类型取值为[0-菜单,1-按钮,2-其他]"); /** * 可枚举值集合 */ public Set<?> enums; public String msg; EnumType(Set<?> enums, String msg) { this.enums = enums; this.msg = msg; } } // 枚举类型 EnumType value() default EnumType.EMPTY; String message() default "枚举字段非法"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
3e0876e3a941ced8ce24f37973fcd3502d76da6d
3,769
java
Java
web/store-wicket/src/main/java/org/yes/cart/web/resource/OrderReceiptPdfResource.java
Yulyalu/yes-cart
611f24daac39a7678400af1bd72e662b6b44c7c2
[ "Apache-2.0" ]
122
2015-07-15T08:26:40.000Z
2022-03-14T08:02:29.000Z
web/store-wicket/src/main/java/org/yes/cart/web/resource/OrderReceiptPdfResource.java
Yulyalu/yes-cart
611f24daac39a7678400af1bd72e662b6b44c7c2
[ "Apache-2.0" ]
42
2016-11-13T07:22:55.000Z
2022-03-31T19:58:11.000Z
web/store-wicket/src/main/java/org/yes/cart/web/resource/OrderReceiptPdfResource.java
Yulyalu/yes-cart
611f24daac39a7678400af1bd72e662b6b44c7c2
[ "Apache-2.0" ]
88
2015-09-04T12:04:45.000Z
2022-02-08T17:29:40.000Z
40.095745
132
0.659857
3,590
/* * Copyright 2009 Inspire-Software.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 org.yes.cart.web.resource; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yes.cart.domain.entity.Customer; import org.yes.cart.domain.entity.CustomerOrder; import org.yes.cart.domain.entity.Shop; import org.yes.cart.shoppingcart.ShoppingCart; import org.yes.cart.web.application.ApplicationDirector; import org.yes.cart.web.support.service.CheckoutServiceFacade; import org.yes.cart.web.support.service.CustomerServiceFacade; import java.io.ByteArrayOutputStream; /** * User: denispavlov * Date: 29/10/2015 * Time: 22:00 */ public class OrderReceiptPdfResource extends AbstractDynamicResource { private static final Logger LOG = LoggerFactory.getLogger(OrderReceiptPdfResource.class); private final CheckoutServiceFacade checkoutServiceFacade; private final CustomerServiceFacade customerServiceFacade; public OrderReceiptPdfResource(final CheckoutServiceFacade checkoutServiceFacade, final CustomerServiceFacade customerServiceFacade) { super("application/pdf"); this.checkoutServiceFacade = checkoutServiceFacade; this.customerServiceFacade = customerServiceFacade; } @Override protected byte[] getData(final Attributes attributes) { String ordernum = attributes.getParameters().get("ordernum").toString(); String guestEmail = null; if (StringUtils.isBlank(ordernum)) { ordernum = attributes.getRequest().getPostParameters().getParameterValue("ordernum").toString(); guestEmail = attributes.getRequest().getPostParameters().getParameterValue("guestEmail").toString(); } if (StringUtils.isNotBlank(ordernum)) { final CustomerOrder order = checkoutServiceFacade.findByReference(ordernum); if (order != null) { final ShoppingCart cart = ApplicationDirector.getShoppingCart(); final Shop shop = ApplicationDirector.getCurrentShop(); final boolean loggedIn = cart != null && cart.getLogonState() == ShoppingCart.LOGGED_IN; final Customer customer = loggedIn ? customerServiceFacade.getCustomerByLogin(shop, cart.getCustomerLogin()) : null; final boolean ownsOrder = (customer != null && customer.getCustomerId() == order.getCustomer().getCustomerId()) || (!loggedIn && guestEmail != null && guestEmail.equalsIgnoreCase(order.getEmail())); if (ownsOrder) { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); checkoutServiceFacade.printOrderByReference(ordernum, baos); baos.close(); return baos.toByteArray(); } catch (Exception exp) { LOG.error("Receipt for " + ordernum + " error, caused by " + exp.getMessage(), exp); } } } } return new byte[0]; } }
3e0876fe16493f506ff519eb5ff80b23e9e40f0e
5,939
java
Java
src/main/java/com/palantir/ptoss/cinch/swing/OnFocusChange.java
palantir/Cinch
0f747cb2ba72a70559c1798fad92cfe452f739a0
[ "Apache-2.0" ]
32
2015-01-16T04:40:59.000Z
2022-01-18T07:11:32.000Z
src/main/java/com/palantir/ptoss/cinch/swing/OnFocusChange.java
palantir/Cinch
0f747cb2ba72a70559c1798fad92cfe452f739a0
[ "Apache-2.0" ]
8
2015-01-31T19:14:48.000Z
2021-04-21T16:20:59.000Z
src/main/java/com/palantir/ptoss/cinch/swing/OnFocusChange.java
palantir/Cinch
0f747cb2ba72a70559c1798fad92cfe452f739a0
[ "Apache-2.0" ]
9
2015-10-14T18:57:56.000Z
2020-05-13T11:57:47.000Z
44.320896
138
0.581243
3,591
// Copyright 2011 Palantir 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 com.palantir.ptoss.cinch.swing; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.palantir.ptoss.cinch.core.Binding; import com.palantir.ptoss.cinch.core.BindingContext; import com.palantir.ptoss.cinch.core.BindingException; import com.palantir.ptoss.cinch.core.BindingWiring; import com.palantir.ptoss.cinch.core.ObjectFieldMethod; /** * A binding that will call one method when the bound component loses focus, and another method when * focus is gained. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface OnFocusChange { String lost() default ""; String gained() default ""; /** * Inner utility class that performs the runtime wiring of all {@link OnFocusChange} bindings. */ static class Wiring implements BindingWiring { private static final Logger logger = LoggerFactory.getLogger(OnFocusChange.class); private static String normalizeString(String string) { if (Bound.Utilities.isNullOrBlank(string)) { return null; } return string; } public Collection<Binding> wire(BindingContext context) { List<Field> actions = context.getAnnotatedFields(OnFocusChange.class); for (Field field : actions) { OnFocusChange focusChange = field.getAnnotation(OnFocusChange.class); String lost = normalizeString(focusChange.lost()); String gained = normalizeString(focusChange.gained()); if (Bound.Utilities.isNullOrBlank(lost) && Bound.Utilities.isNullOrBlank(gained)) { throw new BindingException("either lost or gained must be specified on @OnFocusChange on " + field.getName()); } try { wire(lost, gained, field, context); } catch (Exception e) { throw new BindingException("could not wire up @OnFocusChange " + field.getName(), e); } } return ImmutableList.of(); } private static void wire(String lost, String gained, Field field, BindingContext context) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method aflMethod = field.getType().getMethod("addFocusListener", FocusListener.class); if (aflMethod != null) { Object actionObject = context.getFieldObject(field, Object.class); final ObjectFieldMethod lostOFM; if (lost == null) { lostOFM = null; } else { lostOFM = context.getBindableMethod(lost); if (lostOFM == null) { throw new BindingException("could not find bindable method: " + lost); } } final ObjectFieldMethod gainedOFM; if (gained == null) { gainedOFM = null; } else { gainedOFM = context.getBindableMethod(gained); if (gainedOFM == null) { throw new BindingException("could not find bindable method: " + gained); } } FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { try { if (gainedOFM != null) { boolean accessible = gainedOFM.getMethod().isAccessible(); gainedOFM.getMethod().setAccessible(true); gainedOFM.getMethod().invoke(gainedOFM.getObject()); gainedOFM.getMethod().setAccessible(accessible); } } catch (Exception ex) { logger.error("exception during focusGained firing", ex); } } public void focusLost(FocusEvent e) { try { if (lostOFM != null) { boolean accessible = lostOFM.getMethod().isAccessible(); lostOFM.getMethod().setAccessible(true); lostOFM.getMethod().invoke(lostOFM.getObject()); lostOFM.getMethod().setAccessible(accessible); } } catch (Exception ex) { logger.error("exception during focusLost firing", ex); } } }; aflMethod.invoke(actionObject, focusListener); } } } }
3e08788c91d381a5d3137e53034a336000c8a789
1,093
java
Java
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/extractor/JwtHeaderTokenExtractor.java
augustusliu/thingsboard
61d8b0fabdf0fbf5fcff06a7af42cbada45ab0d3
[ "ECL-2.0", "Apache-2.0" ]
1
2020-12-29T10:54:18.000Z
2020-12-29T10:54:18.000Z
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/extractor/JwtHeaderTokenExtractor.java
harmful-chan/harthb
932d6db029cfa46da7e02041018c283fcc3f61b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/extractor/JwtHeaderTokenExtractor.java
harmful-chan/harthb
932d6db029cfa46da7e02041018c283fcc3f61b0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
39.035714
99
0.767612
3,592
package org.thingsboard.server.service.security.auth.jwt.extractor; import org.apache.commons.lang3.StringUtils; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.stereotype.Component; import org.thingsboard.server.config.ThingsboardSecurityConfiguration; import javax.servlet.http.HttpServletRequest; @Component(value="jwtHeaderTokenExtractor") public class JwtHeaderTokenExtractor implements TokenExtractor { public static final String HEADER_PREFIX = "Bearer "; @Override public String extract(HttpServletRequest request) { String header = request.getHeader(ThingsboardSecurityConfiguration.JWT_TOKEN_HEADER_PARAM); if (StringUtils.isBlank(header)) { throw new AuthenticationServiceException("Authorization header cannot be blank!"); } if (header.length() < HEADER_PREFIX.length()) { throw new AuthenticationServiceException("Invalid authorization header size."); } return header.substring(HEADER_PREFIX.length(), header.length()); } }
3e0878e3fbed59439f07890adf715a967bf1fd0a
2,836
java
Java
src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java
tento64/Mekanism
3637ae19f65e1dc1e63d468218753faace32d484
[ "MIT" ]
null
null
null
src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java
tento64/Mekanism
3637ae19f65e1dc1e63d468218753faace32d484
[ "MIT" ]
null
null
null
src/main/java/mekanism/client/render/tileentity/RenderThermalEvaporationController.java
tento64/Mekanism
3637ae19f65e1dc1e63d468218753faace32d484
[ "MIT" ]
null
null
null
52.518519
161
0.734838
3,593
package mekanism.client.render.tileentity; import com.mojang.blaze3d.matrix.MatrixStack; import javax.annotation.Nonnull; import mekanism.client.render.FluidRenderer; import mekanism.client.render.FluidRenderer.RenderData; import mekanism.client.render.MekanismRenderType; import mekanism.client.render.MekanismRenderer; import mekanism.client.render.MekanismRenderer.GlowInfo; import mekanism.client.render.MekanismRenderer.Model3D; import mekanism.common.tile.TileEntityThermalEvaporationController; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.texture.AtlasTexture; import net.minecraft.client.renderer.tileentity.TileEntityRenderer; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.util.math.BlockPos; public class RenderThermalEvaporationController extends TileEntityRenderer<TileEntityThermalEvaporationController> { public RenderThermalEvaporationController(TileEntityRendererDispatcher renderer) { super(renderer); } @Override public void render(@Nonnull TileEntityThermalEvaporationController tile, float partialTick, @Nonnull MatrixStack matrix, @Nonnull IRenderTypeBuffer renderer, int light, int overlayLight) { if (tile.structured && tile.height - 2 >= 1 && tile.inputTank.getFluidAmount() > 0) { RenderData data = new RenderData(); data.location = tile.getRenderLocation(); data.height = tile.height - 2; //TODO: If we ever allow different width for the evap controller then update this length and width data.length = 2; data.width = 2; data.fluidType = tile.inputTank.getFluid(); renderDispatcher.textureManager.bindTexture(AtlasTexture.LOCATION_BLOCKS_TEXTURE); matrix.push(); BlockPos pos = tile.getPos(); matrix.translate(data.location.x - pos.getX(), data.location.y - pos.getY(), data.location.z - pos.getZ()); float fluidScale = (float) tile.inputTank.getFluidAmount() / (float) tile.getMaxFluid(); GlowInfo glowInfo = MekanismRenderer.enableGlow(data.fluidType); //Render the proper height Model3D fluidModel = FluidRenderer.getFluidModel(data, Math.min(1, fluidScale)); MekanismRenderer.renderObject(fluidModel, matrix, renderer, MekanismRenderType.renderFluidState(AtlasTexture.LOCATION_BLOCKS_TEXTURE), MekanismRenderer.getColorARGB(data.fluidType, fluidScale)); MekanismRenderer.disableGlow(glowInfo); matrix.pop(); } } @Override public boolean isGlobalRenderer(TileEntityThermalEvaporationController tile) { return tile.structured && tile.height - 2 >= 1 && tile.inputTank.getFluidAmount() > 0; } }
3e0878f0da2d99cdfab95ab0b4900d9ee8e983cb
116
java
Java
Battlecode_Arena/bin/battlecode/ide/eclipse/Pre_competition_dev/NavBugState.java
3urningChrome/Battlecode_Arena
20f25d34b95cc6f4deab46260ee95732c49ba85c
[ "MIT" ]
2
2016-01-13T22:32:35.000Z
2016-01-18T08:05:40.000Z
Battlecode_Arena/bin/battlecode/ide/eclipse/Pre_competition_dev/NavBugState.java
3urningChrome/Battlecode_Arena
20f25d34b95cc6f4deab46260ee95732c49ba85c
[ "MIT" ]
null
null
null
Battlecode_Arena/bin/battlecode/ide/eclipse/Pre_competition_dev/NavBugState.java
3urningChrome/Battlecode_Arena
20f25d34b95cc6f4deab46260ee95732c49ba85c
[ "MIT" ]
null
null
null
19.333333
53
0.810345
3,594
package Pre_competition_dev; public enum NavBugState { DIRECT,BUGGING,CLOCKWISE,ANTI_CLOCKWISE,UNREACHABLE }
3e087a199b642ca37ca94975925357e70c5831ec
432
java
Java
CSE116-Programming/Carcasonne/src/ui/Driver.java
VikramGaru/ClassProjects
838ec015c34934ec5d0d94a284147df88fe72d23
[ "Unlicense" ]
null
null
null
CSE116-Programming/Carcasonne/src/ui/Driver.java
VikramGaru/ClassProjects
838ec015c34934ec5d0d94a284147df88fe72d23
[ "Unlicense" ]
4
2016-07-25T22:01:53.000Z
2016-07-25T22:14:37.000Z
CSE116-Programming/Carcasonne/src/ui/Driver.java
VikramGaru/ClassProjects
838ec015c34934ec5d0d94a284147df88fe72d23
[ "Unlicense" ]
null
null
null
18
52
0.666667
3,595
package ui; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import code.FileSave; public class Driver { public static void main(String[] args) { try {for(int i = 0; i<4; i++){ String a = "Enter name of Player " +(i+1); args[i] = JOptionPane.showInputDialog(a); } new FileSave(); SwingUtilities.invokeLater(new Application(args)); } catch (Exception e ){ e.printStackTrace(); } } }
3e087ae625f9a783de4ba7835e488553d81edf8d
2,884
java
Java
projects/OG-Analytics/src/test/java/com/opengamma/analytics/math/integration/GaussianQuadratureIntegrator1DTest.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
1
2020-04-07T12:04:40.000Z
2020-04-07T12:04:40.000Z
projects/OG-Analytics/src/test/java/com/opengamma/analytics/math/integration/GaussianQuadratureIntegrator1DTest.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
null
null
null
projects/OG-Analytics/src/test/java/com/opengamma/analytics/math/integration/GaussianQuadratureIntegrator1DTest.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
null
null
null
29.731959
104
0.694175
3,596
/** * Copyright (C) 2009 - 2009 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.analytics.math.integration; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.Test; import com.opengamma.analytics.math.function.Function1D; /** * */ public class GaussianQuadratureIntegrator1DTest { private static final Function1D<Double, Double> DF1 = new Function1D<Double, Double>() { @Override public Double evaluate(final Double x) { return x * x * x * (x - 4); } }; private static final Function1D<Double, Double> F1 = new Function1D<Double, Double>() { @Override public Double evaluate(final Double x) { return x * x * x * x * (x / 5. - 1); } }; private static final Function1D<Double, Double> DF2 = new Function1D<Double, Double>() { @Override public Double evaluate(final Double x) { return Math.exp(-2 * x); } }; @SuppressWarnings("unused") private static final Function1D<Double, Double> DF3 = new Function1D<Double, Double>() { @Override public Double evaluate(final Double x) { return Math.exp(-x * x); } }; private static final double EPS = 1e-6; @Test public void testGaussLegendre() { double upper = 2; double lower = -6; final Integrator1D<Double, Double> integrator = new GaussLegendreQuadratureIntegrator1D(6); assertEquals(F1.evaluate(upper) - F1.evaluate(lower), integrator.integrate(DF1, lower, upper), EPS); lower = -0.56; upper = 1.4; assertEquals(F1.evaluate(upper) - F1.evaluate(lower), integrator.integrate(DF1, lower, upper), EPS); } @Test public void testGaussLaguerre() { final double upper = Double.POSITIVE_INFINITY; final double lower = 0; final Integrator1D<Double, Double> integrator = new GaussLaguerreQuadratureIntegrator1D(15); assertEquals(0.5, integrator.integrate(DF2, lower, upper), EPS); } @Test public void testRungeKutta() { final RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(); final double lower = -1; final double upper = 2; assertEquals(F1.evaluate(upper) - F1.evaluate(lower), integrator.integrate(DF1, lower, upper), EPS); } @Test public void testGaussJacobi() { final double upper = 12; final double lower = -1; final Integrator1D<Double, Double> integrator = new GaussJacobiQuadratureIntegrator1D(7); assertEquals(F1.evaluate(upper) - F1.evaluate(lower), integrator.integrate(DF1, lower, upper), EPS); } @SuppressWarnings("unused") @Test public void testGaussHermite() { final double upper = Double.POSITIVE_INFINITY; final double lower = Double.NEGATIVE_INFINITY; final Integrator1D<Double, Double> integrator = new GaussHermiteQuadratureIntegrator1D(10); //assertEquals(1, integrator.integrate(DF3, lower, upper), EPS); } }
3e087b7943f4241a2370a5a3a401b5aadcf3691e
5,207
java
Java
sample/src/main/java/nl/nl2312/rxcupboard2/sample/ui/MainActivity.java
erickok/RxCupboard
2c75d880d7aae6d7b86538345b9daa3e438697e8
[ "Apache-2.0" ]
296
2015-04-14T17:42:12.000Z
2021-04-09T06:45:37.000Z
sample/src/main/java/nl/nl2312/rxcupboard2/sample/ui/MainActivity.java
erickok/RxCupboard
2c75d880d7aae6d7b86538345b9daa3e438697e8
[ "Apache-2.0" ]
11
2015-04-20T08:07:22.000Z
2017-11-23T08:50:41.000Z
sample/src/main/java/nl/nl2312/rxcupboard2/sample/ui/MainActivity.java
erickok/RxCupboard
2c75d880d7aae6d7b86538345b9daa3e438697e8
[ "Apache-2.0" ]
19
2015-04-15T16:46:31.000Z
2018-01-17T10:08:46.000Z
34.03268
144
0.745919
3,597
package nl.nl2312.rxcupboard2.sample.ui; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.FlowableEmitter; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import nl.nl2312.rxcupboard2.OnDatabaseChange; import nl.nl2312.rxcupboard2.RxCupboard; import nl.nl2312.rxcupboard2.RxDatabase; import nl.nl2312.rxcupboard2.sample.CupboardDbHelper; import nl.nl2312.rxcupboard2.sample.R; import nl.nl2312.rxcupboard2.sample.model.Item; import static io.reactivex.android.schedulers.AndroidSchedulers.mainThread; import static io.reactivex.schedulers.Schedulers.io; public class MainActivity extends Activity { private CompositeDisposable subscriptions; private ListView itemsList; private EditText addEdit; private Button addButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); subscriptions = new CompositeDisposable(); itemsList = (ListView) findViewById(R.id.itemsList); addEdit = (EditText) findViewById(R.id.addEdit); addButton = (Button) findViewById(R.id.addButton); } @Override protected void onStart() { super.onStart(); // Get handle to your Cupboard database, using the default cupboard() instance final SQLiteDatabase db = CupboardDbHelper.getConnection(this); final RxDatabase rxCupboard = RxCupboard.withDefault(db); // Load all existing items form the database into the list view final ItemsAdapter adapter = new ItemsAdapter(this); // Note that the underlying Cursor is created on calling query(), but individual Item objects are created when iterating (reactive pull) subscriptions.add( rxCupboard.query(Item.class) .subscribeOn(io()) .toList() .observeOn(mainThread()) .subscribe(items -> { adapter.add(items); itemsList.setAdapter(adapter); }, toastErrorAction)); // Add/remove items to/from the list view on any changes in the Item database table subscriptions.add( rxCupboard.changes(Item.class) .subscribeOn(io()) .observeOn(mainThread()) .subscribe(new OnDatabaseChange<Item>() { @Override public void onInsert(Item entity) { adapter.add(entity); } @Override public void onDelete(Item entity) { adapter.remove(entity); } }, toastErrorAction)); // Remove an item from the database when it was clicked subscriptions.add( listItemClicks.map(adapter::getItem) .subscribe(rxCupboard.delete())); // Enable the Add button only when text was entered subscriptions.add( addEditTextChanges.map(text -> !TextUtils.isEmpty(text)) .distinctUntilChanged() .subscribe(enabled -> addButton.setEnabled(enabled))); // Allow adding of items when pressing the Add button subscriptions.add( addButtonClicks.map(click -> addEdit.getText().toString()) .map(entry -> { // Create the pojo Item item = new Item(); item.title = entry; return item; }) .doOnNext(update -> addEdit.setText(null)) .subscribe(rxCupboard.put(), toastErrorAction)); } private Consumer<Throwable> toastErrorAction = throwable -> Toast.makeText(MainActivity.this, throwable.toString(), Toast.LENGTH_SHORT).show(); private Flowable<Integer> listItemClicks = Flowable.create((FlowableEmitter<Integer> emitter) -> { AdapterView.OnItemClickListener onItemClicks = (adapterView, view, i, l) -> emitter.onNext(i); emitter.setCancellable(() -> itemsList.setOnItemClickListener(null)); itemsList.setOnItemClickListener(onItemClicks); }, BackpressureStrategy.BUFFER); private Flowable<CharSequence> addEditTextChanges = Flowable.create((FlowableEmitter<CharSequence> emitter) -> { TextWatcher addEditWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { emitter.onNext(charSequence); } @Override public void afterTextChanged(Editable editable) { } }; emitter.setCancellable(() -> addEdit.removeTextChangedListener(addEditWatcher)); addEdit.addTextChangedListener(addEditWatcher); // Emit initial value emitter.onNext(addEdit.getText()); }, BackpressureStrategy.BUFFER); private Flowable<Object> addButtonClicks = Flowable.create((FlowableEmitter<Object> emitter) -> { View.OnClickListener onAddButtonClicks = view -> emitter.onNext(new Object()); emitter.setCancellable(() -> addButton.setOnClickListener(null)); addButton.setOnClickListener(onAddButtonClicks); }, BackpressureStrategy.BUFFER); @Override protected void onStop() { super.onStop(); subscriptions.clear(); } }
3e087d7b7329fbfb42abd626fe6fe3487f0dfbc3
294
java
Java
src/main/java/com/reandroid/lib/arsc/item/TypeString.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
4
2021-11-17T14:15:17.000Z
2022-03-26T04:24:34.000Z
src/main/java/com/reandroid/lib/arsc/item/TypeString.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
null
null
null
src/main/java/com/reandroid/lib/arsc/item/TypeString.java
REAndroid/ARSCLib
1763dfbc3cf7e80e0485b6a11fcd67a1d813dc66
[ "Apache-2.0" ]
2
2021-11-17T14:15:19.000Z
2022-02-17T09:09:08.000Z
18.375
44
0.608844
3,598
package com.reandroid.lib.arsc.item; public class TypeString extends StringItem { public TypeString(boolean utf8) { super(utf8); } public byte getId(){ return (byte) (getIndex()+1); } @Override public StyleItem getStyle(){ return null; } }
3e087db606ad4426b8d43e743a6da56a3d774c0c
3,892
java
Java
src/test/java/com/uscexp/lang/switchnice/SwitchTest.java
uscexp/snippets
d00829f250c6875fd8909ea01ba4558764fea3bc
[ "Apache-2.0" ]
null
null
null
src/test/java/com/uscexp/lang/switchnice/SwitchTest.java
uscexp/snippets
d00829f250c6875fd8909ea01ba4558764fea3bc
[ "Apache-2.0" ]
null
null
null
src/test/java/com/uscexp/lang/switchnice/SwitchTest.java
uscexp/snippets
d00829f250c6875fd8909ea01ba4558764fea3bc
[ "Apache-2.0" ]
null
null
null
25.774834
71
0.384378
3,599
package com.uscexp.lang.switchnice; import org.junit.Test; import static org.junit.Assert.*; public class SwitchTest { @Test public void testSwitchMatchFirstCase() { String result = Switch.Switch("test") .caseOp("test", () -> { return "OK"; }) .breakOp() .caseOp("test1", () -> { return "NOT OK 1"; }) .breakOp() .defaultOp(() -> { return "NOT OK 2"; }) .get(); assertEquals("OK", result); } @Test public void testSwitchMatchSecondCase() { String value = "test"; String toEvaluate = "test"; SwitchSimple<String> aSwitchSimple = new SwitchSimple<>(value); String result = Switch.Switch("test") .caseOp("test1", () -> { return "NOT OK 1"; }) .breakOp() .caseOp("test", () -> { return "OK"; }) .breakOp() .defaultOp(() -> { return "NOT OK 2"; }) .get(); assertEquals("OK", result); } @Test public void testSwitchMatchDefault() { String value = "test"; String toEvaluate = "test"; SwitchSimple<String> aSwitchSimple = new SwitchSimple<>(value); String result = Switch.Switch("test") .caseOp("test1", () -> { return "NOT OK 1"; }) .breakOp() .caseOp("test2", () -> { return "NOT OK 2"; }) .breakOp() .defaultOp(() -> { return "OK"; }) .get(); assertEquals("OK", result); } @Test public void testSwitchMatchFirstAndSecondCase() { String value = "test"; String toEvaluate = "test"; SwitchSimple<String> aSwitchSimple = new SwitchSimple<>(value); Switch<String> aSwitch = Switch.Switch("test"); String result = aSwitch .caseOp("test", () -> { return "OK 1"; }) .caseOp("test2", () -> { String st = aSwitch.get(); return st + ", OK 2"; }) .breakOp() .defaultOp(() -> { return "NOT OK 2"; }) .get(); assertEquals("OK 1, OK 2", result); } @Test(expected = IllegalStateException.class) public void testSwitchCaseAfterDefault() { String result = Switch.Switch("test") .caseOp("test", () -> { return "OK"; }) .breakOp() .caseOp("test1", () -> { return "NOT OK 1"; }) .breakOp() .defaultOp(() -> { return "NOT OK 2"; }) .caseOp("test2", () -> { return "NOT OK 3"; }) .get(); assertEquals("OK", result); } @Test(expected = IllegalStateException.class) public void testSwitchBreakAfterDefault() { String result = Switch.Switch("test") .caseOp("test", () -> { return "OK"; }) .breakOp() .caseOp("test1", () -> { return "NOT OK 1"; }) .breakOp() .defaultOp(() -> { return "NOT OK 2"; }) .breakOp() .get(); assertEquals("OK", result); } }
3e087de4d8fa23a8d635ad70db97b7a4f33bfaf8
88,733
java
Java
repository/src/main/java/org/apache/atlas/query/antlr4/AtlasDSLParser.java
kirankumardg/apache-atlas-sources-1.1.0
9c27ddaac2072cde86798e643d436e266e8f2e68
[ "Apache-2.0" ]
null
null
null
repository/src/main/java/org/apache/atlas/query/antlr4/AtlasDSLParser.java
kirankumardg/apache-atlas-sources-1.1.0
9c27ddaac2072cde86798e643d436e266e8f2e68
[ "Apache-2.0" ]
3
2020-07-07T20:06:14.000Z
2022-02-26T00:52:09.000Z
repository/src/main/java/org/apache/atlas/query/antlr4/AtlasDSLParser.java
kirankumardg/apache-atlas-sources-1.1.0
9c27ddaac2072cde86798e643d436e266e8f2e68
[ "Apache-2.0" ]
null
null
null
32.634424
288
0.711381
3,600
// Generated from /Users/kdg/intuit_projects/apache-atlas-sources-1.1.0/repository/src/main/java/org/apache/atlas/query/antlr4/AtlasDSLParser.g4 by ANTLR 4.7.2 package org.apache.atlas.query.antlr4; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class AtlasDSLParser extends Parser { static { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int SINGLE_LINE_COMMENT=1, MULTILINE_COMMENT=2, WS=3, NUMBER=4, FLOATING_NUMBER=5, BOOL=6, K_COMMA=7, K_PLUS=8, K_MINUS=9, K_STAR=10, K_DIV=11, K_DOT=12, K_LIKE=13, K_AND=14, K_OR=15, K_LPAREN=16, K_LBRACKET=17, K_RPAREN=18, K_RBRACKET=19, K_LT=20, K_LTE=21, K_EQ=22, K_NEQ=23, K_GT=24, K_GTE=25, K_FROM=26, K_WHERE=27, K_ORDERBY=28, K_GROUPBY=29, K_LIMIT=30, K_SELECT=31, K_MAX=32, K_MIN=33, K_SUM=34, K_COUNT=35, K_OFFSET=36, K_AS=37, K_ISA=38, K_IS=39, K_HAS=40, K_ASC=41, K_DESC=42, K_TRUE=43, K_FALSE=44, K_HASR=45, KEYWORD=46, ID=47, STRING=48; public static final int RULE_identifier = 0, RULE_operator = 1, RULE_sortOrder = 2, RULE_valueArray = 3, RULE_literal = 4, RULE_limitClause = 5, RULE_offsetClause = 6, RULE_atomE = 7, RULE_multiERight = 8, RULE_multiE = 9, RULE_arithERight = 10, RULE_arithE = 11, RULE_comparisonClause = 12, RULE_isClause = 13, RULE_hasClause = 14, RULE_countClause = 15, RULE_maxClause = 16, RULE_minClause = 17, RULE_sumClause = 18, RULE_exprRight = 19, RULE_hasRClause = 20, RULE_compE = 21, RULE_expr = 22, RULE_limitOffset = 23, RULE_selectExpression = 24, RULE_selectExpr = 25, RULE_aliasExpr = 26, RULE_orderByExpr = 27, RULE_fromSrc = 28, RULE_whereClause = 29, RULE_fromExpression = 30, RULE_fromClause = 31, RULE_selectClause = 32, RULE_hasRExpression = 33, RULE_singleQrySrc = 34, RULE_groupByExpression = 35, RULE_commaDelimitedQueries = 36, RULE_spaceDelimitedQueries = 37, RULE_querySrc = 38, RULE_query = 39; private static String[] makeRuleNames() { return new String[] { "identifier", "operator", "sortOrder", "valueArray", "literal", "limitClause", "offsetClause", "atomE", "multiERight", "multiE", "arithERight", "arithE", "comparisonClause", "isClause", "hasClause", "countClause", "maxClause", "minClause", "sumClause", "exprRight", "hasRClause", "compE", "expr", "limitOffset", "selectExpression", "selectExpr", "aliasExpr", "orderByExpr", "fromSrc", "whereClause", "fromExpression", "fromClause", "selectClause", "hasRExpression", "singleQrySrc", "groupByExpression", "commaDelimitedQueries", "spaceDelimitedQueries", "querySrc", "query" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, null, null, null, null, null, null, "','", "'+'", "'-'", "'*'", "'/'", "'.'", null, null, null, "'('", "'['", "')'", "']'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "SINGLE_LINE_COMMENT", "MULTILINE_COMMENT", "WS", "NUMBER", "FLOATING_NUMBER", "BOOL", "K_COMMA", "K_PLUS", "K_MINUS", "K_STAR", "K_DIV", "K_DOT", "K_LIKE", "K_AND", "K_OR", "K_LPAREN", "K_LBRACKET", "K_RPAREN", "K_RBRACKET", "K_LT", "K_LTE", "K_EQ", "K_NEQ", "K_GT", "K_GTE", "K_FROM", "K_WHERE", "K_ORDERBY", "K_GROUPBY", "K_LIMIT", "K_SELECT", "K_MAX", "K_MIN", "K_SUM", "K_COUNT", "K_OFFSET", "K_AS", "K_ISA", "K_IS", "K_HAS", "K_ASC", "K_DESC", "K_TRUE", "K_FALSE", "K_HASR", "KEYWORD", "ID", "STRING" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "AtlasDSLParser.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public AtlasDSLParser(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class IdentifierContext extends ParserRuleContext { public TerminalNode ID() { return getToken(AtlasDSLParser.ID, 0); } public IdentifierContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_identifier; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterIdentifier(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitIdentifier(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitIdentifier(this); else return visitor.visitChildren(this); } } public final IdentifierContext identifier() throws RecognitionException { IdentifierContext _localctx = new IdentifierContext(_ctx, getState()); enterRule(_localctx, 0, RULE_identifier); try { enterOuterAlt(_localctx, 1); { setState(80); match(ID); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OperatorContext extends ParserRuleContext { public TerminalNode K_LT() { return getToken(AtlasDSLParser.K_LT, 0); } public TerminalNode K_LTE() { return getToken(AtlasDSLParser.K_LTE, 0); } public TerminalNode K_EQ() { return getToken(AtlasDSLParser.K_EQ, 0); } public TerminalNode K_NEQ() { return getToken(AtlasDSLParser.K_NEQ, 0); } public TerminalNode K_GT() { return getToken(AtlasDSLParser.K_GT, 0); } public TerminalNode K_GTE() { return getToken(AtlasDSLParser.K_GTE, 0); } public TerminalNode K_LIKE() { return getToken(AtlasDSLParser.K_LIKE, 0); } public OperatorContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_operator; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterOperator(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitOperator(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitOperator(this); else return visitor.visitChildren(this); } } public final OperatorContext operator() throws RecognitionException { OperatorContext _localctx = new OperatorContext(_ctx, getState()); enterRule(_localctx, 2, RULE_operator); int _la; try { enterOuterAlt(_localctx, 1); { setState(82); _la = _input.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << K_LIKE) | (1L << K_LT) | (1L << K_LTE) | (1L << K_EQ) | (1L << K_NEQ) | (1L << K_GT) | (1L << K_GTE))) != 0)) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SortOrderContext extends ParserRuleContext { public TerminalNode K_ASC() { return getToken(AtlasDSLParser.K_ASC, 0); } public TerminalNode K_DESC() { return getToken(AtlasDSLParser.K_DESC, 0); } public SortOrderContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_sortOrder; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSortOrder(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSortOrder(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSortOrder(this); else return visitor.visitChildren(this); } } public final SortOrderContext sortOrder() throws RecognitionException { SortOrderContext _localctx = new SortOrderContext(_ctx, getState()); enterRule(_localctx, 4, RULE_sortOrder); int _la; try { enterOuterAlt(_localctx, 1); { setState(84); _la = _input.LA(1); if ( !(_la==K_ASC || _la==K_DESC) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ValueArrayContext extends ParserRuleContext { public TerminalNode K_LBRACKET() { return getToken(AtlasDSLParser.K_LBRACKET, 0); } public List<TerminalNode> ID() { return getTokens(AtlasDSLParser.ID); } public TerminalNode ID(int i) { return getToken(AtlasDSLParser.ID, i); } public TerminalNode K_RBRACKET() { return getToken(AtlasDSLParser.K_RBRACKET, 0); } public List<TerminalNode> K_COMMA() { return getTokens(AtlasDSLParser.K_COMMA); } public TerminalNode K_COMMA(int i) { return getToken(AtlasDSLParser.K_COMMA, i); } public ValueArrayContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_valueArray; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterValueArray(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitValueArray(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitValueArray(this); else return visitor.visitChildren(this); } } public final ValueArrayContext valueArray() throws RecognitionException { ValueArrayContext _localctx = new ValueArrayContext(_ctx, getState()); enterRule(_localctx, 6, RULE_valueArray); int _la; try { enterOuterAlt(_localctx, 1); { setState(86); match(K_LBRACKET); setState(87); match(ID); setState(92); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_COMMA) { { { setState(88); match(K_COMMA); setState(89); match(ID); } } setState(94); _errHandler.sync(this); _la = _input.LA(1); } setState(95); match(K_RBRACKET); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LiteralContext extends ParserRuleContext { public TerminalNode BOOL() { return getToken(AtlasDSLParser.BOOL, 0); } public TerminalNode NUMBER() { return getToken(AtlasDSLParser.NUMBER, 0); } public TerminalNode FLOATING_NUMBER() { return getToken(AtlasDSLParser.FLOATING_NUMBER, 0); } public TerminalNode ID() { return getToken(AtlasDSLParser.ID, 0); } public ValueArrayContext valueArray() { return getRuleContext(ValueArrayContext.class,0); } public LiteralContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_literal; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterLiteral(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitLiteral(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitLiteral(this); else return visitor.visitChildren(this); } } public final LiteralContext literal() throws RecognitionException { LiteralContext _localctx = new LiteralContext(_ctx, getState()); enterRule(_localctx, 8, RULE_literal); try { setState(104); _errHandler.sync(this); switch (_input.LA(1)) { case BOOL: enterOuterAlt(_localctx, 1); { setState(97); match(BOOL); } break; case NUMBER: enterOuterAlt(_localctx, 2); { setState(98); match(NUMBER); } break; case FLOATING_NUMBER: enterOuterAlt(_localctx, 3); { setState(99); match(FLOATING_NUMBER); } break; case K_LBRACKET: case ID: enterOuterAlt(_localctx, 4); { setState(102); _errHandler.sync(this); switch (_input.LA(1)) { case ID: { setState(100); match(ID); } break; case K_LBRACKET: { setState(101); valueArray(); } break; default: throw new NoViableAltException(this); } } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LimitClauseContext extends ParserRuleContext { public TerminalNode K_LIMIT() { return getToken(AtlasDSLParser.K_LIMIT, 0); } public TerminalNode NUMBER() { return getToken(AtlasDSLParser.NUMBER, 0); } public LimitClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_limitClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterLimitClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitLimitClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitLimitClause(this); else return visitor.visitChildren(this); } } public final LimitClauseContext limitClause() throws RecognitionException { LimitClauseContext _localctx = new LimitClauseContext(_ctx, getState()); enterRule(_localctx, 10, RULE_limitClause); try { enterOuterAlt(_localctx, 1); { setState(106); match(K_LIMIT); setState(107); match(NUMBER); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OffsetClauseContext extends ParserRuleContext { public TerminalNode K_OFFSET() { return getToken(AtlasDSLParser.K_OFFSET, 0); } public TerminalNode NUMBER() { return getToken(AtlasDSLParser.NUMBER, 0); } public OffsetClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_offsetClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterOffsetClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitOffsetClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitOffsetClause(this); else return visitor.visitChildren(this); } } public final OffsetClauseContext offsetClause() throws RecognitionException { OffsetClauseContext _localctx = new OffsetClauseContext(_ctx, getState()); enterRule(_localctx, 12, RULE_offsetClause); try { enterOuterAlt(_localctx, 1); { setState(109); match(K_OFFSET); setState(110); match(NUMBER); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AtomEContext extends ParserRuleContext { public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public AtomEContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_atomE; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterAtomE(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitAtomE(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitAtomE(this); else return visitor.visitChildren(this); } } public final AtomEContext atomE() throws RecognitionException { AtomEContext _localctx = new AtomEContext(_ctx, getState()); enterRule(_localctx, 14, RULE_atomE); try { setState(120); _errHandler.sync(this); switch (_input.LA(1)) { case NUMBER: case FLOATING_NUMBER: case BOOL: case K_LBRACKET: case ID: enterOuterAlt(_localctx, 1); { setState(114); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,3,_ctx) ) { case 1: { setState(112); identifier(); } break; case 2: { setState(113); literal(); } break; } } break; case K_LPAREN: enterOuterAlt(_localctx, 2); { setState(116); match(K_LPAREN); setState(117); expr(); setState(118); match(K_RPAREN); } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class MultiERightContext extends ParserRuleContext { public AtomEContext atomE() { return getRuleContext(AtomEContext.class,0); } public TerminalNode K_STAR() { return getToken(AtlasDSLParser.K_STAR, 0); } public TerminalNode K_DIV() { return getToken(AtlasDSLParser.K_DIV, 0); } public MultiERightContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_multiERight; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterMultiERight(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitMultiERight(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitMultiERight(this); else return visitor.visitChildren(this); } } public final MultiERightContext multiERight() throws RecognitionException { MultiERightContext _localctx = new MultiERightContext(_ctx, getState()); enterRule(_localctx, 16, RULE_multiERight); int _la; try { enterOuterAlt(_localctx, 1); { setState(122); _la = _input.LA(1); if ( !(_la==K_STAR || _la==K_DIV) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(123); atomE(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class MultiEContext extends ParserRuleContext { public AtomEContext atomE() { return getRuleContext(AtomEContext.class,0); } public List<MultiERightContext> multiERight() { return getRuleContexts(MultiERightContext.class); } public MultiERightContext multiERight(int i) { return getRuleContext(MultiERightContext.class,i); } public MultiEContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_multiE; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterMultiE(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitMultiE(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitMultiE(this); else return visitor.visitChildren(this); } } public final MultiEContext multiE() throws RecognitionException { MultiEContext _localctx = new MultiEContext(_ctx, getState()); enterRule(_localctx, 18, RULE_multiE); int _la; try { enterOuterAlt(_localctx, 1); { setState(125); atomE(); setState(129); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_STAR || _la==K_DIV) { { { setState(126); multiERight(); } } setState(131); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ArithERightContext extends ParserRuleContext { public MultiEContext multiE() { return getRuleContext(MultiEContext.class,0); } public TerminalNode K_PLUS() { return getToken(AtlasDSLParser.K_PLUS, 0); } public TerminalNode K_MINUS() { return getToken(AtlasDSLParser.K_MINUS, 0); } public ArithERightContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_arithERight; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterArithERight(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitArithERight(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitArithERight(this); else return visitor.visitChildren(this); } } public final ArithERightContext arithERight() throws RecognitionException { ArithERightContext _localctx = new ArithERightContext(_ctx, getState()); enterRule(_localctx, 20, RULE_arithERight); int _la; try { enterOuterAlt(_localctx, 1); { setState(132); _la = _input.LA(1); if ( !(_la==K_PLUS || _la==K_MINUS) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(133); multiE(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ArithEContext extends ParserRuleContext { public MultiEContext multiE() { return getRuleContext(MultiEContext.class,0); } public List<ArithERightContext> arithERight() { return getRuleContexts(ArithERightContext.class); } public ArithERightContext arithERight(int i) { return getRuleContext(ArithERightContext.class,i); } public ArithEContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_arithE; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterArithE(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitArithE(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitArithE(this); else return visitor.visitChildren(this); } } public final ArithEContext arithE() throws RecognitionException { ArithEContext _localctx = new ArithEContext(_ctx, getState()); enterRule(_localctx, 22, RULE_arithE); int _la; try { enterOuterAlt(_localctx, 1); { setState(135); multiE(); setState(139); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_PLUS || _la==K_MINUS) { { { setState(136); arithERight(); } } setState(141); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ComparisonClauseContext extends ParserRuleContext { public List<ArithEContext> arithE() { return getRuleContexts(ArithEContext.class); } public ArithEContext arithE(int i) { return getRuleContext(ArithEContext.class,i); } public OperatorContext operator() { return getRuleContext(OperatorContext.class,0); } public ComparisonClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_comparisonClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterComparisonClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitComparisonClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitComparisonClause(this); else return visitor.visitChildren(this); } } public final ComparisonClauseContext comparisonClause() throws RecognitionException { ComparisonClauseContext _localctx = new ComparisonClauseContext(_ctx, getState()); enterRule(_localctx, 24, RULE_comparisonClause); try { enterOuterAlt(_localctx, 1); { setState(142); arithE(); setState(143); operator(); setState(144); arithE(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class IsClauseContext extends ParserRuleContext { public ArithEContext arithE() { return getRuleContext(ArithEContext.class,0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public TerminalNode K_ISA() { return getToken(AtlasDSLParser.K_ISA, 0); } public TerminalNode K_IS() { return getToken(AtlasDSLParser.K_IS, 0); } public IsClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_isClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterIsClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitIsClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitIsClause(this); else return visitor.visitChildren(this); } } public final IsClauseContext isClause() throws RecognitionException { IsClauseContext _localctx = new IsClauseContext(_ctx, getState()); enterRule(_localctx, 26, RULE_isClause); int _la; try { enterOuterAlt(_localctx, 1); { setState(146); arithE(); setState(147); _la = _input.LA(1); if ( !(_la==K_ISA || _la==K_IS) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(148); identifier(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class HasClauseContext extends ParserRuleContext { public ArithEContext arithE() { return getRuleContext(ArithEContext.class,0); } public TerminalNode K_HAS() { return getToken(AtlasDSLParser.K_HAS, 0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public HasClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_hasClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterHasClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitHasClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitHasClause(this); else return visitor.visitChildren(this); } } public final HasClauseContext hasClause() throws RecognitionException { HasClauseContext _localctx = new HasClauseContext(_ctx, getState()); enterRule(_localctx, 28, RULE_hasClause); try { enterOuterAlt(_localctx, 1); { setState(150); arithE(); setState(151); match(K_HAS); setState(152); identifier(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CountClauseContext extends ParserRuleContext { public TerminalNode K_COUNT() { return getToken(AtlasDSLParser.K_COUNT, 0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public CountClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_countClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterCountClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitCountClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitCountClause(this); else return visitor.visitChildren(this); } } public final CountClauseContext countClause() throws RecognitionException { CountClauseContext _localctx = new CountClauseContext(_ctx, getState()); enterRule(_localctx, 30, RULE_countClause); try { enterOuterAlt(_localctx, 1); { setState(154); match(K_COUNT); setState(155); match(K_LPAREN); setState(156); match(K_RPAREN); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class MaxClauseContext extends ParserRuleContext { public TerminalNode K_MAX() { return getToken(AtlasDSLParser.K_MAX, 0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public MaxClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_maxClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterMaxClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitMaxClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitMaxClause(this); else return visitor.visitChildren(this); } } public final MaxClauseContext maxClause() throws RecognitionException { MaxClauseContext _localctx = new MaxClauseContext(_ctx, getState()); enterRule(_localctx, 32, RULE_maxClause); try { enterOuterAlt(_localctx, 1); { setState(158); match(K_MAX); setState(159); match(K_LPAREN); setState(160); expr(); setState(161); match(K_RPAREN); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class MinClauseContext extends ParserRuleContext { public TerminalNode K_MIN() { return getToken(AtlasDSLParser.K_MIN, 0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public MinClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_minClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterMinClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitMinClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitMinClause(this); else return visitor.visitChildren(this); } } public final MinClauseContext minClause() throws RecognitionException { MinClauseContext _localctx = new MinClauseContext(_ctx, getState()); enterRule(_localctx, 34, RULE_minClause); try { enterOuterAlt(_localctx, 1); { setState(163); match(K_MIN); setState(164); match(K_LPAREN); setState(165); expr(); setState(166); match(K_RPAREN); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SumClauseContext extends ParserRuleContext { public TerminalNode K_SUM() { return getToken(AtlasDSLParser.K_SUM, 0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public SumClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_sumClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSumClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSumClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSumClause(this); else return visitor.visitChildren(this); } } public final SumClauseContext sumClause() throws RecognitionException { SumClauseContext _localctx = new SumClauseContext(_ctx, getState()); enterRule(_localctx, 36, RULE_sumClause); try { enterOuterAlt(_localctx, 1); { setState(168); match(K_SUM); setState(169); match(K_LPAREN); setState(170); expr(); setState(171); match(K_RPAREN); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExprRightContext extends ParserRuleContext { public CompEContext compE() { return getRuleContext(CompEContext.class,0); } public TerminalNode K_AND() { return getToken(AtlasDSLParser.K_AND, 0); } public TerminalNode K_OR() { return getToken(AtlasDSLParser.K_OR, 0); } public ExprRightContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_exprRight; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterExprRight(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitExprRight(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitExprRight(this); else return visitor.visitChildren(this); } } public final ExprRightContext exprRight() throws RecognitionException { ExprRightContext _localctx = new ExprRightContext(_ctx, getState()); enterRule(_localctx, 38, RULE_exprRight); int _la; try { enterOuterAlt(_localctx, 1); { setState(173); _la = _input.LA(1); if ( !(_la==K_AND || _la==K_OR) ) { _errHandler.recoverInline(this); } else { if ( _input.LA(1)==Token.EOF ) matchedEOF = true; _errHandler.reportMatch(this); consume(); } setState(174); compE(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class HasRClauseContext extends ParserRuleContext { public TerminalNode K_HASR() { return getToken(AtlasDSLParser.K_HASR, 0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public HasRClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_hasRClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterHasRClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitHasRClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitHasRClause(this); else return visitor.visitChildren(this); } } public final HasRClauseContext hasRClause() throws RecognitionException { HasRClauseContext _localctx = new HasRClauseContext(_ctx, getState()); enterRule(_localctx, 40, RULE_hasRClause); try { enterOuterAlt(_localctx, 1); { setState(176); match(K_HASR); setState(177); identifier(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CompEContext extends ParserRuleContext { public ComparisonClauseContext comparisonClause() { return getRuleContext(ComparisonClauseContext.class,0); } public IsClauseContext isClause() { return getRuleContext(IsClauseContext.class,0); } public HasClauseContext hasClause() { return getRuleContext(HasClauseContext.class,0); } public ArithEContext arithE() { return getRuleContext(ArithEContext.class,0); } public CountClauseContext countClause() { return getRuleContext(CountClauseContext.class,0); } public MaxClauseContext maxClause() { return getRuleContext(MaxClauseContext.class,0); } public MinClauseContext minClause() { return getRuleContext(MinClauseContext.class,0); } public SumClauseContext sumClause() { return getRuleContext(SumClauseContext.class,0); } public CompEContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_compE; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterCompE(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitCompE(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitCompE(this); else return visitor.visitChildren(this); } } public final CompEContext compE() throws RecognitionException { CompEContext _localctx = new CompEContext(_ctx, getState()); enterRule(_localctx, 42, RULE_compE); try { setState(187); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,7,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(179); comparisonClause(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(180); isClause(); } break; case 3: enterOuterAlt(_localctx, 3); { setState(181); hasClause(); } break; case 4: enterOuterAlt(_localctx, 4); { setState(182); arithE(); } break; case 5: enterOuterAlt(_localctx, 5); { setState(183); countClause(); } break; case 6: enterOuterAlt(_localctx, 6); { setState(184); maxClause(); } break; case 7: enterOuterAlt(_localctx, 7); { setState(185); minClause(); } break; case 8: enterOuterAlt(_localctx, 8); { setState(186); sumClause(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExprContext extends ParserRuleContext { public CompEContext compE() { return getRuleContext(CompEContext.class,0); } public List<ExprRightContext> exprRight() { return getRuleContexts(ExprRightContext.class); } public ExprRightContext exprRight(int i) { return getRuleContext(ExprRightContext.class,i); } public ExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitExpr(this); else return visitor.visitChildren(this); } } public final ExprContext expr() throws RecognitionException { ExprContext _localctx = new ExprContext(_ctx, getState()); enterRule(_localctx, 44, RULE_expr); int _la; try { enterOuterAlt(_localctx, 1); { setState(189); compE(); setState(193); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_AND || _la==K_OR) { { { setState(190); exprRight(); } } setState(195); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class LimitOffsetContext extends ParserRuleContext { public LimitClauseContext limitClause() { return getRuleContext(LimitClauseContext.class,0); } public OffsetClauseContext offsetClause() { return getRuleContext(OffsetClauseContext.class,0); } public LimitOffsetContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_limitOffset; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterLimitOffset(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitLimitOffset(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitLimitOffset(this); else return visitor.visitChildren(this); } } public final LimitOffsetContext limitOffset() throws RecognitionException { LimitOffsetContext _localctx = new LimitOffsetContext(_ctx, getState()); enterRule(_localctx, 46, RULE_limitOffset); int _la; try { enterOuterAlt(_localctx, 1); { setState(196); limitClause(); setState(198); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_OFFSET) { { setState(197); offsetClause(); } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SelectExpressionContext extends ParserRuleContext { public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public TerminalNode K_AS() { return getToken(AtlasDSLParser.K_AS, 0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public SelectExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_selectExpression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSelectExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSelectExpression(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSelectExpression(this); else return visitor.visitChildren(this); } } public final SelectExpressionContext selectExpression() throws RecognitionException { SelectExpressionContext _localctx = new SelectExpressionContext(_ctx, getState()); enterRule(_localctx, 48, RULE_selectExpression); int _la; try { enterOuterAlt(_localctx, 1); { setState(200); expr(); setState(203); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_AS) { { setState(201); match(K_AS); setState(202); identifier(); } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SelectExprContext extends ParserRuleContext { public List<SelectExpressionContext> selectExpression() { return getRuleContexts(SelectExpressionContext.class); } public SelectExpressionContext selectExpression(int i) { return getRuleContext(SelectExpressionContext.class,i); } public List<TerminalNode> K_COMMA() { return getTokens(AtlasDSLParser.K_COMMA); } public TerminalNode K_COMMA(int i) { return getToken(AtlasDSLParser.K_COMMA, i); } public SelectExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_selectExpr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSelectExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSelectExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSelectExpr(this); else return visitor.visitChildren(this); } } public final SelectExprContext selectExpr() throws RecognitionException { SelectExprContext _localctx = new SelectExprContext(_ctx, getState()); enterRule(_localctx, 50, RULE_selectExpr); int _la; try { enterOuterAlt(_localctx, 1); { setState(205); selectExpression(); setState(210); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_COMMA) { { { setState(206); match(K_COMMA); setState(207); selectExpression(); } } setState(212); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class AliasExprContext extends ParserRuleContext { public TerminalNode K_AS() { return getToken(AtlasDSLParser.K_AS, 0); } public List<IdentifierContext> identifier() { return getRuleContexts(IdentifierContext.class); } public IdentifierContext identifier(int i) { return getRuleContext(IdentifierContext.class,i); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public AliasExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_aliasExpr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterAliasExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitAliasExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitAliasExpr(this); else return visitor.visitChildren(this); } } public final AliasExprContext aliasExpr() throws RecognitionException { AliasExprContext _localctx = new AliasExprContext(_ctx, getState()); enterRule(_localctx, 52, RULE_aliasExpr); try { enterOuterAlt(_localctx, 1); { setState(215); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,12,_ctx) ) { case 1: { setState(213); identifier(); } break; case 2: { setState(214); literal(); } break; } setState(217); match(K_AS); setState(218); identifier(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class OrderByExprContext extends ParserRuleContext { public TerminalNode K_ORDERBY() { return getToken(AtlasDSLParser.K_ORDERBY, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public SortOrderContext sortOrder() { return getRuleContext(SortOrderContext.class,0); } public OrderByExprContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_orderByExpr; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterOrderByExpr(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitOrderByExpr(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitOrderByExpr(this); else return visitor.visitChildren(this); } } public final OrderByExprContext orderByExpr() throws RecognitionException { OrderByExprContext _localctx = new OrderByExprContext(_ctx, getState()); enterRule(_localctx, 54, RULE_orderByExpr); int _la; try { enterOuterAlt(_localctx, 1); { setState(220); match(K_ORDERBY); setState(221); expr(); setState(223); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_ASC || _la==K_DESC) { { setState(222); sortOrder(); } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class FromSrcContext extends ParserRuleContext { public AliasExprContext aliasExpr() { return getRuleContext(AliasExprContext.class,0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public LiteralContext literal() { return getRuleContext(LiteralContext.class,0); } public FromSrcContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_fromSrc; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterFromSrc(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitFromSrc(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitFromSrc(this); else return visitor.visitChildren(this); } } public final FromSrcContext fromSrc() throws RecognitionException { FromSrcContext _localctx = new FromSrcContext(_ctx, getState()); enterRule(_localctx, 56, RULE_fromSrc); try { setState(230); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,15,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(225); aliasExpr(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(228); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,14,_ctx) ) { case 1: { setState(226); identifier(); } break; case 2: { setState(227); literal(); } break; } } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class WhereClauseContext extends ParserRuleContext { public TerminalNode K_WHERE() { return getToken(AtlasDSLParser.K_WHERE, 0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public WhereClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_whereClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterWhereClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitWhereClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitWhereClause(this); else return visitor.visitChildren(this); } } public final WhereClauseContext whereClause() throws RecognitionException { WhereClauseContext _localctx = new WhereClauseContext(_ctx, getState()); enterRule(_localctx, 58, RULE_whereClause); try { enterOuterAlt(_localctx, 1); { setState(232); match(K_WHERE); setState(233); expr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class FromExpressionContext extends ParserRuleContext { public FromSrcContext fromSrc() { return getRuleContext(FromSrcContext.class,0); } public WhereClauseContext whereClause() { return getRuleContext(WhereClauseContext.class,0); } public FromExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_fromExpression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterFromExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitFromExpression(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitFromExpression(this); else return visitor.visitChildren(this); } } public final FromExpressionContext fromExpression() throws RecognitionException { FromExpressionContext _localctx = new FromExpressionContext(_ctx, getState()); enterRule(_localctx, 60, RULE_fromExpression); try { enterOuterAlt(_localctx, 1); { setState(235); fromSrc(); setState(237); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,16,_ctx) ) { case 1: { setState(236); whereClause(); } break; } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class FromClauseContext extends ParserRuleContext { public TerminalNode K_FROM() { return getToken(AtlasDSLParser.K_FROM, 0); } public FromExpressionContext fromExpression() { return getRuleContext(FromExpressionContext.class,0); } public FromClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_fromClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterFromClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitFromClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitFromClause(this); else return visitor.visitChildren(this); } } public final FromClauseContext fromClause() throws RecognitionException { FromClauseContext _localctx = new FromClauseContext(_ctx, getState()); enterRule(_localctx, 62, RULE_fromClause); try { enterOuterAlt(_localctx, 1); { setState(239); match(K_FROM); setState(240); fromExpression(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SelectClauseContext extends ParserRuleContext { public TerminalNode K_SELECT() { return getToken(AtlasDSLParser.K_SELECT, 0); } public SelectExprContext selectExpr() { return getRuleContext(SelectExprContext.class,0); } public SelectClauseContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_selectClause; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSelectClause(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSelectClause(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSelectClause(this); else return visitor.visitChildren(this); } } public final SelectClauseContext selectClause() throws RecognitionException { SelectClauseContext _localctx = new SelectClauseContext(_ctx, getState()); enterRule(_localctx, 64, RULE_selectClause); try { enterOuterAlt(_localctx, 1); { setState(242); match(K_SELECT); setState(243); selectExpr(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class HasRExpressionContext extends ParserRuleContext { public HasRClauseContext hasRClause() { return getRuleContext(HasRClauseContext.class,0); } public TerminalNode K_AS() { return getToken(AtlasDSLParser.K_AS, 0); } public IdentifierContext identifier() { return getRuleContext(IdentifierContext.class,0); } public HasRExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_hasRExpression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterHasRExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitHasRExpression(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitHasRExpression(this); else return visitor.visitChildren(this); } } public final HasRExpressionContext hasRExpression() throws RecognitionException { HasRExpressionContext _localctx = new HasRExpressionContext(_ctx, getState()); enterRule(_localctx, 66, RULE_hasRExpression); int _la; try { enterOuterAlt(_localctx, 1); { setState(245); hasRClause(); setState(248); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_AS) { { setState(246); match(K_AS); setState(247); identifier(); } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SingleQrySrcContext extends ParserRuleContext { public FromClauseContext fromClause() { return getRuleContext(FromClauseContext.class,0); } public HasRExpressionContext hasRExpression() { return getRuleContext(HasRExpressionContext.class,0); } public WhereClauseContext whereClause() { return getRuleContext(WhereClauseContext.class,0); } public FromExpressionContext fromExpression() { return getRuleContext(FromExpressionContext.class,0); } public ExprContext expr() { return getRuleContext(ExprContext.class,0); } public SingleQrySrcContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_singleQrySrc; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSingleQrySrc(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSingleQrySrc(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSingleQrySrc(this); else return visitor.visitChildren(this); } } public final SingleQrySrcContext singleQrySrc() throws RecognitionException { SingleQrySrcContext _localctx = new SingleQrySrcContext(_ctx, getState()); enterRule(_localctx, 68, RULE_singleQrySrc); try { setState(255); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,18,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(250); fromClause(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(251); hasRExpression(); } break; case 3: enterOuterAlt(_localctx, 3); { setState(252); whereClause(); } break; case 4: enterOuterAlt(_localctx, 4); { setState(253); fromExpression(); } break; case 5: enterOuterAlt(_localctx, 5); { setState(254); expr(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class GroupByExpressionContext extends ParserRuleContext { public TerminalNode K_GROUPBY() { return getToken(AtlasDSLParser.K_GROUPBY, 0); } public TerminalNode K_LPAREN() { return getToken(AtlasDSLParser.K_LPAREN, 0); } public SelectExprContext selectExpr() { return getRuleContext(SelectExprContext.class,0); } public TerminalNode K_RPAREN() { return getToken(AtlasDSLParser.K_RPAREN, 0); } public GroupByExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_groupByExpression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterGroupByExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitGroupByExpression(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitGroupByExpression(this); else return visitor.visitChildren(this); } } public final GroupByExpressionContext groupByExpression() throws RecognitionException { GroupByExpressionContext _localctx = new GroupByExpressionContext(_ctx, getState()); enterRule(_localctx, 70, RULE_groupByExpression); try { enterOuterAlt(_localctx, 1); { setState(257); match(K_GROUPBY); setState(258); match(K_LPAREN); setState(259); selectExpr(); setState(260); match(K_RPAREN); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class CommaDelimitedQueriesContext extends ParserRuleContext { public List<SingleQrySrcContext> singleQrySrc() { return getRuleContexts(SingleQrySrcContext.class); } public SingleQrySrcContext singleQrySrc(int i) { return getRuleContext(SingleQrySrcContext.class,i); } public List<TerminalNode> K_COMMA() { return getTokens(AtlasDSLParser.K_COMMA); } public TerminalNode K_COMMA(int i) { return getToken(AtlasDSLParser.K_COMMA, i); } public CommaDelimitedQueriesContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_commaDelimitedQueries; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterCommaDelimitedQueries(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitCommaDelimitedQueries(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitCommaDelimitedQueries(this); else return visitor.visitChildren(this); } } public final CommaDelimitedQueriesContext commaDelimitedQueries() throws RecognitionException { CommaDelimitedQueriesContext _localctx = new CommaDelimitedQueriesContext(_ctx, getState()); enterRule(_localctx, 72, RULE_commaDelimitedQueries); int _la; try { enterOuterAlt(_localctx, 1); { setState(262); singleQrySrc(); setState(267); _errHandler.sync(this); _la = _input.LA(1); while (_la==K_COMMA) { { { setState(263); match(K_COMMA); setState(264); singleQrySrc(); } } setState(269); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class SpaceDelimitedQueriesContext extends ParserRuleContext { public List<SingleQrySrcContext> singleQrySrc() { return getRuleContexts(SingleQrySrcContext.class); } public SingleQrySrcContext singleQrySrc(int i) { return getRuleContext(SingleQrySrcContext.class,i); } public SpaceDelimitedQueriesContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_spaceDelimitedQueries; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterSpaceDelimitedQueries(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitSpaceDelimitedQueries(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitSpaceDelimitedQueries(this); else return visitor.visitChildren(this); } } public final SpaceDelimitedQueriesContext spaceDelimitedQueries() throws RecognitionException { SpaceDelimitedQueriesContext _localctx = new SpaceDelimitedQueriesContext(_ctx, getState()); enterRule(_localctx, 74, RULE_spaceDelimitedQueries); int _la; try { enterOuterAlt(_localctx, 1); { setState(270); singleQrySrc(); setState(274); _errHandler.sync(this); _la = _input.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << NUMBER) | (1L << FLOATING_NUMBER) | (1L << BOOL) | (1L << K_LPAREN) | (1L << K_LBRACKET) | (1L << K_FROM) | (1L << K_WHERE) | (1L << K_MAX) | (1L << K_MIN) | (1L << K_SUM) | (1L << K_COUNT) | (1L << K_HASR) | (1L << ID))) != 0)) { { { setState(271); singleQrySrc(); } } setState(276); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class QuerySrcContext extends ParserRuleContext { public CommaDelimitedQueriesContext commaDelimitedQueries() { return getRuleContext(CommaDelimitedQueriesContext.class,0); } public SpaceDelimitedQueriesContext spaceDelimitedQueries() { return getRuleContext(SpaceDelimitedQueriesContext.class,0); } public QuerySrcContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_querySrc; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterQuerySrc(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitQuerySrc(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitQuerySrc(this); else return visitor.visitChildren(this); } } public final QuerySrcContext querySrc() throws RecognitionException { QuerySrcContext _localctx = new QuerySrcContext(_ctx, getState()); enterRule(_localctx, 76, RULE_querySrc); try { setState(279); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,21,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(277); commaDelimitedQueries(); } break; case 2: enterOuterAlt(_localctx, 2); { setState(278); spaceDelimitedQueries(); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class QueryContext extends ParserRuleContext { public QuerySrcContext querySrc() { return getRuleContext(QuerySrcContext.class,0); } public TerminalNode EOF() { return getToken(AtlasDSLParser.EOF, 0); } public GroupByExpressionContext groupByExpression() { return getRuleContext(GroupByExpressionContext.class,0); } public SelectClauseContext selectClause() { return getRuleContext(SelectClauseContext.class,0); } public OrderByExprContext orderByExpr() { return getRuleContext(OrderByExprContext.class,0); } public LimitOffsetContext limitOffset() { return getRuleContext(LimitOffsetContext.class,0); } public QueryContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_query; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).enterQuery(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof AtlasDSLParserListener ) ((AtlasDSLParserListener)listener).exitQuery(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof AtlasDSLParserVisitor ) return ((AtlasDSLParserVisitor<? extends T>)visitor).visitQuery(this); else return visitor.visitChildren(this); } } public final QueryContext query() throws RecognitionException { QueryContext _localctx = new QueryContext(_ctx, getState()); enterRule(_localctx, 78, RULE_query); int _la; try { enterOuterAlt(_localctx, 1); { setState(281); querySrc(); setState(283); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_GROUPBY) { { setState(282); groupByExpression(); } } setState(286); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_SELECT) { { setState(285); selectClause(); } } setState(289); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_ORDERBY) { { setState(288); orderByExpr(); } } setState(292); _errHandler.sync(this); _la = _input.LA(1); if (_la==K_LIMIT) { { setState(291); limitOffset(); } } setState(294); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\62\u012b\4\2\t\2"+ "\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+ "\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+ "\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+ "\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+ "\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\3\2\3\3\3"+ "\3\3\4\3\4\3\5\3\5\3\5\3\5\7\5]\n\5\f\5\16\5`\13\5\3\5\3\5\3\6\3\6\3\6"+ "\3\6\3\6\5\6i\n\6\5\6k\n\6\3\7\3\7\3\7\3\b\3\b\3\b\3\t\3\t\5\tu\n\t\3"+ "\t\3\t\3\t\3\t\5\t{\n\t\3\n\3\n\3\n\3\13\3\13\7\13\u0082\n\13\f\13\16"+ "\13\u0085\13\13\3\f\3\f\3\f\3\r\3\r\7\r\u008c\n\r\f\r\16\r\u008f\13\r"+ "\3\16\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\21\3\21"+ "\3\21\3\21\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\24\3\24"+ "\3\24\3\24\3\24\3\25\3\25\3\25\3\26\3\26\3\26\3\27\3\27\3\27\3\27\3\27"+ "\3\27\3\27\3\27\5\27\u00be\n\27\3\30\3\30\7\30\u00c2\n\30\f\30\16\30\u00c5"+ "\13\30\3\31\3\31\5\31\u00c9\n\31\3\32\3\32\3\32\5\32\u00ce\n\32\3\33\3"+ "\33\3\33\7\33\u00d3\n\33\f\33\16\33\u00d6\13\33\3\34\3\34\5\34\u00da\n"+ "\34\3\34\3\34\3\34\3\35\3\35\3\35\5\35\u00e2\n\35\3\36\3\36\3\36\5\36"+ "\u00e7\n\36\5\36\u00e9\n\36\3\37\3\37\3\37\3 \3 \5 \u00f0\n \3!\3!\3!"+ "\3\"\3\"\3\"\3#\3#\3#\5#\u00fb\n#\3$\3$\3$\3$\3$\5$\u0102\n$\3%\3%\3%"+ "\3%\3%\3&\3&\3&\7&\u010c\n&\f&\16&\u010f\13&\3\'\3\'\7\'\u0113\n\'\f\'"+ "\16\'\u0116\13\'\3(\3(\5(\u011a\n(\3)\3)\5)\u011e\n)\3)\5)\u0121\n)\3"+ ")\5)\u0124\n)\3)\5)\u0127\n)\3)\3)\3)\2\2*\2\4\6\b\n\f\16\20\22\24\26"+ "\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BDFHJLNP\2\b\4\2\17\17\26\33\3\2"+ "+,\3\2\f\r\3\2\n\13\3\2()\3\2\20\21\2\u0127\2R\3\2\2\2\4T\3\2\2\2\6V\3"+ "\2\2\2\bX\3\2\2\2\nj\3\2\2\2\fl\3\2\2\2\16o\3\2\2\2\20z\3\2\2\2\22|\3"+ "\2\2\2\24\177\3\2\2\2\26\u0086\3\2\2\2\30\u0089\3\2\2\2\32\u0090\3\2\2"+ "\2\34\u0094\3\2\2\2\36\u0098\3\2\2\2 \u009c\3\2\2\2\"\u00a0\3\2\2\2$\u00a5"+ "\3\2\2\2&\u00aa\3\2\2\2(\u00af\3\2\2\2*\u00b2\3\2\2\2,\u00bd\3\2\2\2."+ "\u00bf\3\2\2\2\60\u00c6\3\2\2\2\62\u00ca\3\2\2\2\64\u00cf\3\2\2\2\66\u00d9"+ "\3\2\2\28\u00de\3\2\2\2:\u00e8\3\2\2\2<\u00ea\3\2\2\2>\u00ed\3\2\2\2@"+ "\u00f1\3\2\2\2B\u00f4\3\2\2\2D\u00f7\3\2\2\2F\u0101\3\2\2\2H\u0103\3\2"+ "\2\2J\u0108\3\2\2\2L\u0110\3\2\2\2N\u0119\3\2\2\2P\u011b\3\2\2\2RS\7\61"+ "\2\2S\3\3\2\2\2TU\t\2\2\2U\5\3\2\2\2VW\t\3\2\2W\7\3\2\2\2XY\7\23\2\2Y"+ "^\7\61\2\2Z[\7\t\2\2[]\7\61\2\2\\Z\3\2\2\2]`\3\2\2\2^\\\3\2\2\2^_\3\2"+ "\2\2_a\3\2\2\2`^\3\2\2\2ab\7\25\2\2b\t\3\2\2\2ck\7\b\2\2dk\7\6\2\2ek\7"+ "\7\2\2fi\7\61\2\2gi\5\b\5\2hf\3\2\2\2hg\3\2\2\2ik\3\2\2\2jc\3\2\2\2jd"+ "\3\2\2\2je\3\2\2\2jh\3\2\2\2k\13\3\2\2\2lm\7 \2\2mn\7\6\2\2n\r\3\2\2\2"+ "op\7&\2\2pq\7\6\2\2q\17\3\2\2\2ru\5\2\2\2su\5\n\6\2tr\3\2\2\2ts\3\2\2"+ "\2u{\3\2\2\2vw\7\22\2\2wx\5.\30\2xy\7\24\2\2y{\3\2\2\2zt\3\2\2\2zv\3\2"+ "\2\2{\21\3\2\2\2|}\t\4\2\2}~\5\20\t\2~\23\3\2\2\2\177\u0083\5\20\t\2\u0080"+ "\u0082\5\22\n\2\u0081\u0080\3\2\2\2\u0082\u0085\3\2\2\2\u0083\u0081\3"+ "\2\2\2\u0083\u0084\3\2\2\2\u0084\25\3\2\2\2\u0085\u0083\3\2\2\2\u0086"+ "\u0087\t\5\2\2\u0087\u0088\5\24\13\2\u0088\27\3\2\2\2\u0089\u008d\5\24"+ "\13\2\u008a\u008c\5\26\f\2\u008b\u008a\3\2\2\2\u008c\u008f\3\2\2\2\u008d"+ "\u008b\3\2\2\2\u008d\u008e\3\2\2\2\u008e\31\3\2\2\2\u008f\u008d\3\2\2"+ "\2\u0090\u0091\5\30\r\2\u0091\u0092\5\4\3\2\u0092\u0093\5\30\r\2\u0093"+ "\33\3\2\2\2\u0094\u0095\5\30\r\2\u0095\u0096\t\6\2\2\u0096\u0097\5\2\2"+ "\2\u0097\35\3\2\2\2\u0098\u0099\5\30\r\2\u0099\u009a\7*\2\2\u009a\u009b"+ "\5\2\2\2\u009b\37\3\2\2\2\u009c\u009d\7%\2\2\u009d\u009e\7\22\2\2\u009e"+ "\u009f\7\24\2\2\u009f!\3\2\2\2\u00a0\u00a1\7\"\2\2\u00a1\u00a2\7\22\2"+ "\2\u00a2\u00a3\5.\30\2\u00a3\u00a4\7\24\2\2\u00a4#\3\2\2\2\u00a5\u00a6"+ "\7#\2\2\u00a6\u00a7\7\22\2\2\u00a7\u00a8\5.\30\2\u00a8\u00a9\7\24\2\2"+ "\u00a9%\3\2\2\2\u00aa\u00ab\7$\2\2\u00ab\u00ac\7\22\2\2\u00ac\u00ad\5"+ ".\30\2\u00ad\u00ae\7\24\2\2\u00ae\'\3\2\2\2\u00af\u00b0\t\7\2\2\u00b0"+ "\u00b1\5,\27\2\u00b1)\3\2\2\2\u00b2\u00b3\7/\2\2\u00b3\u00b4\5\2\2\2\u00b4"+ "+\3\2\2\2\u00b5\u00be\5\32\16\2\u00b6\u00be\5\34\17\2\u00b7\u00be\5\36"+ "\20\2\u00b8\u00be\5\30\r\2\u00b9\u00be\5 \21\2\u00ba\u00be\5\"\22\2\u00bb"+ "\u00be\5$\23\2\u00bc\u00be\5&\24\2\u00bd\u00b5\3\2\2\2\u00bd\u00b6\3\2"+ "\2\2\u00bd\u00b7\3\2\2\2\u00bd\u00b8\3\2\2\2\u00bd\u00b9\3\2\2\2\u00bd"+ "\u00ba\3\2\2\2\u00bd\u00bb\3\2\2\2\u00bd\u00bc\3\2\2\2\u00be-\3\2\2\2"+ "\u00bf\u00c3\5,\27\2\u00c0\u00c2\5(\25\2\u00c1\u00c0\3\2\2\2\u00c2\u00c5"+ "\3\2\2\2\u00c3\u00c1\3\2\2\2\u00c3\u00c4\3\2\2\2\u00c4/\3\2\2\2\u00c5"+ "\u00c3\3\2\2\2\u00c6\u00c8\5\f\7\2\u00c7\u00c9\5\16\b\2\u00c8\u00c7\3"+ "\2\2\2\u00c8\u00c9\3\2\2\2\u00c9\61\3\2\2\2\u00ca\u00cd\5.\30\2\u00cb"+ "\u00cc\7\'\2\2\u00cc\u00ce\5\2\2\2\u00cd\u00cb\3\2\2\2\u00cd\u00ce\3\2"+ "\2\2\u00ce\63\3\2\2\2\u00cf\u00d4\5\62\32\2\u00d0\u00d1\7\t\2\2\u00d1"+ "\u00d3\5\62\32\2\u00d2\u00d0\3\2\2\2\u00d3\u00d6\3\2\2\2\u00d4\u00d2\3"+ "\2\2\2\u00d4\u00d5\3\2\2\2\u00d5\65\3\2\2\2\u00d6\u00d4\3\2\2\2\u00d7"+ "\u00da\5\2\2\2\u00d8\u00da\5\n\6\2\u00d9\u00d7\3\2\2\2\u00d9\u00d8\3\2"+ "\2\2\u00da\u00db\3\2\2\2\u00db\u00dc\7\'\2\2\u00dc\u00dd\5\2\2\2\u00dd"+ "\67\3\2\2\2\u00de\u00df\7\36\2\2\u00df\u00e1\5.\30\2\u00e0\u00e2\5\6\4"+ "\2\u00e1\u00e0\3\2\2\2\u00e1\u00e2\3\2\2\2\u00e29\3\2\2\2\u00e3\u00e9"+ "\5\66\34\2\u00e4\u00e7\5\2\2\2\u00e5\u00e7\5\n\6\2\u00e6\u00e4\3\2\2\2"+ "\u00e6\u00e5\3\2\2\2\u00e7\u00e9\3\2\2\2\u00e8\u00e3\3\2\2\2\u00e8\u00e6"+ "\3\2\2\2\u00e9;\3\2\2\2\u00ea\u00eb\7\35\2\2\u00eb\u00ec\5.\30\2\u00ec"+ "=\3\2\2\2\u00ed\u00ef\5:\36\2\u00ee\u00f0\5<\37\2\u00ef\u00ee\3\2\2\2"+ "\u00ef\u00f0\3\2\2\2\u00f0?\3\2\2\2\u00f1\u00f2\7\34\2\2\u00f2\u00f3\5"+ "> \2\u00f3A\3\2\2\2\u00f4\u00f5\7!\2\2\u00f5\u00f6\5\64\33\2\u00f6C\3"+ "\2\2\2\u00f7\u00fa\5*\26\2\u00f8\u00f9\7\'\2\2\u00f9\u00fb\5\2\2\2\u00fa"+ "\u00f8\3\2\2\2\u00fa\u00fb\3\2\2\2\u00fbE\3\2\2\2\u00fc\u0102\5@!\2\u00fd"+ "\u0102\5D#\2\u00fe\u0102\5<\37\2\u00ff\u0102\5> \2\u0100\u0102\5.\30\2"+ "\u0101\u00fc\3\2\2\2\u0101\u00fd\3\2\2\2\u0101\u00fe\3\2\2\2\u0101\u00ff"+ "\3\2\2\2\u0101\u0100\3\2\2\2\u0102G\3\2\2\2\u0103\u0104\7\37\2\2\u0104"+ "\u0105\7\22\2\2\u0105\u0106\5\64\33\2\u0106\u0107\7\24\2\2\u0107I\3\2"+ "\2\2\u0108\u010d\5F$\2\u0109\u010a\7\t\2\2\u010a\u010c\5F$\2\u010b\u0109"+ "\3\2\2\2\u010c\u010f\3\2\2\2\u010d\u010b\3\2\2\2\u010d\u010e\3\2\2\2\u010e"+ "K\3\2\2\2\u010f\u010d\3\2\2\2\u0110\u0114\5F$\2\u0111\u0113\5F$\2\u0112"+ "\u0111\3\2\2\2\u0113\u0116\3\2\2\2\u0114\u0112\3\2\2\2\u0114\u0115\3\2"+ "\2\2\u0115M\3\2\2\2\u0116\u0114\3\2\2\2\u0117\u011a\5J&\2\u0118\u011a"+ "\5L\'\2\u0119\u0117\3\2\2\2\u0119\u0118\3\2\2\2\u011aO\3\2\2\2\u011b\u011d"+ "\5N(\2\u011c\u011e\5H%\2\u011d\u011c\3\2\2\2\u011d\u011e\3\2\2\2\u011e"+ "\u0120\3\2\2\2\u011f\u0121\5B\"\2\u0120\u011f\3\2\2\2\u0120\u0121\3\2"+ "\2\2\u0121\u0123\3\2\2\2\u0122\u0124\58\35\2\u0123\u0122\3\2\2\2\u0123"+ "\u0124\3\2\2\2\u0124\u0126\3\2\2\2\u0125\u0127\5\60\31\2\u0126\u0125\3"+ "\2\2\2\u0126\u0127\3\2\2\2\u0127\u0128\3\2\2\2\u0128\u0129\7\2\2\3\u0129"+ "Q\3\2\2\2\34^hjtz\u0083\u008d\u00bd\u00c3\u00c8\u00cd\u00d4\u00d9\u00e1"+ "\u00e6\u00e8\u00ef\u00fa\u0101\u010d\u0114\u0119\u011d\u0120\u0123\u0126"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
3e087e25eecfcfae2fae0b2456882eceb960fa7b
1,956
java
Java
src/main/java/com/archos/mediacenter/video/browser/adapters/AdapterDefaultValuesGrid.java
s-stark/aos-Video
37968806df24ae36d0e022c6ab49087c97846ce1
[ "Apache-2.0" ]
21
2018-09-14T08:00:47.000Z
2022-03-07T03:03:13.000Z
src/main/java/com/archos/mediacenter/video/browser/adapters/AdapterDefaultValuesGrid.java
s-stark/aos-Video
37968806df24ae36d0e022c6ab49087c97846ce1
[ "Apache-2.0" ]
16
2018-10-12T17:40:13.000Z
2022-02-12T15:14:39.000Z
src/main/java/com/archos/mediacenter/video/browser/adapters/AdapterDefaultValuesGrid.java
s-stark/aos-Video
37968806df24ae36d0e022c6ab49087c97846ce1
[ "Apache-2.0" ]
37
2018-10-12T10:48:04.000Z
2022-02-13T19:55:23.000Z
30.092308
76
0.709611
3,601
// Copyright 2017 Archos SA // // 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.archos.mediacenter.video.browser.adapters; import com.archos.mediacenter.video.R; import android.content.Context; import android.content.res.Resources; public enum AdapterDefaultValuesGrid implements AdapterDefaultValues { INSTANCE; public int getDefaultDirectoryThumbnail() { return R.drawable.filetype_video_folder_vertical; } public int getDefaultShortcutThumbnail() { return R.drawable.filetype_video_folder_indexed_vertical; } public int getDefaultVideoThumbnail() { return R.drawable.filetype_video_large; } public int getMediaSyncIcon(int state) { return R.drawable.label_video_disabled; // not required here } public int getLayoutId() { return R.layout.browser_item_grid; } public int getLayoutId(int itemType) { // This method is only needed for compatibility, // there is only one possible layout anyway return R.layout.browser_item_grid; } public int[] getThumnailHeightWidth(Context context) { Resources res = context.getResources(); return new int[] { res.getDimensionPixelSize(R.dimen.video_grid_poster_height), res.getDimensionPixelSize(R.dimen.video_grid_poster_width) }; } public int getExpandedZone() { return R.id.expanded; } }
3e087f157fecb42e1eefaf8291bc4bc62ff2e86e
3,079
java
Java
src/main/java/POGOProtos/Rpc/GymBattleSettingsProtoOrBuilder.java
celandro/pogoprotos-java
af129776faf08bfbfc69b32e19e8293bff2e8991
[ "BSD-3-Clause" ]
6
2019-07-08T10:29:18.000Z
2020-10-18T20:27:03.000Z
src/main/java/POGOProtos/Rpc/GymBattleSettingsProtoOrBuilder.java
Furtif/POGOProtos-Java-Private
655adefaca9e9185138aad08c55da85048d0c0ef
[ "BSD-3-Clause" ]
4
2018-07-22T19:44:39.000Z
2018-11-17T14:56:13.000Z
src/main/java/POGOProtos/Rpc/GymBattleSettingsProtoOrBuilder.java
Furtif/POGOProtos-Java-Private
655adefaca9e9185138aad08c55da85048d0c0ef
[ "BSD-3-Clause" ]
1
2017-03-29T09:34:17.000Z
2017-03-29T09:34:17.000Z
24.830645
88
0.696655
3,602
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Rpc.proto package POGOProtos.Rpc; public interface GymBattleSettingsProtoOrBuilder extends // @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.GymBattleSettingsProto) com.google.protobuf.MessageOrBuilder { /** * <code>float energy_per_sec = 1;</code> * @return The energyPerSec. */ float getEnergyPerSec(); /** * <code>float dodge_energy_cost = 2;</code> * @return The dodgeEnergyCost. */ float getDodgeEnergyCost(); /** * <code>float retarget_seconds = 3;</code> * @return The retargetSeconds. */ float getRetargetSeconds(); /** * <code>float enemy_attack_interval = 4;</code> * @return The enemyAttackInterval. */ float getEnemyAttackInterval(); /** * <code>float attack_server_interval = 5;</code> * @return The attackServerInterval. */ float getAttackServerInterval(); /** * <code>float round_duration_seconds = 6;</code> * @return The roundDurationSeconds. */ float getRoundDurationSeconds(); /** * <code>float bonus_time_per_ally_seconds = 7;</code> * @return The bonusTimePerAllySeconds. */ float getBonusTimePerAllySeconds(); /** * <code>int32 maximum_attackers_per_battle = 8;</code> * @return The maximumAttackersPerBattle. */ int getMaximumAttackersPerBattle(); /** * <code>float same_type_attack_bonus_multiplier = 9;</code> * @return The sameTypeAttackBonusMultiplier. */ float getSameTypeAttackBonusMultiplier(); /** * <code>int32 maximum_energy = 10;</code> * @return The maximumEnergy. */ int getMaximumEnergy(); /** * <code>float energy_delta_per_health_lost = 11;</code> * @return The energyDeltaPerHealthLost. */ float getEnergyDeltaPerHealthLost(); /** * <code>int32 dodge_duration_ms = 12;</code> * @return The dodgeDurationMs. */ int getDodgeDurationMs(); /** * <code>int32 minimum_player_level = 13;</code> * @return The minimumPlayerLevel. */ int getMinimumPlayerLevel(); /** * <code>int32 swap_duration_ms = 14;</code> * @return The swapDurationMs. */ int getSwapDurationMs(); /** * <code>float dodge_damage_reduction_percent = 15;</code> * @return The dodgeDamageReductionPercent. */ float getDodgeDamageReductionPercent(); /** * <code>int32 minimum_raid_player_level = 16;</code> * @return The minimumRaidPlayerLevel. */ int getMinimumRaidPlayerLevel(); /** * <code>float shadow_pokemon_attack_bonus_multiplier = 17;</code> * @return The shadowPokemonAttackBonusMultiplier. */ float getShadowPokemonAttackBonusMultiplier(); /** * <code>float shadow_pokemon_defense_bonus_multiplier = 18;</code> * @return The shadowPokemonDefenseBonusMultiplier. */ float getShadowPokemonDefenseBonusMultiplier(); /** * <code>float purified_pokemon_attack_multiplier_vs_shadow = 19;</code> * @return The purifiedPokemonAttackMultiplierVsShadow. */ float getPurifiedPokemonAttackMultiplierVsShadow(); }
3e087fb6ae341011de20f82b723ab0befa5de6eb
7,302
java
Java
libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/summary/SummaryBottomSheet.java
m7mdra/flitsmeister-navigation-android
7967f8e0b279280e315a88f9244a31332d742b24
[ "MIT" ]
2
2022-02-23T11:12:13.000Z
2022-02-23T19:59:53.000Z
libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/summary/SummaryBottomSheet.java
m7mdra/flitsmeister-navigation-android
7967f8e0b279280e315a88f9244a31332d742b24
[ "MIT" ]
null
null
null
libandroid-navigation-ui/src/main/java/com/mapbox/services/android/navigation/ui/v5/summary/SummaryBottomSheet.java
m7mdra/flitsmeister-navigation-android
7967f8e0b279280e315a88f9244a31332d742b24
[ "MIT" ]
2
2022-01-21T10:34:08.000Z
2022-03-01T08:28:52.000Z
33.190909
108
0.748562
3,603
package com.mapbox.services.android.navigation.ui.v5.summary; import android.content.Context; import androidx.annotation.Nullable; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LiveData; import androidx.lifecycle.Observer; import androidx.lifecycle.OnLifecycleEvent; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.mapbox.services.android.navigation.ui.v5.ContextHelper; import com.mapbox.services.android.navigation.ui.v5.NavigationViewModel; import com.mapbox.services.android.navigation.ui.v5.R; import com.mapbox.services.android.navigation.ui.v5.ThemeSwitcher; import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants; import com.mapbox.services.android.navigation.v5.navigation.NavigationTimeFormat; import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener; import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress; import com.mapbox.services.android.navigation.v5.utils.DistanceFormatter; import com.mapbox.services.android.navigation.v5.utils.LocaleUtils; import java.text.DecimalFormat; /** * A view with {@link BottomSheetBehavior} * that displays route summary information during navigation. * <p> * Can be expanded / collapsed to show / hide the list of * directions. * * @since 0.6.0 */ public class SummaryBottomSheet extends FrameLayout implements LifecycleObserver { private static final String EMPTY_STRING = ""; private TextView distanceRemainingText; private TextView timeRemainingText; private TextView arrivalTimeText; private ProgressBar rerouteProgressBar; private boolean isRerouting; @NavigationTimeFormat.Type private int timeFormatType; private DistanceFormatter distanceFormatter; private NavigationViewModel navigationViewModel; private LifecycleOwner lifecycleOwner; public SummaryBottomSheet(Context context) { this(context, null); } public SummaryBottomSheet(Context context, AttributeSet attrs) { this(context, attrs, -1); } public SummaryBottomSheet(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(); } /** * After the layout inflates, binds all necessary views, * create a {@link RecyclerView} for the list of directions, * and a new {@link DecimalFormat} for formatting distance remaining. */ @Override protected void onFinishInflate() { super.onFinishInflate(); bind(); } public void subscribe(LifecycleOwner owner, NavigationViewModel navigationViewModel) { lifecycleOwner = owner; lifecycleOwner.getLifecycle().addObserver(this); this.navigationViewModel = navigationViewModel; navigationViewModel.summaryModel.observe(lifecycleOwner, summaryModel -> { if (summaryModel != null && !isRerouting) { arrivalTimeText.setText(summaryModel.getArrivalTime()); timeRemainingText.setText(summaryModel.getTimeRemaining()); distanceRemainingText.setText(summaryModel.getDistanceRemaining()); } }); navigationViewModel.isOffRoute.observe(lifecycleOwner, isOffRoute -> { if (isOffRoute != null) { isRerouting = isOffRoute; if (isRerouting) { showRerouteState(); } else { hideRerouteState(); } } }); } /** * Unsubscribes {@link NavigationViewModel} {@link LiveData} objects * by removing the observers of the {@link LifecycleOwner} when parent view is destroyed */ @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void unsubscribe() { if (navigationViewModel != null) { navigationViewModel.summaryModel.removeObservers(lifecycleOwner); navigationViewModel.isOffRoute.removeObservers(lifecycleOwner); } } /** * Called in {@link ProgressChangeListener}, creates a new model and then * uses it to update the views. * * @param routeProgress used to provide navigation / routeProgress data * @since 0.6.2 */ @SuppressWarnings("UnusedDeclaration") public void update(RouteProgress routeProgress) { if (routeProgress != null && !isRerouting) { SummaryModel model = new SummaryModel(getContext(), distanceFormatter, routeProgress, timeFormatType); arrivalTimeText.setText(model.getArrivalTime()); timeRemainingText.setText(model.getTimeRemaining()); distanceRemainingText.setText(model.getDistanceRemaining()); } } /** * Shows the reroute progress bar and clears current text views. * Also sets boolean to rerouting state so views do not * continue to update while we are fetching a new route. * * @since 0.6.0 */ public void showRerouteState() { rerouteProgressBar.setVisibility(VISIBLE); clearViews(); } /** * Hides the reroute progress bar and sets * rerouting state to false to text will begin updating again. * * @since 0.6.0 */ public void hideRerouteState() { rerouteProgressBar.setVisibility(INVISIBLE); } /** * Sets the time format type to use * * @param type to use */ public void setTimeFormat(@NavigationTimeFormat.Type int type) { this.timeFormatType = type; } /** * Sets the distance formatter * * @param distanceFormatter to set */ public void setDistanceFormatter(DistanceFormatter distanceFormatter) { if (distanceFormatter != null && !distanceFormatter.equals(this.distanceFormatter)) { this.distanceFormatter = distanceFormatter; } } /** * Inflates this layout needed for this view and initializes the locale as the device locale. */ private void initialize() { initializeDistanceFormatter(); inflate(getContext(), R.layout.summary_bottomsheet_layout, this); } private void initializeDistanceFormatter() { LocaleUtils localeUtils = new LocaleUtils(); String language = localeUtils.inferDeviceLanguage(getContext()); String unitType = localeUtils.getUnitTypeForDeviceLocale(getContext()); int roundingIncrement = NavigationConstants.ROUNDING_INCREMENT_FIFTY; distanceFormatter = new DistanceFormatter(getContext(), language, unitType, roundingIncrement); } /** * Finds and binds all necessary views */ private void bind() { distanceRemainingText = findViewById(R.id.distanceRemainingText); timeRemainingText = findViewById(R.id.timeRemainingText); arrivalTimeText = findViewById(R.id.arrivalTimeText); rerouteProgressBar = findViewById(R.id.rerouteProgressBar); updateRouteOverviewImage(); } private void updateRouteOverviewImage() { ImageButton routeOverviewBtn = findViewById(R.id.routeOverviewBtn); routeOverviewBtn.setImageDrawable(ThemeSwitcher.retrieveThemeOverviewDrawable(getContext())); } /** * Clears all {@link View}s. */ private void clearViews() { arrivalTimeText.setText(EMPTY_STRING); timeRemainingText.setText(EMPTY_STRING); distanceRemainingText.setText(EMPTY_STRING); } }
3e0880cc204508d2e27dfa13d5afe2845b636ff9
5,338
java
Java
JCudaJava/src/test/java/jcuda/test/JCudaDriverTextureDescriptorTest.java
jcuda/jcuda
df3a17f995e772efa27483ddc37fffd703bb5769
[ "MIT" ]
193
2015-08-23T21:08:07.000Z
2022-03-23T11:38:10.000Z
JCudaJava/src/test/java/jcuda/test/JCudaDriverTextureDescriptorTest.java
jcuda/jcuda
df3a17f995e772efa27483ddc37fffd703bb5769
[ "MIT" ]
35
2016-02-22T13:51:01.000Z
2022-01-13T08:13:43.000Z
JCudaJava/src/test/java/jcuda/test/JCudaDriverTextureDescriptorTest.java
jcuda/jcuda
df3a17f995e772efa27483ddc37fffd703bb5769
[ "MIT" ]
41
2015-08-26T06:32:25.000Z
2021-12-15T06:50:39.000Z
34.217949
80
0.688647
3,604
/* * JCuda - Java bindings for CUDA * * http://www.jcuda.org */ package jcuda.test; import static jcuda.driver.JCudaDriver.*; import static jcuda.driver.CUmemorytype.*; import static jcuda.driver.CUarray_format.*; import static jcuda.driver.CUresourceViewFormat.*; import static jcuda.driver.CUresourcetype.*; import static jcuda.driver.CUfilter_mode.*; import static jcuda.driver.CUaddress_mode.*; import static jcuda.driver.JCudaDriver.cuDeviceGet; import static jcuda.driver.JCudaDriver.cuInit; import static org.junit.Assert.assertTrue; import org.junit.Test; import jcuda.Pointer; import jcuda.Sizeof; import jcuda.driver.*; /** * A test for the cuTexObjectCreate function */ public class JCudaDriverTextureDescriptorTest { public static void main(String[] args) { JCudaDriverTextureDescriptorTest test = new JCudaDriverTextureDescriptorTest(); test.testTextureObjectCreation(); } @Test public void testTextureObjectCreation() { JCudaDriver.setExceptionsEnabled(true); cuInit(0); CUdevice device = new CUdevice(); cuDeviceGet(device, 0); CUcontext context = new CUcontext(); JCudaDriver.cuCtxCreate(context, 0, device); float[] hostArray = new float[] { 0, 1, 2, 3, 4, 5, 6, 7 }; int[] dims = new int[] { 2, 2, 2 }; CUdeviceptr deviceArray = new CUdeviceptr(); cuMemAlloc(deviceArray, hostArray.length * Sizeof.FLOAT); cuMemcpyHtoD(deviceArray, Pointer.to(hostArray), hostArray.length * Sizeof.FLOAT); CUarray cuArray = makeCudaArray(dims); copyDataIntoCudaArray(deviceArray, cuArray, dims); cuMemFree(deviceArray); CUDA_RESOURCE_DESC resourceDescriptor = makeResourceDescriptor(cuArray); CUDA_TEXTURE_DESC textureDescriptor = makeTextureDescriptor(); CUDA_RESOURCE_VIEW_DESC resourceViewDescriptor = makeResourceViewDescriptor(dims); CUtexObject texture = new CUtexObject(); cuTexObjectCreate(texture, resourceDescriptor, textureDescriptor, resourceViewDescriptor); assertTrue(true); } private static CUarray makeCudaArray(int[] dims) { CUarray array = new CUarray(); CUDA_ARRAY3D_DESCRIPTOR arrayDescriptor = new CUDA_ARRAY3D_DESCRIPTOR(); arrayDescriptor.Width = dims[0]; arrayDescriptor.Height = dims[1]; arrayDescriptor.Depth = dims[2]; arrayDescriptor.Format = CU_AD_FORMAT_FLOAT; arrayDescriptor.NumChannels = 1; arrayDescriptor.Flags = 0; cuArray3DCreate(array, arrayDescriptor); return array; } private static void copyDataIntoCudaArray( CUdeviceptr deviceArray, CUarray array, int[] dims) { CUDA_MEMCPY3D copyParams = new CUDA_MEMCPY3D(); copyParams.srcMemoryType = CU_MEMORYTYPE_DEVICE; copyParams.srcDevice = deviceArray; copyParams.srcXInBytes = 0; copyParams.srcY = 0; copyParams.srcZ = 0; copyParams.srcPitch = (long) dims[0] * Sizeof.FLOAT; copyParams.srcHeight = dims[1]; copyParams.srcLOD = 0; copyParams.dstMemoryType = CU_MEMORYTYPE_ARRAY; copyParams.dstArray = array; copyParams.dstXInBytes = 0; copyParams.dstY = 0; copyParams.dstZ = 0; copyParams.dstLOD = 0; copyParams.WidthInBytes = (long) dims[0] * Sizeof.FLOAT; copyParams.Height = dims[1]; copyParams.Depth = dims[2]; cuMemcpy3D(copyParams); } private static CUDA_RESOURCE_DESC makeResourceDescriptor(CUarray cuArray) { CUDA_RESOURCE_DESC resourceDescriptor = new CUDA_RESOURCE_DESC(); resourceDescriptor.resType = CU_RESOURCE_TYPE_ARRAY; resourceDescriptor.array_hArray = cuArray; resourceDescriptor.flags = 0; return resourceDescriptor; } private static CUDA_TEXTURE_DESC makeTextureDescriptor() { CUDA_TEXTURE_DESC textureDescriptor = new CUDA_TEXTURE_DESC(); textureDescriptor.addressMode[0] = CU_TR_ADDRESS_MODE_CLAMP; textureDescriptor.addressMode[1] = CU_TR_ADDRESS_MODE_CLAMP; textureDescriptor.addressMode[2] = CU_TR_ADDRESS_MODE_CLAMP; textureDescriptor.filterMode = CU_TR_FILTER_MODE_LINEAR; textureDescriptor.flags = 0; textureDescriptor.maxAnisotropy = 1; textureDescriptor.mipmapFilterMode = CU_TR_FILTER_MODE_POINT; textureDescriptor.mipmapLevelBias = 0; textureDescriptor.minMipmapLevelClamp = 0; textureDescriptor.maxMipmapLevelClamp = 0; return textureDescriptor; } static CUDA_RESOURCE_VIEW_DESC makeResourceViewDescriptor(int[] dims) { CUDA_RESOURCE_VIEW_DESC resourceViewDescriptor = new CUDA_RESOURCE_VIEW_DESC(); resourceViewDescriptor.format = CU_RES_VIEW_FORMAT_FLOAT_1X32; resourceViewDescriptor.width = dims[0]; resourceViewDescriptor.height = dims[1]; resourceViewDescriptor.depth = dims[2]; resourceViewDescriptor.firstMipmapLevel = 0; resourceViewDescriptor.lastMipmapLevel = 0; resourceViewDescriptor.firstLayer = 0; resourceViewDescriptor.lastLayer = 0; return resourceViewDescriptor; } }
3e08817a471c202c57f66dc59ad52ac1fe1e8d71
2,630
java
Java
app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV4.java
patarapolw/KeePassDX
87fb94b29bda94b2d7bd00fda191f4d905b27f18
[ "ECL-2.0", "Apache-2.0", "CC-BY-4.0" ]
5
2019-07-16T06:28:40.000Z
2021-09-14T09:17:13.000Z
app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV4.java
patarapolw/KeePassDX
87fb94b29bda94b2d7bd00fda191f4d905b27f18
[ "ECL-2.0", "Apache-2.0", "CC-BY-4.0" ]
null
null
null
app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV4.java
patarapolw/KeePassDX
87fb94b29bda94b2d7bd00fda191f4d905b27f18
[ "ECL-2.0", "Apache-2.0", "CC-BY-4.0" ]
1
2019-11-18T15:17:09.000Z
2019-11-18T15:17:09.000Z
26.836735
77
0.728137
3,605
/* * Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft. * * This file is part of KeePass DX. * * KeePass DX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * KeePass DX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePass DX. If not, see <http://www.gnu.org/licenses/>. * */ package com.kunzisoft.keepass.database.iterator; import com.kunzisoft.keepass.database.PwEntryV4; import com.kunzisoft.keepass.database.search.SearchParametersV4; import com.kunzisoft.keepass.database.security.ProtectedString; import java.util.Iterator; import java.util.Map.Entry; import java.util.NoSuchElementException; public class EntrySearchStringIteratorV4 extends EntrySearchStringIterator { private String current; private Iterator<Entry<String, ProtectedString>> setIterator; private SearchParametersV4 sp; public EntrySearchStringIteratorV4(PwEntryV4 entry) { this.sp = SearchParametersV4.DEFAULT; setIterator = entry.getFields().getListOfAllFields().entrySet().iterator(); advance(); } public EntrySearchStringIteratorV4(PwEntryV4 entry, SearchParametersV4 sp) { this.sp = sp; setIterator = entry.getFields().getListOfAllFields().entrySet().iterator(); advance(); } @Override public boolean hasNext() { return current != null; } @Override public String next() { if (current == null) { throw new NoSuchElementException("Past the end of the list."); } String next = current; advance(); return next; } private void advance() { while (setIterator.hasNext()) { Entry<String, ProtectedString> entry = setIterator.next(); String key = entry.getKey(); if (searchInField(key)) { current = entry.getValue().toString(); return; } } current = null; } private boolean searchInField(String key) { switch (key) { case PwEntryV4.STR_TITLE: return sp.searchInTitles; case PwEntryV4.STR_USERNAME: return sp.searchInUserNames; case PwEntryV4.STR_PASSWORD: return sp.searchInPasswords; case PwEntryV4.STR_URL: return sp.searchInUrls; case PwEntryV4.STR_NOTES: return sp.searchInNotes; default: return sp.searchInOther; } } }
3e0882bb73928dc2de776a82969125b0b0e7c152
1,027
java
Java
07-SQL-JDBS/04-jdbc/01-tracker/src/main/java/com/adidyk/setup/Settings.java
androsdav/01-java-a-to-z
65b005fc9d4558b68f43d1c72ecd8acc356bd98f
[ "Apache-2.0" ]
5
2016-10-21T08:07:13.000Z
2020-05-12T14:41:15.000Z
07-SQL-JDBS/05-control/01-parser-vacancy/src/main/java/com/adidyk/setup/Settings.java
androsdav/01-java-a-to-z
65b005fc9d4558b68f43d1c72ecd8acc356bd98f
[ "Apache-2.0" ]
null
null
null
07-SQL-JDBS/05-control/01-parser-vacancy/src/main/java/com/adidyk/setup/Settings.java
androsdav/01-java-a-to-z
65b005fc9d4558b68f43d1c72ecd8acc356bd98f
[ "Apache-2.0" ]
null
null
null
25.75
118
0.626214
3,606
package com.adidyk.setup; import java.io.InputStream; import java.util.Properties; /** * Class of Setting use to load file from input stream and return parameter by key from file configure app.properties. * @author Didyk Andrey ([email protected]). * @since 04.09.2018. * @version 1.0. */ public class Settings { /** * @param prs - link variable to object of class Properties. */ private final Properties prs = new Properties(); /** * load - loads params from file app.properties. * @param io - link variable to object of class InputStream. */ public void load(InputStream io) { try { this.prs.load(io); } catch (Exception ex) { ex.printStackTrace(); } } /** * getValue - returns parameter by key from file configure app.properties. * @param key - key fo returned parameter. * @return - returns parameter by key. */ String getValue(String key) { return this.prs.getProperty(key); } }
3e0882dd3f820b7d50b5af7c697d3a5e036f725a
4,857
java
Java
src/test/java/PartyPlannerTest.java
seacamjen/party-planner
5215ae9994e8f435ffe7a187e7bff3a6268cd6c5
[ "MIT" ]
null
null
null
src/test/java/PartyPlannerTest.java
seacamjen/party-planner
5215ae9994e8f435ffe7a187e7bff3a6268cd6c5
[ "MIT" ]
null
null
null
src/test/java/PartyPlannerTest.java
seacamjen/party-planner
5215ae9994e8f435ffe7a187e7bff3a6268cd6c5
[ "MIT" ]
null
null
null
38.244094
104
0.722051
3,607
import org.junit.*; import static org.junit.Assert.*; public class PartyPlannerTest { @Test public void PartyPlanner_instantiatesCorrectly() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(true, testPartyPlanner instanceof PartyPlanner); } @Test public void PartyPlanner_getPartySize_10() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(10, testPartyPlanner.getPartySize()); } @Test public void PartyPlanner_getFoodType_String() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals("snacks", testPartyPlanner.getFoodType()); } @Test public void PartyPlanner_getBeverageType_String() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals("light bar", testPartyPlanner.getBeverageType()); } @Test public void PartyPlanner_getEntertainmentType_String() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals("clown", testPartyPlanner.getEntertainmentType()); } @Test public void PartyPlanner_getDecorationsType_String() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals("birthday", testPartyPlanner.getDecorationsType()); } @Test public void PartyPlanner_determineFoodPrice_100() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(100, testPartyPlanner.foodPrice()); } @Test public void PartyPlanner_determineFoodPrice_1875() { PartyPlanner testPartyPlanner = new PartyPlanner(375, "snacks", "light bar", "clown", "birthday"); assertEquals(1875, testPartyPlanner.foodPrice()); } @Test public void PartyPlanner_determineBeveragePrice_150() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(150, testPartyPlanner.beveragePrice()); } @Test public void PartyPlanner_determineBeveragePrice_2107() { PartyPlanner testPartyPlanner = new PartyPlanner(301, "snacks", "light bar", "clown", "birthday"); assertEquals(2107, testPartyPlanner.beveragePrice()); } @Test public void PartyPlanner_determineEntertainmentPrice_200() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(200, testPartyPlanner.entertainmentPrice()); } @Test public void PartyPlanner_determineEntertainmentPrice_600() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "band", "birthday"); assertEquals(600, testPartyPlanner.entertainmentPrice()); } @Test public void PartyPlanner_determineDecorationPrice_100() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "band", "birthday"); assertEquals(100, testPartyPlanner.decorationPrice()); } @Test public void PartyPlanner_determineDecorationPrice_600() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "band", "wedding"); assertEquals(600, testPartyPlanner.decorationPrice()); } @Test public void PartyPlanner_determineTotalPrice_550() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(550, testPartyPlanner.totalPrice()); } @Test public void PartyPlanner_giveBirthdayDiscount_2850() { PartyPlanner testPartyPlanner = new PartyPlanner(50, "dinner", "light bar", "clown", "birthday"); assertEquals(2850, testPartyPlanner.birthdayPackage()); } @Test public void PartyPlanner_giveWeddingDiscount_6700() { PartyPlanner testPartyPlanner = new PartyPlanner(100, "dinner", "premium bar", "band", "wedding"); assertEquals(6700, testPartyPlanner.weddingPackage()); } @Test public void PartyPlanner_giveSportDiscount_3000() { PartyPlanner testPartyPlanner = new PartyPlanner(50, "dinner", "light bar", "comedian", "sports"); assertEquals(3000, testPartyPlanner.sportPackage()); } @Test public void PartyPlanner_giveFiveHundredFiftyDollarDiscount_3000(){ PartyPlanner testPartyPlanner = new PartyPlanner(50, "dinner", "light bar", "comedian", "sports"); assertEquals(3000, testPartyPlanner.fiveFiveZeroDiscount()); } @Test public void PartyPlanner_dontGiveFiveHundredFiftyDollarDiscount_550() { PartyPlanner testPartyPlanner = new PartyPlanner(10, "snacks", "light bar", "clown", "birthday"); assertEquals(550, testPartyPlanner.fiveFiveZeroDiscount()); } }
3e08835a22e4d62a293238fca3d62a3b4b15ecdf
5,282
java
Java
java/src/rkistner/algorithms/WindowRNBinarizer.java
rkistner/binarization
e1496ae172d45117408afea66406e1ece688ba51
[ "Apache-2.0" ]
3
2017-04-13T12:20:14.000Z
2018-08-31T02:47:05.000Z
java/src/rkistner/algorithms/WindowRNBinarizer.java
rkistner/binarization
e1496ae172d45117408afea66406e1ece688ba51
[ "Apache-2.0" ]
null
null
null
java/src/rkistner/algorithms/WindowRNBinarizer.java
rkistner/binarization
e1496ae172d45117408afea66406e1ece688ba51
[ "Apache-2.0" ]
null
null
null
33.643312
134
0.533889
3,608
/* * Copyright 2010 Ralf Kistner * * 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 rkistner.algorithms; import com.google.zxing.Binarizer; import com.google.zxing.LuminanceSource; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; import com.google.zxing.common.BitMatrix; public final class WindowRNBinarizer extends Binarizer { public static BinarizerFactory createFactory(final int bs, final float frac, final int threshold) { return new BinarizerFactory() { public WindowRNBinarizer getBinarizer(LuminanceSource source) { return new WindowRNBinarizer(source, bs, frac, threshold); } public String toString() { return "Window (Reduced Noise) [" + bs + "|" + frac + "|" + threshold + "]"; } }; } private int bs = 8; private float frac = 3; private int threshold = 8; public WindowRNBinarizer(LuminanceSource source, int bs, float frac, int threshold) { super(source); this.bs = bs; this.frac = frac; this.threshold = threshold; } private void blockTotals(byte[] data, int[][] total, int[][] squares) { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); int aw = width / bs; int ah = height / bs; for(int by = 0; by < ah; by++) { int ey = (by+1)*bs; for(int bx = 0; bx < aw; bx++) { int t = 0; int t2 = 0; for(int y = by*bs; y < ey; y++) { int offset = y*width+bx*bs; int ex = offset+bs; for(; offset < ex; offset++) { int v = data[offset] & 0xff; t += v; t2 += v*v; } } total[by][bx] = t; squares[by][bx] = t2; } } } private static int variance(int[][] cumulative, int[][] cumulativeSquares, int x, int y, int r, int width, int height, int mult) { int top = Math.max(0, y - r + 1); int left = Math.max(0, x - r + 1); int bottom = Math.min(height, y + r); int right = Math.min(width, x + r); int block = Common.window(cumulative, top, left, bottom, right); int pixels = (bottom - top) * (right - left) * mult; int avg = block / pixels; int blockSquare = Common.window(cumulativeSquares, top, left, bottom, right); int variance = blockSquare / pixels - avg*avg; return variance; } @Override public BitArray getBlackRow(int y, BitArray row) throws NotFoundException { return null; } @Override public BitMatrix getBlackMatrix() throws NotFoundException { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); int r = (int)(Math.min(width, height) * frac / bs / 2 + 1); int aw = width / bs; int ah = height / bs; byte[] data = source.getMatrix(); int[][] blockTotal = new int[ah][aw]; int[][] blockSquares = new int[ah][aw]; blockTotals(data, blockTotal, blockSquares); int[][] totals = Common.cumulative(blockTotal); int[][] squares = Common.cumulative(blockSquares); int mean = totals[ah][aw] / width / height; int var = squares[ah][aw] / width / height - mean*mean; BitMatrix matrix = new BitMatrix(width, height); for(int by = 0; by < ah; by++) { for(int bx = 0; bx < aw; bx++) { int top = Math.max(0, by - r + 1); int left = Math.max(0, bx - r + 1); int bottom = Math.min(ah, by + r); int right = Math.min(aw, bx + r); int block = Common.window(totals, top, left, bottom, right); int pixels = (bottom - top) * (right - left) * bs * bs; int avg = block / pixels; int variance = variance(totals, squares, bx, by, r, aw, ah, bs*bs); if(variance * threshold > var) { for(int y = by*bs; y < (by+1)*bs; y++) { for(int x = bx*bs; x < (bx+1)*bs; x++) { int pixel = data[y*width + x] & 0xff; if(pixel < avg) matrix.set(x, y); } } } } } return matrix; } @Override public Binarizer createBinarizer(LuminanceSource source) { return null; } }
3e088439022c9aa654a4f5fe9d7d68bf5e4c8728
26,753
java
Java
jdk1.8-source-analysis/src/javax/swing/JToolBar.java
lhj502819/Java-Family-Bucket
95c48664e56ae37b74a393587ae2b218261d18ad
[ "Apache-2.0" ]
1,305
2018-03-11T15:04:26.000Z
2022-03-30T16:02:34.000Z
jdk1.8-source-analysis/src/javax/swing/JToolBar.java
lhj502819/Java-Family-Bucket
95c48664e56ae37b74a393587ae2b218261d18ad
[ "Apache-2.0" ]
7
2019-03-20T09:43:08.000Z
2021-08-20T03:19:24.000Z
jdk1.8-source-analysis/src/javax/swing/JToolBar.java
lhj502819/Java-Family-Bucket
95c48664e56ae37b74a393587ae2b218261d18ad
[ "Apache-2.0" ]
575
2018-03-11T15:15:41.000Z
2022-03-30T16:03:48.000Z
30.680046
110
0.583935
3,609
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.LayoutManager2; import java.awt.event.*; import java.beans.*; import javax.swing.border.Border; import javax.swing.plaf.*; import javax.accessibility.*; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.util.Hashtable; /** * <code>JToolBar</code> provides a component that is useful for * displaying commonly used <code>Action</code>s or controls. * For examples and information on using tool bars see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/toolbar.html">How to Use Tool Bars</a>, * a section in <em>The Java Tutorial</em>. * * <p> * With most look and feels, * the user can drag out a tool bar into a separate window * (unless the <code>floatable</code> property is set to <code>false</code>). * For drag-out to work correctly, it is recommended that you add * <code>JToolBar</code> instances to one of the four "sides" of a * container whose layout manager is a <code>BorderLayout</code>, * and do not add children to any of the other four "sides". * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @beaninfo * attribute: isContainer true * description: A component which displays commonly used controls or Actions. * * @author Georges Saab * @author Jeff Shapiro * @see Action */ public class JToolBar extends JComponent implements SwingConstants, Accessible { /** * @see #getUIClassID * @see #readObject */ private static final String uiClassID = "ToolBarUI"; private boolean paintBorder = true; private Insets margin = null; private boolean floatable = true; private int orientation = HORIZONTAL; /** * Creates a new tool bar; orientation defaults to <code>HORIZONTAL</code>. */ public JToolBar() { this( HORIZONTAL ); } /** * Creates a new tool bar with the specified <code>orientation</code>. * The <code>orientation</code> must be either <code>HORIZONTAL</code> * or <code>VERTICAL</code>. * * @param orientation the orientation desired */ public JToolBar( int orientation ) { this(null, orientation); } /** * Creates a new tool bar with the specified <code>name</code>. The * name is used as the title of the undocked tool bar. The default * orientation is <code>HORIZONTAL</code>. * * @param name the name of the tool bar * @since 1.3 */ public JToolBar( String name ) { this(name, HORIZONTAL); } /** * Creates a new tool bar with a specified <code>name</code> and * <code>orientation</code>. * All other constructors call this constructor. * If <code>orientation</code> is an invalid value, an exception will * be thrown. * * @param name the name of the tool bar * @param orientation the initial orientation -- it must be * either <code>HORIZONTAL</code> or <code>VERTICAL</code> * @exception IllegalArgumentException if orientation is neither * <code>HORIZONTAL</code> nor <code>VERTICAL</code> * @since 1.3 */ public JToolBar( String name , int orientation) { setName(name); checkOrientation( orientation ); this.orientation = orientation; DefaultToolBarLayout layout = new DefaultToolBarLayout( orientation ); setLayout( layout ); addPropertyChangeListener( layout ); updateUI(); } /** * Returns the tool bar's current UI. * @see #setUI */ public ToolBarUI getUI() { return (ToolBarUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ToolBarUI</code> L&amp;F object * @see UIDefaults#getUI * @beaninfo * bound: true * hidden: true * attribute: visualUpdate true * description: The UI object that implements the Component's LookAndFeel. */ public void setUI(ToolBarUI ui) { super.setUI(ui); } /** * Notification from the <code>UIFactory</code> that the L&amp;F has changed. * Called to replace the UI with the latest version from the * <code>UIFactory</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ToolBarUI)UIManager.getUI(this)); // GTKLookAndFeel installs a different LayoutManager, and sets it // to null after changing the look and feel, so, install the default // if the LayoutManager is null. if (getLayout() == null) { setLayout(new DefaultToolBarLayout(getOrientation())); } invalidate(); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ToolBarUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Returns the index of the specified component. * (Note: Separators occupy index positions.) * * @param c the <code>Component</code> to find * @return an integer indicating the component's position, * where 0 is first */ public int getComponentIndex(Component c) { int ncomponents = this.getComponentCount(); Component[] component = this.getComponents(); for (int i = 0 ; i < ncomponents ; i++) { Component comp = component[i]; if (comp == c) return i; } return -1; } /** * Returns the component at the specified index. * * @param i the component's position, where 0 is first * @return the <code>Component</code> at that position, * or <code>null</code> for an invalid index * */ public Component getComponentAtIndex(int i) { int ncomponents = this.getComponentCount(); if ( i >= 0 && i < ncomponents) { Component[] component = this.getComponents(); return component[i]; } return null; } /** * Sets the margin between the tool bar's border and * its buttons. Setting to <code>null</code> causes the tool bar to * use the default margins. The tool bar's default <code>Border</code> * object uses this value to create the proper margin. * However, if a non-default border is set on the tool bar, * it is that <code>Border</code> object's responsibility to create the * appropriate margin space (otherwise this property will * effectively be ignored). * * @param m an <code>Insets</code> object that defines the space * between the border and the buttons * @see Insets * @beaninfo * description: The margin between the tool bar's border and contents * bound: true * expert: true */ public void setMargin(Insets m) { Insets old = margin; margin = m; firePropertyChange("margin", old, m); revalidate(); repaint(); } /** * Returns the margin between the tool bar's border and * its buttons. * * @return an <code>Insets</code> object containing the margin values * @see Insets */ public Insets getMargin() { if(margin == null) { return new Insets(0,0,0,0); } else { return margin; } } /** * Gets the <code>borderPainted</code> property. * * @return the value of the <code>borderPainted</code> property * @see #setBorderPainted */ public boolean isBorderPainted() { return paintBorder; } /** * Sets the <code>borderPainted</code> property, which is * <code>true</code> if the border should be painted. * The default value for this property is <code>true</code>. * Some look and feels might not implement painted borders; * they will ignore this property. * * @param b if true, the border is painted * @see #isBorderPainted * @beaninfo * description: Does the tool bar paint its borders? * bound: true * expert: true */ public void setBorderPainted(boolean b) { if ( paintBorder != b ) { boolean old = paintBorder; paintBorder = b; firePropertyChange("borderPainted", old, b); revalidate(); repaint(); } } /** * Paints the tool bar's border if the <code>borderPainted</code> property * is <code>true</code>. * * @param g the <code>Graphics</code> context in which the painting * is done * @see JComponent#paint * @see JComponent#setBorder */ protected void paintBorder(Graphics g) { if (isBorderPainted()) { super.paintBorder(g); } } /** * Gets the <code>floatable</code> property. * * @return the value of the <code>floatable</code> property * * @see #setFloatable */ public boolean isFloatable() { return floatable; } /** * Sets the <code>floatable</code> property, * which must be <code>true</code> for the user to move the tool bar. * Typically, a floatable tool bar can be * dragged into a different position within the same container * or out into its own window. * The default value of this property is <code>true</code>. * Some look and feels might not implement floatable tool bars; * they will ignore this property. * * @param b if <code>true</code>, the tool bar can be moved; * <code>false</code> otherwise * @see #isFloatable * @beaninfo * description: Can the tool bar be made to float by the user? * bound: true * preferred: true */ public void setFloatable( boolean b ) { if ( floatable != b ) { boolean old = floatable; floatable = b; firePropertyChange("floatable", old, b); revalidate(); repaint(); } } /** * Returns the current orientation of the tool bar. The value is either * <code>HORIZONTAL</code> or <code>VERTICAL</code>. * * @return an integer representing the current orientation -- either * <code>HORIZONTAL</code> or <code>VERTICAL</code> * @see #setOrientation */ public int getOrientation() { return this.orientation; } /** * Sets the orientation of the tool bar. The orientation must have * either the value <code>HORIZONTAL</code> or <code>VERTICAL</code>. * If <code>orientation</code> is * an invalid value, an exception will be thrown. * * @param o the new orientation -- either <code>HORIZONTAL</code> or * <code>VERTICAL</code> * @exception IllegalArgumentException if orientation is neither * <code>HORIZONTAL</code> nor <code>VERTICAL</code> * @see #getOrientation * @beaninfo * description: The current orientation of the tool bar * bound: true * preferred: true * enum: HORIZONTAL SwingConstants.HORIZONTAL * VERTICAL SwingConstants.VERTICAL */ public void setOrientation( int o ) { checkOrientation( o ); if ( orientation != o ) { int old = orientation; orientation = o; firePropertyChange("orientation", old, o); revalidate(); repaint(); } } /** * Sets the rollover state of this toolbar. If the rollover state is true * then the border of the toolbar buttons will be drawn only when the * mouse pointer hovers over them. The default value of this property * is false. * <p> * The implementation of a look and feel may choose to ignore this * property. * * @param rollover true for rollover toolbar buttons; otherwise false * @since 1.4 * @beaninfo * bound: true * preferred: true * attribute: visualUpdate true * description: Will draw rollover button borders in the toolbar. */ public void setRollover(boolean rollover) { putClientProperty("JToolBar.isRollover", rollover ? Boolean.TRUE : Boolean.FALSE); } /** * Returns the rollover state. * * @return true if rollover toolbar buttons are to be drawn; otherwise false * @see #setRollover(boolean) * @since 1.4 */ public boolean isRollover() { Boolean rollover = (Boolean)getClientProperty("JToolBar.isRollover"); if (rollover != null) { return rollover.booleanValue(); } return false; } private void checkOrientation( int orientation ) { switch ( orientation ) { case VERTICAL: case HORIZONTAL: break; default: throw new IllegalArgumentException( "orientation must be one of: VERTICAL, HORIZONTAL" ); } } /** * Appends a separator of default size to the end of the tool bar. * The default size is determined by the current look and feel. */ public void addSeparator() { addSeparator(null); } /** * Appends a separator of a specified size to the end * of the tool bar. * * @param size the <code>Dimension</code> of the separator */ public void addSeparator( Dimension size ) { JToolBar.Separator s = new JToolBar.Separator( size ); add(s); } /** * Adds a new <code>JButton</code> which dispatches the action. * * @param a the <code>Action</code> object to add as a new menu item * @return the new button which dispatches the action */ public JButton add(Action a) { JButton b = createActionComponent(a); b.setAction(a); add(b); return b; } /** * Factory method which creates the <code>JButton</code> for * <code>Action</code>s added to the <code>JToolBar</code>. * The default name is empty if a <code>null</code> action is passed. * * @param a the <code>Action</code> for the button to be added * @return the newly created button * @see Action * @since 1.3 */ protected JButton createActionComponent(Action a) { JButton b = new JButton() { protected PropertyChangeListener createActionPropertyChangeListener(Action a) { PropertyChangeListener pcl = createActionChangeListener(this); if (pcl==null) { pcl = super.createActionPropertyChangeListener(a); } return pcl; } }; if (a != null && (a.getValue(Action.SMALL_ICON) != null || a.getValue(Action.LARGE_ICON_KEY) != null)) { b.setHideActionText(true); } b.setHorizontalTextPosition(JButton.CENTER); b.setVerticalTextPosition(JButton.BOTTOM); return b; } /** * Returns a properly configured <code>PropertyChangeListener</code> * which updates the control as changes to the <code>Action</code> occur, * or <code>null</code> if the default * property change listener for the control is desired. * * @return <code>null</code> */ protected PropertyChangeListener createActionChangeListener(JButton b) { return null; } /** * If a <code>JButton</code> is being added, it is initially * set to be disabled. * * @param comp the component to be enhanced * @param constraints the constraints to be enforced on the component * @param index the index of the component * */ protected void addImpl(Component comp, Object constraints, int index) { if (comp instanceof Separator) { if (getOrientation() == VERTICAL) { ( (Separator)comp ).setOrientation(JSeparator.HORIZONTAL); } else { ( (Separator)comp ).setOrientation(JSeparator.VERTICAL); } } super.addImpl(comp, constraints, index); if (comp instanceof JButton) { ((JButton)comp).setDefaultCapable(false); } } /** * A toolbar-specific separator. An object with dimension but * no contents used to divide buttons on a tool bar into groups. */ static public class Separator extends JSeparator { private Dimension separatorSize; /** * Creates a new toolbar separator with the default size * as defined by the current look and feel. */ public Separator() { this( null ); // let the UI define the default size } /** * Creates a new toolbar separator with the specified size. * * @param size the <code>Dimension</code> of the separator */ public Separator( Dimension size ) { super( JSeparator.HORIZONTAL ); setSeparatorSize(size); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ToolBarSeparatorUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return "ToolBarSeparatorUI"; } /** * Sets the size of the separator. * * @param size the new <code>Dimension</code> of the separator */ public void setSeparatorSize( Dimension size ) { if (size != null) { separatorSize = size; } else { super.updateUI(); } this.invalidate(); } /** * Returns the size of the separator * * @return the <code>Dimension</code> object containing the separator's * size (This is a reference, NOT a copy!) */ public Dimension getSeparatorSize() { return separatorSize; } /** * Returns the minimum size for the separator. * * @return the <code>Dimension</code> object containing the separator's * minimum size */ public Dimension getMinimumSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getMinimumSize(); } } /** * Returns the maximum size for the separator. * * @return the <code>Dimension</code> object containing the separator's * maximum size */ public Dimension getMaximumSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getMaximumSize(); } } /** * Returns the preferred size for the separator. * * @return the <code>Dimension</code> object containing the separator's * preferred size */ public Dimension getPreferredSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getPreferredSize(); } } } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JToolBar</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JToolBar</code>. */ protected String paramString() { String paintBorderString = (paintBorder ? "true" : "false"); String marginString = (margin != null ? margin.toString() : ""); String floatableString = (floatable ? "true" : "false"); String orientationString = (orientation == HORIZONTAL ? "HORIZONTAL" : "VERTICAL"); return super.paramString() + ",floatable=" + floatableString + ",margin=" + marginString + ",orientation=" + orientationString + ",paintBorder=" + paintBorderString; } private class DefaultToolBarLayout implements LayoutManager2, Serializable, PropertyChangeListener, UIResource { BoxLayout lm; DefaultToolBarLayout(int orientation) { if (orientation == JToolBar.VERTICAL) { lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS); } else { lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS); } } public void addLayoutComponent(String name, Component comp) { lm.addLayoutComponent(name, comp); } public void addLayoutComponent(Component comp, Object constraints) { lm.addLayoutComponent(comp, constraints); } public void removeLayoutComponent(Component comp) { lm.removeLayoutComponent(comp); } public Dimension preferredLayoutSize(Container target) { return lm.preferredLayoutSize(target); } public Dimension minimumLayoutSize(Container target) { return lm.minimumLayoutSize(target); } public Dimension maximumLayoutSize(Container target) { return lm.maximumLayoutSize(target); } public void layoutContainer(Container target) { lm.layoutContainer(target); } public float getLayoutAlignmentX(Container target) { return lm.getLayoutAlignmentX(target); } public float getLayoutAlignmentY(Container target) { return lm.getLayoutAlignmentY(target); } public void invalidateLayout(Container target) { lm.invalidateLayout(target); } public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if( name.equals("orientation") ) { int o = ((Integer)e.getNewValue()).intValue(); if (o == JToolBar.VERTICAL) lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS); else { lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS); } } } } public void setLayout(LayoutManager mgr) { LayoutManager oldMgr = getLayout(); if (oldMgr instanceof PropertyChangeListener) { removePropertyChangeListener((PropertyChangeListener)oldMgr); } super.setLayout(mgr); } ///////////////// // Accessibility support //////////////// /** * Gets the AccessibleContext associated with this JToolBar. * For tool bars, the AccessibleContext takes the form of an * AccessibleJToolBar. * A new AccessibleJToolBar instance is created if necessary. * * @return an AccessibleJToolBar that serves as the * AccessibleContext of this JToolBar */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJToolBar(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JToolBar</code> class. It provides an implementation of the * Java Accessibility API appropriate to toolbar user-interface elements. */ protected class AccessibleJToolBar extends AccessibleJComponent { /** * Get the state of this object. * * @return an instance of AccessibleStateSet containing the current * state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = super.getAccessibleStateSet(); // FIXME: [[[WDW - need to add orientation from BoxLayout]]] // FIXME: [[[WDW - need to do SELECTABLE if SelectionModel is added]]] return states; } /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the object */ public AccessibleRole getAccessibleRole() { return AccessibleRole.TOOL_BAR; } } // inner class AccessibleJToolBar }
3e08845d00868deaa4a4460f7cee4db5ca56019b
2,530
java
Java
src/main/java/de/ingogriebsch/sample/spring/data/graphql/relay/PersonLoader.java
ingogriebsch/sample-spring-data-graphql-relay
e2edf6cd99e6c891026ce3b008f82957ba91b0d8
[ "Apache-2.0" ]
null
null
null
src/main/java/de/ingogriebsch/sample/spring/data/graphql/relay/PersonLoader.java
ingogriebsch/sample-spring-data-graphql-relay
e2edf6cd99e6c891026ce3b008f82957ba91b0d8
[ "Apache-2.0" ]
36
2021-04-29T16:30:07.000Z
2022-03-28T01:20:32.000Z
src/main/java/de/ingogriebsch/sample/spring/data/graphql/relay/PersonLoader.java
ingogriebsch/sample-spring-data-graphql-relay
e2edf6cd99e6c891026ce3b008f82957ba91b0d8
[ "Apache-2.0" ]
null
null
null
36.666667
128
0.665613
3,610
/*- * Copyright 2019-2021 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 * * https://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.ingogriebsch.sample.spring.data.graphql.relay; import static java.lang.String.valueOf; import static org.apache.commons.lang3.RandomUtils.nextInt; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * A {@link CommandLineRunner} implementation the adds some example data to the repository during startup. */ @Component @RequiredArgsConstructor @Slf4j class PersonLoader implements CommandLineRunner { private static final String[] forenames = new String[] { "Max", "Paul", "Peter", "Sira", "Leonhard", "Ingo", "Steve", "Yago", "Christian", "Jan", "Pablo", "Alex", "Alexandre", "David", "Elias", "Eloy", "Emanuele", "Fabio", "Francisco", "Frederik", "Lukas", "Mohamed" }; private static final String[] surnames = new String[] { "Lopez", "Mustermann", "Poster", "Fonda", "Gabriel", "Müller", "Meyer", "Hawking", "Grünig", "Rhazi", "Videira", "Iglesias", "Castelo", "Otero", "Hermann" }; private final PersonRepository personRepository; @Override public void run(String... args) throws Exception { int count = 10; log.info("Loading {} persons into the database...", count); for (int i = 0; i < count; i++) { personRepository.save(person(valueOf(i), name(), age())); } log.info("Loading done!", count); } private static Person person(String id, String name, Integer age) { return new Person(id, name, age); } private static String name() { return new StringBuilder() // .append(forenames[nextInt(0, forenames.length)]) // .append(" ") // .append(surnames[nextInt(0, surnames.length)]) // .toString(); } private static Integer age() { return nextInt(18, 100); } }
3e0886e27ab055eedca17d042d091184879ae5fa
11,451
java
Java
control/src/main/java/org/syphr/mythtv/control/impl/Translator0_24.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
null
null
null
control/src/main/java/org/syphr/mythtv/control/impl/Translator0_24.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
null
null
null
control/src/main/java/org/syphr/mythtv/control/impl/Translator0_24.java
syphr42/libmythtv-java
cc7a2012fbd4a4ba2562dda6b2614fb0548526ea
[ "Apache-2.0" ]
1
2018-10-04T06:40:21.000Z
2018-10-04T06:40:21.000Z
48.113445
158
0.693389
3,611
/* * Copyright 2011-2012 Gregory P. Moyer * * 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.syphr.mythtv.control.impl; import java.util.HashMap; import java.util.Map; import org.syphr.mythtv.commons.translate.AbstractTranslator; import org.syphr.mythtv.types.FrontendLocation; import org.syphr.mythtv.types.Key; import org.syphr.mythtv.types.PlaybackType; import org.syphr.mythtv.types.SeekTarget; import org.syphr.mythtv.types.Verbose; import com.google.common.collect.BiMap; import com.google.common.collect.EnumHashBiMap; public class Translator0_24 extends AbstractTranslator { private static final BiMap<FrontendLocation, String> FE_LOCATION_MAP = EnumHashBiMap.create(FrontendLocation.class); static { FE_LOCATION_MAP.put(FrontendLocation.CHANNEL_PRIORITIES, "channelpriorities"); FE_LOCATION_MAP.put(FrontendLocation.CHANNEL_REC_PRIORITY, "channelrecpriority"); FE_LOCATION_MAP.put(FrontendLocation.DELETE_BOX, "deletebox"); FE_LOCATION_MAP.put(FrontendLocation.DELETE_RECORDINGS, "deleterecordings"); FE_LOCATION_MAP.put(FrontendLocation.FLIX_BROWSE, "flixbrowse"); FE_LOCATION_MAP.put(FrontendLocation.FLIX_HISTORY, "flixhistory"); FE_LOCATION_MAP.put(FrontendLocation.FLIX_QUEUE, "flixqueue"); FE_LOCATION_MAP.put(FrontendLocation.GUIDE_GRID, "guidegrid"); FE_LOCATION_MAP.put(FrontendLocation.LIVE_TV, "livetv"); FE_LOCATION_MAP.put(FrontendLocation.LIVE_TV_IN_GUIDE, "livetvinguide"); FE_LOCATION_MAP.put(FrontendLocation.MAIN_MENU, "mainmenu"); FE_LOCATION_MAP.put(FrontendLocation.MANAGE_RECORDINGS, "managerecordings"); FE_LOCATION_MAP.put(FrontendLocation.MANUAL_BOX, "manualbox"); FE_LOCATION_MAP.put(FrontendLocation.MANUAL_RECORDING, "manualrecording"); FE_LOCATION_MAP.put(FrontendLocation.MUSIC_PLAYLISTS, "musicplaylists"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_GALLERY, "mythgallery"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_GAME, "mythgame"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_MOVIETIME, "mythmovietime"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_NEWS, "mythnews"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_VIDEO, "mythvideo"); FE_LOCATION_MAP.put(FrontendLocation.MYTH_WEATHER, "mythweather"); FE_LOCATION_MAP.put(FrontendLocation.PLAYBACK_BOX, "playbackbox"); FE_LOCATION_MAP.put(FrontendLocation.PLAYBACK_RECORDINGS, "playbackrecordings"); FE_LOCATION_MAP.put(FrontendLocation.PLAY_DVD, "playdvd"); FE_LOCATION_MAP.put(FrontendLocation.PLAY_MUSIC, "playmusic"); FE_LOCATION_MAP.put(FrontendLocation.PREVIOUS_BOX, "previousbox"); FE_LOCATION_MAP.put(FrontendLocation.PROG_FINDER, "progfinder"); FE_LOCATION_MAP.put(FrontendLocation.PROGRAM_FINDER, "programfinder"); FE_LOCATION_MAP.put(FrontendLocation.PROGRAM_GUIDE, "programguide"); FE_LOCATION_MAP.put(FrontendLocation.PROGRAM_REC_PRIORITY, "programrecpriority"); FE_LOCATION_MAP.put(FrontendLocation.RECORDING_PRIORITIES, "recordingpriorities"); FE_LOCATION_MAP.put(FrontendLocation.RIP_CD, "ripcd"); FE_LOCATION_MAP.put(FrontendLocation.RIP_DVD, "ripdvd"); FE_LOCATION_MAP.put(FrontendLocation.SNAPSHOT, "snapshot"); FE_LOCATION_MAP.put(FrontendLocation.STATUS_BOX, "statusbox"); FE_LOCATION_MAP.put(FrontendLocation.VIDEO_BROWSER, "videobrowser"); FE_LOCATION_MAP.put(FrontendLocation.VIDEO_GALLERY, "videogallery"); FE_LOCATION_MAP.put(FrontendLocation.VIDEO_LISTINGS, "videolistings"); FE_LOCATION_MAP.put(FrontendLocation.VIDEO_MANAGER, "videomanager"); FE_LOCATION_MAP.put(FrontendLocation.VIEW_SCHEDULED, "viewscheduled"); FE_LOCATION_MAP.put(FrontendLocation.ZONEMINDER_CONSOLE, "zoneminderconsole"); FE_LOCATION_MAP.put(FrontendLocation.ZONEMINDER_EVENTS, "zoneminderevents"); FE_LOCATION_MAP.put(FrontendLocation.ZONEMINDER_LIVE_VIEW, "zoneminderliveview"); } private static final BiMap<Key, String> KEY_MAP = EnumHashBiMap.create(Key.class); static { KEY_MAP.put(Key.BACKSPACE, "backspace"); KEY_MAP.put(Key.BACKTAB, "backtab"); KEY_MAP.put(Key.DELETE, "delete"); KEY_MAP.put(Key.UP, "up"); KEY_MAP.put(Key.LEFT, "left"); KEY_MAP.put(Key.DOWN, "down"); KEY_MAP.put(Key.RIGHT, "right"); KEY_MAP.put(Key.PAGEDOWN, "pagedown"); KEY_MAP.put(Key.PAGEUP, "pageup"); KEY_MAP.put(Key.END, "end"); KEY_MAP.put(Key.ENTER, "enter"); KEY_MAP.put(Key.ESCAPE, "escape"); KEY_MAP.put(Key.HOME, "home"); KEY_MAP.put(Key.INSERT, "insert"); KEY_MAP.put(Key.SPACE, "space"); KEY_MAP.put(Key.TAB, "tab"); KEY_MAP.put(Key.F1, "f1"); KEY_MAP.put(Key.F2, "f2"); KEY_MAP.put(Key.F3, "f3"); KEY_MAP.put(Key.F4, "f4"); KEY_MAP.put(Key.F5, "f5"); KEY_MAP.put(Key.F6, "f6"); KEY_MAP.put(Key.F7, "f7"); KEY_MAP.put(Key.F8, "f8"); KEY_MAP.put(Key.F9, "f9"); KEY_MAP.put(Key.F10, "f10"); KEY_MAP.put(Key.F11, "f11"); KEY_MAP.put(Key.F12, "f12"); KEY_MAP.put(Key.F13, "f13"); KEY_MAP.put(Key.F14, "f14"); KEY_MAP.put(Key.F15, "f15"); KEY_MAP.put(Key.F16, "f16"); KEY_MAP.put(Key.F17, "f17"); KEY_MAP.put(Key.F18, "f18"); KEY_MAP.put(Key.F19, "f19"); KEY_MAP.put(Key.F20, "f20"); KEY_MAP.put(Key.F21, "f21"); KEY_MAP.put(Key.F22, "f22"); KEY_MAP.put(Key.F23, "f23"); KEY_MAP.put(Key.F24, "f24"); } private static final BiMap<Verbose, String> LOG_OPTION_MAP = EnumHashBiMap.create(Verbose.class); static { LOG_OPTION_MAP.put(Verbose.ALL, "all"); LOG_OPTION_MAP.put(Verbose.IMPORTANT, "important"); LOG_OPTION_MAP.put(Verbose.NONE, "none"); LOG_OPTION_MAP.put(Verbose.MOST, "most"); LOG_OPTION_MAP.put(Verbose.GENERAL, "general"); LOG_OPTION_MAP.put(Verbose.RECORD, "record"); LOG_OPTION_MAP.put(Verbose.PLAYBACK, "playback"); LOG_OPTION_MAP.put(Verbose.CHANNEL, "channel"); LOG_OPTION_MAP.put(Verbose.OSD, "osd"); LOG_OPTION_MAP.put(Verbose.FILE, "file"); LOG_OPTION_MAP.put(Verbose.SCHEDULE, "schedule"); LOG_OPTION_MAP.put(Verbose.NETWORK, "network"); LOG_OPTION_MAP.put(Verbose.COMM_FLAG, "commflag"); LOG_OPTION_MAP.put(Verbose.AUDIO, "audio"); LOG_OPTION_MAP.put(Verbose.LIBAV, "libav"); LOG_OPTION_MAP.put(Verbose.JOB_QUEUE, "jobqueue"); LOG_OPTION_MAP.put(Verbose.SI_PARSER, "siparser"); LOG_OPTION_MAP.put(Verbose.EIT, "eit"); LOG_OPTION_MAP.put(Verbose.VBI, "vbi"); LOG_OPTION_MAP.put(Verbose.DATABASE, "database"); LOG_OPTION_MAP.put(Verbose.DSMCC, "dsmcc"); LOG_OPTION_MAP.put(Verbose.MHEG, "mheg"); LOG_OPTION_MAP.put(Verbose.UPNP, "upnp"); LOG_OPTION_MAP.put(Verbose.SOCKET, "socket"); LOG_OPTION_MAP.put(Verbose.XMLTV, "xmltv"); LOG_OPTION_MAP.put(Verbose.DVB_CAM, "dvbcam"); LOG_OPTION_MAP.put(Verbose.MEDIA, "media"); LOG_OPTION_MAP.put(Verbose.IDLE, "idle"); LOG_OPTION_MAP.put(Verbose.CHANNEL_SCAN, "channelscan"); LOG_OPTION_MAP.put(Verbose.GUI, "gui"); LOG_OPTION_MAP.put(Verbose.SYSTEM, "system"); LOG_OPTION_MAP.put(Verbose.EXTRA, "extra"); LOG_OPTION_MAP.put(Verbose.TIMESTAMP, "timestamp"); LOG_OPTION_MAP.put(Verbose.NOT_MOST, "nomost"); LOG_OPTION_MAP.put(Verbose.NOT_GENERAL, "nogeneral"); LOG_OPTION_MAP.put(Verbose.NOT_RECORD, "norecord"); LOG_OPTION_MAP.put(Verbose.NOT_PLAYBACK, "noplayback"); LOG_OPTION_MAP.put(Verbose.NOT_CHANNEL, "nochannel"); LOG_OPTION_MAP.put(Verbose.NOT_OSD, "noosd"); LOG_OPTION_MAP.put(Verbose.NOT_FILE, "nofile"); LOG_OPTION_MAP.put(Verbose.NOT_SCHEDULE, "noschedule"); LOG_OPTION_MAP.put(Verbose.NOT_NETWORK, "nonetwork"); LOG_OPTION_MAP.put(Verbose.NOT_COMM_FLAG, "nocommflag"); LOG_OPTION_MAP.put(Verbose.NOT_AUDIO, "noaudio"); LOG_OPTION_MAP.put(Verbose.NOT_LIBAV, "nolibav"); LOG_OPTION_MAP.put(Verbose.NOT_JOB_QUEUE, "nojobqueue"); LOG_OPTION_MAP.put(Verbose.NOT_SI_PARSER, "nosiparser"); LOG_OPTION_MAP.put(Verbose.NOT_EIT, "noeit"); LOG_OPTION_MAP.put(Verbose.NOT_VBI, "novbi"); LOG_OPTION_MAP.put(Verbose.NOT_DATABASE, "nodatabase"); LOG_OPTION_MAP.put(Verbose.NOT_DSMCC, "nodsmcc"); LOG_OPTION_MAP.put(Verbose.NOT_MHEG, "nomheg"); LOG_OPTION_MAP.put(Verbose.NOT_UPNP, "noupnp"); LOG_OPTION_MAP.put(Verbose.NOT_SOCKET, "nosocket"); LOG_OPTION_MAP.put(Verbose.NOT_XMLTV, "noxmltv"); LOG_OPTION_MAP.put(Verbose.NOT_DVB_CAM, "nodvbcam"); LOG_OPTION_MAP.put(Verbose.NOT_MEDIA, "nomedia"); LOG_OPTION_MAP.put(Verbose.NOT_IDLE, "noidle"); LOG_OPTION_MAP.put(Verbose.NOT_CHANNEL_SCAN, "nochannelscan"); LOG_OPTION_MAP.put(Verbose.NOT_GUI, "nogui"); LOG_OPTION_MAP.put(Verbose.NOT_SYSTEM, "nosystem"); LOG_OPTION_MAP.put(Verbose.NOT_EXTRA, "noextra"); LOG_OPTION_MAP.put(Verbose.NOT_TIMESTAMP, "notimestamp"); LOG_OPTION_MAP.put(Verbose.DEFAULT, "default"); } private static final BiMap<PlaybackType, String> PLAYBACK_TYPE_MAP = EnumHashBiMap.create(PlaybackType.class); static { PLAYBACK_TYPE_MAP.put(PlaybackType.LIVE_TV, "LiveTV"); PLAYBACK_TYPE_MAP.put(PlaybackType.DVD, "DVD"); PLAYBACK_TYPE_MAP.put(PlaybackType.RECORDED, "Recorded"); PLAYBACK_TYPE_MAP.put(PlaybackType.VIDEO, "Video"); } private static final BiMap<SeekTarget, String> SEEK_TARGET_MAP = EnumHashBiMap.create(SeekTarget.class); static { SEEK_TARGET_MAP.put(SeekTarget.BEGINNING, "beginning"); SEEK_TARGET_MAP.put(SeekTarget.FORWARD, "forward"); SEEK_TARGET_MAP.put(SeekTarget.BACKWARD, "backward"); } @SuppressWarnings("rawtypes") private static final Map<Class<? extends Enum>, BiMap<? extends Enum, String>> MAPS = new HashMap<Class<? extends Enum>, BiMap<? extends Enum, String>>(); static { MAPS.put(FrontendLocation.class, FE_LOCATION_MAP); MAPS.put(Key.class, KEY_MAP); MAPS.put(Verbose.class, LOG_OPTION_MAP); MAPS.put(PlaybackType.class, PLAYBACK_TYPE_MAP); MAPS.put(SeekTarget.class, SEEK_TARGET_MAP); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected <E extends Enum<E>> BiMap<E, String> getMap(Class<E> type) { if (!MAPS.containsKey(type)) { throw new IllegalArgumentException("Unknown type: " + type); } return (BiMap) MAPS.get(type); } }
3e0887e638bf1de395dc05171edb389e6eb7676c
2,142
java
Java
freerouting-1-4-4-pm/freerouting/src/main/java/eu/mihosoft/freerouting/geometry/planar/ShapeBoundingDirections.java
pierremolinaro/ElCanari
fd9d87cee18ad484da263959a1c08424c7264eaf
[ "MIT" ]
3
2019-12-18T12:47:51.000Z
2020-12-21T14:07:43.000Z
freerouting-1-4-4-pm/freerouting/src/main/java/eu/mihosoft/freerouting/geometry/planar/ShapeBoundingDirections.java
pierremolinaro/ElCanari
fd9d87cee18ad484da263959a1c08424c7264eaf
[ "MIT" ]
1
2018-09-11T09:11:45.000Z
2018-09-12T12:13:10.000Z
freerouting-1-4-4-pm/freerouting/src/main/java/eu/mihosoft/freerouting/geometry/planar/ShapeBoundingDirections.java
pierremolinaro/ElCanari-dev
e5368983cf1558f6f4d567e7171beda56b5218b8
[ "MIT" ]
null
null
null
31.558824
80
0.67288
3,612
/* * Copyright (C) 2014 Alfons Wirtz * website www.freerouting.net * * Copyright (C) 2017 Michael Hoffer <[email protected]> * Website www.freerouting.mihosoft.eu * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License at <http://www.gnu.org/licenses/> * for more details. */ package eu.mihosoft.freerouting.geometry.planar; /** * * Describing the functionality for the fixed directions of a RegularTileShape. * * @author Alfons Wirtz */ public interface ShapeBoundingDirections { /** * Retuns the count of the fixed directions. */ int count(); /** * Calculates for an abitrary ConvexShape a surrounding RegularTileShape * with this fixed directions. * Is used in the implementation of the seach trees. */ RegularTileShape bounds(ConvexShape p_shape); /** * Auxiliary function to implement the same function with parameter * type ConvexShape. */ RegularTileShape bounds(IntBox p_box); /** * Auxiliary function to implement the same function with parameter * type ConvexShape. */ RegularTileShape bounds(IntOctagon p_oct); /** * Auxiliary function to implement the same function with parameter * type ConvexShape. */ RegularTileShape bounds(Simplex p_simplex); /** * Auxiliary function to implement the same function with parameter * type ConvexShape. */ RegularTileShape bounds(Circle p_circle); /** * Auxiliary function to implement the same function with parameter * type ConvexShape. */ RegularTileShape bounds(PolygonShape p_polygon); }
3e08880c448179674d1925aefbc41e9b6e765008
260
java
Java
src/main/java/io/github/rypofalem/weighted_table/WeightedLeaf.java
RypoFalem/WeightedMap
6a523014048ceb46b7e3ccb11eefaff19f970c2c
[ "MIT" ]
1
2018-12-07T00:52:04.000Z
2018-12-07T00:52:04.000Z
src/main/java/io/github/rypofalem/weighted_table/WeightedLeaf.java
RypoFalem/WeightedMap
6a523014048ceb46b7e3ccb11eefaff19f970c2c
[ "MIT" ]
null
null
null
src/main/java/io/github/rypofalem/weighted_table/WeightedLeaf.java
RypoFalem/WeightedMap
6a523014048ceb46b7e3ccb11eefaff19f970c2c
[ "MIT" ]
null
null
null
16.25
60
0.6
3,613
package io.github.rypofalem.weighted_table; public final class WeightedLeaf<T> extends WeightedNode<T> { private T t; WeightedLeaf(double weight, T t) { super(weight); this.t = t; } public T get(){ return t; } }
3e0888b174e170f1b5d571eeff9fcc2654b30c32
2,892
java
Java
src/backend/codecc/core/codeccjob/biz-codeccjob/src/main/java/com/tencent/bk/codecc/codeccjob/service/impl/CCNAuthorTransBizServiceImpl.java
crb2046/bk-ci
adbf3f4e92900db7b1db19c7760f926c98bffd95
[ "MIT" ]
1,939
2019-05-29T05:15:45.000Z
2022-03-29T11:49:16.000Z
src/backend/codecc/core/codeccjob/biz-codeccjob/src/main/java/com/tencent/bk/codecc/codeccjob/service/impl/CCNAuthorTransBizServiceImpl.java
crb2046/bk-ci
adbf3f4e92900db7b1db19c7760f926c98bffd95
[ "MIT" ]
3,608
2019-06-05T07:55:23.000Z
2022-03-31T15:03:41.000Z
src/backend/codecc/core/codeccjob/biz-codeccjob/src/main/java/com/tencent/bk/codecc/codeccjob/service/impl/CCNAuthorTransBizServiceImpl.java
crb2046/bk-ci
adbf3f4e92900db7b1db19c7760f926c98bffd95
[ "MIT" ]
561
2019-05-29T07:15:10.000Z
2022-03-29T09:32:15.000Z
39.616438
123
0.706777
3,614
/* * Tencent is pleased to support the open source community by making BlueKing available. * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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.tencent.bk.codecc.codeccjob.service.impl; import com.tencent.bk.codecc.defect.model.CCNDefectEntity; import com.tencent.bk.codecc.defect.vo.common.AuthorTransferVO; import com.tencent.bk.codecc.codeccjob.dao.mongorepository.CCNDefectRepository; import com.tencent.bk.codecc.codeccjob.service.AbstractAuthorTransBizService; import com.tencent.devops.common.api.pojo.Result; import com.tencent.devops.common.constant.ComConstants; import com.tencent.devops.common.constant.CommonMessageCode; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * ccn类工具的作者转换 * * @version V1.0 * @date 2019/11/1 */ @Service("CCNAuthorTransBizService") @Slf4j public class CCNAuthorTransBizServiceImpl extends AbstractAuthorTransBizService { @Autowired private CCNDefectRepository ccnDefectRepository; @Override public Result processBiz(AuthorTransferVO authorTransferVO) { List<CCNDefectEntity> ccnDefectEntityList = ccnDefectRepository.findNotRepairedDefect(authorTransferVO.getTaskId(), ComConstants.DEFECT_STATUS_CLOSED); if (CollectionUtils.isNotEmpty(ccnDefectEntityList)) { List<CCNDefectEntity> needRefreshDefectList = new ArrayList<>(); ccnDefectEntityList.forEach(ccnDefectEntity -> { String author = ccnDefectEntity.getAuthor(); String newAuthor = transferAuthor(authorTransferVO.getTransferAuthorList(), author); if (!newAuthor.equals(author)) { ccnDefectEntity.setAuthor(newAuthor); needRefreshDefectList.add(ccnDefectEntity); } } ); if (CollectionUtils.isNotEmpty(needRefreshDefectList)) { ccnDefectRepository.save(needRefreshDefectList); } } return new Result(CommonMessageCode.SUCCESS); } }
3e088935eb756364b7711b2c15819cd9f0a4a078
905
java
Java
mgmt/java/src/main/java/com/aliyun/pds/mgmt/client/models/VideoPreviewAutoScale.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
4
2020-08-21T08:40:27.000Z
2021-04-04T03:39:06.000Z
mgmt/java/src/main/java/com/aliyun/pds/mgmt/client/models/VideoPreviewAutoScale.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
35
2020-08-31T08:10:53.000Z
2022-03-24T09:43:11.000Z
mgmt/java/src/main/java/com/aliyun/pds/mgmt/client/models/VideoPreviewAutoScale.java
lancer-chen/alibabacloud-pds-sdk
f9cea449693eb96288b4c98078cd43c5559f3bd9
[ "Apache-2.0" ]
16
2020-08-24T05:42:43.000Z
2022-03-16T03:03:53.000Z
23.815789
94
0.668508
3,615
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.pds.mgmt.client.models; import com.aliyun.tea.*; /** * */ public class VideoPreviewAutoScale extends TeaModel { @NameInMap("enabled") public Boolean enabled; @NameInMap("max_length") public Long maxLength; public static VideoPreviewAutoScale build(java.util.Map<String, ?> map) throws Exception { VideoPreviewAutoScale self = new VideoPreviewAutoScale(); return TeaModel.build(map, self); } public VideoPreviewAutoScale setEnabled(Boolean enabled) { this.enabled = enabled; return this; } public Boolean getEnabled() { return this.enabled; } public VideoPreviewAutoScale setMaxLength(Long maxLength) { this.maxLength = maxLength; return this; } public Long getMaxLength() { return this.maxLength; } }
3e08894cff9e80c2a0d2b8953d56dc91e812a675
17,541
java
Java
datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/interpreter/pipelined/recursion/seminaive/CliqueNode.java
YoufuLi/radlog
669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
2
2020-12-08T01:53:18.000Z
2021-01-08T17:46:53.000Z
datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/interpreter/pipelined/recursion/seminaive/CliqueNode.java
YoufuLi/radlog
669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
1
2021-08-31T03:40:28.000Z
2021-08-31T06:38:38.000Z
datalog/src/main/java/edu/ucla/cs/wis/bigdatalog/interpreter/pipelined/recursion/seminaive/CliqueNode.java
YoufuLi/radlog
669c2b28f7ef4f9f6d94d353a3b180c1ad3b99e5
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
null
null
null
34.529528
140
0.719058
3,616
package edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.seminaive; import java.util.LinkedList; import edu.ucla.cs.wis.bigdatalog.compiler.variable.Binding; import edu.ucla.cs.wis.bigdatalog.database.Database; import edu.ucla.cs.wis.bigdatalog.database.Tuple; import edu.ucla.cs.wis.bigdatalog.database.cursor.FixpointCursor; import edu.ucla.cs.wis.bigdatalog.database.cursor.NaiveCursor; import edu.ucla.cs.wis.bigdatalog.database.cursor.Cursor; import edu.ucla.cs.wis.bigdatalog.database.cursor.IndexCursor; import edu.ucla.cs.wis.bigdatalog.database.store.tuple.TupleStoreConfiguration; import edu.ucla.cs.wis.bigdatalog.database.store.tuple.TupleStoreManager.TupleStoreType; import edu.ucla.cs.wis.bigdatalog.exception.InterpreterException; import edu.ucla.cs.wis.bigdatalog.interpreter.EvaluationType; import edu.ucla.cs.wis.bigdatalog.interpreter.Node; import edu.ucla.cs.wis.bigdatalog.interpreter.Status; import edu.ucla.cs.wis.bigdatalog.interpreter.argument.NodeArguments; import edu.ucla.cs.wis.bigdatalog.interpreter.argument.VariableList; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.OrNode; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.ProgramContext; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.RecursiveLiteral; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.fs.EMSNCliqueNode; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.fs.FSCliqueNode; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.fs.MutualEMSNCliqueNode; import edu.ucla.cs.wis.bigdatalog.interpreter.pipelined.recursion.statistics.StageStatisticsManager; import edu.ucla.cs.wis.bigdatalog.system.DeALSContext; public class CliqueNode extends CliqueBaseNode implements IClique { protected OrNode recursiveRulesOrNode; protected boolean isFixpointReached; protected Database database; public CliqueNode(String predicateName, NodeArguments args, Binding binding, VariableList freeVariables, String recursiveRelationName, boolean isSharable) { super(predicateName, args, binding, freeVariables, recursiveRelationName, isSharable); this.exitRulesOrNode = null; this.recursiveRulesOrNode = null; this.isFixpointReached = false; this.evaluationType = EvaluationType.SemiNaive; } public OrNode getRecursiveRulesOrNode() { return this.recursiveRulesOrNode; } public void addRecursiveRulesOrNode(OrNode node) { this.recursiveRulesOrNode = node; } @Override public boolean initialize() { boolean status = false; if (!this.initialized) { if (this.recursiveRelationName != null) { TupleStoreConfiguration tsc = new TupleStoreConfiguration(TupleStoreType.UnorderedHeap); this.recursiveRelation = this.database.getRelationManager().createRecursiveRelation(this.recursiveRelationName, this.getSchema(), tsc, true); this.initializeIndex(); this.fixpointCursor = this.database.getCursorManager().createSemiNaiveCursor(this.recursiveRelation, null); if ((this.exitRulesOrNode != null) && (status = this.exitRulesOrNode.initialize()) && (this.recursiveRulesOrNode != null) && (status = this.recursiveRulesOrNode.initialize())) { this.initialized = true; } this.isCleanedUp = false; this.stage = 0; this.numberOfDeltaFactsByIteration = new LinkedList<>(); this.numberOfGeneratedFactsByIteration = new LinkedList<>(); this.numberOfGeneratedFactsThisIteration = 0; this.returnedTuple = this.recursiveRelation.getEmptyTuple(); } else { this.logError("Can not initialize clique no relation {}", this.predicateName); throw new InterpreterException("Can not initialize clique no relation " + this.predicateName); } } else { status = true; } return status; } protected boolean addTuple() { if (DEBUG) this.logTrace("Entering addTuple"); boolean status = false; for (int i = 0; i < this.arity; i++) this.returnedTuple.columns[i] = this.getArgumentAsDbType(i); if (DEBUG) { if (this.arguments.size() > 0) this.logDebug("////////// [addTuple: {}] //////////", this.returnedTuple); } this.numberOfGeneratedFactsThisIteration++; status = (this.recursiveRelation.add(this.returnedTuple) != null); if (DEBUG) { if (status) this.logDebug("{}{} added to the recursive relation.", this.recursiveRelation.getName(), this.returnedTuple); else this.logDebug("{} not added to {}", this.returnedTuple, this.recursiveRelation.getName()); } /*if (!status) //System.out.println(this.recursiveRelation.getName() + " " + this.returnedTuple + " added to the recursive relation."); //else System.out.println(this.returnedTuple + " not added to " + this.recursiveRelation.getName()); */ if (status) { if (DEBUG && this.deALSContext.isStatisticsEnabled() && StageStatisticsManager.isValidPredicate(this.predicateName)) StageStatisticsManager.getInstance().markTupleAdded(this.predicateName, this.returnedTuple); this.numberOfRecursiveFactsDerived++; } if (DEBUG) this.logTrace("Exiting addTuple with status = {}", status); return status; } @Override public int getAnyTuple(Cursor readCursor, CliqueBaseNode clique, Tuple tuple) { if (DEBUG) this.logTrace("Entering getAnyTuple for {}", this.toStringNode()); int status = readCursor.getTuple(tuple); if (status == 0) { // If we are here, then it implies that we have reached the end of the // local recursive relation of clique_ptr. Let us see if we can generate // a new local tuple by using our exit and recursive rules. Okay, "grunt" ... // Here, if the actual clique is the parent clique, we continue only if we have not reached a fixpoint if ((this != clique) || (!this.isFixpointReached)) { // Note that generateTuple for mutual clique does not depend on the 'this.fixedpoint' flag // we also know that if we have reached a fixed-point on the main parent clique // no more new tuples can be generated for the parent predicate even though // we may generate new tuples for the mutual clique while (clique.generateTuple() == Status.SUCCESS) { if (readCursor instanceof IndexCursor) ((IndexCursor)readCursor).refresh(); status = readCursor.getTuple(tuple); if (status > 0) break; } // If we didn't generate any tuple and the getAnyTuple request was originally directed // at a subclique (this would be true if (this != clique_ptr)), then we try to // generate local tuples hoping that this would generate tuples in the subclique "clique_ptr" if (this != clique) { while ((status == 0) && !this.isFixpointReached) { // It does not matter if the generateTuple on the parent clique will succeed or not // because we might generate some tuples for the mutual clique this.generateTuple(); while (true) { status = readCursor.getTuple(tuple); if (status > 0) break; if (clique.generateTuple() != Status.SUCCESS) break; } } } } } if (DEBUG) { if (status > 0) this.logTrace("Exiting getAnyTuple {} with tuple {} with SUCCESS (status = {})", this.getPredicateNameWithBinding(), tuple, status); else this.logTrace("Exiting getAnyTuple {} with FAIL (status = {})", this.getPredicateNameWithBinding(), status); } return status; } protected Status getRecursiveTuple() { if (DEBUG) this.logTrace("Entering getRecursiveTuple for {}", this.toStringNode()); Status status = Status.FAIL; // If we generated a tuple, we better add it in our local recursive // relation. If it was a duplicate, we try again, else we are done while (((status = this.recursiveRulesOrNode.getTuple()) == Status.SUCCESS) && (!this.addTuple())); if (DEBUG) this.logTrace("Exiting getRecursiveTuple for {} with status = {}", this.toStringNode(), status); return status; } public Status generateTuple() { if (DEBUG) this.logTrace("Entering generateTuple for {}", this.toStringNode()); Status status = Status.FAIL; this.isCleanedUp = false; if (this.currentRuleType == CliqueRuleType.EXIT_RULE) { status = this.getExitTuple(); if (status != Status.SUCCESS) { this.currentRuleType = CliqueRuleType.RECURSIVE_RULE; this.prepareForNextStage(); } } if (this.currentRuleType == CliqueRuleType.RECURSIVE_RULE) { while (true) { status = this.getRecursiveTuple(); if (status == Status.SUCCESS) { break; } else if (this.isFixedpointReached()) { break; } else { this.prepareForNextStage(); } } } if (DEBUG) this.logTrace("Exiting generateTuple for {} with status = {}", this.toStringNode(), status); return status; } protected boolean isFixedpointReached() { if (DEBUG) this.logTrace("Entering isFixedpointReached"); boolean status = false; if (this.fixpointCursor.isFixedPointReached()) { boolean fixpointReached = true; for (IMutualClique mutualClique : this.getMutualCliqueList()) { if (!mutualClique.getFixpointCursor().isFixedPointReached()) { fixpointReached = false; break; } } if (fixpointReached) status = true; } this.isFixpointReached = status; if (DEBUG && this.deALSContext.isInfoEnabled()) { if (status) { if (this.recursiveRelation != null) this.logInfo("****** Fixed Point reached for relation '{}' ******", this.recursiveRelation.getName()); else this.logInfo("****** Fixed Point reached for recursive relation ******"); } else { if (this.recursiveRelation != null) this.logInfo("****** Fixed Point NOT reached for relation '{}' ******", this.recursiveRelation.getName()); else this.logInfo("****** Fixed Point NOT reached for recursive relation ******"); } } if (DEBUG && this.deALSContext.isDebugEnabled()) if (this.recursiveRelation != null) this.logDebug(this.recursiveRelation.toString()); if (DEBUG && this.deALSContext.isDerivationTrackingEnabled() && status) { if (this.recursiveRelation != null) this.logDerivationTracking("****** Fixed Point reached for relation '{}' ******", this.recursiveRelation.getName()); else this.logDerivationTracking("****** Fixed Point reached for recursive relation ******"); } if (DEBUG) this.logTrace("Exiting isFixpointReached with status = {}", status); return status; } // added so all subclasses in class hierarchy follow a pattern // really needed because cliques with FS aggregates must do more at stage // boundaries than basic cliques public void prepareForNextStage() { if (DEBUG) this.logTrace("Entering prepareForNextStage"); this.beginNextStageForRecursiveCursors(); if (DEBUG && this.deALSContext.isStatisticsEnabled() && StageStatisticsManager.isValidPredicate(this.predicateName)) StageStatisticsManager.getInstance().stageComplete(this.predicateName); for (IMutualClique mutualClique : this.mutualCliqueList) { if (mutualClique instanceof MutualEMSNCliqueNode) ((MutualEMSNCliqueNode)mutualClique).prepareForNextStage(); if (DEBUG && this.deALSContext.isDebugEnabled()) { this.logDebug("Mutual clique {} contains:", mutualClique.getPredicateName()); if (mutualClique.getRecursiveRelation() != null) this.logDebug(mutualClique.getRecursiveRelation().toString()); else if (mutualClique instanceof MutualEMSNCliqueNode) this.logDebug(((MutualEMSNCliqueNode)mutualClique).aggregateRelation.toString()); } } if (!(this instanceof FSCliqueNode) && !(this instanceof EMSNCliqueNode)) this.numberOfDeltaFactsByIteration.add(this.fixpointCursor.getIterationSize()); if (DEBUG) { this.logInfo("stage {} [{} - {}]{}", this.stage, ((NaiveCursor)this.fixpointCursor).baseTupleAddress, ((NaiveCursor)this.fixpointCursor).endTupleAddress, System.currentTimeMillis()); this.logTrace("Exiting prepareForNextStage"); } } protected void beginNextStageForRecursiveCursors() { if (DEBUG) this.logTrace("Entering beginNextStageForRecursiveCursors"); //System.out.println("total derived tuples this iteration : " + this.numberOfGeneratedFactsThisIteration); //System.out.println("total recursive tuples so far: " + this.numberOfRecursiveFactsDerived); //APS 3/19/2013 this.stage++; this.numberOfGeneratedFactsByIteration.add(this.numberOfGeneratedFactsThisIteration); this.numberOfGeneratedFactsThisIteration = 0; //this.numberOfRecursiveFactsDerived = 0; if (DEBUG) this.logInfo("Beginning next stage for cursors for " + this.predicateName); Cursor<?> cursor; for (RecursiveLiteral recursiveLiteral : this.recursiveLiteralList) { cursor = recursiveLiteral.getCursor(); if (cursor instanceof FixpointCursor) ((FixpointCursor)cursor).beginNextStage(this.deALSContext, this.stage); } // APS 2/12/2014 - using fifo queue of eager monotonic for (IMutualClique mutualClique : this.mutualCliqueList) if (mutualClique.getFixpointCursor() != null) mutualClique.getFixpointCursor().beginNextStage(this.deALSContext, this.stage); // APS 2/12/2014 - using fifo queue of eager monotonic if (this.fixpointCursor != null) this.fixpointCursor.beginNextStage(this.deALSContext, this.stage); if (DEBUG) this.logTrace("Exiting beginNextStageForRecursiveCursors"); } public void cleanUp() { if (DEBUG) this.logTrace("Entering cleanUp for {}", this.toStringNode()); if (!this.isCleanedUp) { this.cliqueCleanUp(); this.backtrackCount = 0; // Init the various SemiNaive Cursors that are used for (RecursiveLiteral recursiveLiteral : this.recursiveLiteralList) { if (recursiveLiteral.getCursor() instanceof FixpointCursor) ((FixpointCursor)recursiveLiteral.getCursor()).initialize(); } for (IMutualClique mutualClique : this.mutualCliqueList) mutualClique.getFixpointCursor().initialize(); this.fixpointCursor.initialize(); this.isCleanedUp = true; } if (DEBUG) this.logTrace("Exiting cleanUp for {}", this.toStringNode()); } protected void cliqueCleanUp() { super.cliqueCleanUp(); if (this.exitRulesOrNode != null) this.exitRulesOrNode.cleanUp(); if (this.recursiveRulesOrNode != null) this.recursiveRulesOrNode.cleanUp(); // APS 2/5/2014 - eager monotonic won't have a recursive relation if (this.recursiveRelation != null) this.recursiveRelation.cleanUp(); this.isFixpointReached = false; this.currentRuleType = CliqueRuleType.EXIT_RULE; } public void deleteRelationsAndCursors() { if (this.initialized) { if (this.exitRulesOrNode != null) this.exitRulesOrNode.deleteRelationsAndCursors(); if (this.recursiveRulesOrNode != null) this.recursiveRulesOrNode.deleteRelationsAndCursors(); // APS 2/5/2014 - eager monotonic won't have a recursive relation if (this.recursiveRelation != null) this.database.getRelationManager().deleteRecursiveRelation(this.recursiveRelation); this.recursiveRelation = null; this.fixpointCursor = null; this.initialized = false; } } public String toString() { StringBuilder output = new StringBuilder(); output.append(Node.toStringIndent()); output.append(this.toStringNode()); //displayIndentLevel++; //output.append(Node.toStringIndent()); if ((this.exitRulesOrNode.getClass() != OrNode.class) || this.exitRulesOrNode.hasChildren()) { //if (this.exitRulesOrNode.hasChildren()) { output.append("\n"); for (int i = 0; i < displayIndentLevel; i++) output.append(" "); output.append("Exit Rules: "); if (this.exitRulesOrNode != null) { displayIndentLevel++; output.append(this.exitRulesOrNode.toStringTree()); displayIndentLevel--; } } //output.append(Node.toStringIndent()); output.append("\n"); for (int i = 0; i < displayIndentLevel; i++) output.append(" "); output.append("Recursive Rules: "); if (this.recursiveRulesOrNode != null) { displayIndentLevel++; output.append(this.recursiveRulesOrNode.toStringTree()); displayIndentLevel--; } //displayIndentLevel--; return output.toString(); } @Override public CliqueNode copy(ProgramContext programContext) { if (programContext.getCliqueMapping().containsKey(this)) return (CliqueNode) programContext.getCliqueMapping().get(this); CliqueNode copy = new CliqueNode(new String(this.predicateName), programContext.copyArguments(this.arguments), this.bindingPattern.copy(), programContext.copyVariableList(this.freeVariableList), new String(this.recursiveRelationName), this.isSharable); programContext.getCliqueMapping().put(this, copy); copy.exitRulesOrNode = this.exitRulesOrNode.copy(programContext); copy.recursiveRulesOrNode = this.recursiveRulesOrNode.copy(programContext); copy.evaluationType = this.evaluationType; copy.stage = this.stage; for (IMutualClique mc : this.mutualCliqueList) copy.mutualCliqueList.add((IMutualClique) programContext.getCliqueMapping().get(mc)); for (RecursiveLiteral rl : this.recursiveLiteralList) copy.recursiveLiteralList.add((RecursiveLiteral) programContext.getNodeMapping().get(rl)); return copy; } @Override public void attachContext(DeALSContext deALSContext) { super.attachContext(deALSContext); this.database = deALSContext.getDatabase(); this.recursiveRulesOrNode.attachContext(deALSContext); } }
3e088972f5c069d01d4194f40a36b42658a21fb2
6,520
java
Java
rxandroidorm-compiler/src/main/java/com/github/florent37/rxandroidorm/Constants.java
florent37/RxAndroidOrm
169378bb4617fdffcbd383b07a196798fbe2f7fc
[ "Apache-2.0" ]
39
2017-05-08T12:17:14.000Z
2018-11-06T03:15:37.000Z
rxandroidorm-compiler/src/main/java/com/github/florent37/rxandroidorm/Constants.java
florent37/RxAndroidOrm
169378bb4617fdffcbd383b07a196798fbe2f7fc
[ "Apache-2.0" ]
2
2017-05-09T11:51:13.000Z
2017-05-10T15:15:35.000Z
rxandroidorm-compiler/src/main/java/com/github/florent37/rxandroidorm/Constants.java
florent37/RxAndroidOrm
169378bb4617fdffcbd383b07a196798fbe2f7fc
[ "Apache-2.0" ]
9
2017-05-08T17:17:46.000Z
2019-12-26T08:05:52.000Z
65.2
180
0.794632
3,617
package com.github.florent37.rxandroidorm; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; import java.text.SimpleDateFormat; import java.util.Date; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.ObservableSource; import io.reactivex.functions.Function; /** * Created by florentchampigny on 18/01/2016. */ public class Constants { public static final String DAO_PACKAGE = "com.github.florent37.rxandroidorm"; public static final String DAO_CLASS_NAME = "RxAndroidOrm"; public static final String DATABASE_HELPER_CLASS_NAME = "DatabaseHelper"; public static final String DATABASE_COMMON_INTERFACE_NAME = "Database"; public static final String MIGRATOR = "Migrator"; public static final String CALLBACK = "Callback"; public static final String DAO_SUFFIX = "Database"; public static final String CURSOR_HELPER_SUFFIX = "CursorHelper"; public static final String QUERY_BUILDER_SUFFIX = "QueryBuilder"; public static final String ENUM_COLUMN_SUFFIX = "Columns"; public static final TypeName daoClassName = ClassName.get(Constants.DAO_PACKAGE, DAO_CLASS_NAME); public static final TypeName dbHelperClassName = ClassName.get(Constants.DAO_PACKAGE, DATABASE_HELPER_CLASS_NAME); public static final TypeName queryBuilderClassName = ClassName.get(Constants.DAO_PACKAGE, QUERY_BUILDER_SUFFIX); public static final TypeName databaseCommonInterfaceClassName = ClassName.get(Constants.DAO_PACKAGE, DATABASE_COMMON_INTERFACE_NAME); public static final TypeName migrator = ClassName.get(Constants.DAO_PACKAGE+".migration", MIGRATOR); public static final TypeName applicationClassName = ClassName.get("android.app", "Application"); public static final TypeName databaseClassName = ClassName.get("android.database.sqlite", "SQLiteDatabase"); public static final TypeName sqliteOpenHelperClassName = ClassName.get("android.database.sqlite", "SQLiteOpenHelper"); public static final TypeName contextClassName = ClassName.get("android.content", "Context"); public static final TypeName cursorClassName = ClassName.get("android.database", "Cursor"); public static final TypeName contentValuesClassName = ClassName.get("android.content", "ContentValues"); public static final TypeName dateClassName = ClassName.get(Date.class); public static final TypeName simpleDateFormatClassName = ClassName.get(SimpleDateFormat.class); public static final TypeName stringBuilderClassName = ClassName.get(StringBuilder.class); public static final String ENUM_COLUMN_ELEMENT_NAME = "column_name"; public static final String ENUM_COLUMN_IS_PRIMITIVE = "column_is_primitive"; public static final String FIELD_ID = "_id"; public static final String FIELD_NAME = "_field_name"; public static final String QUERY_TABLE_VARIABLE = "t"; public static final String QUERY_NAMED = "NAMED"; public static final String PRIMITIVE_CURSOR_HELPER = "PrimitiveCursorHelper"; public static final TypeName primitiveCursorHelper = ClassName.get(Constants.DAO_PACKAGE, PRIMITIVE_CURSOR_HELPER); public static final String PRIMITIVE_TABLE_INT = "MODEL_INT"; public static final String PRIMITIVE_TABLE_LONG = "MODEL_INT"; public static final String PRIMITIVE_TABLE_STRING = "MODEL_STRING"; public static final String PRIMITIVE_TABLE_FLOAT = "MODEL_FLOAT"; public static final String PRIMITIVE_TABLE_DOUBLE = "MODEL_FLOAT"; public static final String PRIMITIVE_TABLE_BOOLEAN = "MODEL_BOOLEAN"; public static final String SELECTOR_NUMBER = "NumberSelector"; public static final String SELECTOR_NUMBER_LIST = "ListNumberSelector"; public static final String SELECTOR_BOOLEAN = "BooleanSelector"; public static final String SELECTOR_BOOLEAN_LIST = "ListBooleanSelector"; public static final String SELECTOR_STRING = "StringSelector"; public static final String SELECTOR_STRING_LIST = "ListStringSelector"; public static final String SELECTOR_DATE = "DateSelector"; public static final ClassName queryBuilder_NumberSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_NUMBER); public static final ClassName queryBuilder_ListNumberSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_NUMBER_LIST); public static final ClassName queryBuilder_BooleanSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_BOOLEAN); public static final ClassName queryBuilder_ListBooleanSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_BOOLEAN_LIST); public static final ClassName queryBuilder_StringSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_STRING); public static final ClassName queryBuilder_ListStringSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_STRING_LIST); public static final ClassName queryBuilder_DateSelectorClassName = ClassName.bestGuess(Constants.DAO_PACKAGE + "." + QUERY_BUILDER_SUFFIX + "." + SELECTOR_DATE); public static final ClassName RX_OBSERVABLE = ClassName.get(Observable.class); public static final ClassName RX_OBSERVABLE_EMITTER = ClassName.get(ObservableEmitter.class); public static final ClassName RX_OBSERVABLE_ON_SUBSCRIBE = ClassName.get(ObservableOnSubscribe.class); public static final ClassName RX_OBSERVABLE_SOURCE = ClassName.get(ObservableSource.class); public static final ClassName RX_FUNCTION = ClassName.get(Function.class); public static final String QUERY_LOGGER = "QueryLogger"; public static final String MODEL_ENTITY_PROXY = "Entity"; public static final String MODEL_ENTITY_PROXY_INTERFACE = "DataBaseModel"; public static final String MODEL_ENTITY_PROXY_GET_ID_METHOD = "getDatabaseModelId"; public static final String MODEL_ENTITY_PROXY_SET_ID_METHOD = "setDatabaseModelId"; public static final String entityProxyClassString = Constants.DAO_PACKAGE + "." + MODEL_ENTITY_PROXY_INTERFACE; public static final ClassName entityProxyClass = ClassName.bestGuess(entityProxyClassString); public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String PARCEL_CREATOR = "CREATOR"; }