blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
87d1cd06e291abcde155a4fd758980a41c864bed
624c22afec6e08f33735b268263200ddd68bf9b8
/src/test/java/ru/dnsk/sweater/LoginTest.java
d7a1cff8bb25334941d532ba21ba8347e16e2d11
[]
no_license
SergeyDnv/sweater
a2704185a85dad06ba9a3814c61e6d708b197602
ab29d16eaf8e939cb146d3974455d13befa9b8a9
refs/heads/master
2023-08-06T08:17:25.717280
2021-09-28T10:42:57
2021-09-28T10:42:57
411,221,109
0
0
null
null
null
null
UTF-8
Java
false
false
2,520
java
package ru.dnsk.sweater; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.core.StringContains.containsString; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @TestPropertySource("/application-test.properties") public class LoginTest { @Autowired private MockMvc mockMvc; @Test public void contextLoads() throws Exception { this.mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().string(containsString("Hello"))) .andExpect(content().string(containsString("This is simple clone of twitter"))); } @Test public void accessDeniedTest() throws Exception { this.mockMvc.perform(get("/main")) .andDo(print()) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("http://localhost/login")); } @Test @Sql(value = {"/create-user-before.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = {"/create-user-after.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) public void correctLoginTest() throws Exception { this.mockMvc.perform(formLogin().user("admin").password("admin")) .andDo(print()) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); } @Test public void badCredentials() throws Exception { this.mockMvc.perform(post("/login").param("user", "badUser")) .andExpect(status().isForbidden()); } }
a9e39f73fbf69775669f9130256fa964c5906677
22b1d8ca17fa0ee10dd2c560dd9de06633781bb6
/CB_UI_Base/src/de/droidcachebox/gdx/graphics/SolidTextureRegion.java
72fb4f3cdf150ce20f1d2d9176bb6698fa2e4d96
[]
no_license
Ging-Buh/cachebox
52060e224388f06829c6dddfac8aaaf35a5f2294
d1f8518bb9cb05c624802dc34fd77579aaa4b9c1
refs/heads/master
2023-06-08T00:04:38.292185
2023-05-31T12:40:38
2023-05-31T12:40:38
39,300,643
7
2
null
2019-11-04T19:50:20
2015-07-18T14:21:17
Java
UTF-8
Java
false
false
1,253
java
/* * Copyright (C) 2014 team-cachebox.de * * Licensed under the : GNU General Public License (GPL); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/gpl.html * * 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.droidcachebox.gdx.graphics; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; /** * @author Longri */ public class SolidTextureRegion extends TextureRegion { public SolidTextureRegion(Color color, float width, float height) { Pixmap pix = new Pixmap(2, 2, Format.RGB565); pix.setColor(color); pix.fill(); Texture tex = new Texture(pix); pix.dispose(); this.setRegion(tex); setRegion(0, 0, width, height); } }
dec32d7ab9da18092a2dd2655b339a16715e095c
027fd4a4af2993a078c5a74d92bfe47529a2a6ca
/geode-core/src/integrationTest/java/org/apache/geode/internal/cache/CacheDistributionAdvisorConcurrentTest.java
6dfce1fd948923d60e01d41bdac211128993474a
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
gmstrbytes/geode
e03a814d11482d0ea64de3d665f6a4e643eb0d74
265d00c4e03b013a54266675ed51309722b76b07
refs/heads/develop
2022-01-12T14:20:29.133115
2021-06-02T15:05:58
2021-06-02T15:05:58
125,238,887
1
0
Apache-2.0
2021-06-02T15:08:12
2018-03-14T16:04:23
Java
UTF-8
Java
false
false
4,270
java
/* * 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.geode.internal.cache; import static org.apache.geode.internal.inet.LocalHostUtil.getLocalHost; import static org.apache.geode.test.concurrency.Utilities.availableProcessors; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; import java.net.UnknownHostException; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.apache.geode.CancelCriterion; import org.apache.geode.cache.Operation; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.CacheDistributionAdvisor.CacheProfile; import org.apache.geode.test.concurrency.ConcurrentTestRunner; import org.apache.geode.test.concurrency.ParallelExecutor; @RunWith(ConcurrentTestRunner.class) public class CacheDistributionAdvisorConcurrentTest { private final int count = availableProcessors() * 2; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Test public void getAdviseAllEventsOrCachedForConcurrentUpdateShouldSucceed(ParallelExecutor executor) throws Exception { CacheDistributionAdvisor advisor = createCacheDistributionAdvisor(); CacheProfile profile = createCacheProfile(); advisor.putProfile(profile, true); executor.inParallel(() -> { advisor.adviseAllEventsOrCached(); }, count); executor.execute(); assertThat(advisor.adviseAllEventsOrCached()) .contains(profile.getDistributedMember()); assertThat(advisor.adviseAllEventsOrCached()) .hasSize(1); } @Test public void getAdviseUpdateForConcurrentUpdateShouldSucceed(ParallelExecutor executor) throws Exception { EntryEventImpl event = new EntryEventImpl(); event.setNewValue(null); event.setOperation(Operation.CREATE); CacheDistributionAdvisor advisor = createCacheDistributionAdvisor(); CacheProfile profile = createCacheProfile(); advisor.putProfile(profile, true); executor.inParallel(() -> { advisor.adviseUpdate(event); }, count); executor.execute(); assertThat(advisor.adviseAllEventsOrCached()) .contains(profile.getDistributedMember()); assertThat(advisor.adviseAllEventsOrCached()) .hasSize(1); } private CacheDistributionAdvisor createCacheDistributionAdvisor() { CacheDistributionAdvisee advisee = mock(CacheDistributionAdvisee.class); CancelCriterion cancelCriterion = mock(CancelCriterion.class); DistributionManager distributionManager = mock(DistributionManager.class); when(advisee.getCancelCriterion()).thenReturn(cancelCriterion); when(advisee.getDistributionManager()).thenReturn(distributionManager); CacheDistributionAdvisor result = CacheDistributionAdvisor.createCacheDistributionAdvisor(advisee); when(advisee.getDistributionAdvisor()).thenReturn(result); return result; } private CacheProfile createCacheProfile() throws UnknownHostException { InternalDistributedMember member = new InternalDistributedMember(getLocalHost(), 0, false, false); return new CacheProfile(member, 1); } private static <T> T mock(Class<T> classToMock) { return Mockito.mock(classToMock, withSettings().stubOnly()); } }
52f19e923eeff8c2d35a06841d8b63ceccc29474
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/1/1_16714d595deeb36f0d454ddc637c1bae695df480/ANTLRGrammarGenerator/1_16714d595deeb36f0d454ddc637c1bae695df480_ANTLRGrammarGenerator_t.java
77e3969ddd0c1370af6f29b7f2633db33e1727a4
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
84,156
java
/******************************************************************************* * Copyright (c) 2006-2010 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.generators; import static org.emftext.sdk.codegen.generators.IClassNameConstants.ANTLR_INPUT_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.ANTLR_STRING_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.ARRAY_LIST; import static org.emftext.sdk.codegen.generators.IClassNameConstants.BIT_SET; import static org.emftext.sdk.codegen.generators.IClassNameConstants.COLLECTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.COLLECTIONS; import static org.emftext.sdk.codegen.generators.IClassNameConstants.COMMON_TOKEN; import static org.emftext.sdk.codegen.generators.IClassNameConstants.COMMON_TOKEN_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.EARLY_EXIT_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.E_CLASS; import static org.emftext.sdk.codegen.generators.IClassNameConstants.E_OBJECT; import static org.emftext.sdk.codegen.generators.IClassNameConstants.E_STRUCTURAL_FEATURE; import static org.emftext.sdk.codegen.generators.IClassNameConstants.FAILED_PREDICATE_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.ILLEGAL_ARGUMENT_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.INPUT_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.INTEGER; import static org.emftext.sdk.codegen.generators.IClassNameConstants.INT_STREAM; import static org.emftext.sdk.codegen.generators.IClassNameConstants.IO_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.LINKED_HASH_SET; import static org.emftext.sdk.codegen.generators.IClassNameConstants.LIST; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MAP; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MATH; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MISMATCHED_NOT_SET_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MISMATCHED_RANGE_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MISMATCHED_SET_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MISMATCHED_TOKEN_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.MISMATCHED_TREE_NODE_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.NO_VIABLE_ALT_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.OBJECT; import static org.emftext.sdk.codegen.generators.IClassNameConstants.RECOGNITION_EXCEPTION; import static org.emftext.sdk.codegen.generators.IClassNameConstants.SET; import static org.emftext.sdk.codegen.generators.IClassNameConstants.STRING; import static org.emftext.sdk.codegen.generators.IClassNameConstants.TOKEN; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil.Copier; import org.emftext.sdk.LeftRecursionDetector; import org.emftext.sdk.codegen.EArtifact; import org.emftext.sdk.codegen.GenerationContext; import org.emftext.sdk.codegen.GenerationProblem; import org.emftext.sdk.codegen.GeneratorUtil; import org.emftext.sdk.codegen.IGenerator; import org.emftext.sdk.codegen.OptionManager; import org.emftext.sdk.codegen.GenerationProblem.Severity; import org.emftext.sdk.codegen.composites.ANTLRGrammarComposite; import org.emftext.sdk.codegen.composites.StringComponent; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.generators.code_completion.helpers.Expectation; import org.emftext.sdk.codegen.generators.code_completion.helpers.ExpectationComputer; import org.emftext.sdk.codegen.util.ConcreteSyntaxUtil; import org.emftext.sdk.codegen.util.GenClassUtil; import org.emftext.sdk.concretesyntax.Annotation; import org.emftext.sdk.concretesyntax.AnnotationType; import org.emftext.sdk.concretesyntax.Choice; import org.emftext.sdk.concretesyntax.CompleteTokenDefinition; import org.emftext.sdk.concretesyntax.CompoundDefinition; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.ConcretesyntaxPackage; import org.emftext.sdk.concretesyntax.Containment; import org.emftext.sdk.concretesyntax.CsString; import org.emftext.sdk.concretesyntax.Definition; import org.emftext.sdk.concretesyntax.LineBreak; import org.emftext.sdk.concretesyntax.OperatorAnnotationProperty; import org.emftext.sdk.concretesyntax.OptionTypes; import org.emftext.sdk.concretesyntax.Placeholder; import org.emftext.sdk.concretesyntax.Rule; import org.emftext.sdk.concretesyntax.Sequence; import org.emftext.sdk.concretesyntax.Terminal; import org.emftext.sdk.concretesyntax.WhiteSpaces; import org.emftext.sdk.finders.GenClassFinder; import org.emftext.sdk.util.EObjectUtil; import org.emftext.sdk.util.StringUtil; /** * The text parser generator maps from one or more concrete syntaxes (*.cs) and * one or more Ecore generator models to an ANTLR parser specification. If the * derived specification does not contain syntactical conflicts which could * break the ANTLR generation algorithm or the ANTLR parsing algorithm (e.g. * ambiguities in the configuration or in token definitions which are not * checked by this generator) it can be used to generate a text parser which * allows to create model instances from plain text files. * * To enable code completion the grammar is augmented with addition code. For * example, for each terminal a field is created and all terminals are connected * to their follow set. During code completion the parser runs in a special mode * (rememberExpectations=true). To derive the set of elements that can potentially * occur after the cursor, the last follow set that was added before the last * complete element is needing. Whenever an element (EObject) is complete during * parsing, the current token index (getTokenStream().index()) and the last follow * set is stored. To compute the completion proposals, this preliminary follow set * must be reduced using the token at the stored index. The remaining subset is * then queried for its follows, where the same procedure is applied again * (reduction using the next token). this is performed until the cursor position * (end of the document) is reached. * * @author Sven Karol ([email protected]) */ public class ANTLRGrammarGenerator extends BaseGenerator { /** * The name of the EOF token which can be printed to force end of file after * a parse from the root. */ public static final String EOF_TOKEN_NAME = "EOF"; private static final GenClassUtil genClassUtil = new GenClassUtil(); private ConcreteSyntax concreteSyntax; // some fully qualified names of classes that are repeatedly used private String tokenResolverFactoryClassName; private String dummyEObjectClassName; private String tokenResolveResultClassName; private String contextDependentURIFragmentFactoryClassName; private String expectedCsStringClassName; private String expectedStructuralFeatureClassName; private String iTextResourceClassName; private String iCommandClassName; private String iParseResultClassName; private String expectedTerminalClassName; private String iExpectedElementClassName; private String parseResultClassName; private String pairClassName; /** * A map that projects the fully qualified name of generator classes to the * set of fully qualified names of all their super classes. */ private Map<String, Collection<String>> genClassNames2superClassNames; private Collection<GenClass> allGenClasses; private Set<String> keywords; private GenClassFinder genClassFinder = new GenClassFinder(); private GeneratorUtil generatorUtil = new GeneratorUtil(); private ConcreteSyntaxUtil csUtil = new ConcreteSyntaxUtil(); private boolean forceEOFToken; /** * A unique ID that is assigned to each follow set while generating * the grammar. This ID is reset to zero when the grammar generation * starts and incremented by one after each follow set. */ private int followSetID; private ExpectationComputer computer = new ExpectationComputer(); /** * A map that contains the terminal elements of the syntax specification * (keywords and placeholders) to the name of the field that represents * them. */ private Map<EObject, String> idMap = new LinkedHashMap<EObject, String>(); /** * A counter that is used to indicate the next free id in 'idMap'. */ private int idCounter = 0; private int featureCounter = 0; private Map<GenFeature, String> eFeatureToConstantNameMap = new LinkedHashMap<GenFeature, String>(); /** * A map that contains names of fields representing terminals and their * follow set. This map is used to create the code that links terminals * and the potential next elements (i.e., their follow set). */ private Map<String, Set<Expectation>> followSetMap = new LinkedHashMap<String, Set<Expectation>>(); public ANTLRGrammarGenerator() { super(); } private ANTLRGrammarGenerator(GenerationContext context) { super(context, EArtifact.ANTLR_GRAMMAR); concreteSyntax = context.getConcreteSyntax(); // initialize class names tokenResolverFactoryClassName = context.getQualifiedClassName(EArtifact.TOKEN_RESOLVER_FACTORY); dummyEObjectClassName = context.getQualifiedClassName(EArtifact.DUMMY_E_OBJECT); tokenResolveResultClassName = context.getQualifiedClassName(EArtifact.TOKEN_RESOLVE_RESULT); contextDependentURIFragmentFactoryClassName = context.getQualifiedClassName(EArtifact.CONTEXT_DEPENDENT_URI_FRAGMENT_FACTORY); expectedCsStringClassName = context.getQualifiedClassName(EArtifact.EXPECTED_CS_STRING); expectedStructuralFeatureClassName = context.getQualifiedClassName(EArtifact.EXPECTED_STRUCTURAL_FEATURE); iTextResourceClassName = context.getQualifiedClassName(EArtifact.I_TEXT_RESOURCE); iCommandClassName = context.getQualifiedClassName(EArtifact.I_COMMAND); iParseResultClassName = context.getQualifiedClassName(EArtifact.I_PARSE_RESULT); expectedTerminalClassName = context.getQualifiedClassName(EArtifact.EXPECTED_TERMINAL); iExpectedElementClassName = context.getQualifiedClassName(EArtifact.I_EXPECTED_ELEMENT); parseResultClassName = getContext().getQualifiedClassName(EArtifact.PARSE_RESULT); pairClassName = getContext().getQualifiedClassName(EArtifact.PAIR); } private void initOptions() { forceEOFToken = OptionManager.INSTANCE.getBooleanOptionValue( concreteSyntax, OptionTypes.FORCE_EOF); } private void initCaches() { allGenClasses = genClassFinder.findAllGenClasses(concreteSyntax, true, true); genClassNames2superClassNames = genClassFinder.findAllSuperclasses(allGenClasses); keywords = new LinkedHashSet<String>(); List<Rule> allRules = concreteSyntax.getAllRules(); for (Rule rule : allRules) { Collection<CsString> keywordsInRule = EObjectUtil.getObjectsByType(rule.eAllContents(), ConcretesyntaxPackage.eINSTANCE.getCsString()); for (CsString nextKeyword : keywordsInRule) { keywords.add(nextKeyword.getValue()); } } } public boolean generate(PrintWriter writer) { followSetID = 0; initOptions(); initCaches(); String csName = getResourceClassName(); String lexerName = getLexerName(csName); String parserName = getParserName(csName); boolean backtracking = OptionManager.INSTANCE.getBooleanOptionValue( concreteSyntax, OptionTypes.ANTLR_BACKTRACKING); boolean memoize = OptionManager.INSTANCE.getBooleanOptionValue( concreteSyntax, OptionTypes.ANTLR_MEMOIZE); StringComposite sc = new ANTLRGrammarComposite(); sc.add("grammar " + csName + ";"); sc.addLineBreak(); sc.add("options {"); sc.add("superClass = " + getContext().getClassName(EArtifact.ANTLR_PARSER_BASE) + ";"); sc.add("backtrack = " + backtracking + ";"); sc.add("memoize = " + memoize + ";"); sc.add("}"); sc.addLineBreak(); // the lexer: package definition and error handling sc.add("@lexer::header {"); sc.add("package " + getResourcePackageName() + ";"); sc.add("}"); sc.addLineBreak(); sc.add("@lexer::members {"); sc.add("public " + LIST + "<" + RECOGNITION_EXCEPTION + "> lexerExceptions = new " + ARRAY_LIST + "<" + RECOGNITION_EXCEPTION + ">();"); sc.add("public " + LIST + "<" + INTEGER + "> lexerExceptionsPosition = new " + ARRAY_LIST + "<" + INTEGER + ">();"); sc.addLineBreak(); sc.add("public void reportError(" + RECOGNITION_EXCEPTION + " e) {"); sc.add("lexerExceptions.add(e);"); sc.add("lexerExceptionsPosition.add(((" + ANTLR_STRING_STREAM + ") input).index());"); sc.add("}"); sc.add("}"); // the parser: package definition and entry (doParse) method sc.add("@header{"); sc.add("package " + getResourcePackageName() + ";"); sc.add("}"); sc.addLineBreak(); StringComposite grammarCore = new ANTLRGrammarComposite(); addRules(grammarCore); addTokenDefinitions(grammarCore); sc.add("@members{"); addFields(sc); addMethods(lexerName, parserName, sc); addTerminalConstants(sc); sc.add("}"); sc.addLineBreak(); sc.add(grammarCore.toString()); writer.print(sc.toString()); return getCollectedErrors().isEmpty(); } private void addRules(StringComposite sc) { printStartRule(sc); EList<GenClass> eClassesWithSyntax = new BasicEList<GenClass>(); Map<GenClass, Collection<Terminal>> eClassesReferenced = new LinkedHashMap<GenClass, Collection<Terminal>>(); printGrammarRules(sc, eClassesWithSyntax, eClassesReferenced); printImplicitChoiceRules(sc, eClassesWithSyntax, eClassesReferenced); } private void addMethods(String lexerName, String parserName, StringComposite sc) { generatorUtil.addAddErrorToResourceMethod(sc, getClassNameHelper()); addAddExpectedElementMethod(sc); generatorUtil.addAddMapEntryMethod(sc, dummyEObjectClassName, getClassNameHelper()); generatorUtil.addAddObjectToListMethod(sc); addApplyMethod(sc); addCollectHiddenTokensMethod(lexerName, sc); addCopyLocalizationInfosMethod1(sc); addCopyLocalizationInfosMethod2(sc); addCreateInstanceMethod(lexerName, parserName, sc); addDefaultConstructor(parserName, sc); addDoParseMethod(lexerName, sc); generatorUtil.addGetFreshTokenResolveResultMethod(sc, tokenResolveResultClassName); addGetMismatchedTokenRecoveryTriesMethod(sc); addGetMissingSymbolMethod(sc); addGetOptionsMethod(sc); getContext().addGetMetaInformationMethod(sc); addGetParseToIndexTypeObjectMethod(sc); generatorUtil.addGetReferenceResolverSwitchMethod(getContext(), sc); addGetTypeObjectMethod(sc); addParseMethod(sc); addParseToExpectedElementsMethod(sc); addSetPositionMethod(sc); addRecoverFromMismatchedTokenMethod(sc); generatorUtil.addRegisterContextDependentProxyMethod(sc, contextDependentURIFragmentFactoryClassName, true, getClassNameHelper()); addReportErrorMethod(sc); addReportLexicalErrorsMethod(sc); addSetOptionsMethod(sc); addTerminateMethod(sc); addCompletedElementMethod(sc); } private void addGetMissingSymbolMethod(StringComposite sc) { sc.add("public " + OBJECT + " getMissingSymbol(" + INT_STREAM + " arg0, " + RECOGNITION_EXCEPTION + " arg1, int arg2, " + BIT_SET + " arg3) {"); sc.add("mismatchedTokenRecoveryTries++;"); sc.add("return super.getMissingSymbol(arg0, arg1, arg2, arg3);"); sc.add("}"); sc.addLineBreak(); } private void addGetMismatchedTokenRecoveryTriesMethod(StringComposite sc) { sc.add("public int getMismatchedTokenRecoveryTries() {"); sc.add("return mismatchedTokenRecoveryTries;"); sc.add("}"); sc.addLineBreak(); } private void addReportLexicalErrorsMethod(StringComposite sc) { sc.add("// Translates errors thrown by the lexer into human readable messages."); sc.add("public void reportLexicalError(final " + RECOGNITION_EXCEPTION + " e) {"); sc.add(STRING + " message = \"\";"); sc.add("if (e instanceof " + MISMATCHED_TOKEN_EXCEPTION + ") {"); sc.add(MISMATCHED_TOKEN_EXCEPTION + " mte = (" + MISMATCHED_TOKEN_EXCEPTION + ") e;"); sc.add("message = \"Syntax error on token \\\"\" + ((char) e.c) + \"\\\", \\\"\" + (char) mte.expecting + \"\\\" expected\";"); sc.add("} else if (e instanceof " + NO_VIABLE_ALT_EXCEPTION + ") {"); sc.add("message = \"Syntax error on token \\\"\" + ((char) e.c) + \"\\\", delete this token\";"); sc.add("} else if (e instanceof " + EARLY_EXIT_EXCEPTION + ") {"); sc.add(EARLY_EXIT_EXCEPTION + " eee = (" + EARLY_EXIT_EXCEPTION + ") e;"); sc.add("message =\"required (...)+ loop (decision=\" + eee.decisionNumber + \") did not match anything; on line \" + e.line + \":\" + e.charPositionInLine + \" char=\" + ((char) e.c) + \"'\";"); sc.add("} else if (e instanceof " + MISMATCHED_SET_EXCEPTION + ") {"); sc.add(MISMATCHED_SET_EXCEPTION + " mse = (" + MISMATCHED_SET_EXCEPTION + ") e;"); sc.add("message =\"mismatched char: '\" + ((char) e.c) + \"' on line \" + e.line + \":\" + e.charPositionInLine + \"; expecting set \" + mse.expecting;"); sc.add("} else if (e instanceof " + MISMATCHED_NOT_SET_EXCEPTION + ") {"); sc.add(MISMATCHED_NOT_SET_EXCEPTION + " mse = (" + MISMATCHED_NOT_SET_EXCEPTION + ") e;"); sc.add("message =\"mismatched char: '\" + ((char) e.c) + \"' on line \" + e.line + \":\" + e.charPositionInLine + \"; expecting set \" + mse.expecting;"); sc.add("} else if (e instanceof " + MISMATCHED_RANGE_EXCEPTION + ") {"); sc.add(MISMATCHED_RANGE_EXCEPTION + " mre = (" + MISMATCHED_RANGE_EXCEPTION + ") e;"); sc.add("message =\"mismatched char: '\" + ((char) e.c) + \"' on line \" + e.line + \":\" + e.charPositionInLine + \"; expecting set '\" + (char) mre.a + \"'..'\" + (char) mre.b + \"'\";"); sc.add("} else if (e instanceof " + FAILED_PREDICATE_EXCEPTION + ") {"); sc.add(FAILED_PREDICATE_EXCEPTION + " fpe = (" + FAILED_PREDICATE_EXCEPTION + ") e;"); sc.add("message =\"rule \" + fpe.ruleName + \" failed predicate: {\" + fpe.predicateText + \"}?\";"); sc.add("}"); sc.add("addErrorToResource(message, e.index, e.line, lexerExceptionsPosition.get(lexerExceptions.indexOf(e)), lexerExceptionsPosition.get(lexerExceptions.indexOf(e)));"); sc.add("}"); sc.addLineBreak(); } private void addReportErrorMethod(StringComposite sc) { sc.add("// Translates errors thrown by the parser into human readable messages."); sc.add("public void reportError(final " + RECOGNITION_EXCEPTION + " e) {"); sc.add(STRING + " message = e.getMessage();"); sc.add("if (e instanceof " + MISMATCHED_TOKEN_EXCEPTION + ") {"); sc.add(MISMATCHED_TOKEN_EXCEPTION + " mte = (" + MISMATCHED_TOKEN_EXCEPTION + ") e;"); sc.add(STRING + " tokenName = \"<unknown>\";"); sc.add("if (mte.expecting == Token.EOF) {"); sc.add("tokenName = \"EOF\";"); sc.add("} else {"); sc.add("tokenName = getTokenNames()[mte.expecting];"); sc.add("tokenName = " + getClassNameHelper().getSTRING_UTIL() + ".formatTokenName(tokenName);"); sc.add("}"); sc.add("message = \"Syntax error on token \\\"\" + e.token.getText() + \"\\\", \\\"\" + tokenName + \"\\\" expected\";"); sc.add("} else if (e instanceof " + MISMATCHED_TREE_NODE_EXCEPTION + ") {"); sc.add(MISMATCHED_TREE_NODE_EXCEPTION + " mtne = (" + MISMATCHED_TREE_NODE_EXCEPTION + ") e;"); sc.add(STRING + " tokenName = \"<unknown>\";"); sc.add("if (mtne.expecting == Token.EOF) {"); sc.add("tokenName = \"EOF\";"); sc.add("} else {"); sc.add("tokenName = getTokenNames()[mtne.expecting];"); sc.add("}"); sc.add("message = \"mismatched tree node: \"+\"xxx\" +\"; expecting \" + tokenName;"); sc.add("} else if (e instanceof " + NO_VIABLE_ALT_EXCEPTION + ") {"); sc.add("message = \"Syntax error on token \\\"\" + e.token.getText() + \"\\\", check following tokens\";"); sc.add("} else if (e instanceof " + EARLY_EXIT_EXCEPTION + ") {"); sc.add("message = \"Syntax error on token \\\"\" + e.token.getText() + \"\\\", delete this token\";"); sc.add("} else if (e instanceof " + MISMATCHED_SET_EXCEPTION + ") {"); sc.add(MISMATCHED_SET_EXCEPTION + " mse = (" + MISMATCHED_SET_EXCEPTION + ") e;"); sc.add("message = \"mismatched token: \" + e.token + \"; expecting set \" + mse.expecting;"); sc.add("} else if (e instanceof " + MISMATCHED_NOT_SET_EXCEPTION + ") {"); sc.add(MISMATCHED_NOT_SET_EXCEPTION + " mse = (" + MISMATCHED_NOT_SET_EXCEPTION + ") e;"); sc.add("message = \"mismatched token: \" + e.token + \"; expecting set \" + mse.expecting;"); sc.add("} else if (e instanceof " + FAILED_PREDICATE_EXCEPTION + ") {"); sc.add(FAILED_PREDICATE_EXCEPTION + " fpe = (" + FAILED_PREDICATE_EXCEPTION + ") e;"); sc.add("message = \"rule \" + fpe.ruleName + \" failed predicate: {\" + fpe.predicateText+\"}?\";"); sc.add("}"); sc.add("// the resource may be null if the parse is used for code completion"); sc.add("final " + STRING + " finalMessage = message;"); sc.add("if (e.token instanceof " + COMMON_TOKEN + ") {"); sc.add("final " + COMMON_TOKEN + " ct = (" + COMMON_TOKEN + ") e.token;"); sc.add("addErrorToResource(finalMessage, ct.getCharPositionInLine(), ct.getLine(), ct.getStartIndex(), ct.getStopIndex());"); sc.add("} else {"); // TODO what the heck is this 5? sc.add("addErrorToResource(finalMessage, e.token.getCharPositionInLine(), e.token.getLine(), 1, 5);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addTerminateMethod(StringComposite sc) { sc.add("public void terminate() {"); sc.add("terminateParsing = true;"); sc.add("}"); sc.addLineBreak(); } private void addParseMethod(StringComposite sc) { sc.add("// Implementation that calls {@link #doParse()} and handles the thrown"); sc.add("// RecognitionExceptions."); sc.add("public " + getClassNameHelper().getI_PARSE_RESULT() + " parse() {"); sc.add("terminateParsing = false;"); sc.add("postParseCommands = new " + ARRAY_LIST + "<" + getClassNameHelper().getI_COMMAND() + "<" + getClassNameHelper().getI_TEXT_RESOURCE() + ">>();"); sc.add(parseResultClassName + " parseResult = new " + parseResultClassName + "();"); sc.add("try {"); sc.add(E_OBJECT + " result = doParse();"); sc.add("if (lexerExceptions.isEmpty()) {"); sc.add("parseResult.setRoot(result);"); sc.add("}"); sc.add("} catch (" + RECOGNITION_EXCEPTION + " re) {"); sc.add("reportError(re);"); sc.add("} catch (" + ILLEGAL_ARGUMENT_EXCEPTION + " iae) {"); sc.add("if (\"The 'no null' constraint is violated\".equals(iae.getMessage())) {"); sc.add("//? can be caused if a null is set on EMF models where not allowed;"); sc.add("//? this will just happen if other errors occurred before"); sc.add("} else {"); sc.add("iae.printStackTrace();"); sc.add("}"); sc.add("}"); sc.add("for (" + RECOGNITION_EXCEPTION + " re : lexerExceptions) {"); sc.add("reportLexicalError(re);"); sc.add("}"); sc.add("parseResult.getPostParseCommands().addAll(postParseCommands);"); sc.add("return parseResult;"); sc.add("}"); sc.addLineBreak(); } private void addApplyMethod(StringComposite sc) { sc.add("protected " + E_OBJECT + " apply(" + E_OBJECT + " target, " + LIST + "<" + E_OBJECT + "> dummyEObjects) {"); sc.add(E_OBJECT + " currentTarget = target;"); sc.add("for (" + E_OBJECT + " object : dummyEObjects) {"); sc.add("assert(object instanceof " + dummyEObjectClassName + ");"); sc.add(dummyEObjectClassName + " dummy = (" + dummyEObjectClassName + ") object;"); sc.add(E_OBJECT + " newEObject = dummy.applyTo(currentTarget);"); sc.add("currentTarget = newEObject;"); sc.add("}"); sc.add("return currentTarget;"); sc.add("}"); sc.addLineBreak(); } private void addCompletedElementMethod(StringComposite sc) { sc.add("protected void completedElement(Object element) {"); sc.add("if (element instanceof " + E_OBJECT + ") {"); sc.add("this.tokenIndexOfLastCompleteElement = getTokenStream().index();"); sc.add("this.expectedElementsIndexOfLastCompleteElement = expectedElements.size() - 1;"); // TODO mseifert: remove this debug output //sc.add("System.out.println(\"COMPLETED : \" + element + \" TOKEN INDEX = \" + tokenIndexOfLastCompleteElement + \" EXP INDEX = \" + expectedElementsIndexOfLastCompleteElement);"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addGetOptionsMethod(StringComposite sc) { sc.add("protected " + MAP + "<?,?> getOptions() {"); sc.add("return options;"); sc.add("}"); sc.addLineBreak(); } private void addSetOptionsMethod(StringComposite sc) { sc.add("public void setOptions(" + MAP + "<?,?> options) {"); sc.add("this.options = options;"); sc.add("}"); sc.addLineBreak(); } private void addDefaultConstructor(String parserName, StringComposite sc) { sc.add("// This default constructor is only used to call createInstance() on it"); sc.add("public " + parserName + "() {"); sc.add("super(null);"); sc.add("}"); sc.addLineBreak(); } private void addGetTypeObjectMethod(StringComposite sc) { sc.add("protected " + OBJECT + " getTypeObject() {"); sc.add(OBJECT + " typeObject = getParseToIndexTypeObject();"); sc.add("if (typeObject != null) {"); sc.add("return typeObject;"); sc.add("}"); sc.add(MAP + "<?,?> options = getOptions();"); sc.add("if (options != null) {"); sc.add("typeObject = options.get(" + getClassNameHelper().getI_OPTIONS() + ".RESOURCE_CONTENT_TYPE);"); sc.add("}"); sc.add("return typeObject;"); sc.add("}"); sc.addLineBreak(); } private void addDoParseMethod(String lexerName, StringComposite sc) { sc.add("protected " + E_OBJECT + " doParse() throws " + RECOGNITION_EXCEPTION + " {"); sc.add("this.lastPosition = 0;"); sc.add("// required because the lexer class can not be subclassed"); sc.add("((" + lexerName + ") getTokenStream().getTokenSource()).lexerExceptions = lexerExceptions;"); sc.add("((" + lexerName + ") getTokenStream().getTokenSource()).lexerExceptionsPosition = lexerExceptionsPosition;"); sc.add(OBJECT + " typeObject = getTypeObject();"); sc.add("if (typeObject == null) {"); sc.add("return start();"); sc.add("} else if (typeObject instanceof " + E_CLASS + ") {"); sc.add(E_CLASS + " type = (" + E_CLASS + ") typeObject;"); for (Rule rule : concreteSyntax.getAllRules()) { // operator rules cannot be used as start symbol // TODO mseifert: check whether this is checked by a post processor if (rule.getOperatorAnnotation() == null) { String qualifiedClassName = genClassFinder.getQualifiedInterfaceName(rule.getMetaclass()); String ruleName = getRuleName(rule.getMetaclass()); sc.add("if (type.getInstanceClass() == " + qualifiedClassName + ".class) {"); sc.add("return " + ruleName + "();"); sc.add("}"); } } sc.add("}"); sc.add("throw new " + getClassNameHelper().getUNEXPECTED_CONTENT_TYPE_EXCEPTION() + "(typeObject);"); sc.add("}"); sc.addLineBreak(); } private void addCollectHiddenTokensMethod(String lexerName, StringComposite sc) { List<CompleteTokenDefinition> collectTokenDefinitions = collectCollectTokenDefinitions(concreteSyntax.getActiveTokens()); sc.add("protected void collectHiddenTokens(" + E_OBJECT + " element) {"); if (!collectTokenDefinitions.isEmpty()) { // sc.add("System.out.println(\"collectHiddenTokens(\" + element.getClass().getSimpleName() + \", \" + o + \") \");"); sc.add("int currentPos = getTokenStream().index();"); sc.add("if (currentPos == 0) {"); sc.add("return;"); sc.add("}"); sc.add("int endPos = currentPos - 1;"); sc.add("for (; endPos >= this.lastPosition; endPos--) {"); sc.add(TOKEN + " token = getTokenStream().get(endPos);"); sc.add("int _channel = token.getChannel();"); sc.add("if (_channel != 99) {"); sc.add("break;"); sc.add("}"); sc.add("}"); sc.add("for (int pos = this.lastPosition; pos < endPos; pos++) {"); sc.add(TOKEN + " token = getTokenStream().get(pos);"); sc.add("int _channel = token.getChannel();"); sc.add("if (_channel == 99) {"); // sc.add("System.out.println(\"\t\" + token);"); for (CompleteTokenDefinition tokenDefinition : collectTokenDefinitions) { String attributeName = tokenDefinition.getAttributeName(); // figure out which feature the token belongs to sc.add("if (token.getType() == " + lexerName + "." + tokenDefinition.getName() + ") {"); // Unfortunately, we must use the feature name instead of the // constant here, // because collect-in tokens can be stored in arbitrary classes. // Therefore, // we do not know the EClass of the element at generation time. sc.add(E_STRUCTURAL_FEATURE + " feature = element.eClass().getEStructuralFeature(\"" + attributeName + "\");"); sc.add("if (feature != null) {"); sc.add("// call token resolver"); String identifierPrefix = "resolved"; String resolverIdentifier = identifierPrefix + "Resolver"; String resolvedObjectIdentifier = identifierPrefix + "Object"; String resolveResultIdentifier = identifierPrefix + "Result"; sc .add(getClassNameHelper().getI_TOKEN_RESOLVER() + " " + resolverIdentifier + " = tokenResolverFactory.createCollectInTokenResolver(\"" + attributeName + "\");"); sc.add(resolverIdentifier + ".setOptions(getOptions());"); sc.add(getClassNameHelper().getI_TOKEN_RESOLVE_RESULT() + " " + resolveResultIdentifier + " = getFreshTokenResolveResult();"); sc.add(resolverIdentifier + ".resolve(token.getText(), feature, " + resolveResultIdentifier + ");"); sc.add(OBJECT + " " + resolvedObjectIdentifier + " = " + resolveResultIdentifier + ".getResolvedToken();"); sc.add("if (" + resolvedObjectIdentifier + " == null) {"); sc.add("addErrorToResource(" + resolveResultIdentifier + ".getErrorMessage(), ((" + COMMON_TOKEN + ") token).getLine(), ((" + COMMON_TOKEN + ") token).getCharPositionInLine(), ((" + COMMON_TOKEN + ") token).getStartIndex(), ((" + COMMON_TOKEN + ") token).getStopIndex());\n"); sc.add("}"); sc.add("if (java.lang.String.class.isInstance(" + resolvedObjectIdentifier + ")) {"); sc.add("((" + LIST + ") element.eGet(feature)).add((java.lang.String) " + resolvedObjectIdentifier + ");"); sc.add("} else {"); sc .add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" has wrong type in element \" + element + \" (expected java.lang.String).\");"); sc.add("}"); sc.add("} else {"); sc .add("System.out.println(\"WARNING: Attribute " + attributeName + " for token \" + token + \" was not found in element \" + element + \".\");"); sc.add("}"); sc.add("}"); } sc.add("}"); sc.add("}"); sc.add("this.lastPosition = (endPos < 0 ? 0 : endPos);"); } sc.add("}"); sc.addLineBreak(); } private void addCreateInstanceMethod(String lexerName, String parserName, StringComposite sc) { sc.add("public " + getClassNameHelper().getI_TEXT_PARSER() + " createInstance(" + INPUT_STREAM + " actualInputStream, " + STRING + " encoding) {"); sc.add("try {"); sc.add("if (encoding == null) {"); sc.add("return new " + parserName + "(new " + COMMON_TOKEN_STREAM + "(new " + lexerName + "(new " + ANTLR_INPUT_STREAM + "(actualInputStream))));"); sc.add("} else {"); sc.add("return new " + parserName + "(new " + COMMON_TOKEN_STREAM + "(new " + lexerName + "(new " + ANTLR_INPUT_STREAM + "(actualInputStream, encoding))));"); sc.add("}"); sc.add("} catch (" + IO_EXCEPTION + " e) {"); sc.add(getClassNameHelper().getPLUGIN_ACTIVATOR() + ".logError(\"Error while creating parser.\", e);"); sc.add("return null;"); sc.add("}"); sc.add("}"); sc.addLineBreak(); } private void addFields(StringComposite sc) { sc.add("private " + getClassNameHelper().getI_TOKEN_RESOLVER_FACTORY() + " tokenResolverFactory = new " + tokenResolverFactoryClassName + "();"); sc.add("@SuppressWarnings(\"unused\")"); sc.addLineBreak(); sc.add("private int lastPosition;"); sc.add("private " + tokenResolveResultClassName + " tokenResolveResult = new " + tokenResolveResultClassName + "();"); sc.add("private boolean rememberExpectedElements = false;"); sc.add("private " + OBJECT + " parseToIndexTypeObject;"); sc.add("private int lastTokenIndex = 0;"); sc.add("private " + LIST + "<" + expectedTerminalClassName + "> expectedElements = new " + ARRAY_LIST + "<" + expectedTerminalClassName + ">();"); sc.add("private int mismatchedTokenRecoveryTries = 0;"); sc.add("private " + MAP + "<?, ?> options;"); sc.add("//helper lists to allow a lexer to pass errors to its parser"); sc.add("protected " + LIST + "<" + RECOGNITION_EXCEPTION + "> lexerExceptions = " + COLLECTIONS + ".synchronizedList(new " + ARRAY_LIST + "<" + RECOGNITION_EXCEPTION + ">());"); sc.add("protected " + LIST + "<" + INTEGER + "> lexerExceptionsPosition = " + COLLECTIONS + ".synchronizedList(new " + ARRAY_LIST + "<" + INTEGER + ">());"); sc.add("private int stopIncludingHiddenTokens;"); sc.add("private int stopExcludingHiddenTokens;"); sc.add("private " + COLLECTION + "<" + getClassNameHelper().getI_COMMAND() + "<" + getClassNameHelper().getI_TEXT_RESOURCE() + ">> postParseCommands;"); sc.add("private boolean terminateParsing;"); sc.add("private int tokenIndexOfLastCompleteElement;"); sc.add("private int expectedElementsIndexOfLastCompleteElement;"); sc.addLineBreak(); } private void addParseToExpectedElementsMethod(StringComposite sc) { sc.add("public " + LIST + "<" + expectedTerminalClassName + "> parseToExpectedElements(" + E_CLASS + " type, " + iTextResourceClassName + " dummyResource) {"); sc.add("rememberExpectedElements = true;"); sc.add("parseToIndexTypeObject = type;"); sc.add("final " + COMMON_TOKEN_STREAM + " tokenStream = (" + COMMON_TOKEN_STREAM + ") getTokenStream();"); sc.add(iParseResultClassName + " result = parse();"); sc.add("if (result != null) {"); sc.add(E_OBJECT + " root = result.getRoot();"); sc.add("if (root != null) {"); sc.add("dummyResource.getContents().add(root);"); sc.add("}"); sc.add("for (" + iCommandClassName + "<" + iTextResourceClassName + "> command : result.getPostParseCommands()) {"); sc.add("command.execute(dummyResource);"); sc.add("}"); sc.add("}"); sc.add("// remove all expected elements that were added after the last complete element"); sc.add("expectedElements = expectedElements.subList(0, expectedElementsIndexOfLastCompleteElement + 1);"); sc.add("int lastFollowSetID = expectedElements.get(expectedElementsIndexOfLastCompleteElement).getFollowSetID();"); sc.add(SET + "<" + expectedTerminalClassName + "> currentFollowSet = new " + LINKED_HASH_SET +"<" + expectedTerminalClassName + ">();"); sc.add(LIST + "<" + expectedTerminalClassName + "> newFollowSet = new " + ARRAY_LIST +"<" + expectedTerminalClassName + ">();"); sc.add("for (int i = expectedElementsIndexOfLastCompleteElement; i >= 0; i--) {"); sc.add(expectedTerminalClassName + " expectedElementI = expectedElements.get(i);"); sc.add("if (expectedElementI.getFollowSetID() == lastFollowSetID) {"); sc.add("System.out.println(\"FOLLOW ELEMENT \" + expectedElementI);"); sc.add("currentFollowSet.add(expectedElementI);"); sc.add("} else {"); sc.add("break;"); sc.add("}"); sc.add("}"); // now the follow set IDs must be calculated dynamically sc.add("int followSetID = " + followSetID + ";"); sc.add("int i;"); sc.add("for (i = tokenIndexOfLastCompleteElement; i < tokenStream.size(); i++) {"); sc.add(COMMON_TOKEN + " nextToken = (" + COMMON_TOKEN + ") tokenStream.get(i);"); sc.add("System.out.println(\"REMAINING TOKEN: \" + nextToken);"); sc.add("if (nextToken.getChannel() == 99) {"); sc.add("// hidden tokens do not reduce the follow set"); sc.add("} else {"); sc.add("// now that we have found the next visible token the position for that expected terminals"); sc.add("// can be set"); sc.add("for (" + expectedTerminalClassName + " nextFollow : newFollowSet) {"); // TODO this is somewhat inefficient since the token stream is searched from // the beginning sc.add("lastTokenIndex = 0;"); sc.add("setPosition(nextFollow, i);"); sc.add("}"); sc.add("newFollowSet.clear();"); sc.add("// normal tokens do reduce the follow set - only elements that match the token are kept"); sc.add("for (" + expectedTerminalClassName + " nextFollow : currentFollowSet) {"); sc.add("System.out.println(\"CHECKING : \" + nextFollow);"); sc.add("if (nextFollow.getTerminal().getTokenName().equals(getTokenNames()[nextToken.getType()])) {"); sc.add("// keep this one - it matches"); sc.add("System.out.println(\"MATCH! \" + nextFollow);"); sc.add(COLLECTION + "<" + pairClassName + "<" + iExpectedElementClassName + ", " + E_STRUCTURAL_FEATURE + "[]>> newFollowers = nextFollow.getTerminal().getFollowers();"); sc.add("for (" + pairClassName + "<" + iExpectedElementClassName + ", " + E_STRUCTURAL_FEATURE + "[]> newFollowerPair : newFollowers) {"); sc.add(iExpectedElementClassName + " newFollower = newFollowerPair.getLeft();"); sc.add(expectedTerminalClassName + " newFollowTerminal = new " + expectedTerminalClassName + "(newFollower, followSetID, newFollowerPair.getRight());"); sc.add("newFollowSet.add(newFollowTerminal);"); sc.add("expectedElements.add(newFollowTerminal);"); sc.add("}"); sc.add("}"); sc.add("}"); sc.add("currentFollowSet.clear();"); sc.add("currentFollowSet.addAll(newFollowSet);"); sc.add("}"); sc.add("followSetID++;"); sc.add("}"); sc.add("// after the last token in the stream we must set the position for the elements that were"); sc.add("// added during the last iteration of the loop"); sc.add("for (" + expectedTerminalClassName + " nextFollow : newFollowSet) {"); // TODO this is somewhat inefficient since the token stream is searched from // the beginning sc.add("lastTokenIndex = 0;"); sc.add("setPosition(nextFollow, i);"); sc.add("}"); sc.add("return this.expectedElements;"); sc.add("}"); sc.addLineBreak(); } private void addCopyLocalizationInfosMethod1(StringComposite sc) { sc.add("protected void copyLocalizationInfos(final " + E_OBJECT + " source, final " + E_OBJECT + " target) {"); sc.add("postParseCommands.add(new " + getClassNameHelper().getI_COMMAND() + "<" + getClassNameHelper().getI_TEXT_RESOURCE() + ">() {"); sc.add("public boolean execute(" + getClassNameHelper().getI_TEXT_RESOURCE() + " resource) {"); sc.add(getClassNameHelper().getI_LOCATION_MAP() + " locationMap = resource.getLocationMap();"); sc.add("if (locationMap == null) {"); sc.add("// the locationMap can be null if the parser is used for"); sc.add("// code completion"); sc.add("return true;"); sc.add("}"); sc.add("locationMap.setCharStart(target, locationMap.getCharStart(source));"); sc.add("locationMap.setCharEnd(target, locationMap.getCharEnd(source));"); sc.add("locationMap.setColumn(target, locationMap.getColumn(source));"); sc.add("locationMap.setLine(target, locationMap.getLine(source));"); sc.add("return true;"); sc.add("}"); sc.add("});"); sc.add("}"); sc.addLineBreak(); } private void addCopyLocalizationInfosMethod2(StringComposite sc) { sc.add("protected void copyLocalizationInfos(final " + COMMON_TOKEN + " source, final " + E_OBJECT + " target) {"); sc.add("postParseCommands.add(new " + getClassNameHelper().getI_COMMAND() + "<" + getClassNameHelper().getI_TEXT_RESOURCE() + ">() {"); sc.add("public boolean execute(" + getClassNameHelper().getI_TEXT_RESOURCE() + " resource) {"); sc.add(getClassNameHelper().getI_LOCATION_MAP() + " locationMap = resource.getLocationMap();"); sc.add("if (locationMap == null) {"); sc.add("// the locationMap can be null if the parser is used for"); sc.add("// code completion"); sc.add("return true;"); sc.add("}"); sc.add("if (source == null) {"); sc.add("return true;"); sc.add("}"); sc.add("locationMap.setCharStart(target, source.getStartIndex());"); sc.add("locationMap.setCharEnd(target, source.getStopIndex());"); sc.add("locationMap.setColumn(target, source.getCharPositionInLine());"); sc.add("locationMap.setLine(target, source.getLine());"); sc.add("return true;"); sc.add("}"); sc.add("});"); sc.add("}"); sc.addLineBreak(); } private void addAddExpectedElementMethod(StringComposite sc) { // TODO potential memory consumption improvement: // we can throw away expected elements that are not important // for the current parse run. the concrete set of element that // can be thrown away is determined by the cursor index where // code completion is requested sc.add("public void addExpectedElement(" + expectedTerminalClassName + " expectedElement) {"); sc.add("if (!this.rememberExpectedElements) {"); sc.add("return;"); sc.add("}"); sc.add("setPosition(expectedElement, input.index());"); //sc.add("System.out.println(\"Adding expected element (\" + message + \"): \" + expectedElement + \"\");"); sc.add("this.expectedElements.add(expectedElement);"); sc.add("}"); sc.addLineBreak(); } private void addSetPositionMethod(StringComposite sc) { sc.add("public void setPosition(" + expectedTerminalClassName + " expectedElement, int tokenIndex) {"); sc.add("int currentIndex = " + MATH + ".max(0, tokenIndex);"); sc.add("for (int index = lastTokenIndex; index < currentIndex; index++) {"); sc.add("if (index >= input.size()) {"); sc.add("break;"); sc.add("}"); sc.add(COMMON_TOKEN + " tokenAtIndex = (" + COMMON_TOKEN + ") input.get(index);"); sc.add("stopIncludingHiddenTokens = tokenAtIndex.getStopIndex() + 1;"); sc.add("if (tokenAtIndex.getChannel() != 99) {"); sc.add("stopExcludingHiddenTokens = tokenAtIndex.getStopIndex() + 1;"); sc.add("}"); sc.add("}"); sc.add("lastTokenIndex = " + MATH + ".max(0, currentIndex);"); sc.add("expectedElement.setPosition(stopExcludingHiddenTokens, stopIncludingHiddenTokens);"); sc.add("}"); sc.addLineBreak(); } private void addGetParseToIndexTypeObjectMethod(StringComposite sc) { sc.add("public " + OBJECT + " getParseToIndexTypeObject() {"); sc.add("return parseToIndexTypeObject;"); sc.add("}"); sc.addLineBreak(); } private void addRecoverFromMismatchedTokenMethod(StringComposite sc) { sc.add("public " + OBJECT + " recoverFromMismatchedToken(" + INT_STREAM + " input, int ttype, " + BIT_SET + " follow) throws " + RECOGNITION_EXCEPTION + " {"); sc.add("if (!rememberExpectedElements) {"); sc.add("return super.recoverFromMismatchedToken(input, ttype, follow);"); sc.add("} else {"); sc.add("return null;"); sc.add("}"); sc.add("}"); } private List<CompleteTokenDefinition> collectCollectTokenDefinitions( List<CompleteTokenDefinition> tokenDefinitions) { List<CompleteTokenDefinition> collectList = new LinkedList<CompleteTokenDefinition>(); for (CompleteTokenDefinition tokenDefinition : tokenDefinitions) { String attributeName = tokenDefinition.getAttributeName(); if (attributeName != null) { collectList.add(tokenDefinition); } } return collectList; } private String getLexerName(String csName) { return csName + "Lexer"; } private String getParserName(String csName) { return csName + "Parser"; } private void printStartRule(StringComposite sc) { ConcreteSyntax syntax = getContext().getConcreteSyntax(); // do the start symbol rule sc.add("start "); sc.add("returns [ " + E_OBJECT + " element = null]"); sc.add(":"); sc.add("{"); Set<Expectation> expectations = new LinkedHashSet<Expectation>(); for (GenClass startSymbol : concreteSyntax.getActiveStartSymbols()) { Collection<Rule> startRules = csUtil.getRules(concreteSyntax, startSymbol); for (Rule startRule : startRules) { Set<Expectation> firstSet = computer.computeFirstSet(syntax, startRule); firstSet.remove(ExpectationComputer.EPSILON); expectations.addAll(firstSet); } } sc.add("// follow set for start rule(s)"); addExpectationsCode(sc, expectations); sc.add("expectedElementsIndexOfLastCompleteElement = expectedElements.size() - 1;"); sc.add("}"); sc.add("("); int count = 0; int i = 0; for (GenClass startSymbol : concreteSyntax.getActiveStartSymbols()) { // there may also be rules for subclasses of the start symbol class // thus, we create an alternative for each rule Collection<Rule> startRules = csUtil.getRules(concreteSyntax, startSymbol); for (Rule startRule : startRules) { if (count > 0) { sc.add("| "); } i++; sc.add("c" + count + " = " + getRuleName(startRule.getMetaclass()) + "{ element = c" + count + "; }"); count++; } } sc.add(")"); if (forceEOFToken) { sc.add(EOF_TOKEN_NAME); } sc.addLineBreak(); sc.add(";"); sc.addLineBreak(); } private void printRightRecursion(StringComposite sc, Rule rule, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> classesReferenced) { String ruleName = getRuleName(rule.getMetaclass()); GenClass recursiveType = rule.getMetaclass(); { Copier copier = new Copier(true, true); Rule ruleCopy = (Rule) copier.copy(rule); copier.copyReferences(); sc.add(ruleName); sc.add(" returns [" + genClassFinder.getQualifiedInterfaceName(recursiveType) + " element = null]"); sc.add("@init{"); sc.add("element = " + genClassUtil.getCreateObjectCall(recursiveType, dummyEObjectClassName) + ";"); sc.add("collectHiddenTokens(element);"); sc.add(LIST + "<" + E_OBJECT + "> dummyEObjects = new " + ARRAY_LIST + "<" + E_OBJECT + ">();"); sc.add("}"); sc.add(":"); Choice choice = ConcretesyntaxPackage.eINSTANCE .getConcretesyntaxFactory().createChoice(); Sequence newSequence = ConcretesyntaxPackage.eINSTANCE .getConcretesyntaxFactory().createSequence(); Choice reducedChoice = ConcretesyntaxPackage.eINSTANCE .getConcretesyntaxFactory().createChoice(); CompoundDefinition compound = ConcretesyntaxPackage.eINSTANCE .getConcretesyntaxFactory().createCompoundDefinition(); compound.setDefinitions(reducedChoice); newSequence.getParts().add(compound); choice.getOptions().add(newSequence); List<Sequence> recursionFreeSequences = new ArrayList<Sequence>(); LeftRecursionDetector lrd = new LeftRecursionDetector( genClassNames2superClassNames, concreteSyntax); for (Sequence sequence : ruleCopy.getDefinition().getOptions()) { Rule leftProducingRule = lrd.findLeftProducingRule(rule .getMetaclass(), sequence, rule); if (leftProducingRule == null) { recursionFreeSequences.add(sequence); } } reducedChoice.getOptions().addAll(recursionFreeSequences); ruleCopy.setDefinition(choice); printChoice(ruleCopy.getDefinition(), ruleCopy, sc, 0, classesReferenced, "0"); sc.add(" ( dummyEObject = " + ruleName + "_tail { dummyEObjects.add(dummyEObject);} )*"); sc.add("{"); sc.add("element = (" + ruleName + ") apply(element, dummyEObjects);"); sc.add("}"); sc.add(";"); sc.addLineBreak(); } { Rule tailCopy = rule; EList<Sequence> options = tailCopy.getDefinition().getOptions(); String recurseName = ""; List<Sequence> sequencesToRemove = new ArrayList<Sequence>(); for (Sequence sequence : options) { int indexRecurse = 0; EList<Definition> parts = sequence.getParts(); for (Definition definition : parts) { if (definition instanceof Containment) { Containment containment = (Containment) definition; GenFeature feature = containment.getFeature(); GenClass featureType = feature.getTypeGenClass(); if (recursiveType.equals(featureType) || genClassNames2superClassNames .get( genClassFinder .getQualifiedInterfaceName(featureType)) .contains( genClassFinder .getQualifiedInterfaceName(recursiveType)) || genClassNames2superClassNames .get( genClassFinder .getQualifiedInterfaceName(recursiveType)) .contains( genClassFinder .getQualifiedInterfaceName(featureType))) { indexRecurse = parts.indexOf(definition); recurseName = feature.getName(); break; } } } if (parts.size() - 1 == indexRecurse) { sequencesToRemove.add(sequence); } else { for (int i = 0; i <= indexRecurse; i++) { parts.remove(i); } } } for (Sequence sequence : sequencesToRemove) { tailCopy.getDefinition().getOptions().remove(sequence); } sc.add(ruleName + "_tail"); sc.add(" returns [" + dummyEObjectClassName + " element = null]"); sc.add("@init{"); sc.add("element = new " + dummyEObjectClassName + "(" + genClassUtil.getCreateObjectCall(rule.getMetaclass(), dummyEObjectClassName) + "()" + ", \"" + recurseName + "\");"); sc.add("collectHiddenTokens(element);"); sc.add("}"); sc.add(":"); printChoice(tailCopy.getDefinition(), tailCopy, sc, 0, classesReferenced, "0"); sc.add(";"); sc.addLineBreak(); } eClassesWithSyntax.add(rule.getMetaclass()); } private void printGrammarRules(StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> eClassesReferenced) { for (Rule rule : concreteSyntax.getAllRules()) { // operator rules must be handled separately if (concreteSyntax.getOperatorRules().contains(rule)) { continue; } LeftRecursionDetector lrd = new LeftRecursionDetector( genClassNames2superClassNames, concreteSyntax); Rule recursionRule = lrd.findLeftRecursion(rule); if (recursionRule != null) { boolean autofix = OptionManager.INSTANCE.getBooleanOptionValue( concreteSyntax, OptionTypes.AUTOFIX_SIMPLE_LEFTRECURSION); if (lrd.isDirectLeftRecursive(rule)) {// direct left recursion if (autofix) { printRightRecursion(sc, rule, eClassesWithSyntax, eClassesReferenced); Collection<GenClass> subClasses = csUtil .getSubClassesWithSyntax(rule.getMetaclass(), concreteSyntax); if (!subClasses.isEmpty()) { sc.add("|//derived choice rules for sub-classes: "); printSubClassChoices(sc, subClasses); sc.addLineBreak(); } String message = "Applied experimental autofix: Rule \"" + rule.getMetaclass().getName() + "\" is direct left recursive by rule \"" + recursionRule.getMetaclass().getName() + "\"."; GenerationProblem generationWarning = new GenerationProblem( message, rule, Severity.WARNING); addProblem(generationWarning); continue; } else { String message = "Warning: Rule \"" + rule.getMetaclass().getName() + "\" is direct left recursive by rule \"" + recursionRule.getMetaclass().getName() + "\"."; GenerationProblem generationWarning = new GenerationProblem( message, rule, Severity.WARNING); addProblem(generationWarning); printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced); } } else { String message = "Rule \"" + rule.getMetaclass().getName() + "\" is mutual left recursive by rule \"" + recursionRule.getMetaclass().getName() + "\"! Please restructure the grammar."; GenerationProblem generationWarning = new GenerationProblem( message, rule, Severity.WARNING); addProblem(generationWarning); printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced); } } else { printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced); } } // handle operator rules if (!concreteSyntax.getOperatorRules().isEmpty()) { for (String expressionIdent : concreteSyntax.getOperatorRuleSubsets()) { EList<Rule> expressionSubset = concreteSyntax.getOperatorRuleSubset(expressionIdent); printGrammarExpressionSlice(expressionSubset, sc, eClassesWithSyntax, eClassesReferenced); } } } private void printGrammarRulePrefix(GenClass genClass, String ruleName, StringComposite sc) { String qualifiedClassName = genClassFinder .getQualifiedInterfaceName(genClass); sc.add(ruleName); if (Map.Entry.class.getName().equals( genClass.getEcoreClass().getInstanceClassName())) { sc.add(" returns [" + dummyEObjectClassName + " element = null]"); } else { sc.add(" returns [" + qualifiedClassName + " element = null]"); } sc.add("@init{"); sc.add("}"); sc.add(":"); } private void printGrammarRuleSuffix(StringComposite sc) { sc.add(";"); sc.addLineBreak(); } private void printGrammarRule(Rule rule, StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> eClassesReferenced) { GenClass genClass = rule.getMetaclass(); String ruleName = getRuleName(genClass); printGrammarRulePrefix(genClass,ruleName,sc); printChoice(rule.getDefinition(), rule, sc, 0, eClassesReferenced, "0"); Collection<GenClass> subClasses = csUtil .getSubClassesWithSyntax(genClass, concreteSyntax); if (!subClasses.isEmpty()) { sc.add("|//derived choice rules for sub-classes: "); sc.addLineBreak(); printSubClassChoices(sc, subClasses); sc.addLineBreak(); } printGrammarRuleSuffix(sc); eClassesWithSyntax.add(genClass); } // TODO mseifert: split this method into smaller ones private void printGrammarExpressionSlice(List<Rule> slice, StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> eClassesReferenced) { ListIterator<Rule> it = slice.listIterator(); while (it.hasNext()) { //TODO: Add a check that all equal weight rules are equally structured Rule firstRule = it.next(); int weight = firstRule.getOperatorWeight(); List<Rule> equalWeightOPs = new LinkedList<Rule>(); equalWeightOPs.add(firstRule); while (it.hasNext()) { Rule currentRule = it.next(); int currentWeight = currentRule.getOperatorWeight(); if (currentWeight == weight) { equalWeightOPs.add(currentRule); } else { it.previous(); break; } } boolean isLast = !it.hasNext(); Sequence firstSequence = firstRule.getDefinition().getOptions().get(0); AnnotationType operatorType = firstRule.getOperatorAnnotation().getType(); String ruleName = getExpressionSliceRuleName(firstRule); GenClass returnGenClass = firstRule.getMetaclass(); for (GenClass metaClass : allGenClasses) { if (metaClass.getName().equals(firstRule.getOperatorAnnotation().getValue(OperatorAnnotationProperty.IDENTIFIER.toString()))) { returnGenClass = metaClass; } } printGrammarRulePrefix(returnGenClass,ruleName,sc); if (!isLast) { //we assume all arguments to be typed by the same class final String nextRuleName = getExpressionSliceRuleName(it.next()); it.previous(); //we do unary operators first if (operatorType == AnnotationType.OP_UNARY) { //1st case: unary operator starts with keyword if (firstSequence.getParts().get(0) instanceof CsString) { for (Rule rule : equalWeightOPs) { List<Definition> definitions = rule.getDefinition().getOptions().get(0).getParts(); assert definitions.size() == 2; assert definitions.get(0) instanceof CsString; assert definitions.get(1) instanceof Containment; CsString csString = (CsString) definitions.get(0); Containment containment = (Containment) definitions.get(1); printCsString(csString, rule, sc, 0, eClassesReferenced); sc.add("arg = " + nextRuleName); printTerminalAction(containment, firstRule, sc, "arg", "", "arg", null, "null"); sc.add("|"); sc.addLineBreak(); } sc.addLineBreak(); sc.add("arg = " + nextRuleName + "{ element = arg; }"); } //2nd case: unary operator starts with argument (this means left recursion) else { sc.add("arg = "+ nextRuleName); sc.add("("); for (Rule rule : equalWeightOPs) { List<Definition> definitions = rule.getDefinition().getOptions().get(0).getParts(); assert definitions.size() == 2; assert definitions.get(0) instanceof Containment; assert definitions.get(1) instanceof CsString; CsString csString = (CsString) firstSequence.getParts().get(1); Containment containment = (Containment) definitions.get(1); printCsString(csString, rule, sc, 0, eClassesReferenced); printTerminalAction(containment, rule, sc, "arg", "", "arg", null, "null"); sc.add("|"); sc.addLineBreak(); } sc.add("/* epsilon */ { element = arg; } "); sc.addLineBreak(); sc.add(")"); } } // now we do binary infix operators else { //1st case left associative operators, e.g., -,+,*,/ etc. if (operatorType == AnnotationType.OP_LEFTASSOC) { sc.add("leftArg = " + nextRuleName); sc.add("(("); for (Iterator<Rule> ruleIt = equalWeightOPs.iterator(); ruleIt.hasNext();) { Rule rule = ruleIt.next(); List<Definition> definitions = rule.getDefinition().getOptions().get(0).getParts(); assert definitions.size() == 3; assert definitions.get(0) instanceof Containment; assert definitions.get(1) instanceof CsString; assert definitions.get(2) instanceof Containment; Containment leftContainment = (Containment) definitions.get(0); CsString csString = (CsString) definitions.get(1); Containment rightContainment = (Containment) definitions.get(2); sc.add("{ element = null; }"); printCsString(csString, rule, sc, 0, eClassesReferenced); sc.add("rightArg = " + nextRuleName); printTerminalAction(leftContainment, rule, sc, "leftArg", "", "leftArg", null, "null"); printTerminalAction(rightContainment, rule, sc, "rightArg", "", "rightArg", null, "null"); sc.add("{ leftArg = element; /* this may become an argument in the next iteration */ }"); if (ruleIt.hasNext()) { sc.add("|"); sc.addLineBreak(); } } sc.add(")+ | /* epsilon */ { element = leftArg; }"); sc.addLineBreak(); sc.add(")"); } //2nd case right associative operators , e.g., ^ else { assert operatorType == AnnotationType.OP_RIGHTASSOC; //final String thisRuleName = getRuleName(rule.getMetaclass()); sc.add("leftArg = " + nextRuleName); sc.add("(("); for (Iterator<Rule> ruleIt = equalWeightOPs.iterator(); ruleIt.hasNext();) { Rule rule = ruleIt.next(); List<Definition> definitions = rule.getDefinition().getOptions().get(0).getParts(); assert definitions.size() == 3; assert definitions.get(0) instanceof Containment; assert definitions.get(1) instanceof CsString; assert definitions.get(2) instanceof Containment; Containment leftContainment = (Containment) definitions.get(0); CsString csString = (CsString) definitions.get(1); Containment rightContainment = (Containment) definitions.get(2); printCsString(csString, rule, sc, 0, eClassesReferenced); sc.add("rightArg = " + ruleName); printTerminalAction(leftContainment, rule, sc, "leftArg", "", "leftArg", null, "null"); printTerminalAction(rightContainment, rule, sc, "rightArg", "", "rightArg", null, "null"); if (ruleIt.hasNext()) { sc.add("|"); sc.addLineBreak(); } } sc.add(") | /* epsilon */ { element = leftArg; }"); sc.addLineBreak(); sc.add(")"); } } printGrammarRuleSuffix(sc); } else { assert operatorType == AnnotationType.OP_PRIMITIVE; List<GenClass> choiceClasses = new LinkedList<GenClass>(); for (Rule rule : equalWeightOPs) { choiceClasses.add(rule.getMetaclass()); } printSubClassChoices(sc, choiceClasses); printGrammarRuleSuffix(sc); for (Rule rule : equalWeightOPs) { printGrammarRule(rule, sc, eClassesWithSyntax, eClassesReferenced); } } } } private String getExpressionSliceRuleName(Rule rule){ // TODO mseifert: make sure the names generated by this method do not // overlap with names for normal rules Annotation operatorAnnotation = rule.getOperatorAnnotation(); String ruleName = operatorAnnotation.getValue(OperatorAnnotationProperty.IDENTIFIER.toString()) + "_level_"; String weight = operatorAnnotation.getValue(OperatorAnnotationProperty.WEIGHT.toString()).replace('-','_'); ruleName += weight; return "parse_" + ruleName; } private String getRuleName(GenClass genClass) { String ruleName = genClassFinder.getEscapedTypeName(genClass); return "parse_" + ruleName; } private int printChoice(Choice choice, Rule rule, StringComposite sc, int count, Map<GenClass, Collection<Terminal>> eClassesReferenced, String scopeID) { Iterator<Sequence> it = choice.getOptions().iterator(); while (it.hasNext()) { Sequence seq = it.next(); count = printSequence(seq, rule, sc, count, eClassesReferenced, scopeID); if (it.hasNext()) { sc.addLineBreak(); sc.add("|"); } } return count; } private int printSequence(Sequence sequence, Rule rule, StringComposite sc, int count, Map<GenClass, Collection<Terminal>> eClassesReferenced, String scopeID) { int i = 0; for (Definition definition : sequence.getParts()) { if (definition instanceof LineBreak || definition instanceof WhiteSpaces) { continue; } ConcreteSyntax syntax = getContext().getConcreteSyntax(); Set<Expectation> expectations = computer.computeFollowSet(syntax, definition); addToFollowSetMap(definition, expectations); String cardinality = csUtil.computeCardinalityString(definition); if (!"".equals(cardinality)) { sc.add("("); } if (definition instanceof CompoundDefinition) { String subScopeID = scopeID + "." + i; CompoundDefinition compoundDef = (CompoundDefinition) definition; sc.add("("); count = printChoice(compoundDef.getDefinitions(), rule, sc, count, eClassesReferenced, subScopeID); sc.add(")"); i++; } else if (definition instanceof CsString) { final CsString csString = (CsString) definition; count = printCsString(csString, rule, sc, count, eClassesReferenced); } else { assert definition instanceof Terminal; final Terminal terminal = (Terminal) definition; count = printTerminal(terminal, rule, sc, count, eClassesReferenced); } if (!"".equals(cardinality)) { sc.addLineBreak(); sc.add(")" + cardinality); } sc.add("{"); sc.add("// expected elements (follow set)"); addExpectationsCode(sc, expectations); sc.add("}"); sc.addLineBreak(); } return count; } private void addToFollowSetMap(Definition definition, Set<Expectation> expectations) { // only terminals are important here if (definition instanceof Placeholder) { GenFeature feature = ((Placeholder) definition).getFeature(); if (feature == ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) { return; } followSetMap.put(getID(definition), expectations); } else if (definition instanceof CsString) { followSetMap.put(getID(definition), expectations); } } private void addExpectationsCode(StringComposite sc, Set<Expectation> expectations) { for (Expectation expectation : expectations) { EObject expectedElement = expectation.getExpectedElement(); String terminalID = getID(expectedElement); // here the containment trace is used // TODO mseifert: figure out whether this is really needed StringBuilder traceArguments = new StringBuilder(); List<GenFeature> containmentTrace = expectation.getContainmentTrace(); for (GenFeature genFeature : containmentTrace) { traceArguments.append(", "); traceArguments.append(getFeatureConstantFieldName(genFeature)); } sc.add("addExpectedElement(new " + expectedTerminalClassName + "(" + terminalID + ", " + followSetID + traceArguments + "));"); } followSetID++; } // TODO mseifert: put this constants into a separate class private void addTerminalConstants(StringComposite sc) { for (EObject expectedElement : idMap.keySet()) { String terminalID = idMap.get(expectedElement); GenClass genClass = csUtil.findContainingRule(expectedElement).getMetaclass(); String eClassConstantAccessor = generatorUtil.getClassAccessor(genClass); if (expectedElement instanceof Placeholder) { Placeholder placeholder = (Placeholder) expectedElement; GenFeature genFeature = placeholder.getFeature(); // ignore the anonymous features if (genFeature == ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) { continue; } String featureConstantAccessor = generatorUtil.getFeatureAccessor(genClass, genFeature); sc.add("private final static " + iExpectedElementClassName + " " + terminalID + " = new " + expectedStructuralFeatureClassName + "(" + eClassConstantAccessor + ", " + featureConstantAccessor + ", \"" + placeholder.getToken().getName() + "\");"); } else if (expectedElement instanceof CsString) { CsString expectedKeyword = (CsString) expectedElement; String escapedCsString = StringUtil.escapeToJavaStringInANTLRGrammar(expectedKeyword.getValue()); sc.add("private final static " + iExpectedElementClassName + " " + terminalID + " = new " + expectedCsStringClassName + "(" + eClassConstantAccessor + ", \"" + escapedCsString + "\");"); } else { throw new RuntimeException("Unknown expected element type: " + expectedElement); } } sc.addLineBreak(); // ask for all features to make sure respective fields are generated for (String firstID : followSetMap.keySet()) { for (Expectation expectation : followSetMap.get(firstID)) { List<GenFeature> containmentTrace = expectation.getContainmentTrace(); for (GenFeature genFeature : containmentTrace) { getFeatureConstantFieldName(genFeature); } } } // generate fields for all used features for (GenFeature genFeature : eFeatureToConstantNameMap.keySet()) { String fieldName = getFeatureConstantFieldName(genFeature); String featureAccessor = generatorUtil.getFeatureAccessor(genFeature.getGenClass(), genFeature); sc.add("private final static " + E_STRUCTURAL_FEATURE + " " + fieldName + " = " + featureAccessor + ";"); } sc.addLineBreak(); sc.add("private final static " + E_STRUCTURAL_FEATURE + "[] EMPTY_FEATURE_ARRAY = new " + E_STRUCTURAL_FEATURE + "[0];"); sc.addLineBreak(); // we need to split the code to wire the terminals with their // followers, because the code does exceed the 64KB limit for // methods if the grammar is big int bytesUsedInCurrentMethod = 0; boolean methodIsFull = true; int i = 0; int numberOfMethods = 0; // create multiple wireX() methods for (String firstID : followSetMap.keySet()) { if (methodIsFull) { sc.add("public static void wire" + numberOfMethods + "() {"); numberOfMethods++; methodIsFull = false; } for (Expectation expectation : followSetMap.get(firstID)) { EObject follower = expectation.getExpectedElement(); List<GenFeature> containmentTrace = expectation.getContainmentTrace(); StringBuilder trace = new StringBuilder(); if (containmentTrace.isEmpty()) { trace.append(", EMPTY_FEATURE_ARRAY"); } else { trace.append(", new " + E_STRUCTURAL_FEATURE + "[] {"); for (GenFeature genFeature : containmentTrace) { trace.append(getFeatureConstantFieldName(genFeature) + ", "); // another 16 bytes for each access to a constant bytesUsedInCurrentMethod += 16; } trace.append("}"); } sc.add(firstID + ".addFollower(" + getID(follower) + trace + ");"); // the method call takes 19 bytes bytesUsedInCurrentMethod += 19; } if (bytesUsedInCurrentMethod >= 63 * 1024) { methodIsFull = true; bytesUsedInCurrentMethod = 0; } if (methodIsFull || i == followSetMap.keySet().size() - 1) { sc.add("}"); } i++; } // call all wireX() methods from the static constructor sc.add("// wire the terminals"); sc.add("static {"); for (int c = 0; c < numberOfMethods; c++) { sc.add("wire" + c + "();"); } sc.add("}"); } private String getFeatureConstantFieldName(GenFeature genFeature) { if (!eFeatureToConstantNameMap.keySet().contains(genFeature)) { String featureConstantName = "FEATURE_" + featureCounter; featureCounter++; eFeatureToConstantNameMap.put(genFeature, featureConstantName); } return eFeatureToConstantNameMap.get(genFeature); } private String getID(EObject expectedElement) { if (!idMap.containsKey(expectedElement)) { idMap.put(expectedElement, "TERMINAL_" + idCounter); idCounter++; } return idMap.get(expectedElement); } private int printCsString(CsString csString, Rule rule, StringComposite sc, int count, Map<GenClass, Collection<Terminal>> eClassesReferenced) { String identifier = "a" + count; String escapedCsString = StringUtil.escapeToANTLRKeyword(csString.getValue()); sc.add(identifier + " = '" + escapedCsString + "' {"); sc.add("if (element == null) {"); sc.add("element = " + genClassUtil.getCreateObjectCall(rule.getMetaclass(), dummyEObjectClassName) + ";"); sc.add("}"); sc.add("collectHiddenTokens(element);"); sc.add("copyLocalizationInfos((" + COMMON_TOKEN + ")" + identifier + ", element);"); sc.add("}"); return ++count; } private int printTerminal(Terminal terminal, Rule rule, StringComposite sc, int count, Map<GenClass, Collection<Terminal>> eClassesReferenced) { final GenClass genClass = rule.getMetaclass(); final GenFeature genFeature = terminal.getFeature(); final EStructuralFeature eFeature = genFeature.getEcoreFeature(); final String ident = "a" + count; final String proxyIdent = "proxy"; StringComposite resolvements = new ANTLRGrammarComposite(); sc.add("("); if (terminal instanceof Containment) { assert ((EReference) eFeature).isContainment(); Containment containment = (Containment) terminal; EList<GenClass> types = csUtil.getAllowedSubTypes(containment); int internalCount = 0; for (GenClass type : types) { if (internalCount != 0) { sc.add("|"); } String internalIdent = ident + "_" + internalCount; sc.add(internalIdent + " = " + getRuleName(type)); if (!(genFeature.getEcoreFeature() instanceof EAttribute)) { // remember which classes are referenced to add choice rules // for these classes later if (!eClassesReferenced.keySet().contains(type)) { eClassesReferenced.put(type, new LinkedHashSet<Terminal>()); } eClassesReferenced.get(type).add(terminal); } printTerminalAction(terminal, rule, sc, internalIdent, proxyIdent, internalIdent, resolvements, null); internalCount++; } } else { assert terminal instanceof Placeholder; Placeholder placeholder = (Placeholder) terminal; CompleteTokenDefinition token = placeholder.getToken(); String tokenName = token.getName(); sc.add(ident + " = " + tokenName); sc.addLineBreak(); // ignore the anonymous features if (genFeature != ConcreteSyntaxUtil.ANONYMOUS_GEN_FEATURE) { String targetTypeName = null; String resolvedIdent = "resolved"; String preResolved = resolvedIdent + "Object"; String resolverIdent = "tokenResolver"; resolvements.add(getClassNameHelper().getI_TOKEN_RESOLVER() + " " + resolverIdent + " = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"); resolvements.add(resolverIdent + ".setOptions(getOptions());"); resolvements.add(getClassNameHelper().getI_TOKEN_RESOLVE_RESULT() + " result = getFreshTokenResolveResult();"); resolvements.add(resolverIdent + ".resolve(" + ident + ".getText(), element.eClass().getEStructuralFeature(" + generatorUtil.getFeatureConstant(genClass, genFeature) + "), result);"); resolvements.add(OBJECT + " " + preResolved + " = result.getResolvedToken();"); resolvements.add("if (" + preResolved + " == null) {"); resolvements.add("addErrorToResource(result.getErrorMessage(), ((" + COMMON_TOKEN + ") " + ident + ").getLine(), ((" + COMMON_TOKEN + ") " + ident + ").getCharPositionInLine(), ((" + COMMON_TOKEN + ") " + ident + ").getStartIndex(), ((" + COMMON_TOKEN + ") " + ident + ").getStopIndex());"); resolvements.add("}"); String expressionToBeSet = null; if (eFeature instanceof EReference) { targetTypeName = "String"; expressionToBeSet = proxyIdent; // a sub type that can be instantiated as a proxy GenClass instanceType = genFeature.getTypeGenClass(); GenClass proxyType = null; if (genClassUtil.isNotConcrete(instanceType)) { // TODO mseifert: replace this code with a call to class // GenClassFinder // a slightly more elegant version of this code can also be // found in the ScannerlessParserGenerator for (GenClass instanceCand : allGenClasses) { Collection<String> supertypes = genClassNames2superClassNames .get(genClassFinder .getQualifiedInterfaceName(instanceCand)); if (genClassUtil.isConcrete(instanceCand) && supertypes .contains(genClassFinder .getQualifiedInterfaceName(instanceType))) { proxyType = instanceCand; break; } } } else { proxyType = instanceType; } resolvements.add(targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") " + preResolved + ";"); resolvements.add(genClassFinder .getQualifiedInterfaceName(proxyType) + " " + expressionToBeSet + " = " + genClassUtil.getCreateObjectCall(proxyType, dummyEObjectClassName) + ";"); resolvements.add("collectHiddenTokens(element);"); resolvements .add("registerContextDependentProxy(new " + contextDependentURIFragmentFactoryClassName + "<" + genClassFinder .getQualifiedInterfaceName(genFeature .getGenClass()) + ", " + genClassFinder .getQualifiedInterfaceName(genFeature .getTypeGenClass()) + ">(" + getContext() .getReferenceResolverAccessor(genFeature) + "), element, (org.eclipse.emf.ecore.EReference) element.eClass().getEStructuralFeature(" + generatorUtil.getFeatureConstant(genClass, genFeature) + "), " + resolvedIdent + ", " + proxyIdent + ");"); // remember that we must resolve proxy objects for this feature getContext().addNonContainmentReference(genFeature); } else { // the feature is an EAttribute targetTypeName = genFeature.getQualifiedListItemType(null); resolvements.add(targetTypeName + " " + resolvedIdent + " = (" + getObjectTypeName(targetTypeName) + ")" + preResolved + ";"); expressionToBeSet = "resolved"; } printTerminalAction(placeholder, rule, sc, ident, proxyIdent, expressionToBeSet, resolvements, tokenName); } } sc.add(")"); return ++count; } private void printTerminalAction(Terminal terminal, Rule rule, StringComposite sc, final String ident, final String proxyIdent, String expressionToBeSet, StringComposite resolvements, String tokenName) { // FIXME mseifert: this is not correct! final GenFeature genFeature = terminal.getFeature(); final GenClass genClass = genFeature.getGenClass(); final EStructuralFeature eFeature = genFeature.getEcoreFeature(); sc.add("{"); sc.add("if (terminateParsing) {"); sc.add("throw new " + getClassNameHelper().getTERMINATE_PARSING_EXCEPTION() + "();"); sc.add("}"); sc.add("if (element == null) {"); sc.add("element = " + genClassUtil.getCreateObjectCall(rule.getMetaclass(), dummyEObjectClassName) + ";"); sc.add("}"); // TODO mseifert: escape tokeName correctly sc.add(new StringComponent(STRING + " tokenName = \"" + tokenName + "\";", "tokenName")); sc.add("if (" + ident + " != null) {"); if (resolvements != null) { sc.add(resolvements); } sc.add("if (" + expressionToBeSet + " != null) {"); final String featureConstant = generatorUtil.getFeatureConstant(genClass, genFeature); generatorUtil.addCodeToSetFeature(sc, genClass, featureConstant, eFeature, expressionToBeSet); sc.add("}"); sc.add("collectHiddenTokens(element);"); if (terminal instanceof Containment) { sc.add("copyLocalizationInfos(" + ident + ", element); "); } else { sc.add("copyLocalizationInfos((" + COMMON_TOKEN + ") " + ident + ", element);"); if (eFeature instanceof EReference) { // additionally set position information for the proxy instance sc.add("copyLocalizationInfos((" + COMMON_TOKEN + ") " + ident + ", " + proxyIdent + ");"); } } sc.add("}"); sc.add("}"); } private void printImplicitChoiceRules(StringComposite sc, EList<GenClass> eClassesWithSyntax, Map<GenClass, Collection<Terminal>> eClassesReferenced) { for (GenClass referencedClass : eClassesReferenced.keySet()) { if (!containsEqualByName(eClassesWithSyntax, referencedClass)) { // rule not explicitly defined in CS: most likely a choice rule // in the AS Collection<GenClass> subClasses = csUtil .getSubClassesWithSyntax(referencedClass, concreteSyntax); if (!subClasses.isEmpty()) { sc.add(getRuleName(referencedClass)); sc.add(" returns [" + genClassFinder .getQualifiedInterfaceName(referencedClass) + " element = null]"); sc.add(":"); //Expression slices are formed over a common abstract superclass if (concreteSyntax.getOperatorRuleSubset(referencedClass.getName()).isEmpty()) { printSubClassChoices(sc, subClasses); } else { List<Rule> slice = concreteSyntax.getOperatorRuleSubset(referencedClass.getName()); sc.add("c = " + getExpressionSliceRuleName(slice.get(0))+"{ element = c; /* this rule is an expression root */ }"); } sc.addLineBreak(); sc.add(";"); sc.addLineBreak(); eClassesWithSyntax.add(referencedClass); } } } } private void printSubClassChoices(StringComposite sc, Collection<GenClass> subClasses) { int count = 0; for (Iterator<GenClass> subClassIterator = subClasses.iterator(); subClassIterator.hasNext();) { GenClass subRef = subClassIterator.next(); String identifier = "c" + count; sc.add(identifier + " = " + getRuleName(subRef) + "{ element = " + identifier + "; /* this is a subclass or expression choice */ }"); if (subClassIterator.hasNext()) { sc.add("|"); } count++; } } // TODO this method does not belong here private boolean containsEqualByName(EList<GenClass> list, GenClass o) { for (GenClass entry : list) { EClass entryClass = entry.getEcoreClass(); EClass oClass = o.getEcoreClass(); if (entryClass.getName().equals(oClass.getName()) && entryClass.getEPackage().getNsURI().equals( oClass.getEPackage().getNsURI())) { return true; } } return false; } private void addTokenDefinitions(StringComposite sc) { for (CompleteTokenDefinition tokenDefinition : concreteSyntax.getActiveTokens()) { printToken(tokenDefinition, sc); } } private void printToken(CompleteTokenDefinition definition, StringComposite sc) { sc.add(definition.getName()); sc.add(":"); sc.add(definition.getRegex()); // keyword tokens do never go to channel 99, because they // are contained in the grammar. if they are sent to channel // 99 rules containing the keywords will never be matched if (definition.isHidden() && !isKeyword(definition)) { sc.add("{ _channel = 99; }"); } sc.add(";"); } private boolean isKeyword(CompleteTokenDefinition definition) { // this comparison of the regular expression should in theory be // replaced by a comparison of the two automata. however, ANTLR // does not compare the in-line tokens (keywords) and the defined // tokens using automata, but uses a string comparison of the // regular expressions. if we compare the tokens using the automata // the resulting ANTLR grammars will not work. String assumeKeyword = definition.getRegex().substring(1, definition.getRegex().length() - 1); boolean contains = keywords.contains(assumeKeyword); return contains; } public IGenerator newInstance(GenerationContext context) { return new ANTLRGrammarGenerator(context); } }
9e4a4e11e8c6fd9a643238f5e55124cecff9aa07
556a3ad3b99e5ab974516e2cb4fb27155801b56a
/spring/SpringAOP/src/com/training/spring/aop/CalculatorPointcuts.java
0c51673cdecbbecabd325f521763381c53b6fc84
[]
no_license
guptanitesh-ng/learnspace
a7ccbad7371300e2f351f9b179673ccfc3e60254
1544f78e6eedb9f4593434cdb7cdbd96c2bb3a7f
refs/heads/master
2023-03-11T02:40:08.119710
2023-03-07T10:27:46
2023-03-07T10:27:46
96,972,542
0
0
null
2022-11-16T02:49:07
2017-07-12T06:23:06
Java
UTF-8
Java
false
false
690
java
package com.training.spring.aop; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class CalculatorPointcuts { @Pointcut("within(com.training.spring.aop.BasicArithmeticCalculator)") public void arithmeticOperation() { } @Pointcut("within(com.training.spring.aop.UnitConversionCalculator)") public void unitConversionOperation() { } @Pointcut("arithmeticOperation() || unitConversionOperation()") public void loggingOperation() { } @Pointcut("arithmeticOperation() && args(arg1, arg2)") public void validateArithmeticInput(double arg1, double arg2) { } }
137ba5008770de7257f788e265f34b1b857bb4dc
fe5f78b0858506234d8059db2fda00b5ef9671aa
/src/main/java/com/petrz/instructors/data/service/SemesterService.java
9b4ddd4051cd6ef645e3820ec62efae4ff11d06e
[ "Unlicense" ]
permissive
andrey1025-zz/vaadin_instructor
21f48127133bd5a2c67c1db28a9c10135c36a173
4ba71f7cf789fd6e160ebddf5e70d74dc5b2b68e
refs/heads/main
2023-01-27T21:00:38.944986
2020-12-07T06:18:39
2020-12-07T06:18:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
592
java
package com.petrz.instructors.data.service; import com.petrz.instructors.data.entity.Semester; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.vaadin.artur.helpers.CrudService; @Service public class SemesterService extends CrudService<Semester, Integer> { private SemesterRepository repository; public SemesterService(@Autowired SemesterRepository repository) { this.repository = repository; } @Override protected SemesterRepository getRepository() { return repository; } }
a8a720cdab116faaa962b09aa6c6458a482b112d
902564d740bee866d7798df985a25f0f664f6240
/src/trunk/mywar-game-msgbody/src/main/java/com/fantingame/game/msgbody/client/mail/MailAction_deleteRes.java
5c9d0fc3b39b485d96ad549b5e0c57a73a34f2b9
[]
no_license
hw233/Server-java
539b416821ad67d22120c7146b4c3c7d4ad15929
ff74787987f146553684bd823d6bd809eb1e27b6
refs/heads/master
2020-04-29T04:46:03.263306
2016-05-20T12:45:44
2016-05-20T12:45:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
526
java
package com.fantingame.game.msgbody.client.mail; import com.fantingame.game.msgbody.common.io.iface.IXInputStream; import com.fantingame.game.msgbody.common.io.iface.IXOutStream; import com.fantingame.game.msgbody.common.model.ICodeAble; import java.io.IOException; /**删除邮件**/ public class MailAction_deleteRes implements ICodeAble { @Override public void encode(IXOutStream outputStream) throws IOException { } @Override public void decode(IXInputStream inputStream) throws IOException { } }
273bf31a6fec55bcbad199ded2cdf0064f0333b3
b15c768a3d81acc300b253e09103cb305d0b5301
/gupaoedu-vip-pattern/gupaoedu-vip-pattern-proxy/src/main/java/com/gupaoedu/vip/pattern/proxy/dynamicproxy/gpproxy/client/Zhangsan.java
3f197e8a93a54301098125232f5f0700e404741c
[]
no_license
JoyiforStudy/design-samples
86e56d5935b117a9f67070915906a2f0bc594bff
e7b8c76f04b45b091ffdc16eb7bc72df6dcb64fe
refs/heads/master
2023-08-29T07:55:31.454849
2021-11-02T05:21:41
2021-11-02T05:21:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package com.gupaoedu.vip.pattern.proxy.dynamicproxy.gpproxy.client; /** * Created by Tom. */ public class Zhangsan implements IPerson { public void findLove() { System.out.println("张三要求:肤白貌美大长腿"); } public void buyInsure() { System.out.println("30万"); } }
01485d497df5e2763e1a4366937925d4f342fb24
90ebbeccd207b2b288a85c315ecce83e83cfa61f
/app/src/main/java/Adapter/CreditNoteAdapter.java
37860d6569aad4c6c1ccb333b63b989824310adc
[]
no_license
rajeev1505/JSON99retailsolution27june
9cbf0db65416fce84862b3782676222654e0d586
d4369696b4b36029ef190564a1750bd5036769a0
refs/heads/master
2021-01-23T12:04:43.614030
2016-12-22T07:47:01
2016-12-22T07:47:01
62,326,744
0
0
null
null
null
null
UTF-8
Java
false
false
2,848
java
package Adapter; import android.content.Context; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.TextView; import com.mycompany.apps.ActivitySalesbill; import com.mycompany.apps.ActivitySalesreturn; import com.mycompany.apps.R; import java.util.ArrayList; import Pojo.CreditNote; import Pojo.Customer; import Pojo.Sales; import Pojo.Salesreturndetail; /** * Created by shilpa on 30/4/16. */ public class CreditNoteAdapter extends ArrayAdapter<CreditNote> { private final int layoutResourceId; ActivitySalesbill activity; private LayoutInflater mInflater; public CreditNoteAdapter(ActivitySalesbill activity, int layoutResourceId, ArrayList<CreditNote> mcreditnotelist) { super(activity, layoutResourceId, mcreditnotelist); this.layoutResourceId = layoutResourceId; this.CreditNotelist = mcreditnotelist; this.activity = activity; this.mInflater = mInflater; } public void setCreditNotelist(ArrayList<CreditNote> creditNotelist) { this.CreditNotelist = creditNotelist; } private ArrayList<CreditNote> CreditNotelist; public int getCount() { if (CreditNotelist.size() < 0) return 1; return CreditNotelist.size(); } public CreditNote getItem(int position) { return CreditNotelist.get(position); } public long getItemId(int position) { //.getCustomermobileno(); return position; } public static class ViewHolder { public TextView billno; public TextView creditnotevalue; } public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); LayoutInflater mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.display_creditnote_row, parent, false); holder.billno = (TextView) convertView.findViewById(R.id.billno); // holder.creditnotevalue = (TextView) convertView.findViewById(R.id.creditamount_tv); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.billno.setText(CreditNotelist.get(position).getReturnInvoiceno()); // holder.creditnotevalue.setText(CreditNotelist.get(position).getCreditnotevalue()); return convertView; } }
0363a45ef7a82c0501d6a44e78f638256659f6e1
1c3577e6a181542eba8f7447ad2ced3bb4f95288
/vueadmin-java/src/main/java/com/qi/config/KaptchaConfig.java
852dc545a8ef3eca180b5a070ad73a75490e588f
[]
no_license
chaoqi666/vueadmin
c0772bd715de423ab50e95d71b369f0f18a4796a
be5d574f1ad79cb053c97ab0e29c2b40343b70b2
refs/heads/master
2023-07-23T19:00:20.990682
2021-09-07T09:46:03
2021-09-07T09:46:03
403,918,522
2
1
null
null
null
null
UTF-8
Java
false
false
1,065
java
package com.qi.config; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.parameters.P; import java.util.Properties; @Configuration public class KaptchaConfig { @Bean DefaultKaptcha producer() { Properties properties = new Properties(); properties.put("kaptcha.border", "no"); properties.put("kaptcha.textproducer.font.color", "black"); properties.put("kaptcha.textproducer.char.space", "4"); properties.put("kaptcha.image.height", "40"); properties.put("kaptcha.image.width", "120"); properties.put("kaptcha.textproducer.font.size", "30"); properties.put("kaptcha.textproducer.char.length","4"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
7954fb1f54249b0ed8463730abf271bff70d1e5f
8f8f22d23c049015162ac38b3308a376fe57e25b
/modules/core/src/main/java/cgl/iotcloud/core/sensor/SCSensorUtils.java
59c639ef189da8088ab5d406946169c722f1ee07
[]
no_license
kouweizhong/IoTCloud
9b7470fa518c3845eb02d8763d2ae8fdca1b5a1d
8e6e0b6d4c1d81facfe0539eab28bfdc17a4bcf7
refs/heads/master
2020-03-26T10:51:56.431517
2018-02-25T16:18:58
2018-02-25T16:18:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,318
java
package cgl.iotcloud.core.sensor; import cgl.iotcloud.core.Constants; import cgl.iotcloud.core.IOTRuntimeException; import cgl.iotcloud.core.endpoint.JMSEndpoint; import cgl.iotcloud.core.endpoint.StreamingEndpoint; import com.iotcloud.sensorInfo.xsd.*; import com.iotcloud.sensorInfo.xsd.Endpoint; import com.iotcloud.sensorInfo.xsd.Sensor; import org.apache.xmlbeans.XmlException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility class for converting sensor */ public class SCSensorUtils { private static Logger log = LoggerFactory.getLogger(SCSensorUtils.class); public static String convertToString(List<SCSensor> sensors) { AllSensorsDocument document = AllSensorsDocument.Factory.newInstance(); AllSensorsDocument.AllSensors allSensors = document.addNewAllSensors(); Sensor []sensorArray = new Sensor[sensors.size()]; for (int i = 0; i < sensors.size(); i++) { sensorArray[i] = convertToXML(sensors.get(i)); } if (sensors.size() > 0) { allSensors.setSensorArray(sensorArray); } return document.toString(); } public static String convertToString(SCSensor sensor) { SensorInfoDocument document = SensorInfoDocument.Factory.newInstance(); Sensor s = convertToXML(sensor); document.setSensorInfo(s); return document.toString(); } private static Sensor convertToXML(SCSensor sensor) { Sensor sensorInfo = Sensor.Factory.newInstance(); sensorInfo.setName(sensor.getName()); sensorInfo.setType(sensor.getType()); sensorInfo.setId(sensor.getId()); Endpoint controlEndpoint = sensorInfo.addNewControlEndpoint(); Endpoint dataEndpoint = sensorInfo.addNewDataEndpoint(); Endpoint updateEndpoint = sensorInfo.addNewUpdateEndpoint(); cgl.iotcloud.core.Endpoint epr = sensor.getControlEndpoint(); controlEndpoint.setAddress(epr.getAddress()); Properties properties = controlEndpoint.addNewProperties(); for (Map.Entry<String, String> e : epr.getProperties().entrySet()) { Property property = properties.addNewProperty(); property.setName(e.getKey()); property.setStringValue(e.getValue()); } epr = sensor.getDataEndpoint(); dataEndpoint.setAddress(epr.getAddress()); properties = dataEndpoint.addNewProperties(); for (Map.Entry<String, String> e : epr.getProperties().entrySet()) { Property property = properties.addNewProperty(); property.setName(e.getKey()); property.setStringValue(e.getValue()); } epr = sensor.getUpdateEndpoint(); updateEndpoint.setAddress(epr.getAddress()); properties = updateEndpoint.addNewProperties(); for (Map.Entry<String, String> e : epr.getProperties().entrySet()) { Property property = properties.addNewProperty(); property.setName(e.getKey()); property.setStringValue(e.getValue()); } return sensorInfo; } public static List<SCSensor> convertToSensors(InputStream in) { try { AllSensorsDocument document = AllSensorsDocument.Factory.parse(in); List<SCSensor> ss = new ArrayList<SCSensor>(); Sensor sensors[] = document.getAllSensors().getSensorArray(); for (Sensor s : sensors) { ss.add(convertToSensor(s)); } return ss; } catch (XmlException e) { handleException("Invalid XML returned", e); } catch (IOException e) { handleException("Error reading the XML from the input stream", e); } return null; } public static List<SCSensor> convertToSensors(String string) { try { AllSensorsDocument document = AllSensorsDocument.Factory.parse(string); List<SCSensor> ss = new ArrayList<SCSensor>(); Sensor sensors[] = document.getAllSensors().getSensorArray(); for (Sensor s : sensors) { ss.add(convertToSensor(s)); } return ss; } catch (XmlException e) { handleException("Invalid XML returned", e); } return null; } public static SCSensor convertToSensor(InputStream in) { try { SensorInfoDocument document = SensorInfoDocument.Factory.parse(in); return convertToSensor(document.getSensorInfo()); } catch (XmlException e) { handleException("Failed to convert the text to a XML", e); } catch (IOException e) { handleException("Error reading the XML from the input stream", e); } return null; } public static SCSensor convertToSensor(String string) { try { SensorInfoDocument document = SensorInfoDocument.Factory.parse(string); return convertToSensor(document.getSensorInfo()); } catch (XmlException e) { handleException("Failed to convert the text to a XML", e); } return null; } public static SCSensor convertToSensor(Sensor xmlSensor) { SCSensor sensor = new SCSensor(xmlSensor.getName()); sensor.setId(xmlSensor.getId()); sensor.setType(xmlSensor.getType()); cgl.iotcloud.core.Endpoint epr; if (sensor.getType().equals(Constants.SENSOR_TYPE_BLOCK)) { epr = convertToEndpoint(xmlSensor.getDataEndpoint(), 0); sensor.setDataEndpoint(epr); } else if (sensor.getType().equals(Constants.SENSOR_TYPE_STREAMING)) { epr = convertToEndpoint(xmlSensor.getDataEndpoint(), 1); sensor.setDataEndpoint(epr); } if (xmlSensor.getControlEndpoint() != null) { epr = convertToEndpoint(xmlSensor.getControlEndpoint(), 0); sensor.setControlEndpoint(epr); } if (xmlSensor.getUpdateEndpoint() != null) { epr = convertToEndpoint(xmlSensor.getUpdateEndpoint(), 0); sensor.setUpdateEndpoint(epr); } return sensor; } private static cgl.iotcloud.core.Endpoint convertToEndpoint(Endpoint endpoint, int type) { cgl.iotcloud.core.Endpoint epr; if (type == 0) { epr = new JMSEndpoint(); } else if (type == 1) { epr = new StreamingEndpoint(); } else { handleException(""); return null; } epr.setAddress(endpoint.getAddress()); Properties properties = endpoint.getProperties(); Map<String, String> props = new HashMap<String, String>(); for (Property p : properties.getPropertyArray()) { props.put(p.getName(), p.getStringValue()); } epr.setProperties(props); return epr; } private static void handleException(String s, Exception e) { log.error(s, e); throw new IOTRuntimeException(s, e); } private static void handleException(String s) { log.error(s); throw new IOTRuntimeException(s); } }
c50a02d565a7ff51bd4d92f14cdfd75766124ecd
411a9b53b24a245d43fcbf8884900ac6890ebc12
/IoT-rest/src/main/java/cz/vutbr/feec/iot/rest/ApiEndpoints.java
daa665c12a235398c4283dfefd1e840867632b66
[]
no_license
SedaQ/IoT-parent
c8bce6c3293ea9c1e6be00810adf015c8723c1ef
19a500b3696ef74a1c82f393ef98f98d8075046b
refs/heads/master
2021-07-03T17:18:19.372467
2017-09-25T12:28:47
2017-09-25T12:28:47
104,290,392
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package cz.vutbr.feec.iot.rest; /** * @author Pavel Šeda * */ public class ApiEndpoints { public static final String BASE_URL = "/api/rest"; public static final String ROOT_URI_USERS = BASE_URL + "/users"; }
320f51e73ebde584be481cd31ea4b5014a30618d
aa5f25d714519ccfda2a89f382dfcefe1b3642fc
/trunk/dmisArea/src/com/techstar/dmis/service/workflow/handler/DDDayPlanSent.java
af3cfe3c018e28e08e40c4b99bd9f9e86ef8711d
[]
no_license
BGCX261/zhouwei-repository-svn-to-git
2b85060757568fadc0d45b526e2546ed1965d48a
cd7f50db245727418d5f1c0061681c11703d073e
refs/heads/master
2021-01-23T03:44:27.914196
2015-08-25T15:45:29
2015-08-25T15:45:29
41,599,666
0
0
null
null
null
null
UTF-8
Java
false
false
1,812
java
// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html // Decompiler options: packimports(3) fieldsfirst ansi // Source File Name: DDDayPlanSent.java package com.techstar.dmis.service.workflow.handler; import com.techstar.dmis.service.workflow.impl.helper.DimsWorkflowHelper; import com.techstar.framework.service.workflow.IAssignment; import java.sql.*; import org.jbpm.JbpmContext; import org.jbpm.context.exe.ContextInstance; import org.jbpm.graph.exe.ExecutionContext; import org.jbpm.taskmgmt.def.Task; import org.jbpm.taskmgmt.exe.Assignable; import org.jbpm.taskmgmt.exe.TaskInstance; public class DDDayPlanSent implements IAssignment { public DDDayPlanSent() { } public void assign(Assignable arg0, ExecutionContext arg1) throws Exception { arg1.getTaskInstance().setBussId((String)arg1.getContextInstance().getVariable("businessId")); long taskId = arg1.getTaskInstance().getTask().getId(); String taskRoles = ""; String agencyRoles = ""; Connection connection = arg1.getJbpmContext().getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet; for(resultSet = statement.executeQuery("select TASK_ROLE,AGENCY_ROLE from JBPM_EXT_PERMISSION where task_id='" + taskId + "' "); resultSet.next();) { taskRoles = resultSet.getString("TASK_ROLE"); agencyRoles = resultSet.getString("AGENCY_ROLE"); } resultSet.close(); statement.close(); String currentUserIds[] = DimsWorkflowHelper.getCurrentUsers(taskRoles, agencyRoles); arg0.setPooledActors(currentUserIds); } }
be5865ef5e1083e4dc13a47eebd8a605114f2750
aa6997aba1475b414c1688c9acb482ebf06511d9
/src/com/sun/org/apache/xml/internal/serializer/WriterToUTF8Buffered.java
b494bdb2d3ddd339fd98c3adf9acfe7455953468
[]
no_license
yueny/JDKSource1.8
eefb5bc88b80ae065db4bc63ac4697bd83f1383e
b88b99265ecf7a98777dd23bccaaff8846baaa98
refs/heads/master
2021-06-28T00:47:52.426412
2020-12-17T13:34:40
2020-12-17T13:34:40
196,523,101
4
2
null
null
null
null
UTF-8
Java
false
false
15,892
java
/* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 1999-2005 The Apache Software Foundation. * * 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. */ /* * $Id: WriterToUTF8Buffered.java,v 1.2.4.1 2005/09/15 08:15:31 suresh_emailid Exp $ */ package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * This class writes unicode characters to a byte stream (java.io.OutputStream) * as quickly as possible. It buffers the output in an internal * buffer which must be flushed to the OutputStream when done. This flushing * is done via the close() flush() or flushBuffer() method. * * This class is only used internally within Xalan. * * @xsl.usage internal */ final class WriterToUTF8Buffered extends Writer implements WriterChain { /** * number of bytes that the byte buffer can hold. * This is a fixed constant is used rather than m_outputBytes.lenght for performance. */ private static final int BYTES_MAX = 16 * 1024; /** * number of characters that the character buffer can hold. * This is 1/3 of the number of bytes because UTF-8 encoding * can expand one unicode character by up to 3 bytes. */ private static final int CHARS_MAX = (BYTES_MAX / 3); // private static final int /** * The byte stream to write to. (sc & sb remove final to compile in JDK 1.1.8) */ private final OutputStream m_os; /** * The internal buffer where data is stored. * (sc & sb remove final to compile in JDK 1.1.8) */ private final byte m_outputBytes[]; private final char m_inputChars[]; /** * The number of valid bytes in the buffer. This value is always * in the range <tt>0</tt> through <tt>m_outputBytes.length</tt>; elements * <tt>m_outputBytes[0]</tt> through <tt>m_outputBytes[count-1]</tt> contain valid * byte data. */ private int count; /** * Create an buffered UTF-8 writer. * * @param out the underlying output stream. */ public WriterToUTF8Buffered(OutputStream out) throws UnsupportedEncodingException { m_os = out; // get 3 extra bytes to make buffer overflow checking simpler and faster // we won't have to keep checking for a few extra characters m_outputBytes = new byte[BYTES_MAX + 3]; // Big enough to hold the input chars that will be transformed // into output bytes in m_ouputBytes. m_inputChars = new char[CHARS_MAX + 2]; count = 0; // the old body of this constructor, before the buffersize was changed to a constant // this(out, 8*1024); } /** * Create an buffered UTF-8 writer to write data to the * specified underlying output stream with the specified buffer * size. * * @param out the underlying output stream. * @param size the buffer size. * @exception IllegalArgumentException if size <= 0. */ // public WriterToUTF8Buffered(final OutputStream out, final int size) // { // // m_os = out; // // if (size <= 0) // { // throw new IllegalArgumentException( // SerializerMessages.createMessage(SerializerErrorResources.ER_BUFFER_SIZE_LESSTHAN_ZERO, null)); //"Buffer size <= 0"); // } // // m_outputBytes = new byte[size]; // count = 0; // } /** * Write a single character. The character to be written is contained in * the 16 low-order bits of the given integer value; the 16 high-order bits * are ignored. * * <p> Subclasses that intend to support efficient single-character output * should override this method. * * @param c int specifying a character to be written. * @throws IOException If an I/O error occurs */ public void write(final int c) throws IOException { /* If we are close to the end of the buffer then flush it. * Remember the buffer can hold a few more bytes than BYTES_MAX */ if (count >= BYTES_MAX) { flushBuffer(); } if (c < 0x80) { m_outputBytes[count++] = (byte) (c); } else if (c < 0x800) { m_outputBytes[count++] = (byte) (0xc0 + (c >> 6)); m_outputBytes[count++] = (byte) (0x80 + (c & 0x3f)); } else if (c < 0x10000) { m_outputBytes[count++] = (byte) (0xe0 + (c >> 12)); m_outputBytes[count++] = (byte) (0x80 + ((c >> 6) & 0x3f)); m_outputBytes[count++] = (byte) (0x80 + (c & 0x3f)); } else { m_outputBytes[count++] = (byte) (0xf0 + (c >> 18)); m_outputBytes[count++] = (byte) (0x80 + ((c >> 12) & 0x3f)); m_outputBytes[count++] = (byte) (0x80 + ((c >> 6) & 0x3f)); m_outputBytes[count++] = (byte) (0x80 + (c & 0x3f)); } } /** * Write a portion of an array of characters. * * @param chars Array of characters * @param start Offset from which to start writing characters * @param length Number of characters to write * @throws IOException If an I/O error occurs */ public void write(final char chars[], final int start, final int length) throws java.io.IOException { // We multiply the length by three since this is the maximum length // of the characters that we can put into the buffer. It is possible // for each Unicode character to expand to three bytes. int lengthx3 = 3 * length; if (lengthx3 >= BYTES_MAX - count) { // The requested length is greater than the unused part of the buffer flushBuffer(); if (lengthx3 > BYTES_MAX) { /* * The requested length exceeds the size of the buffer. * Cut the buffer up into chunks, each of which will * not cause an overflow to the output buffer m_outputBytes, * and make multiple recursive calls. * Be careful about integer overflows in multiplication. */ int split = length / CHARS_MAX; final int chunks; if (length % CHARS_MAX > 0) { chunks = split + 1; } else { chunks = split; } int end_chunk = start; for (int chunk = 1; chunk <= chunks; chunk++) { int start_chunk = end_chunk; end_chunk = start + (int) ((((long) length) * chunk) / chunks); // Adjust the end of the chunk if it ends on a high char // of a Unicode surrogate pair and low char of the pair // is not going to be in the same chunk final char c = chars[end_chunk - 1]; int ic = chars[end_chunk - 1]; if (c >= 0xD800 && c <= 0xDBFF) { // The last Java char that we were going // to process is the first of a // Java surrogate char pair that // represent a Unicode character. if (end_chunk < start + length) { // Avoid spanning by including the low // char in the current chunk of chars. end_chunk++; } else { /* This is the last char of the last chunk, * and it is the high char of a high/low pair with * no low char provided. * TODO: error message needed. * The char array incorrectly ends in a high char * of a high/low surrogate pair, but there is * no corresponding low as the high is the last char */ end_chunk--; } } int len_chunk = (end_chunk - start_chunk); this.write(chars, start_chunk, len_chunk); } return; } } final int n = length + start; final byte[] buf_loc = m_outputBytes; // local reference for faster access int count_loc = count; // local integer for faster access int i = start; { /* This block could be omitted and the code would produce * the same result. But this block exists to give the JIT * a better chance of optimizing a tight and common loop which * occurs when writing out ASCII characters. */ char c; for (; i < n && (c = chars[i]) < 0x80; i++) { buf_loc[count_loc++] = (byte) c; } } for (; i < n; i++) { final char c = chars[i]; if (c < 0x80) { buf_loc[count_loc++] = (byte) (c); } else if (c < 0x800) { buf_loc[count_loc++] = (byte) (0xc0 + (c >> 6)); buf_loc[count_loc++] = (byte) (0x80 + (c & 0x3f)); } /** * The following else if condition is added to support XML 1.1 Characters for * UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* * Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) * [1101 11yy] [yyxx xxxx] (low surrogate) * * uuuuu = wwww + 1 */ else if (c >= 0xD800 && c <= 0xDBFF) { char high, low; high = c; i++; low = chars[i]; buf_loc[count_loc++] = (byte) (0xF0 | (((high + 0x40) >> 8) & 0xf0)); buf_loc[count_loc++] = (byte) (0x80 | (((high + 0x40) >> 2) & 0x3f)); buf_loc[count_loc++] = (byte) (0x80 | ((low >> 6) & 0x0f) + ((high << 4) & 0x30)); buf_loc[count_loc++] = (byte) (0x80 | (low & 0x3f)); } else { buf_loc[count_loc++] = (byte) (0xe0 + (c >> 12)); buf_loc[count_loc++] = (byte) (0x80 + ((c >> 6) & 0x3f)); buf_loc[count_loc++] = (byte) (0x80 + (c & 0x3f)); } } // Store the local integer back into the instance variable count = count_loc; } /** * Write a string. * * @param s String to be written * @throws IOException If an I/O error occurs */ public void write(final String s) throws IOException { // We multiply the length by three since this is the maximum length // of the characters that we can put into the buffer. It is possible // for each Unicode character to expand to three bytes. final int length = s.length(); int lengthx3 = 3 * length; if (lengthx3 >= BYTES_MAX - count) { // The requested length is greater than the unused part of the buffer flushBuffer(); if (lengthx3 > BYTES_MAX) { /* * The requested length exceeds the size of the buffer, * so break it up in chunks that don't exceed the buffer size. */ final int start = 0; int split = length / CHARS_MAX; final int chunks; if (length % CHARS_MAX > 0) { chunks = split + 1; } else { chunks = split; } int end_chunk = 0; for (int chunk = 1; chunk <= chunks; chunk++) { int start_chunk = end_chunk; end_chunk = start + (int) ((((long) length) * chunk) / chunks); s.getChars(start_chunk, end_chunk, m_inputChars, 0); int len_chunk = (end_chunk - start_chunk); // Adjust the end of the chunk if it ends on a high char // of a Unicode surrogate pair and low char of the pair // is not going to be in the same chunk final char c = m_inputChars[len_chunk - 1]; if (c >= 0xD800 && c <= 0xDBFF) { // Exclude char in this chunk, // to avoid spanning a Unicode character // that is in two Java chars as a high/low surrogate end_chunk--; len_chunk--; if (chunk == chunks) { /* TODO: error message needed. * The String incorrectly ends in a high char * of a high/low surrogate pair, but there is * no corresponding low as the high is the last char * Recover by ignoring this last char. */ } } this.write(m_inputChars, 0, len_chunk); } return; } } s.getChars(0, length, m_inputChars, 0); final char[] chars = m_inputChars; final int n = length; final byte[] buf_loc = m_outputBytes; // local reference for faster access int count_loc = count; // local integer for faster access int i = 0; { /* This block could be omitted and the code would produce * the same result. But this block exists to give the JIT * a better chance of optimizing a tight and common loop which * occurs when writing out ASCII characters. */ char c; for (; i < n && (c = chars[i]) < 0x80; i++) { buf_loc[count_loc++] = (byte) c; } } for (; i < n; i++) { final char c = chars[i]; if (c < 0x80) { buf_loc[count_loc++] = (byte) (c); } else if (c < 0x800) { buf_loc[count_loc++] = (byte) (0xc0 + (c >> 6)); buf_loc[count_loc++] = (byte) (0x80 + (c & 0x3f)); } /** * The following else if condition is added to support XML 1.1 Characters for * UTF-8: [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* * Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) * [1101 11yy] [yyxx xxxx] (low surrogate) * * uuuuu = wwww + 1 */ else if (c >= 0xD800 && c <= 0xDBFF) { char high, low; high = c; i++; low = chars[i]; buf_loc[count_loc++] = (byte) (0xF0 | (((high + 0x40) >> 8) & 0xf0)); buf_loc[count_loc++] = (byte) (0x80 | (((high + 0x40) >> 2) & 0x3f)); buf_loc[count_loc++] = (byte) (0x80 | ((low >> 6) & 0x0f) + ((high << 4) & 0x30)); buf_loc[count_loc++] = (byte) (0x80 | (low & 0x3f)); } else { buf_loc[count_loc++] = (byte) (0xe0 + (c >> 12)); buf_loc[count_loc++] = (byte) (0x80 + ((c >> 6) & 0x3f)); buf_loc[count_loc++] = (byte) (0x80 + (c & 0x3f)); } } // Store the local integer back into the instance variable count = count_loc; } /** * Flush the internal buffer */ public void flushBuffer() throws IOException { if (count > 0) { m_os.write(m_outputBytes, 0, count); count = 0; } } /** * Flush the stream. If the stream has saved any characters from the * various write() methods in a buffer, write them immediately to their * intended destination. Then, if that destination is another character or * byte stream, flush it. Thus one flush() invocation will flush all the * buffers in a chain of Writers and OutputStreams. * * @throws IOException If an I/O error occurs */ public void flush() throws java.io.IOException { flushBuffer(); m_os.flush(); } /** * Close the stream, flushing it first. Once a stream has been closed, * further write() or flush() invocations will cause an IOException to be * thrown. Closing a previously-closed stream, however, has no effect. * * @throws IOException If an I/O error occurs */ public void close() throws java.io.IOException { flushBuffer(); m_os.close(); } /** * Get the output stream where the events will be serialized to. * * @return reference to the result stream, or null of only a writer was set. */ public OutputStream getOutputStream() { return m_os; } public Writer getWriter() { // Only one of getWriter() or getOutputStream() can return null // This type of writer wraps an OutputStream, not a Writer. return null; } }
5d6b7b667b823e0015f90796d5dacda4561ac7c3
047a34b168ae085a6cc4fa8ab2784f5755b45ad3
/src/main/java/com/tomas/messenger/presentation/model/request/MessageDetailsRequest.java
6e64148ef79ea6a0a462e92653d3ea6a561bfa02
[]
no_license
TomasKadlcek/MessengerAPI
a98a48974c7af815060bd307d434123525e33926
f8bb80fd190ad2fd7ec99f7d59c8ec4a901f2e13
refs/heads/main
2023-01-20T18:32:01.504159
2020-12-02T15:02:58
2020-12-02T15:02:58
317,868,283
1
0
null
null
null
null
UTF-8
Java
false
false
493
java
package com.tomas.messenger.presentation.model.request; public class MessageDetailsRequest { private String receiverUserId; private String message; public String getReceiverUserIdId() { return receiverUserId; } public void setReceiverUserId(String receiverId) { this.receiverUserId = receiverId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
5042448a0d0475aa2da46528b7a08f65d04dcf0d
5f82aae041ab05a5e6c3d9ddd8319506191ab055
/Projects/Math/105/src/test/org/apache/commons/math/stat/descriptive/SummaryStatisticsImplTest.java
a57202933b987e97b34c848f071f98b8a33a88e2
[]
no_license
lingming/prapr_data
e9ddabdf971451d46f1ef2cdbee15ce342a6f9dc
be9ababc95df45fd66574c6af01122ed9df3db5d
refs/heads/master
2023-08-14T20:36:23.459190
2021-10-17T13:49:39
2021-10-17T13:49:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,558
java
/* * Copyright 2003-2004 The Apache Software Foundation. * * 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.apache.commons.math.stat.descriptive; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.commons.math.TestUtils; /** * Test cases for the {@link DescriptiveStatistics} class. * * @version $Revision$ $Date$ */ public final class SummaryStatisticsImplTest extends TestCase { private double one = 1; private float twoF = 2; private long twoL = 2; private int three = 3; private double mean = 2; private double sumSq = 18; private double sum = 8; private double var = 0.666666666666666666667; private double std = Math.sqrt(var); private double n = 4; private double min = 1; private double max = 3; private double tolerance = 10E-15; protected SummaryStatistics u = null; public SummaryStatisticsImplTest(String name) { super(name); } public void setUp() { u = SummaryStatistics.newInstance(); } public static Test Norun() { TestSuite suite = new TestSuite(SummaryStatisticsImplTest.class); suite.setName("Frequency Tests"); return suite; } /** test stats */ public void testStats() { assertEquals("total count",0,u.getN(),tolerance); u.addValue(one); u.addValue(twoF); u.addValue(twoL); u.addValue(three); assertEquals("N",n,u.getN(),tolerance); assertEquals("sum",sum,u.getSum(),tolerance); assertEquals("sumsq",sumSq,u.getSumsq(),tolerance); assertEquals("var",var,u.getVariance(),tolerance); assertEquals("std",std,u.getStandardDeviation(),tolerance); assertEquals("mean",mean,u.getMean(),tolerance); assertEquals("min",min,u.getMin(),tolerance); assertEquals("max",max,u.getMax(),tolerance); u.clear(); assertEquals("total count",0,u.getN(),tolerance); } public void testN0andN1Conditions() throws Exception { assertTrue("Mean of n = 0 set should be NaN", Double.isNaN( u.getMean() ) ); assertTrue("Standard Deviation of n = 0 set should be NaN", Double.isNaN( u.getStandardDeviation() ) ); assertTrue("Variance of n = 0 set should be NaN", Double.isNaN(u.getVariance() ) ); /* n=1 */ u.addValue(one); assertTrue("mean should be one (n = 1)", u.getMean() == one); assertTrue("geometric should be one (n = 1) instead it is " + u.getGeometricMean(), u.getGeometricMean() == one); assertTrue("Std should be zero (n = 1)", u.getStandardDeviation() == 0.0); assertTrue("variance should be zero (n = 1)", u.getVariance() == 0.0); /* n=2 */ u.addValue(twoF); assertTrue("Std should not be zero (n = 2)", u.getStandardDeviation() != 0.0); assertTrue("variance should not be zero (n = 2)", u.getVariance() != 0.0); } public void testProductAndGeometricMean() throws Exception { u.addValue( 1.0 ); u.addValue( 2.0 ); u.addValue( 3.0 ); u.addValue( 4.0 ); assertEquals( "Geometric mean not expected", 2.213364, u.getGeometricMean(), 0.00001 ); } public void testNaNContracts() { double nan = Double.NaN; assertTrue("mean not NaN",Double.isNaN(u.getMean())); assertTrue("min not NaN",Double.isNaN(u.getMin())); assertTrue("std dev not NaN",Double.isNaN(u.getStandardDeviation())); assertTrue("var not NaN",Double.isNaN(u.getVariance())); assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(1.0); assertEquals( "mean not expected", 1.0, u.getMean(), Double.MIN_VALUE); assertEquals( "variance not expected", 0.0, u.getVariance(), Double.MIN_VALUE); assertEquals( "geometric mean not expected", 1.0, u.getGeometricMean(), Double.MIN_VALUE); u.addValue(-1.0); assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); u.addValue(0.0); assertTrue("geom mean not NaN",Double.isNaN(u.getGeometricMean())); //FiXME: test all other NaN contract specs } public void testGetSummary() { StatisticalSummary summary = u.getSummary(); verifySummary(summary); u.addValue(1d); summary = u.getSummary(); verifySummary(summary); u.addValue(2d); summary = u.getSummary(); verifySummary(summary); u.addValue(2d); summary = u.getSummary(); verifySummary(summary); } public void testSerialization() { // Empty test TestUtils.checkSerializedEquality(u); SummaryStatistics s = (SummaryStatistics) TestUtils.serializeAndRecover(u); StatisticalSummary summary = s.getSummary(); verifySummary(summary); // Add some data u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); u.addValue(5d); // Test again TestUtils.checkSerializedEquality(u); s = (SummaryStatistics) TestUtils.serializeAndRecover(u); summary = s.getSummary(); verifySummary(summary); } public void testEqualsAndHashCode() { SummaryStatistics t = null; int emptyHash = u.hashCode(); assertTrue("reflexive", u.equals(u)); assertFalse("non-null compared to null", u.equals(t)); assertFalse("wrong type", u.equals(new Double(0))); t = SummaryStatistics.newInstance(); assertTrue("empty instances should be equal", t.equals(u)); assertTrue("empty instances should be equal", u.equals(t)); assertEquals("empty hash code", emptyHash, t.hashCode()); // Add some data to u u.addValue(2d); u.addValue(1d); u.addValue(3d); u.addValue(4d); assertFalse("different n's should make instances not equal", t.equals(u)); assertFalse("different n's should make instances not equal", u.equals(t)); assertTrue("different n's should make hashcodes different", u.hashCode() != t.hashCode()); //Add data in different order to t, should not affect identity or hashcode t.addValue(4d); t.addValue(2d); t.addValue(3d); t.addValue(1d); assertTrue("summaries based on same data should be equal", t.equals(u)); assertTrue("summaries based on same data should be equal", u.equals(t)); assertEquals("summaries based on same data should have same hashcodes", u.hashCode(), t.hashCode()); // Clear and make sure summaries are indistinguishable from empty summary u.clear(); t.clear(); assertTrue("empty instances should be equal", t.equals(u)); assertTrue("empty instances should be equal", u.equals(t)); assertEquals("empty hash code", emptyHash, t.hashCode()); assertEquals("empty hash code", emptyHash, u.hashCode()); } private void verifySummary(StatisticalSummary s) { assertEquals("N",s.getN(),u.getN()); TestUtils.assertEquals("sum",s.getSum(),u.getSum(),tolerance); TestUtils.assertEquals("var",s.getVariance(),u.getVariance(),tolerance); TestUtils.assertEquals("std",s.getStandardDeviation(),u.getStandardDeviation(),tolerance); TestUtils.assertEquals("mean",s.getMean(),u.getMean(),tolerance); TestUtils.assertEquals("min",s.getMin(),u.getMin(),tolerance); TestUtils.assertEquals("max",s.getMax(),u.getMax(),tolerance); } }
bcf91dcd45400638ff50015f4dfd255245a51e25
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/63/1957.java
3979e586e189ba370a328f42f9a631a6eec9e555
[ "MIT" ]
permissive
qiuchili/ggnn_graph_classification
c2090fefe11f8bf650e734442eb96996a54dc112
291ff02404555511b94a4f477c6974ebd62dcf44
refs/heads/master
2021-10-18T14:54:26.154367
2018-10-21T23:34:14
2018-10-21T23:34:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,214
java
package <missing>; public class GlobalMembers { public static int Main() { int[][] a = new int[100][100]; int[][] b = new int[100][100]; int x1; int y1; int x2; int y2; int x3; int y3; int c; int d; int[][] e = new int[100][100]; char i; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { x1 = Integer.parseInt(tempVar); } String tempVar2 = ConsoleInput.scanfRead(" "); if (tempVar2 != null) { y1 = Integer.parseInt(tempVar2); } for (c = 0;c <= x1 - 1;c++) { for (d = 0;d <= y1 - 1;d++) { String tempVar3 = ConsoleInput.scanfRead(); if (tempVar3 != null) { a[c][d] = Integer.parseInt(tempVar3); } String tempVar4 = ConsoleInput.scanfRead(null, 1); if (tempVar4 != null) { i = tempVar4.charAt(0); } if (i != ' ') { break; } else { ; } } } String tempVar5 = ConsoleInput.scanfRead(); if (tempVar5 != null) { x2 = Integer.parseInt(tempVar5); } String tempVar6 = ConsoleInput.scanfRead(" "); if (tempVar6 != null) { y2 = Integer.parseInt(tempVar6); } for (c = 0;c <= x2 - 1;c++) { for (d = 0;d <= y2 - 1;d++) { String tempVar7 = ConsoleInput.scanfRead(); if (tempVar7 != null) { b[c][d] = Integer.parseInt(tempVar7); } String tempVar8 = ConsoleInput.scanfRead(null, 1); if (tempVar8 != null) { i = tempVar8.charAt(0); } if (i != ' ') { break; } else { ; } } } x3 = x1; y3 = y2; // printf("%d\n",a[0][4]); for (c = 0;c <= x3 - 1;c++) { for (d = 0;d <= y3 - 1;d++) { e[c][d] = 0; for (i = 0;i <= x2 - 1;i++) { e[c][d] = e[c][d] + a[c][i] * b[i][d]; //printf("%d %d %d\n",i,c,d); //printf("%d %d %d\n",a[c][i],b[i][d],e[c][d]); } } } for (c = 0;c <= x3 - 1;c++) { for (d = 0;d <= y3 - 2;d++) { System.out.printf("%d ",e[c][d]); } System.out.printf("%d\n",e[c][y3 - 1]); } //printf("%d",e[0][1]); } }
6ee315bda7d6a28aa47275bae154ac8ef9839e5d
182f4e1c795d4eab5ad5fd3a6eab11be3c4c2588
/src/main/java/com/github/crob1140/confluence/content/SortDirection.java
aca1f23ad88f5844587996f4e8bc6028b37129e9
[ "MIT" ]
permissive
jeansalama/confluence-java-client
3b1db66027d6ba57ac9f8e71e27f81d583763f53
7aed4f9eb7ceb0907e0e7a97d8b3c50066172143
refs/heads/master
2023-03-23T20:45:50.050828
2019-09-01T03:56:33
2019-09-01T03:56:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
516
java
package com.github.crob1140.confluence.content; /** * This enumerable represents the possible directions that can be used in an order-by clause */ public enum SortDirection { ASCENDING("asc"), DESCENDING("desc"); private String identifier; SortDirection(String identifier) { this.identifier = identifier; } /** * This method returns the identifier for the direction. * * @return The identifier for the direction. */ public String getIdentifier() { return this.identifier; } }
d828d500e917c79db3d6de94be2e2d0780c09d51
1665a423eaf7cffe71b3af4150bbb7677e9d2d54
/src/main/java/com/poker/model/Card.java
e671c1aee31f1b897de67cd2b6c4aa02a8efc0d4
[]
no_license
DKS1974/poker
824bb86b0943e5e9c9cb20cfd168926b1815795f
cbd7251e25fab2ab6d650170d7adeae70da71a5a
refs/heads/master
2021-02-04T04:54:00.890289
2020-02-27T22:14:25
2020-02-27T22:14:25
243,620,792
0
0
null
null
null
null
UTF-8
Java
false
false
277
java
package com.poker.model; import lombok.*; @NoArgsConstructor @Setter @Getter @Builder @AllArgsConstructor public class Card { private Ranks rank; private Suits suit; public @Override String toString() { return rank.getAsChar() + suit.name(); } }
25743fb0f4b28e92cc10373ab1b3105443e0d0ff
1ecf6fcce9fa81cf42d31629b2ebecd4caf4444c
/uizabase/src/test/java/vn/uiza/restapi/restclient/BaseRestClientTest.java
ebd3bc173a7b258692bab65380bf59c553d8abfe
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
uizaio/uiza-android-sdk-player
a913b4ee5e47bb160583cc5c6cb015ca3c6134ea
dec7c2247ee1cfce604b6cbe1b2bb490559fdf02
refs/heads/master
2021-06-02T12:09:07.895425
2019-08-15T08:02:58
2019-08-15T08:02:58
131,246,500
11
14
BSD-2-Clause
2019-12-23T12:15:48
2018-04-27T04:43:58
Java
UTF-8
Java
false
false
918
java
package vn.uiza.restapi.restclient; import android.text.TextUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest(TextUtils.class) @PowerMockIgnore("javax.net.ssl.*") @Ignore(value = "This is base class, and no testcase here") public class BaseRestClientTest { String validURL = "https://uiza.io"; String inValidURL = "uiza.io"; String authorizationHeader = "Authorization"; String accessToken = "AccessToken"; String testHeader = "TEST"; String testHeaderValue = "TEST_VALUE"; @Before public void setup() { PowerMockito.mockStatic(TextUtils.class); } }
89bcb2bbb61738b0118221153412c95c9d9e73e7
0c669c238f7106566f275b24549932f127e69f56
/app/src/main/java/com/jinhui/androidprojecthelper/base/baseadapter/ScaleInAnimation.java
805981c123c1dc7fefc097c9e9910ffb4cf96383
[]
no_license
jimmyleung/AndroidProjectHelper
28cfb74a9bcb7eb2efdf7ca7b04f0807c1b3bd53
e0f60a66514cd9b6abf0464e7f8500120abde240
refs/heads/master
2020-05-02T18:41:48.449758
2018-09-22T08:14:22
2018-09-22T08:14:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
708
java
package com.jinhui.androidprojecthelper.base.baseadapter; import android.animation.Animator; import android.animation.ObjectAnimator; import android.view.View; public class ScaleInAnimation implements BaseAnimation { private static final float DEFAULT_SCALE_FROM = .5f; private final float mFrom; public ScaleInAnimation() { this(DEFAULT_SCALE_FROM); } public ScaleInAnimation(float from) { mFrom = from; } @Override public Animator[] getAnimators(View view) { ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", mFrom, 1f); ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", mFrom, 1f); return new ObjectAnimator[] { scaleX, scaleY }; } }
8eb329bde93bd744a2f6e3ed9868bb3a004d8674
0ad84c9bd6e83abd5cff0761c26a3d72f8a6e51c
/src/main/java/state/connection/StateCerrado.java
b1292b775f04de1be264650a23e029ee8e36f491
[]
no_license
dsmontoro/PD.ECP1
1daba68a287d3ccc39d5506e549a30375eb71540
49d8a2108457f644c594125b93e6b070f5462443
refs/heads/master
2021-01-10T12:21:59.506506
2015-10-18T10:59:55
2015-10-18T10:59:55
43,964,763
0
0
null
null
null
null
UTF-8
Java
false
false
935
java
package state.connection; public class StateCerrado extends State { private static final Estado estado = Estado.CERRADO; @Override public void abrir(Conexion conexion) { conexion.setState(new StatePreparado()); } @Override public void cerrar(Conexion conexion) { } @Override public void parar(Conexion conexion) { throw new UnsupportedOperationException("Acción no permitida... "); } @Override public void iniciar(Conexion conexion) { throw new UnsupportedOperationException("Acción no permitida... "); } @Override public void enviar(String msg, Conexion conexion) { throw new UnsupportedOperationException("Acción no permitida... "); } @Override public void recibir(int respuesta, Conexion conexion) { throw new UnsupportedOperationException("Acción no permitida... "); } @Override public Estado getEstado() { return estado; } }
79d91367ae5af900aa5951b2d8d25b7090f2e28c
6da41ff4cb5b2534711d7db3196573ba6f2c4195
/src/main/java/com/tkextraction/repository/CVRepository.java
aac4e2c7ada4a1fa92cc379170dbadf4c99461b3
[]
no_license
IliyaDimchoglo/TKExtraction
291db05b185a421e904e1c002e98d852c49711fa
ce396032b5792f266c2f029087546d420f932a3f
refs/heads/master
2023-07-08T06:43:51.046062
2021-08-10T12:05:58
2021-08-10T12:05:58
394,581,625
2
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.tkextraction.repository; import com.tkextraction.domain.CVEntity; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; import java.util.UUID; public interface CVRepository extends JpaRepository<CVEntity, UUID> { Optional<CVEntity> findByProcessIdAndUserUserName(Long processId, String userName); Optional<CVEntity> findByUserUserName(String userName); }
4fe322fedc156b0297a222ab8bd7b1021a3f4fbd
5b20d9882c6b42bc5f30bf42414cd2a734e30fd5
/FakeSearchView/app/src/main/java/com/github/leonardoxh/fakesearchview/FakeSearchView.java
dc60a16d3b0b58b70777d162438ed1622c73344f
[ "Apache-2.0" ]
permissive
longtaoge/FakeSearchView
bc1944ab5e60060cc9261638ec4a50eb32920a85
219efac5cbf5002d9d32eac03f0508418d784fd5
refs/heads/master
2021-01-18T13:18:57.440087
2015-04-22T14:45:25
2015-04-22T14:45:25
34,391,691
1
0
null
2015-04-22T13:24:01
2015-04-22T13:24:01
null
UTF-8
Java
false
false
3,786
java
/* * Copyright 2015 Leonardo Rossetto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.leonardoxh.fakesearchview; import android.annotation.TargetApi; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; /** * The main lib actor this is a custom FrameLayout * wrapper with an EditText with a simple interface to perform the search * it collects the user input and pass to an Activity or a Fragment or where you need * * @author Leonardo Rossetto */ public class FakeSearchView extends FrameLayout implements TextWatcher, TextView.OnEditorActionListener { private OnSearchListener searchListener; public FakeSearchView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public FakeSearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @TargetApi(21) public FakeSearchView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } public FakeSearchView(Context context) { super(context); init(context); } public void setOnSearchListener(OnSearchListener searchListener) { this.searchListener = searchListener; } /** * Inflate the layout to this FrameLayout wrapper * @param context */ private void init(Context context) { View view = LayoutInflater.from(context).inflate(R.layout.fake_search_view, this, true); EditText wrappedEditText = (EditText) view.findViewById(R.id.wrapped_search); wrappedEditText.addTextChangedListener(this); wrappedEditText.setOnEditorActionListener(this); } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { if (searchListener != null) { searchListener.onSearch(charSequence); } else { Log.w(getClass().getName(), "SearchListener == null"); } } @Override public void afterTextChanged(Editable editable) { } @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (searchListener != null) { searchListener.onSearchHint(textView.getText()); } else { Log.w(getClass().getName(), "SearchListener == null"); } return true; } /** * This interface is an custom method to wrapp the * TextWatcher implementation and provide the search constraint * * @author Leonardo Rossetto */ public interface OnSearchListener { /** * This method is called every time the EditText change it content * @param constraint the current input data */ void onSearch(CharSequence constraint); /** * This method is called when the user press the search button on the keyboard * @param constraint the current input data */ void onSearchHint(CharSequence constraint); } }
d9b4bfa9228f9c8552be8eb3c218d08acb452700
6aefa64d30949edfff0cd9da8283ae93f57043fa
/agrest-cayenne/src/test/java/io/agrest/cayenne/POST/RelateIT.java
bd45f6267f4a9d06e87b98e43d5fd849ff226406
[ "Apache-2.0" ]
permissive
agrestio/agrest
75e58103fea11c797093e9a86b2475578c7fd7ac
328b9610b7a490d6fcb5c1554a3ef6bf7e5e4248
refs/heads/master
2023-09-05T02:29:17.222528
2023-07-31T11:48:20
2023-07-31T11:48:20
19,821,698
25
15
Apache-2.0
2023-07-29T16:43:45
2014-05-15T14:09:45
Java
UTF-8
Java
false
false
6,334
java
package io.agrest.cayenne.POST; import io.agrest.DataResponse; import io.agrest.cayenne.cayenne.main.E2; import io.agrest.cayenne.cayenne.main.E29; import io.agrest.cayenne.cayenne.main.E3; import io.agrest.cayenne.cayenne.main.E30; import io.agrest.cayenne.unit.main.MainDbTest; import io.agrest.cayenne.unit.main.MainModelTester; import io.agrest.jaxrs3.AgJaxrs; import io.bootique.junit5.BQTestTool; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.Configuration; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriInfo; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; public class RelateIT extends MainDbTest { @BQTestTool static final MainModelTester tester = tester(Resource.class) .entitiesAndDependencies(E2.class, E3.class, E29.class, E30.class) .build(); @Test public void toOne() { tester.e2().insertColumns("id_", "name") .values(1, "xxx") .values(8, "yyy").exec(); tester.target("/e3") .post("{\"e2\":8,\"name\":\"MM\"}") .wasCreated() .replaceId("RID") .bodyEquals(1, "{\"id\":RID,\"name\":\"MM\",\"phoneNumber\":null}"); tester.e3().matcher().assertOneMatch(); tester.e3().matcher().eq("e2_id", 8).andEq("name", "MM").assertOneMatch(); } @Test public void toOne_Null() { tester.target("/e3") .post("{\"e2\":null,\"name\":\"MM\"}") .wasCreated() .replaceId("RID") .bodyEquals(1, "{\"id\":RID,\"name\":\"MM\",\"phoneNumber\":null}"); tester.e3().matcher().assertOneMatch(); tester.e3().matcher().eq("e2_id", null).assertOneMatch(); } @Test public void toOne_CompoundId() { tester.e29().insertColumns("id1", "id2") .values(11, 21) .values(12, 22).exec(); tester.target("/e30") .queryParam("include", "e29.id") .post("{\"e29\":{\"db:id1\":11,\"id2Prop\":21}}") .wasCreated() .replaceId("RID") .bodyEquals(1, "{\"id\":RID,\"e29\":{\"id\":{\"db:id1\":11,\"id2Prop\":21}}}"); tester.e30().matcher().assertOneMatch(); } @Test public void toOne_BadFK() { tester.target("/e3") .post("{\"e2\":15,\"name\":\"MM\"}") .wasNotFound() .bodyEquals("{\"message\":\"Related object 'E2' with id of '15' is not found\"}"); tester.e3().matcher().assertNoMatches(); } @Test public void toMany() { tester.e3().insertColumns("id_", "name") .values(1, "xxx") .values(8, "yyy").exec(); Long id = tester.target("/e2") .queryParam("include", E2.E3S.getName()) .queryParam("exclude", E2.ADDRESS.getName(), E2.E3S.dot(E3.NAME).getName(), E2.E3S.dot(E3.PHONE_NUMBER).getName()) .post("{\"e3s\":[1,8],\"name\":\"MM\"}") .wasCreated() .replaceId("RID") .bodyEquals(1, "{\"id\":RID,\"e3s\":[{\"id\":1},{\"id\":8}],\"name\":\"MM\"}") .getId(); assertNotNull(id); tester.e3().matcher().eq("e2_id", id).assertMatches(2); } @Test // so while e29 -> e30 is a multi-column join, e30's own ID is single column public void toMany_OverMultiKeyRelationship() { tester.e30().insertColumns("id") .values(100) .values(101) .values(102).exec(); tester.target("/e29") .queryParam("include", "e30s.id") .queryParam("exclude", "id") .post("{\"id2Prop\":54,\"e30s\":[100, 102]}") .wasCreated() .bodyEquals(1, "{\"e30s\":[{\"id\":100},{\"id\":102}],\"id2Prop\":54}"); tester.e29().matcher().assertOneMatch(); } @Test public void toMany_AsNewObjects() { tester.target("/e2") .queryParam("include", "name", "e3s.name") .post("{\"e3s\":[{\"name\":\"new_to_many1\"},{\"name\":\"new_to_many2\"}],\"name\":\"MM\"}") .wasCreated() .bodyEquals(1, "{\"e3s\":[],\"name\":\"MM\"}") .getId(); tester.e2().matcher().assertOneMatch(); tester.e3().matcher().assertNoMatches(); } @Test public void toOne_AsNewObject() { // While Agrest does not yet support processing full related objects, it should not fail either. // Testing this condition here. tester.target("/e3") .queryParam("include", "name", "e2.id") .post("{\"e2\":{\"name\":\"new_to_one\"},\"name\":\"MM\"}") .wasCreated() .replaceId("RID") .bodyEquals(1, "{\"e2\":null,\"name\":\"MM\"}"); tester.e3().matcher().assertOneMatch(); tester.e2().matcher().assertNoMatches(); } @Path("") public static class Resource { @Context private Configuration config; @POST @Path("e2") public DataResponse<E2> createE2(String targetData, @Context UriInfo uriInfo) { return AgJaxrs.create(E2.class, config).clientParams(uriInfo.getQueryParameters()).syncAndSelect(targetData); } @POST @Path("e3") public DataResponse<E3> create(@Context UriInfo uriInfo, String requestBody) { return AgJaxrs.create(E3.class, config).clientParams(uriInfo.getQueryParameters()).syncAndSelect(requestBody); } @POST @Path("e29") public DataResponse<E29> createE29(String targetData, @Context UriInfo uriInfo) { return AgJaxrs.create(E29.class, config) .clientParams(uriInfo.getQueryParameters()) .syncAndSelect(targetData); } @POST @Path("e30") public DataResponse<E30> createE30(String targetData, @Context UriInfo uriInfo) { return AgJaxrs.create(E30.class, config) .clientParams(uriInfo.getQueryParameters()) .syncAndSelect(targetData); } } }
30f0d29984a8bf4bd7d680d3a1828413ca69a364
8eabbaac7e38e33077156498a5e0da9152af759c
/ControlleurGUI.java
5721b33b1602be94863dacd57474045ec5294093
[]
no_license
marcantoinelecuyer/FlappyGhost
c1571e4fda514b3cc68cba6f43922bfa871a2b4e
6e380c5eaf0fefe9dc1f07a6a12cfff71685331d
refs/heads/master
2020-05-18T03:48:55.745662
2019-04-29T23:15:48
2019-04-29T23:15:48
184,156,293
0
0
null
null
null
null
UTF-8
Java
false
false
3,744
java
import java.util.ArrayList; public class ControlleurGUI { // La vue est le point d'entrée de l'Application JavaFX private FlappyGhost vue; public Ghost player; private ArrayList<Obstacle> obstacles; private boolean debugging; private boolean[] twado; public double posPause; ControlleurGUI(FlappyGhost vue) { this.vue = vue; this.player = new Ghost(); obstacles=new ArrayList<>(); debugging=false;//Activation du mode debug twado=new boolean[5];//Activation du code secret } public void sauter(){ ((Ghost) player).sauter(); } public void setDebugging(boolean debug){ debugging=debug; } public void collision() { for (Obstacle obstacle : obstacles) { if (((Ghost) player).collision(obstacle)) { obstacle.setCollision(true); }else{ obstacle.setCollision(false); } } if (!debugging&&player.getCollide()) {//Si le joueur meurt vue.recommencer(); } player.setCollide(false); } /** * Changer le score affiché sur la fenetre de jeu */ public void updateScore(){ vue.changerScore(player.getScore()); } public double getVitesse(){ return player.getVitesse(); } /** * Ajoute un type d'obstacle aléatoire */ public void ajouterObstacles() { switch ((int) (Math.random() * 5)) { case 0: obstacles.add(new Simple()); break; case 1: obstacles.add(new Sinus()); break; case 2: obstacles.add(new Quantique()); break; case 3: obstacles.add(new Explosion()); break; case 4: obstacles.add(new Oscillation()); break; } } /** * Anime les éléments * @param deltaTime */ public void animer(double deltaTime, boolean pause) { //Animer les obstacles if (!pause) { for (Obstacle obstacle : obstacles) { if (obstacle.getX() < -200) { obstacles.remove(obstacle);//Enlever si hors fenetre break; } else { vue.draw(obstacle, debugging); obstacle.update(deltaTime, (Ghost) player); } } //Animer le joueur (ghost) vue.draw(player, debugging); player.update(deltaTime, null); } else { player.setY(posPause); } } public void codeSecret(String value){ switch(value){ case "T": twado[0]=true; break; case "W": if(twado[0]) twado[1]=true; break; case "A": if(twado[1]) twado[2]=true; break; case "D": if(twado[2]) twado[3]=true; break; case "O": if(twado[3]) twado[4]=true; break; default://Reset twado si autre caractère twado = new boolean[5]; return; } //Return si tous les elements de twado ne sont pas true for (int i = 0; i < twado.length; i++) { if(!twado[i]){ return; } } //Exécuter le code secret twado = new boolean[5]; vue.codeSecret(); } }
0022bba1bb2980c3eb6fec9404edb35b35331766
f857d6dee05996f018006936ac51ea527966578c
/Veda2TestAutomation/src/com/viteos/veda/master/legalentitytestscripts/LegalEntityMaster_CheckerOperations_TC2.java
0bacd8d996d59234dfe5329107440b9f02b1bb4c
[]
no_license
MummanaSubramanya/VEDA_v2.0_QA
6d736a71507a09f34812fca30a87c444615c9a93
1760e3aacc0d2bc2e620d9080d49ce1dddf1dce6
refs/heads/master
2020-04-23T03:46:58.743651
2016-07-06T07:03:28
2016-07-06T07:03:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,170
java
package com.viteos.veda.master.legalentitytestscripts; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.tenx.framework.lib.Messages; import com.tenx.framework.lib.Utilities; import com.tenx.framework.reporting.Reporting; import com.viteos.veda.master.lib.Global; import com.viteos.veda.master.lib.NewUICommonFunctions; import com.viteos.veda.master.lib.NewUICommonFunctions.dashboardMainDropdownToSelect; import com.viteos.veda.master.lib.NewUICommonFunctions.dashboardSubDropdownToSelect; public class LegalEntityMaster_CheckerOperations_TC2 { static boolean bStatus; static String sRefrenceLESheetName = "LegalEntityDetailsTestData"; @BeforeMethod public static void setUp(){ Reporting.Functionality ="Legal Entity Master"; Reporting.Testcasename = "Open Application"; bStatus = NewUICommonFunctions.loginToApplication(Global.sCheckerUserName, Global.sCheckerPassword); if(!bStatus){ Reporting.logResults("Fail", "Login into application", "Login to application Failed.Error: "+Messages.errorMsg); Assert.fail(Messages.errorMsg); } Reporting.logResults("Pass", "Login into application ", "Login into application successfully"); } @Test public static void testCheckerOperations(){ try{ Map<String, Map<String, String>> mapAllLegalEntityDetails = Utilities.readMultipleTestData(Global.sLegalEntityTestDataFilePath,sRefrenceLESheetName,"Y"); Map<String, Map<String, String>> VerifyMap = new HashMap<String, Map<String, String>>(); for(int index = 1;index <= mapAllLegalEntityDetails.size();index++){ Map<String, String> mapLegalEntityDetails = mapAllLegalEntityDetails.get("Row"+index); if(mapLegalEntityDetails.get("VerifyCloneData")!=null && mapLegalEntityDetails.get("VerifyCloneData").equalsIgnoreCase("Yes")){ continue; } if(mapLegalEntityDetails.get("Entity Type")!=null && mapLegalEntityDetails.get("Clone")!=null){ if(mapLegalEntityDetails.get("Entity Type").equalsIgnoreCase("Feeder") || mapLegalEntityDetails.get("Clone").equalsIgnoreCase("Yes")){ continue; } } if(mapLegalEntityDetails.get("Entity Type") == null){ if(mapLegalEntityDetails.get("Clone")!=null && mapLegalEntityDetails.get("Clone").equalsIgnoreCase("Yes")){ continue; } } if(mapLegalEntityDetails.get("Clone") == null){ if(mapLegalEntityDetails.get("Entity Type") != null && mapLegalEntityDetails.get("Entity Type").equalsIgnoreCase("Feeder")){ continue; } } if(!mapLegalEntityDetails.get("OperationType").equalsIgnoreCase("Save") || mapLegalEntityDetails.get("ExpectedResults").equalsIgnoreCase("Fail")){ continue; } Map<String, String> innerMap = new HashMap<String, String>(); Reporting.Testcasename = mapLegalEntityDetails.get("TestcaseName"); bStatus = NewUICommonFunctions.selectMenu("Dashboard","None"); if(!bStatus){ Reporting.logResults("Fail", "Navigate to DashBoard", "Menu cannot be selected. Error: "+Messages.errorMsg); continue; } Reporting.logResults("Pass", "Navigate to DashBoard", "DashBoard Menu selected succesfully"); bStatus = NewUICommonFunctions.performOperationsOnTable(dashboardMainDropdownToSelect.MASTERS, dashboardSubDropdownToSelect.NEW,mapLegalEntityDetails.get("Legal Entity Name"),mapLegalEntityDetails.get("CheckerOperations")); if(bStatus && mapLegalEntityDetails.get("ExpectedResultsAfterCheckerOperations").equalsIgnoreCase("Pass")){ Reporting.logResults("Pass","Perform Checker Operation: "+mapLegalEntityDetails.get("CheckerOperations"), "Successfully Performed checker operations for Legal Entity: "+mapLegalEntityDetails.get("Legal Entity Name")); } if(!bStatus && mapLegalEntityDetails.get("ExpectedResultsAfterCheckerOperations").equalsIgnoreCase("Pass")){ Reporting.logResults("Fail","Perform Checker Operation: "+mapLegalEntityDetails.get("CheckerOperations"), "Cannot Perform Checker Operations. Error: "+Messages.errorMsg+". For Legal Entity: "+mapLegalEntityDetails.get("Legal Entity Name")); continue; } if(!bStatus && mapLegalEntityDetails.get("ExpectedResultsAfterCheckerOperations").equalsIgnoreCase("Fail")){ Reporting.logResults("Pass","Perform Checker Operation: "+mapLegalEntityDetails.get("CheckerOperations"), "Negative testcase - Cannot Perform Checker Operations for Legal Entity "+mapLegalEntityDetails.get("Legal Entity Name")); } if(bStatus && mapLegalEntityDetails.get("ExpectedResultsAfterCheckerOperations").equalsIgnoreCase("Fail")){ Reporting.logResults("Fail","Perform Checker Operation: "+mapLegalEntityDetails.get("CheckerOperations"), "Peformed Checker operations with negative testdata. for Legal Entity Name: "+mapLegalEntityDetails.get("Legal Entity Name")); continue; } if(mapLegalEntityDetails.get("CheckerOperations").equalsIgnoreCase("Approve") && bStatus){ innerMap.put("Status", "active"); innerMap.put("Legal Entity Name", mapLegalEntityDetails.get("Legal Entity Name")); VerifyMap.put(Reporting.Testcasename,innerMap ); } if(mapLegalEntityDetails.get("CheckerOperations").equalsIgnoreCase("Reject") && bStatus){ innerMap.put("Status", "inactive"); innerMap.put("Legal Entity Name", mapLegalEntityDetails.get("Legal Entity Name")); VerifyMap.put(Reporting.Testcasename,innerMap ); } } verifyValuesinSearchPanel(VerifyMap); } catch(Exception e){ e.printStackTrace(); } } @AfterMethod public static void tearDown(){ Reporting.Testcasename = "Close Application"; bStatus = NewUICommonFunctions.logoutFromApplication(); if(!bStatus){ Reporting.logResults("Fail", "Close Application","Cannot logout from application. Error "+Messages.errorMsg); Assert.fail("Cannot logout from application. Error "+Messages.errorMsg); } Reporting.logResults("Pass","Logout from Application","Logged Out from application successfully"); } public static void verifyValuesinSearchPanel(Map<String, Map<String, String>> verifyLE) { try{ for (Entry<String, Map<String, String>> test : verifyLE.entrySet()) { Reporting.Testcasename = test.getKey(); //Navigate to Series Master bStatus = NewUICommonFunctions.selectMenu("Fund Setup","Legal Entity"); if(!bStatus){ Reporting.logResults("Fail", "Navigate To Legal Entity Master","Cannot Navigate to Legal Entity Master"); continue; } Reporting.logResults("Pass","Navigate To Legal Entity Master", "Navigated to Legal Entity Master"); int time =10 ; if(test.getValue().get("Status").equalsIgnoreCase("inactive")){ time = 4; } // Search the Series in drop down bStatus = NewUICommonFunctions.verifyRecordIsDisplayedInTheGridTable("Legal Entity Name", test.getValue().get("Legal Entity Name"), test.getValue().get("Status"),"LegalEntity", time); if(bStatus && test.getValue().get("Status").equalsIgnoreCase("inactive")){ Reporting.logResults("Pass", "Verify Legal Entity Name shouldnot be in active state",test.getValue().get("Legal Entity Name")+" Legal Entity Name is not active state"); //continue; } if(!bStatus && test.getValue().get("Status").equalsIgnoreCase("inactive")){ Reporting.logResults("Fail", "Verify Legal Entity Name shouldnot be in active state",test.getValue().get("Legal Entity Name")+" Legal Entity Name is in active state"); } if(!bStatus && test.getValue().get("Status").equalsIgnoreCase("active")){ Reporting.logResults("Fail", "Verify Legal Entity Name should be in active state",test.getValue().get("Legal Entity Name")+" Legal Entity Name is not in active state"); //continue; } if(bStatus && test.getValue().get("Status").equalsIgnoreCase("active")){ Reporting.logResults("Pass", "Verify Legal Entity Name should be in active state",test.getValue().get("Legal Entity Name")+" Legal Entity Name is in active state"); } } } catch(Exception e){ e.printStackTrace(); } } }
7becde4b2b07d35a80a8db918422bedaccaffb9b
e2e1ed13113d2055e7764ae372312f66dd03d1b1
/ListViewTable/gen/com/android/listview/table/BuildConfig.java
87f54a5ebad43ece64a855222c40b3cbe13b6b98
[]
no_license
hello022546/ListViewTable
fd1053035dc219c6dac15289fcdb0e727b0fa653
bf6f394b6da51926e93f4fb17a57d1f9ec4e7e60
refs/heads/master
2021-05-29T11:12:44.077554
2014-10-06T01:59:19
2014-10-06T01:59:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
168
java
/** Automatically generated file. DO NOT MODIFY */ package com.android.listview.table; public final class BuildConfig { public final static boolean DEBUG = true; }
f5978369c72614e0bbe512efa98cabdb1f59094e
60add028efbdd94f37be24a59e0d596afba997d5
/src/main/java/com/cs4everyone/algorithms/sort/QuickDualPivot.java
e39bd80ed0b7d1168cc64b5d204a89ce2b5dd758
[ "Apache-2.0" ]
permissive
pedro-abundio-wang/algorithms-in-java
202f9fe050bf55c62bc2879c8d9df92cdeff8fa4
994ecc0ab1c8012bef0a09f76caa0db284d85258
refs/heads/main
2023-08-31T15:11:49.703355
2021-10-25T03:33:31
2021-10-25T03:33:31
325,492,294
0
0
null
null
null
null
UTF-8
Java
false
false
1,231
java
package com.cs4everyone.algorithms.sort; public class QuickDualPivot { // quicksort the array array[] using dual-pivot quicksort public static void sort(Comparable[] array) { Knuth.shuffle(array); sort(array, 0, array.length - 1); } // quicksort the subarray array[low .. high] using dual-pivot quicksort private static void sort(Comparable[] array, int low, int high) { if (high <= low) return; // make sure array[low] <= array[high] if (less(array[high], array[low])) swap(array, low, high); int lt = low + 1, gt = high - 1; int i = low + 1; while (i <= gt) { if (less(array[i], array[low])) swap(array, lt++, i++); else if (less(array[high], array[i])) swap(array, i, gt--); else i++; } swap(array, low, --lt); swap(array, high, ++gt); // recursively sort three subarrays sort(array, low, lt - 1); if (less(array[lt], array[gt])) sort(array, lt + 1, gt - 1); sort(array, gt + 1, high); } private static boolean less(Comparable a, Comparable b) { return a.compareTo(b) < 0; } private static void swap(Comparable[] array, int i, int j) { Comparable swap = array[i]; array[i] = array[j]; array[j] = swap; } }
e61bb82e47edaa36ded0dfeb97e62e55640e3924
da1a73dd07c05585454153e24ba3ce497e631af7
/src/main/java/io/dotinc/vivawallet/command/impl/CreateTransaction.java
b69bdfba69f8fbe6de6733172809caac2da0d0e8
[]
no_license
bulivlad/vivawallet-api
5fb7d09900862da1735b6323727b07bd0a22221b
d8d7951ab278cba40cbba5a8a3e4306922b9ebf0
refs/heads/master
2023-03-28T00:19:10.249310
2021-03-25T07:41:38
2021-03-25T07:41:38
289,017,145
0
0
null
null
null
null
UTF-8
Java
false
false
1,159
java
package io.dotinc.vivawallet.command.impl; import io.dotinc.vivawallet.MinimalistClient; import io.dotinc.vivawallet.command.Transaction; import io.dotinc.vivawallet.enums.TransactionAction; import io.dotinc.vivawallet.exception.VivaWalletException; import io.dotinc.vivawallet.model.transaction.create.CreateTransactionRequest; import io.dotinc.vivawallet.model.transaction.create.CreateTransactionResponse; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.ToString; import lombok.experimental.FieldDefaults; import java.io.IOException; /** * @author vbulimac on 21/08/2020. */ @ToString @AllArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) public class CreateTransaction implements Transaction { CreateTransactionRequest createTransactionRequest; @Override public CreateTransactionResponse execute(String apiKeyBase64, TransactionAction transactionAction) throws IOException, VivaWalletException { return MinimalistClient.call(CreateTransactionResponse.class, "POST", path("/api/transactions/%s", createTransactionRequest.getTransactionId()), createTransactionRequest, apiKeyBase64); } }
4299ad57a18c1cd9eb9af393ca7c719d7829de53
ebabfc3286d09a2ae8840ff017610542b31cbf12
/teamapps-ux/src/main/java/org/teamapps/ux/component/field/upload/UploadedFileToRecordConverter.java
12b4951a758e52a85e10ff3eee1085a2c1032bbb
[ "Apache-2.0" ]
permissive
bumbeishvili/teamapps
e4a209f92fb221bb6023b449aac0239f2ba6f693
def03c0613f8c8929e4b2eb38b4fe127a9f16f4f
refs/heads/master
2020-05-17T14:05:47.556514
2019-05-22T07:31:24
2019-05-22T07:31:24
183,755,673
0
0
Apache-2.0
2019-04-27T09:51:38
2019-04-27T09:51:37
null
UTF-8
Java
false
false
928
java
/*- * ========================LICENSE_START================================= * TeamApps * --- * Copyright (C) 2014 - 2019 TeamApps.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. * =========================LICENSE_END================================== */ package org.teamapps.ux.component.field.upload; public interface UploadedFileToRecordConverter<RECORD> { RECORD convert(UploadedFile file); }
2ce60b5360a8873cbd2be6b5daa3ad8501fb93ee
ae63e93496afbef9bcec28ba5d0675d1b98c7b88
/app/src/main/java/com/leungjch/universemaker/universe/Star.java
798f56ee1ba40ac21fde44ac2780b998917341e8
[ "Apache-2.0" ]
permissive
leungjch/universe-maker-app
dd4235fb4d68bfb2d835f5c6ea1f3b189044c440
5d4bb0da39c34af1970d3941b7e33f7b6ae11c2f
refs/heads/master
2023-02-07T06:52:19.359950
2021-01-04T03:56:45
2021-01-04T03:56:45
291,570,869
3
0
null
null
null
null
UTF-8
Java
false
false
2,008
java
package com.leungjch.universemaker.universe; import android.graphics.Paint; import com.leungjch.universemaker.GameView; import com.leungjch.universemaker.helpers.MassRadiusTuple; import com.leungjch.universemaker.helpers.Vector2D; import java.util.Random; // Star is a subclass of a celestial body public class Star extends CelestialBody { Random rand = new Random(); // Constants for radii of stars public static final class SIZES { public static final MassRadiusTuple SMALL = new MassRadiusTuple(1000, 25); public static final MassRadiusTuple MEDIUM = new MassRadiusTuple(3000,50); public static final MassRadiusTuple LARGE = new MassRadiusTuple(10000,100); } public Star(GameView.SIZE_TYPE size, Paint starPaint) { Vector2D starVel = new Vector2D(0,0); Vector2D starAcc = new Vector2D(0,0); Vector2D starFnet = new Vector2D(0,0); switch (size) { case SMALL: super.setMass(Star.SIZES.SMALL.mass); super.setRadius(Star.SIZES.SMALL.radius); break; case MEDIUM: super.setMass(Star.SIZES.MEDIUM.mass); super.setRadius(Star.SIZES.MEDIUM.radius); break; case LARGE: super.setMass(Star.SIZES.LARGE.mass); super.setRadius(Star.SIZES.LARGE.radius); break; case RANDOM: double randRadius = Star.SIZES.SMALL.radius + rand.nextDouble()*(Star.SIZES.LARGE.radius - Star.SIZES.SMALL.radius); super.setRadius(Star.SIZES.SMALL.radius + rand.nextDouble()*(Star.SIZES.LARGE.radius - Star.SIZES.SMALL.radius)); // apply a standard density super.setMass(randRadius * Star.SIZES.LARGE.mass/ Star.SIZES.LARGE.radius); break; } super.setVel(starVel); super.setAcc(starAcc); super.setFnet(starFnet); super.setPaint(starPaint); } }
ea17785a79ef8d6d9f17213cf964461fa64ef281
374ad03287670140e4a716aa211cdaf60f50c944
/ztr-framework/framework-dao-base/src/main/java/com/travelzen/framework/dao/rdbms/SequenceGenerator.java
901a40917614ef96afb40c0cf5d0f47ffe1efbab
[]
no_license
xxxJppp/firstproj
ca541f8cbe004a557faff577698c0424f1bbd1aa
00dcfbe731644eda62bd2d34d55144a3fb627181
refs/heads/master
2020-07-12T17:00:00.549410
2017-04-17T08:29:58
2017-04-17T08:29:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,575
java
package com.travelzen.framework.dao.rdbms; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; public class SequenceGenerator { private static Map<String, SequencePool> seqMap = new ConcurrentHashMap<String, SequencePool>(); private BatchSequenceDaoImpl batchSequenceDao; //每次请求分配的序列数个数 private final int allotment = 100; public synchronized String getNextSeq(String sequenceName, int width, int allotment) throws Exception { SequencePool pool = seqMap.get(sequenceName); if (seqMap.get(sequenceName) == null || pool.isEmpty()) { pool = refillPool(sequenceName, allotment); seqMap.put(sequenceName, pool); } if (width > 0) { return formatSequence(String.valueOf(pool.next()), width); } else { return String.valueOf(pool.next()); } } public synchronized String getNextSeq(String sequenceName, int width) throws Exception { return getNextSeq(sequenceName, width, allotment); } public synchronized String getNextSeq(String sequenceName) throws Exception { return getNextSeq(sequenceName, -1, allotment); } private SequencePool refillPool(String sequenceName, int allotment) throws Exception { long nextSeq = batchSequenceDao.getNextSeq(sequenceName, allotment); return new SequencePool(nextSeq, nextSeq + allotment - 1); } /** * description: 将传入的字符串的长度限制为一定值 * * @param is * @param width * @return */ private static String formatSequence(String is, int width) { if (is.length() < width) { return StringUtils.leftPad(is, width, '0'); } // for (; is.length() < width; is = "0" + is) ; else { is = is.substring(is.length() - width, is.length()); } return is; } private static class SequencePool { private long low; private long high; public SequencePool(long low, long high) { this.low = low; this.high = high; } public long next() { return low++; } public boolean isEmpty() { return low > high; } } public BatchSequenceDaoImpl getBatchSequenceDao() { return batchSequenceDao; } public void setBatchSequenceDao(BatchSequenceDaoImpl batchSequenceDao) { this.batchSequenceDao = batchSequenceDao; } }
964f83615fd0d4fb5f34273a4b8d065794aa570b
371a934133856754c09afd654e52e0a739eb432a
/src/main/java/MathQuestion/core/QuestionCore.java
96f612f88d6e68ace750e3d4a014485bad2cad67
[]
no_license
fudannlp16/MathQuestion
21f167ecb7e515dd7a4bb77e423d31db21559657
243989d67f94f711c4f4e437f5f52e18e3cd4286
refs/heads/master
2021-06-15T02:04:15.540014
2017-03-12T10:53:00
2017-03-12T10:53:00
84,396,369
1
0
null
null
null
null
UTF-8
Java
false
false
3,509
java
package MathQuestion.core; /** * Created by liuxiaoyu on 16-11-6. */ import MathQuestion.tntity.ResultEntity; import MathQuestion.fencheng.fenchengReg; import MathQuestion.tntity.EQ; import MathQuestion.tntity.SO; import java.util.List; /** * 概率题目分成抽样语义标签提取 */ public class QuestionCore { /** * 获取分成抽样题目XML标签 * @param q1 * @return */ public static String getXML(String q1,String resources) { String q=q1.split("\n")[0]; Q1Analysis q1Analysis=new Q1Analysis(resources); ResultEntity stratificationSampling=new fenchengReg(resources).getResult(q1); String result="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; result+="<Stratification>\n"; result+=" <TS>\n"; result+=" <name>"+stratificationSampling.getTSName()+"</name>\n"; result+=" <quantity>"+stratificationSampling.getQuantity()+"</quantity>\n"; result+=" <unit>"+stratificationSampling.getUnit()+"</unit>\n"; result+=" </TS>\n"; List<SO> sot=stratificationSampling.getSots(); if (sot!=null) { for (SO so : sot) { result+=" <SOT>\n"; result+=" <name>"+so.getName()+"</name>\n"; result+=" <quantity>"+so.getQuantity()+"</quantity>\n"; result+=" <unit>"+stratificationSampling.getUnit()+"</unit>\n"; result+=" </SOT>\n"; } } SO ss=stratificationSampling.getS(); result+=" <S>\n"; result+=" <name>"+ss.getName()+"</name>\n"; result+=" <quantity>"+ss.getQuantity()+"</quantity>\n"; result+=" <unit>"+stratificationSampling.getUnit()+"</unit>\n"; result+=" </S>\n"; List<SO> sos=stratificationSampling.getSoss(); if (sos!=null) { for (SO so : sos) { result+=" <SOS>\n"; result+=" <name>"+so.getName()+"</name>\n"; result+=" <quantity>"+so.getQuantity()+"</quantity>\n"; result+=" <unit>"+stratificationSampling.getUnit()+"</unit>\n"; result+=" </SOS>\n"; } } EQ eq=stratificationSampling.getEq(); if (eq==null) { result+=" <EQ>\n"; result+=" </EQ>\n"; } else { result+=" <EQ>\n"; result+=" <entityName>"+eq.getEntityName()+"</entityName>\n"; result+=" <relation>"+eq.getRelation()+"</relation>\n"; result+=" <value>"+eq.getValue()+"</value>\n"; result+=" </EQ>\n"; } result+=" <QUE>\n"; result+=" <description>"+stratificationSampling.getDescription()+"</description>\n"; result+=" <belong>"+stratificationSampling.getBelong()+"</belong>\n"; result+=" <name>"+stratificationSampling.getName()+"</name>\n"; result+=" <unit>"+stratificationSampling.getUnit()+"</unit>\n"; result+=" </QUE>\n"; result+="</Stratification>"; return result; } public static void main(String[] args) { System.out.println(getXML("某社区现有480个住户,其中中等收入家庭200户、低收入家庭160户,其他为高收入家庭。在建设幸福广东的某次分层抽样调查中,高收入家庭被抽取了6户,则该社区本次被抽取的总户数为","src/main/resources")); } }
52b1e9473559e12957091ed89b3c3b51ae423092
387df90e72b2a7b22a6194e3b7dcea8affba340a
/bioeasy-common/src/main/java/com/bioeasy/common/utils/FileUtils.java
2b3ac0cc53883175532ffd9b1e5b868a1085bc18
[]
no_license
lihuiyao1986/bioeasy
d4d8d71a164fd043013683d8ae0e2cf8b88af692
78a6becc23927fc978a76c5c13ba1f557023417d
refs/heads/master
2020-07-22T21:34:38.425360
2016-11-15T14:44:40
2016-11-15T14:44:40
73,822,706
0
0
null
null
null
null
UTF-8
Java
false
false
11,778
java
package com.bioeasy.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; /** * 文件操作工具类 * 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能 */ public class FileUtils extends org.apache.commons.io.FileUtils { private static Logger log = LoggerFactory.getLogger(FileUtils.class); /** * 复制单个文件,如果目标文件存在,则不覆盖 * @param srcFileName 待复制的文件名 * @param descFileName 目标文件名 * @return 如果复制成功,则返回true,否则返回false */ public static boolean copyFile(String srcFileName, String descFileName) { return FileUtils.copyFileCover(srcFileName, descFileName, false); } /** * 复制单个文件 * @param srcFileName 待复制的文件名 * @param descFileName 目标文件名 * @param coverlay 如果目标文件已存在,是否覆盖 * @return 如果复制成功,则返回true,否则返回false */ public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); // 判断源文件是否存在 if (!srcFile.exists()) { log.debug("复制文件失败,源文件 " + srcFileName + " 不存在!"); return false; } // 判断源文件是否是合法的文件 else if (!srcFile.isFile()) { log.debug("复制文件失败," + srcFileName + " 不是一个文件!"); return false; } File descFile = new File(descFileName); // 判断目标文件是否存在 if (descFile.exists()) { // 如果目标文件存在,并且允许覆盖 if (coverlay) { log.debug("目标文件已存在,准备删除!"); if (!FileUtils.delFile(descFileName)) { log.debug("删除目标文件 " + descFileName + " 失败!"); return false; } } else { log.debug("复制文件失败,目标文件 " + descFileName + " 已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { // 如果目标文件所在的目录不存在,则创建目录 log.debug("目标文件所在的目录不存在,创建目录!"); // 创建目标文件所在的目录 if (!descFile.getParentFile().mkdirs()) { log.debug("创建目标文件所在的目录失败!"); return false; } } } // 准备复制文件 // 读取的位数 int readByte = 0; InputStream ins = null; OutputStream outs = null; try { // 打开源文件 ins = new FileInputStream(srcFile); // 打开目标文件的输出流 outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; // 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕 while ((readByte = ins.read(buf)) != -1) { // 将读取的字节流写入到输出流 outs.write(buf, 0, readByte); } log.debug("复制单个文件 " + srcFileName + " 到" + descFileName + "成功!"); return true; } catch (Exception e) { log.debug("复制文件失败:" + e.getMessage()); return false; } finally { // 关闭输入输出流,首先关闭输出流,然后再关闭输入流 if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } /** * 复制整个目录的内容,如果目标目录存在,则不覆盖 * @param srcDirName 源目录名 * @param descDirName 目标目录名 * @return 如果复制成功返回true,否则返回false */ public static boolean copyDirectory(String srcDirName, String descDirName) { return FileUtils.copyDirectoryCover(srcDirName, descDirName, false); } /** * 复制整个目录的内容 * @param srcDirName 源目录名 * @param descDirName 目标目录名 * @param coverlay 如果目标目录存在,是否覆盖 * @return 如果复制成功返回true,否则返回false */ public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) { File srcDir = new File(srcDirName); // 判断源目录是否存在 if (!srcDir.exists()) { log.debug("复制目录失败,源目录 " + srcDirName + " 不存在!"); return false; } // 判断源目录是否是目录 else if (!srcDir.isDirectory()) { log.debug("复制目录失败," + srcDirName + " 不是一个目录!"); return false; } // 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符 String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); // 如果目标文件夹存在 if (descDir.exists()) { if (coverlay) { // 允许覆盖目标目录 log.debug("目标目录已存在,准备删除!"); if (!FileUtils.delFile(descDirNames)) { log.debug("删除目录 " + descDirNames + " 失败!"); return false; } } else { log.debug("目标目录复制失败,目标目录 " + descDirNames + " 已存在!"); return false; } } else { // 创建目标目录 log.debug("目标目录不存在,准备创建!"); if (!descDir.mkdirs()) { log.debug("创建目标目录失败!"); return false; } } boolean flag = true; // 列出源目录下的所有文件名和子目录名 File[] files = srcDir.listFiles(); for (int i = 0; i < files.length; i++) { // 如果是一个单个文件,则直接复制 if (files[i].isFile()) { flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName()); // 如果拷贝文件失败,则退出循环 if (!flag) { break; } } // 如果是子目录,则继续复制目录 if (files[i].isDirectory()) { flag = FileUtils.copyDirectory(files[i] .getAbsolutePath(), descDirName + files[i].getName()); // 如果拷贝目录失败,则退出循环 if (!flag) { break; } } } if (!flag) { log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 失败!"); return false; } log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 成功!"); return true; } /** * * 删除文件,可以删除单个文件或文件夹 * * @param fileName 被删除的文件名 * @return 如果删除成功,则返回true,否是返回false */ public static boolean delFile(String fileName) { File file = new File(fileName); if (!file.exists()) { log.debug(fileName + " 文件不存在!"); return true; } else { if (file.isFile()) { return FileUtils.deleteFile(fileName); } else { return FileUtils.deleteDirectory(fileName); } } } /** * * 删除单个文件 * * @param fileName 被删除的文件名 * @return 如果删除成功,则返回true,否则返回false */ public static boolean deleteFile(String fileName) { File file = new File(fileName); if (file.exists() && file.isFile()) { if (file.delete()) { log.debug("删除文件 " + fileName + " 成功!"); return true; } else { log.debug("删除文件 " + fileName + " 失败!"); return false; } } else { log.debug(fileName + " 文件不存在!"); return true; } } /** * * 删除目录及目录下的文件 * * @param dirName 被删除的目录所在的文件路径 * @return 如果目录删除成功,则返回true,否则返回false */ public static boolean deleteDirectory(String dirName) { String dirNames = dirName; if (!dirNames.endsWith(File.separator)) { dirNames = dirNames + File.separator; } File dirFile = new File(dirNames); if (!dirFile.exists() || !dirFile.isDirectory()) { log.debug(dirNames + " 目录不存在!"); return true; } boolean flag = true; // 列出全部文件及子目录 File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // 删除子文件 if (files[i].isFile()) { flag = FileUtils.deleteFile(files[i].getAbsolutePath()); // 如果删除文件失败,则退出循环 if (!flag) { break; } } // 删除子目录 else if (files[i].isDirectory()) { flag = FileUtils.deleteDirectory(files[i] .getAbsolutePath()); // 如果删除子目录失败,则退出循环 if (!flag) { break; } } } if (!flag) { log.debug("删除目录失败!"); return false; } // 删除当前目录 if (dirFile.delete()) { log.debug("删除目录 " + dirName + " 成功!"); return true; } else { log.debug("删除目录 " + dirName + " 失败!"); return false; } } /** * 创建单个文件 * @param descFileName 文件名,包含路径 * @return 如果创建成功,则返回true,否则返回false */ public static boolean createFile(String descFileName) { File file = new File(descFileName); if (file.exists()) { log.debug("文件 " + descFileName + " 已存在!"); return false; } if (descFileName.endsWith(File.separator)) { log.debug(descFileName + " 为目录,不能创建目录!"); return false; } if (!file.getParentFile().exists()) { // 如果文件所在的目录不存在,则创建目录 if (!file.getParentFile().mkdirs()) { log.debug("创建文件所在的目录失败!"); return false; } } // 创建文件 try { if (file.createNewFile()) { log.debug(descFileName + " 文件创建成功!"); return true; } else { log.debug(descFileName + " 文件创建失败!"); return false; } } catch (Exception e) { e.printStackTrace(); log.debug(descFileName + " 文件创建失败!"); return false; } } /** * 创建目录 * @param descDirName 目录名,包含路径 * @return 如果创建成功,则返回true,否则返回false */ public static boolean createDirectory(String descDirName) { String descDirNames = descDirName; if (!descDirNames.endsWith(File.separator)) { descDirNames = descDirNames + File.separator; } File descDir = new File(descDirNames); if (descDir.exists()) { log.debug("目录 " + descDirNames + " 已存在!"); return false; } // 创建目录 if (descDir.mkdirs()) { log.debug("目录 " + descDirNames + " 创建成功!"); return true; } else { log.debug("目录 " + descDirNames + " 创建失败!"); return false; } } /** * 写入文件 */ public static void writeToFile(String fileName, String content, boolean append) { try { FileUtils.write(new File(fileName), content, "utf-8", append); log.debug("文件 " + fileName + " 写入成功!"); } catch (IOException e) { log.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); } } /** * 写入文件 */ public static void writeToFile(String fileName, String content, String encoding, boolean append) { try { FileUtils.write(new File(fileName), content, encoding, append); log.debug("文件 " + fileName + " 写入成功!"); } catch (IOException e) { log.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); } } /** * 修复路径,将 \\ 或 / 等替换为 File.separator * @param path * @return */ public static String path(String path){ String p = StringUtils.replace(path, "\\", "/"); p = StringUtils.join(StringUtils.split(p, "/"), "/"); if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")){ p += "/"; } if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")){ p = p + "/"; } if (path != null && path.startsWith("/")){ p = "/" + p; // linux下路径 } return p; } }
[ "zjh123456" ]
zjh123456
41411b07f9c528eb5008565d150c46bba1930c39
e4b2b535b6f1e0c54f2f1424d6303db336512532
/app/src/main/java/com/exalpme/bozhilun/android/bean/B15PSleepBean.java
3ea63ffe41c56cc274a4075cfa8ca80a88ecfa22
[ "Apache-2.0" ]
permissive
axdx1314/RaceFitPro
56a7a4cefefc56373b94eb383d130f1bd4f7c6d9
6778c6c4fb11ba8697a64c6ddde8bfe95dbbb505
refs/heads/master
2020-03-17T08:29:10.096792
2018-05-23T02:08:23
2018-05-23T02:08:23
133,440,315
0
1
null
null
null
null
UTF-8
Java
false
false
5,411
java
package com.exalpme.bozhilun.android.bean; import android.os.Parcel; import android.os.Parcelable; import com.exalpme.bozhilun.android.bleutil.MyCommandManager; import com.exalpme.bozhilun.android.util.Common; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.NotNull; /** * Created by thinkpad on 2017/3/17. */ @Entity public class B15PSleepBean implements Parcelable { @Id(autoincrement = true) private Long id; @NotNull private String deviceCode; @NotNull private String userId; @NotNull private String startTime; private String endTime; private int count; private int deepLen; private int sleepLen; private int shallowLen; private int sleepQuality; private String sleepCurveS; private String sleepCurveP; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDeviceCode() { return deviceCode; } public void setDeviceCode(String deviceCode) { this.deviceCode = deviceCode; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getDeepLen() { return deepLen; } public void setDeepLen(int deepLen) { this.deepLen = deepLen; } public int getSleepLen() { return sleepLen; } public void setSleepLen(int sleepLen) { this.sleepLen = sleepLen; } public int getShallowLen() { return shallowLen; } public void setShallowLen(int shallowLen) { this.shallowLen = shallowLen; } public int getSleepQuality() { return sleepQuality; } public void setSleepQuality(int sleepQuality) { this.sleepQuality = sleepQuality; } public String getSleepCurveS() { return sleepCurveS; } public void setSleepCurveS(String sleepCurveS) { this.sleepCurveS = sleepCurveS; } public String getSleepCurveP() { return sleepCurveP; } public void setSleepCurveP(String sleepCurveP) { this.sleepCurveP = sleepCurveP; } protected B15PSleepBean(Parcel in) { deviceCode = in.readString(); userId = in.readString(); startTime = in.readString(); endTime = in.readString(); count = in.readInt(); deepLen = in.readInt(); sleepLen = in.readInt(); shallowLen = in.readInt(); sleepQuality = in.readInt(); sleepCurveS = in.readString(); sleepCurveP = in.readString(); } public B15PSleepBean(String startTime, String endTime, int count, int deepLen, int shallowLen, int sleepQuality) { this.deviceCode = MyCommandManager.ADDRESS; this.userId = Common.customer_id; this.startTime = startTime; this.endTime = endTime; this.count = count; this.deepLen = deepLen; this.shallowLen = shallowLen; this.sleepLen = deepLen + shallowLen; this.sleepQuality = sleepQuality; } @Generated(hash = 1037938592) public B15PSleepBean(Long id, @NotNull String deviceCode, @NotNull String userId, @NotNull String startTime, String endTime, int count, int deepLen, int sleepLen, int shallowLen, int sleepQuality, String sleepCurveS, String sleepCurveP) { this.id = id; this.deviceCode = deviceCode; this.userId = userId; this.startTime = startTime; this.endTime = endTime; this.count = count; this.deepLen = deepLen; this.sleepLen = sleepLen; this.shallowLen = shallowLen; this.sleepQuality = sleepQuality; this.sleepCurveS = sleepCurveS; this.sleepCurveP = sleepCurveP; } @Generated(hash = 764697241) public B15PSleepBean() { } public static final Creator<B15PSleepBean> CREATOR = new Creator<B15PSleepBean>() { @Override public B15PSleepBean createFromParcel(Parcel in) { return new B15PSleepBean(in); } @Override public B15PSleepBean[] newArray(int size) { return new B15PSleepBean[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(deviceCode); parcel.writeString(userId); parcel.writeString(startTime); parcel.writeString(endTime); parcel.writeInt(count); parcel.writeInt(deepLen); parcel.writeInt(sleepLen); parcel.writeInt(shallowLen); parcel.writeInt(sleepQuality); parcel.writeString(sleepCurveS); parcel.writeString(sleepCurveP); } }
ff8633e2ec58df60cc85af94e96f441176baaabb
b7968352a602687f59cb801dcec234d12d0a491b
/studentManage/src/main/webapp/js/web/dao/StudentDao.java
04a34d06cb8f537d4a47c472ea78f37229f6dcc5
[ "MIT" ]
permissive
IsSenHu/studentRedisManage
5338abbaac5a9a24ab465a6f27fed3121282eaee
b09e4e84c56a43149f06fa9b226b604eb38ea93d
refs/heads/master
2021-05-01T21:25:47.410618
2018-02-10T02:33:06
2018-02-10T02:33:06
120,977,382
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package com.husen.web.dao; import com.husen.web.pojo.Student; import java.util.List; public interface StudentDao { boolean addStudent(Student student) throws Exception; List<Student> pageStudent(long offset, long end) throws Exception; Long total() throws Exception; Student findStudentById(String studentId) throws Exception; boolean updateStudent(Student student) throws Exception; boolean deleteStudent(String studentId) throws Exception; }
9b88c0c3db45f72492d6dc94d8b49b12f49a5bdd
1dd6c249609b1806b04c4f6aeac1f8fe49526878
/src/java/org/chefx3d/model/MoveEntityTransientCommand.java
e53bac62a7fd19a01c58c5da21d8ad0fd5f50c06
[]
no_license
rmelton/ChefX3D
fd6c05d2fe5f5ffa3f33a61fecfa57859ce51ff0
d4580a8e885cdc8cd36ca384f309a16bb234f70e
refs/heads/master
2020-12-25T05:18:00.352831
2011-05-31T16:53:15
2011-05-31T16:53:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,427
java
/***************************************************************************** * Copyright Yumetech, Inc (c) 2006-2007 * Java Source * * This source is licensed under the GNU LGPL v2.1 * Please read http://www.gnu.org/copyleft/lgpl.html for more information * * This software comes with the standard NO WARRANTY disclaimer for any * purpose. Use it at your own risk. If there's a problem you get to fix it. * ****************************************************************************/ package org.chefx3d.model; //External Imports import java.io.OutputStream; import java.io.PrintStream; import java.util.*; import org.w3c.dom.*; //Internal Imports import org.chefx3d.util.DOMUtils; import org.chefx3d.util.DefaultErrorReporter; import org.chefx3d.util.ErrorReporter; /** * A command for moving an entity. * * @author Alan Hudson * @version $Revision: 1.23 $ */ public class MoveEntityTransientCommand implements Command, DeadReckonedCommand, RuleDataAccessor, RuleBypassFlag { /** The model */ private BaseWorldModel model; /** The new entityID */ private int entityID; /** The entity to update */ private PositionableEntity entity; /** The position */ private double[] pos; /** The velocity */ private float[] linearVelocity; /** Is this a local add */ private boolean local; /** The transactionID */ private int transactionID; /** A list of strings of class names of rules to ignore*/ private HashSet<String> ignoreRuleList; /** The description of the <code>Command</code> */ private String description; /** The flag to indicate transient status */ private boolean transientState; /** The flag to indicate undoable status */ private boolean undoableState; /** The ErrorReporter for messages */ private ErrorReporter errorReporter; /** Should the command die */ private boolean shouldDie = false; /** Pick entity that would be the parent if placed at this position */ private Entity pickEntity = null; /** The rule bypass flag, default is false */ private boolean ruleBypassFlag; /** * Add an entity. * * @param model The model to change * @param transactionID The transactionID * @param entityID The unique entityID assigned by the view * @param position The position in world coordinates(meters, Y-UP, X3D * System). * @param velocity The velocity vector */ public MoveEntityTransientCommand( WorldModel model, int transactionID, int entityID, double[] position, float[] velocity) { // Cast to package definition to access protected methods this.model = (BaseWorldModel) model; this.entityID = entityID; this.transactionID = transactionID; this.pos = new double[3]; this.pos[0] = position[0]; this.pos[1] = position[1]; this.pos[2] = position[2]; linearVelocity = new float[3]; linearVelocity[0] = velocity[0]; linearVelocity[1] = velocity[1]; linearVelocity[2] = velocity[2]; description = "MoveEntityTransientCommand -> "+entityID; local = true; entity = (PositionableEntity)model.getEntity(entityID); ruleBypassFlag = false; init(); } /** * Overloaded constructor in order to specify the potential pick parent. * * @param model The model to change * @param transactionID The transaction id * @param entityID The entity id of the entity to update * @param position The position in world coordinates (meters, Y-UP, X3D * System) * @param velocity The velocity vector * @param pickParent The first entity returned from the pick parents */ public MoveEntityTransientCommand( WorldModel model, int transactionID, int entityID, double[] position, float[] velocity, Entity pickParent){ this(model, transactionID, entityID, position, velocity); pickEntity = pickParent; } /** * Basic constructor. * * @param model The model to change */ public MoveEntityTransientCommand(WorldModel model) { // Cast to package definition to access protected methods this.model = (BaseWorldModel) model; ruleBypassFlag = false; init(); } /** * Common initialization method. */ private void init() { errorReporter = DefaultErrorReporter.getDefaultReporter(); transientState = true; undoableState = false; } // ---------------------------------------------------------- // Methods required by DeadReckonedCommand // ---------------------------------------------------------- /** * Get the dead reckoning params. * * @param position The position data * @param orientation The orientation data * @param lVelocity The linear velocity * @param aVelocity The angular velocity */ public void getDeadReckoningParams(double[] position, float[] orientation, float[] lVelocity, float[] aVelocity) { position[0] = pos[0]; position[1] = pos[1]; position[2] = pos[2]; lVelocity[0] = linearVelocity[0]; lVelocity[1] = linearVelocity[1]; lVelocity[2] = linearVelocity[2]; } /** * Set the dead reckoning params. * * @param position The position data * @param orientation The orientation data * @param lVelocity The linear velocity * @param aVelocity The angular velocity */ public void setDeadReckoningParams(double[] position, float[] orientation, float[] lVelocity, float[] aVelocity) { pos[0] = position[0]; pos[1] = position[1]; pos[2] = position[2]; linearVelocity[0] = lVelocity[0]; linearVelocity[1] = lVelocity[1]; linearVelocity[2] = lVelocity[2]; } /** * Set the local flag. * * @param isLocal Is this a local update */ public void setLocal(boolean isLocal) { local = isLocal; } /** * Is the command locally generated. * * @return Is local */ public boolean isLocal() { return local; } /** * Get the position. * * @param position The preallocated array to fill in */ public void getPosition(double[] position) { position[0] = pos[0]; position[1] = pos[1]; position[2] = pos[2]; } /** * Execute the command. */ public void execute() { if (entity == null) return; entity.setPosition(pos, transientState); } /** * Undo the affects of this command. */ public void undo() { // ignore } /** * Redo the affects of this command. */ public void redo() { // ignore } /** * Get the text description of this <code>Command</code>. */ public String getDescription() { return description; } /** * Set the text description of this <code>Command</code>. */ public void setDescription(String desc) { description = desc; } /** * Get the state of this <code>Command</code>. */ public boolean isTransient() { return transientState; } /** * Get the transactionID for this command. * * @return The transactionID */ public int getTransactionID() { return transactionID; } /** * Get the undo setting of this <code>Command</code>. true = * <code>Command</code> may be undone false = <code>Command</code> may * never undone */ public boolean isUndoable() { return undoableState; } /** * Serialize this command. * * @param method What method should we use * @param os The stream to output to */ public void serialize(int method, OutputStream os) { switch (method) { case METHOD_XML: /* * <MoveEntityTransientCommand entityID='1' tID='' px='' py='' pz='' * vx='' vy='' vz=''/> */ StringBuilder sbuff = new StringBuilder(); sbuff.append("<MoveEntityTransientCommand entityID='"); sbuff.append(entityID); sbuff.append("' tID='"); sbuff.append(transactionID); sbuff.append("' px='"); sbuff.append(String.format("%.3f", pos[0])); sbuff.append("' py='"); sbuff.append(String.format("%.3f", pos[1])); sbuff.append("' pz='"); sbuff.append(String.format("%.3f", pos[2])); sbuff.append("' vx='"); sbuff.append(String.format("%.3f", linearVelocity[0])); sbuff.append("' vy='"); sbuff.append(String.format("%.3f", linearVelocity[1])); sbuff.append("' vz='"); sbuff.append(String.format("%.3f", linearVelocity[2])); sbuff.append("' />"); String st = sbuff.toString(); PrintStream ps = new PrintStream(os); ps.print(st); break; case METHOD_XML_FAST_INFOSET: errorReporter.messageReport("Unsupported serialization method"); break; } } /** * Deserialize a stream * * @param st The xml string to deserialize */ public void deserialize(String st) { Document doc = DOMUtils.parseXML(st); Element e = (Element) doc.getFirstChild(); String d; pos = new double[3]; d = e.getAttribute("px"); pos[0] = Double.parseDouble(d); d = e.getAttribute("py"); pos[1] = Double.parseDouble(d); d = e.getAttribute("pz"); pos[2] = Double.parseDouble(d); String f; linearVelocity = new float[3]; f = e.getAttribute("vx"); linearVelocity[0] = Float.parseFloat(f); f = e.getAttribute("vy"); linearVelocity[1] = Float.parseFloat(f); f = e.getAttribute("vz"); linearVelocity[2] = Float.parseFloat(f); entityID = Integer.parseInt(e.getAttribute("entityID")); transactionID = Integer.parseInt(e.getAttribute("tID")); entity = (PositionableEntity)model.getEntity(entityID); local = false; } /** * Register an error reporter with the command instance * so that any errors generated can be reported in a nice manner. * * @param reporter The new ErrorReporter to use. */ public void setErrorReporter(ErrorReporter reporter) { errorReporter = reporter; if(errorReporter == null) errorReporter = DefaultErrorReporter.getDefaultReporter(); } /** * Sets the position for the command. * * @param pos xyz indexed array with values to set */ public void setPosition(double[] pos){ this.pos[0] = pos[0]; this.pos[1] = pos[1]; this.pos[2] = pos[2]; } /** * Get the Entity * * @return Entity or null if it doesn't exist */ public Entity getEntity(){ return entity; } /** * Get the WorldModel * * @return WorldModel or null if it doesn't exist */ public WorldModel getWorldModel(){ return model; } public HashSet<String> getIgnoreRuleList() { // TODO Auto-generated method stub return ignoreRuleList; } public void setIgnoreRuleList(HashSet<String> ignoreRuleList) { this.ignoreRuleList = ignoreRuleList; } public void resetToStart() { // TODO Auto-generated method stub } /** * Set the die state of the command. Setting this to true will * only cause the command to die if the rule engine execution * returns false. * * @param die True to have command die and not execute */ public void setCommandShouldDie(boolean die) { shouldDie = die; } /** * Get the die value of the command. * * @return True to have command die, false otherwise */ public boolean shouldCommandDie() { return shouldDie; } /** * Get the pick parent entity * * @return Entity or null if not set */ public Entity getPickParentEntity(){ return pickEntity; } /** * Set the pick parent entity * * @param pickParent Pick parent entity to set */ public void setPickParentEntity(Entity pickParent) { pickEntity = pickParent; } /** * Compare external command to this one to see if they are the same. * * @param externalCommand command to compare against * @return True if the same, false otherwise */ public boolean isEqualTo(Command externalCommand) { // Check for appropriate command type(s) if (externalCommand instanceof MoveEntityTransientCommand) { if (((MoveEntityTransientCommand)externalCommand).transactionID == this.transactionID) { return true; } double[] position = new double[3]; ((MoveEntityTransientCommand)externalCommand).getPosition( position); if (((MoveEntityTransientCommand)externalCommand).getEntity() != entity) { return false; } else if (((MoveEntityTransientCommand)externalCommand). getPickParentEntity() != this.pickEntity) { return false; } else if (!Arrays.equals(position, this.pos)) { return false; } return true; } return false; } /** * Override object's equals method */ @Override public boolean equals(Object obj) { if (obj instanceof Command) { return isEqualTo((Command)obj); } return false; } //-------------------------------------------------------------------- // Routines required by RuleBypassFlag //-------------------------------------------------------------------- /** * Set the rule bypass flag value. * * @param ruleBypassFlag True to bypass rules, false otherwise */ public void setBypassRules(boolean bypass){ this.ruleBypassFlag = bypass; } /** * Get the rule bypass flag value. * * @return boolean True to bypass, false otherwise */ public boolean bypassRules() { return ruleBypassFlag; } }
bb6a6b5233171fd68c523b56f17f9c0e8e807ad9
c54db4844a5d93c0a6b57fdb680f306fe934fdb2
/4.Breath First Search/Topological Sorting.java
b4e90de440b3979cd69de8421a97125c14b9c260
[]
no_license
hanrick2000/9chapters_algorithm
17dd8e21331ff7dda1f91f76d53b7ea399a8704c
31da8a79fa143a502609552cc45cba076244aeba
refs/heads/master
2022-01-16T22:27:02.384855
2019-09-08T19:54:30
2019-09-08T19:54:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,716
java
/* Given an directed graph, a topological order of the graph nodes is defined as follow: For each directed edge A -> B in graph, A must before B in the order list. The first node in the order can be any node in the graph with no nodes direct to it. Find any topological order for the given graph. Notice You can assume that there is at least one topological order in the graph. Have you met this question in a real interview? Yes Clarification Learn more about representation of graphs Example For graph as follow: picture The topological order can be: [0, 1, 2, 3, 4, 5] [0, 2, 3, 1, 5, 4] ... Challenge Can you do it in both BFS and DFS? Tags LintCode Copyright Geeks for Geeks Topological Sort Depth First Search Breadth First Search Related Problems Medium Course Schedule 23 % Medium Course Schedule II 21 % Medium Sequence Reconstruction 19 % */ /** * Definition for Directed graph. * class DirectedGraphNode { * int label; * ArrayList<DirectedGraphNode> neighbors; * DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); } * }; */ public class Solution { /* * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) { // write your code here ArrayList<DirectedGraphNode> ans = new ArrayList<>(); if (graph == null || graph.size() == 0) { return ans; } Map<Integer, Integer> inDegree = new HashMap<>(); for (DirectedGraphNode node: graph) { ArrayList<DirectedGraphNode> neighbors = node.neighbors; for (DirectedGraphNode nei: neighbors) { int key = nei.label; if (inDegree.containsKey(key)) { inDegree.put(key, inDegree.get(key) + 1); } else { inDegree.put(key, 1); } } } Queue<DirectedGraphNode> queue = new LinkedList<>(); for (DirectedGraphNode node: graph) { if (!inDegree.containsKey(node.label)) { queue.offer(node); } } while (!queue.isEmpty()) { DirectedGraphNode node = queue.poll(); ans.add(node); ArrayList<DirectedGraphNode> neighbors = node.neighbors; for (DirectedGraphNode nei: neighbors) { int key = nei.label; inDegree.put(key, inDegree.get(key) - 1); if (inDegree.get(key) == 0) { queue.offer(nei); } } } return ans; } }
0e2e383fdfa50007e655ff69f426d5695c22275e
69f7759eeae8f293b05464e9e3d514aba102071f
/src/org/xgx/basic/concurrent/c5/Memoizer.java
1023dbc06f5f353c72259c62683f08acf7d02313
[]
no_license
mythsya/javabasic
2b33e54b64bca777707f0c0a879649e4336c5319
b7c82e2a02cc03bd2d983761485dba30213c56b6
refs/heads/master
2016-09-13T13:10:51.745011
2016-05-11T06:15:41
2016-05-11T06:15:41
58,472,688
0
0
null
null
null
null
UTF-8
Java
false
false
1,067
java
package org.xgx.basic.concurrent.c5; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class Memoizer<A, V> implements Computable<A, V> { private final ConcurrentHashMap<A, Future<V>> cache = new ConcurrentHashMap<>(); private final Computable<A, V> c; public Memoizer(final Computable<A, V> c) { this.c = c; } @Override public V compute(final A arg) throws InterruptedException { while (true) { Future<V> f = cache.get(arg); if (f == null) { Callable<V> eval = () -> c.compute(arg); FutureTask<V> ft = new FutureTask<>(eval); f = cache.putIfAbsent(arg, ft); if (f == null) { f = ft; ft.run(); } } try { return f.get(); } catch (CancellationException e) { cache.remove(arg, f); } catch (ExecutionException e) { throw new InterruptedException(e.getMessage()); } } } }
[ "xgx@ubuntu" ]
xgx@ubuntu
06d65a8a96d5a4d4c4fe344a082bc5f69a58caaf
2ef484d237fccf39fecd1963bf956ffe6f1b80b3
/service/src/main/java/com/yanerwu/annotation/Id.java
bc0b1a41892eb90e1128d07b4e31d7fc4aff1c82
[]
no_license
zhi-heart/yanerwu
b279ac9d50da3b3573b2c54beb3e5f28c0307a15
31384ab075c8d906b52cef9f4c07243efb9f31cf
refs/heads/master
2021-01-23T03:12:08.053223
2018-01-23T08:59:21
2018-01-23T08:59:21
86,053,812
2
1
null
null
null
null
UTF-8
Java
false
false
345
java
package com.yanerwu.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by Zuz on 2017/4/27. */ @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Id { }
f3e27458c86840987d6f5a7e3e4e422f2fa9d41c
898d37790e866039ed5fb315982592d1965b0c09
/app/src/main/java/com/example/midterm/MainActivity3.java
ac33c9200ccd200beeb7a5768194a5a7c46351da
[]
no_license
layaliElkordy/Midterm
3d125bbea92be2f63620be8c0f06bf8d2b2a7304
5bd6a1c01d5d13195006f03c9a53203767cc28e4
refs/heads/master
2023-03-21T22:12:26.187904
2021-03-08T15:11:07
2021-03-08T15:11:07
345,697,144
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
package com.example.midterm; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); } }
e76dfe219f1b469f3838f26675179e11549d2bcb
6c24145ec45c05059a36f79d7910579a57af424f
/library/src/main/java/me/drakeet/library/UIImageView.java
db29517d7411bdc7c4fe2de6e8e7b7aed19ff067
[ "MIT" ]
permissive
peterdocter/AndroidUIView
569232291448635be6cce037f5fdb8faa3d13c1a
7bc68ba1c1a8d94d7d2886bcd7cb686d45e4e9ed
refs/heads/master
2021-01-17T18:09:43.863422
2015-09-02T13:35:30
2015-09-02T13:35:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,149
java
/* * The MIT License (MIT) * * Copyright (c) 2015 drakeet (http://drakeet.me) * * 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 me.drakeet.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; /** * Created by drakeet on 3/27/15. */ public class UIImageView extends ImageView { private int WIDTH; private int HEIGHT; private int PAINT_ALPHA = 48; private int mPressedColor; private Paint mPaint; private int mShapeType; private int mRadius; public UIImageView(Context context) { super(context); } public UIImageView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public UIImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(final Context context, final AttributeSet attrs) { if (isInEditMode()) return; final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UIButton); mPressedColor = typedArray.getColor(R.styleable.UIButton_color_pressed, getResources().getColor(R.color.color_pressed)); PAINT_ALPHA = typedArray.getInteger(R.styleable.UIButton_alpha_pressed, PAINT_ALPHA); mShapeType = typedArray.getInt(R.styleable.UIButton_shape_type, 1); mRadius = typedArray.getDimensionPixelSize(R.styleable.UIButton_radius, getResources().getDimensionPixelSize(R.dimen.ui_radius)); typedArray.recycle(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mPressedColor); this.setWillNotDraw(false); mPaint.setAlpha(0); mPaint.setAntiAlias(true); this.setDrawingCacheEnabled(true); this.setClickable(true); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); WIDTH = w; HEIGHT = h; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPaint == null) return; if (mShapeType == 0) { canvas.drawCircle(WIDTH/2, HEIGHT/2, WIDTH/2.1038f, mPaint); } else { RectF rectF = new RectF(); rectF.set(0, 0, WIDTH, HEIGHT); canvas.drawRoundRect(rectF, mRadius, mRadius, mPaint); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mPaint.setAlpha(PAINT_ALPHA); invalidate(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mPaint.setAlpha(0); invalidate(); break; } return super.onTouchEvent(event); } }
4c8de418dcfddad20ffa984adc69e9418966c1e7
5cd490e7a4e1deada9a8b502edeff06829bbe029
/app/src/main/java/com/example/doctruyen/ManDangNhap.java
68e90f93a9676be902d4e45773801dbd79efcb37
[]
no_license
BaiKaiTa/DocTruyen
3c761a569cc535e8adae246d05450f4116b5430b
933d07ccd8bc9d7741ce1b086e1205bd69227b65
refs/heads/main
2023-09-03T18:03:28.717578
2021-10-30T13:23:57
2021-10-30T13:23:57
421,880,971
0
0
null
null
null
null
UTF-8
Java
false
false
2,721
java
package com.example.doctruyen; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.doctruyen.database.databasedoctruyen; public class ManDangNhap extends AppCompatActivity { EditText edtTaiKhoan,edtMatKhau; Button btnDangNhap,btnDangKy; com.example.doctruyen.database.databasedoctruyen databasedoctruyen; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_man_dang_nhap); AnhXa(); //đối tượng databasedoctruyen = new databasedoctruyen(this); btnDangKy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ManDangNhap.this,ManDangKy.class); startActivity(intent); } }); btnDangNhap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tentaikhoan = edtTaiKhoan.getText().toString(); String matkhau = edtMatKhau.getText().toString(); Cursor cursor = databasedoctruyen.getCData(); while (cursor.moveToNext()){ String datatentaikhoan = cursor.getString(1); String datamatkhau = cursor.getString(2); if (datatentaikhoan.equals(tentaikhoan) && datamatkhau.equals(matkhau)) { int phanquyen = cursor.getInt(4); int idd = cursor.getInt(0); String email = cursor.getString(3); String tentk = cursor.getString(1); //chuyển sang màn hình mainactivty Intent intent = new Intent(ManDangNhap.this,MainActivity.class); intent.putExtra("phanq", phanquyen); intent.putExtra("idd",idd); intent.putExtra("email",email); intent.putExtra("tentaikhoan", tentk); startActivity(intent); } } cursor.moveToFirst(); cursor.close(); } }); } private void AnhXa() { edtMatKhau = findViewById(R.id.matkhau); edtTaiKhoan = findViewById(R.id.taikhoan); btnDangKy = findViewById(R.id.dangky); btnDangNhap = findViewById(R.id.dangnhap); } }
6ccdb370e14249d603912584eac224506b9e6ad6
632b69bd7637a01077ec7754d5011c52f4541022
/FunctionalTest/src/main/java/com/accusoft/tests/ocs/common/utils/amazon/DownloadFileFromS3.java
93aeab81d0c25a88a66646a68ca37e04e7ae89da
[]
no_license
ArtemKasjanenko/FunctionalTest
7bcd150821bbd31a5f1d4d8dfeb20ad5ebba9679
7211865cc786b14a7b996cafc640d38a268feb4a
refs/heads/master
2021-01-21T21:42:36.108756
2016-02-04T14:33:37
2016-02-04T14:33:37
49,976,580
0
0
null
null
null
null
UTF-8
Java
false
false
5,786
java
package com.accusoft.tests.ocs.common.utils.amazon; import java.io.File; import java.util.List; import com.accusoft.tests.ocs.common.utils.FSUtils; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.S3ObjectSummary; public class DownloadFileFromS3 extends BasicS3Step { private final static int NUMBER_OF_S3_REQUEST_RETRIES = 10; private final static String ARG_S3_FILE_NAME = "awsS3FileName"; private final static String ARG_LOCAL_FILE_NAME = "localFileName"; private final static String ARG_OVERWRITE_EXISTING_FILE = "overwriteExistingFile"; private final static String ARG_AWS_ACCESS_KEY_ID = "awsAccessKeyId"; private final static String ARG_AWS_SECRET_ACCESS_KEY = "awsSecretAccessKey"; private final static String ARG_AWS_S3_BUCKET_NAME = "awsS3BucketName"; private static String s3FileName = null; private static String localFileName = null; private static boolean overwriteExistingFile = false; private static boolean checkExistanceOfFileInS3 = false; public static void main(String[] args) { initTestProperties(); run(); System.exit(0); } public static void initTestProperties() { s3FileName = FSUtils.prettifyFilePath(System .getProperty(ARG_S3_FILE_NAME)); localFileName = FSUtils.prettifyFilePath(System .getProperty(ARG_LOCAL_FILE_NAME)); overwriteExistingFile = Boolean.parseBoolean(FSUtils .prettifyFilePath(System.getProperty( ARG_OVERWRITE_EXISTING_FILE, "false"))); accessKeyId = FSUtils.prettifyFilePath(System .getProperty(ARG_AWS_ACCESS_KEY_ID)); secretAccessKey = FSUtils.prettifyFilePath(System .getProperty(ARG_AWS_SECRET_ACCESS_KEY)); bucketName = FSUtils.prettifyFilePath(System .getProperty(ARG_AWS_S3_BUCKET_NAME)); LOGGER.info("\nDOWNLOAD FILE FROM S3 STEP PROPERTIES:"); LOGGER.info("S3 FILE NAME: " + s3FileName); LOGGER.info("LOCAL FILE NAME: " + localFileName); LOGGER.info("OVERWRITE EXISTING FILE: " + overwriteExistingFile); LOGGER.info("ACCESS KEY ID: " + accessKeyId); LOGGER.info("SECRET ACCESS KEY: " + secretAccessKey); LOGGER.info("BUCKET NAME: " + bucketName); } public static void init(String accessKeyId_, String secretAccessKey_, String bucketName_, String s3FileName_, String localFileName_, boolean overwriteExistingFile_) { accessKeyId = accessKeyId_; secretAccessKey = secretAccessKey_; bucketName = bucketName_; s3FileName = s3FileName_; localFileName = localFileName_; overwriteExistingFile = overwriteExistingFile_; } public static void run(String accessKeyId_, String secretAccessKey_, String bucketName_, String s3FileName_, String localFileName_, boolean overwriteExistingFile_, boolean checkExistanceOfFileInS3_) { accessKeyId = accessKeyId_; secretAccessKey = secretAccessKey_; bucketName = bucketName_; s3FileName = s3FileName_; localFileName = localFileName_; overwriteExistingFile = overwriteExistingFile_; checkExistanceOfFileInS3 = checkExistanceOfFileInS3_; run(); } public static void run() { // if (s3FileName == null) { throw new RuntimeException("S3 File Name can not be null or empty"); } if (s3FileName.isEmpty()) { throw new RuntimeException("S3 File Name can not be null or empty"); } // Check if local file exists File localFile = new File(localFileName); boolean localFileExists = localFile.exists(); if (localFileExists) { LOGGER.info("Local file " + localFileName + " exists"); } AmazonS3 s3Client = getAwsClient(); // Check if file exists in S3 if(checkExistanceOfFileInS3){ String s3DirName = FSUtils.getParentFolderPath(s3FileName); List<S3ObjectSummary> fileList = Manager.getFolderContentList( getBucketName(), s3DirName, s3Client); boolean fileExistsInS3 = false; for (S3ObjectSummary file : fileList) { if (file.getKey().equalsIgnoreCase(s3FileName)) { LOGGER.info("File [" + s3FileName + "] exists inside S3 Bucket folder"); fileExistsInS3 = true; break; } } if (!fileExistsInS3) { throw new RuntimeException("Requested file does not exist in S3 " + s3FileName); } } if (overwriteExistingFile || !localFileExists) { // Creation of local dir String localDirPath = FSUtils .getParentFolderPath(localFileName); File localDir = new File(localDirPath); if (!localDir.exists()) { localDir.mkdirs(); } LOGGER.debug("Downloading S3 file " + FSUtils.prettifyFilePath(getBucketName() + File.pathSeparator + s3FileName) + "] to local file system [" + localFileName + "]"); boolean error = false; for (int retries = 1; retries <= NUMBER_OF_S3_REQUEST_RETRIES; retries++) { try { s3Client.getObject(new GetObjectRequest(getBucketName(), s3FileName), new File(localFileName)); error = false; break; } catch (Exception ex) { LOGGER.error("Some error during file transmission from AWS S3 bucket " + ex.getMessage()); LOGGER.error("Resending download request [" + (retries + 1) + "] from [" + NUMBER_OF_S3_REQUEST_RETRIES + "] in 1 second"); error = true; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } if (error) { throw new RuntimeException("Can not download file from S3 [" + s3FileName + "] to local location [" + localFileName + "]"); } LOGGER.debug("AWS S3 File " + s3FileName + " is downloaded to " + localFileName); } } }
52bcc87e632f6db71f7a4aeb4ef388e6629190f2
ec2f55cfe93425b4237d656242a4f5be2d61aed3
/AndroidLibrary/src/com/vlabs/ane/cameraroll/functions/LoadPhotoAtIndexFunction.java
87573441874ce191cb013d66168e145ad9161449
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
rivella50/ANE-CameraRoll
4d3c0e7b5fee598ae3215232f5f372e13e290d4b
ac0602a57e52f8948654b66f5e58503a9d9e4fdf
refs/heads/master
2020-12-30T09:37:57.399995
2013-04-23T13:30:36
2013-04-23T13:30:36
8,653,016
8
2
null
null
null
null
UTF-8
Java
false
false
338
java
package com.vlabs.ane.cameraroll.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; public class LoadPhotoAtIndexFunction implements FREFunction { @Override public FREObject call(FREContext arg0, FREObject[] arg1) { // TODO Auto-generated method stub return null; } }
60abeb77f7f37e7c7b44f8011536dbcc9906e545
c74c2e590b6c6f967aff980ce465713b9e6fb7ef
/game-logic-reset/src/main/java/com/bdoemu/gameserver/model/skills/buffs/effects/SwimmingSpeedEffect.java
be54441e9b70318c665a3c5ea50803a396a1b659
[]
no_license
lingfan/bdoemu
812bb0abb219ddfc391adadf68079efa4af43353
9c49b29bfc9c5bfe3192b2a7fb1245ed459ef6c1
refs/heads/master
2021-01-01T13:10:13.075388
2019-12-02T09:23:20
2019-12-02T09:23:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,165
java
package com.bdoemu.gameserver.model.skills.buffs.effects; import com.bdoemu.gameserver.model.creature.Creature; import com.bdoemu.gameserver.model.creature.player.Player; import com.bdoemu.gameserver.model.skills.buffs.ABuffEffect; import com.bdoemu.gameserver.model.skills.buffs.ActiveBuff; import com.bdoemu.gameserver.model.skills.buffs.templates.BuffTemplate; import com.bdoemu.gameserver.model.skills.templates.SkillT; import com.bdoemu.gameserver.model.stats.elements.BuffElement; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @ClassName SwimmingSpeedEffect * @Description TODO * @Author JiangBangMing * @Date 2019/7/12 10:18 * VERSION 1.0 */ public class SwimmingSpeedEffect extends ABuffEffect { @Override public Collection<ActiveBuff> initEffect(final Creature owner, final Collection<? extends Creature> targets, final SkillT skillT, final BuffTemplate buffTemplate) { final List<ActiveBuff> buffs = new ArrayList<ActiveBuff>(); final Integer[] params = buffTemplate.getParams(); final int swimmingValue = params[0]; final BuffElement element = new BuffElement(swimmingValue); for (final Creature target : targets) { buffs.add(new ActiveBuff(skillT, buffTemplate, owner, target, element)); } return buffs; } @Override public void applyEffect(final ActiveBuff activeBuff) { final Creature target = activeBuff.getTarget(); if (target.isPlayer()) { target.getGameStats().getSwimmingStat().addElement(activeBuff.getElement()); final Player player = (Player) target; // player.sendBroadcastItSelfPacket(new SMSetCharacterPublicPoints(player)); } } @Override public void endEffect(final ActiveBuff activeBuff) { final Creature target = activeBuff.getTarget(); if (target.isPlayer()) { target.getGameStats().getSwimmingStat().removeElement(activeBuff.getElement()); final Player player = (Player) target; // player.sendBroadcastItSelfPacket(new SMSetCharacterPublicPoints(player)); } } }
c27238ccb17f77c635592f0015ceacaa3bfd0c5b
dcbc03ccddb98fdc7fe2035edaa78b28a9629474
/src/com/chinaunicom/homework/servlet/LogoutServelt.java
256e8f8861dcd011c7b92de8d384b6acc9ce4196
[]
no_license
chengxinxiaofeng/chinaUnicomTrainPractice
9d3d3479781eca380fcfd2a9a5bff319e28941b5
661b71cfbc09cd2e28cb1bec21a6f2a1d676a908
refs/heads/master
2020-06-11T15:26:49.472217
2019-06-27T02:51:25
2019-06-27T02:51:25
194,010,901
0
0
null
null
null
null
UTF-8
Java
false
false
737
java
package com.chinaunicom.homework.servlet; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 张永峰 * @author Administrator * 退出登录 * */ @WebServlet("/logout") public class LogoutServelt extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { doGet(req, resp); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse resp) { request.getSession().removeAttribute("isLogin"); //request.getSession().invalidate(); } }
a809710b7aada686ac1d28d06f1ecf88308ab677
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/main/java/org/gradle/test/performancenull_439/Productionnull_43877.java
3319675afc55a43a33b7a79ec8c9f98aebe48194
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
588
java
package org.gradle.test.performancenull_439; public class Productionnull_43877 { private final String property; public Productionnull_43877(String param) { this.property = param; } public String getProperty() { return property; } private String prop0; public String getProp0() { return prop0; } public void setProp0(String value) { prop0 = value; } private String prop1; public String getProp1() { return prop1; } public void setProp1(String value) { prop1 = value; } }
5528cadb2513565a9b30562db36d4154af8e215b
dd8529d8747d129ac019f683cdb42c504ca36fa5
/Week_04/class4/src/main/java/gaol/practice/class4/MyCallable.java
6fff694c0bd5666dabc3e93ee2898febe02acb4a
[]
no_license
gaoliang-dl/JAVA-000
b994f9d20e324cb1ccc3df8ca59705a55c9e73df
b92813da033b5d01d49e79469fb98c1986549987
refs/heads/main
2023-02-23T21:45:31.561250
2021-02-02T10:35:05
2021-02-02T10:35:05
305,244,318
18
10
null
null
null
null
UTF-8
Java
false
false
373
java
package gaol.practice.class4; import java.util.concurrent.Callable; public class MyCallable implements Callable<Integer> { @Override public Integer call() { System.out.println("线程执行......"); int returnValue = Class4Application.sum(); System.out.println("线程执行完毕......"); return returnValue; } }
f91235458cf4f73856ed6866e73bb8f16c43f850
7ae75038fa483db726152aa2c546441eced38505
/two-fer/src/main/java/Twofer.java
d4f58b1c4c96e68c916444636ea872614c7a989b
[]
no_license
AsmitaHari/ExercismCode
41364f2de03ffb23f4c5fef1cf5e1708becc1491
ab0362b67c000769b865d5c2b438d730d4c9fac0
refs/heads/master
2022-12-24T04:51:50.689604
2020-09-18T23:09:29
2020-09-18T23:09:29
296,747,036
0
0
null
null
null
null
UTF-8
Java
false
false
287
java
public class Twofer { public String twofer(String name) { String message = new String("One for %s, one for me."); if (name == null) { return String.format(message,"you"); } else { return String.format(message, name); } } }
8fc36f2a52e258554a05b460a02a24676dd5d229
13d11f557f625c7c57397ecb7e78bcfe64c8121c
/src/main/java/com/example/administrator/fragmenttest_04_44/BookDetailFragment.java
e50e53e7e7ddc398bea37de5b7c23eb58571b8cd
[]
no_license
shenquan/GithubFragmentTest_04_4.42
97cd3bfd71ae7253021e35d06beea77f2939dc44
e1b67a0f4ae586dba82fbf2988a1f628dfcd9c45
refs/heads/master
2021-01-10T03:47:06.430919
2016-01-14T16:20:01
2016-01-14T16:20:01
49,659,041
0
0
null
null
null
null
UTF-8
Java
false
false
1,640
java
package com.example.administrator.fragmenttest_04_44; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by Administrator on 2016/1/14. */ public class BookDetailFragment extends Fragment { public static final String ITEM_ID = "item_id"; // 保存该Fragment显示的Book对象 BookContent.Book book; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 如果启动该Fragment时包含了ITEM_ID参数 if (getArguments().containsKey(ITEM_ID)) { book = BookContent.ITEM_MAP.get(getArguments() .getInt(ITEM_ID)); // ① } } // 重写该方法,该方法返回的View将作为Fragment显示的组件 @Override public View onCreateView(LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState) { // 加载/res/layout/目录下的fragment_book_detail.xml布局文件 View rootView = inflater.inflate(R.layout.fragment_book_detail, container, false); if (book != null) { // 让book_title文本框显示book对象的title属性 ((TextView) rootView.findViewById(R.id.book_title)) .setText(book.title); // 让book_desc文本框显示book对象的desc属性 ((TextView) rootView.findViewById(R.id.book_desc)) .setText(book.desc); } return rootView; } }
4fb40ed4f31260aea43819da0c588a65c7ac9302
f3332975a54623a1ef31aced2c20e355c7626fa0
/library/src/main/java/com/mobilesolutionworks/android/exe/WorksExecutor.java
e2bf5c6f04a75ed15cae100487b8f2e084f29941
[]
no_license
yunarta/works-base-android
1e55a04b6c71b65b9a2995d12f1092f1d28fb472
508533bb56cc38babb88c3e034eb9af8f464df03
refs/heads/master
2021-01-23T12:57:21.635940
2016-01-10T17:14:39
2016-01-10T17:14:39
46,443,289
0
2
null
null
null
null
UTF-8
Java
false
false
598
java
package com.mobilesolutionworks.android.exe; import android.os.Handler; import android.os.Looper; import java.util.concurrent.Executor; /** * Created by yunarta on 19/11/15. */ public class WorksExecutor { static class MainExecutor implements Executor { MainExecutor() { mHandler = new Handler(Looper.getMainLooper()); } private Handler mHandler; @Override public void execute(Runnable runnable) { mHandler.post(runnable); } } public static final Executor MAIN = new MainExecutor(); }
08b32335db1db4d7e507d9557abf59568e7a54f3
b75f9e2399a67d4d25219d6bd55a31d93aa7255d
/MoodAnalyzerTest.java
76666e8b68e252397439a87cc06162c43933c530
[]
no_license
Ansh2103/Mood_Analyzer_Test
5e30728755356114997fd892ba4e35ab76b55dc6
7df31e1e8ab2c664b8ff0869560ec5c64cbe2a2a
refs/heads/master
2023-01-04T18:56:28.521936
2020-11-02T14:04:48
2020-11-02T14:04:48
309,381,387
0
0
null
null
null
null
UTF-8
Java
false
false
604
java
import org.junit.Assert; import org.junit.Test; public class MoodAnalyzerTest { @Test public void testMood_WhenStringContainSad_ShouldReturnSad() { MoodAnalyzer moodAnalyser = new MoodAnalyzer("I am in Sad Mood"); String isMoodSad = moodAnalyser.analyzeMood(); Assert.assertEquals("SAD" , isMoodSad); } @Test public void testMood_WhenStringContainHappy_ShouldReturnHappy() { MoodAnalyzer moodAnalyser = new MoodAnalyzer(null); String isMoodHappy = moodAnalyser.analyzeMood(); Assert.assertEquals("HAPPY", isMoodHappy); } }
f0b43ddc1f7d93220ce042999b93ea0a42cd794a
c7723fcf2a69a60b07fb866afa3bd0456474bc7b
/src/main/java/org/robotframework/formslibrary/operator/HorizontalScrollBarOperator.java
409c55d3313c3d14e19bb145f26caeff5916190c
[ "Apache-2.0" ]
permissive
dvanherbergen/robotframework-formslibrary
295db27bf5213dfb9784a5815a66229351b78a48
c71aadc994f40d828c35155f6a35c8d9d7a1e888
refs/heads/master
2020-04-12T03:46:44.091434
2017-04-20T14:42:41
2017-04-20T14:42:41
62,289,888
5
4
null
null
null
null
UTF-8
Java
false
false
2,296
java
package org.robotframework.formslibrary.operator; import java.awt.Component; import java.awt.Container; import org.robotframework.formslibrary.chooser.ByComponentTypeChooser; import org.robotframework.formslibrary.chooser.ByOrientationChooser; import org.robotframework.formslibrary.chooser.CompositeChooser; import org.robotframework.formslibrary.util.ComponentType; import org.robotframework.formslibrary.util.ObjectUtil; /** * Operator for working with horizontal scroll bars. */ public class HorizontalScrollBarOperator extends AbstractComponentOperator { /** * Initialize a HorizontalScrollBarOperator with the n'th horizontal scroll * bar in the current context. * * @param index * 0 (first), 1 (second), ... */ public HorizontalScrollBarOperator(int index) { super(new CompositeChooser(new ByOrientationChooser(ByOrientationChooser.Orientation.HORIZONTAL), new ByComponentTypeChooser(index, ComponentType.ALL_SCROLL_BAR_TYPES))); } /** * Scroll left by pressing the left arrow button in the scroll bar. * * @param count * number of times to press the button. */ public void scrollLeft(int count) { Component[] buttons = ((Container) getSource()).getComponents(); Component leftButton = null; if (buttons[1].getX() < buttons[0].getX()) { leftButton = buttons[1]; } else { leftButton = buttons[0]; } for (int i = 0; i < count; i++) { ObjectUtil.invokeMethod(leftButton, "simulatePush"); } } /** * Scroll right by pressing the right arrow button in the scroll bar. * * @param count * number of times to press the button. */ public void scrollRight(int count) { Component[] buttons = ((Container) getSource()).getComponents(); Component rightButton = null; if (buttons[1].getX() > buttons[0].getX()) { rightButton = buttons[1]; } else { rightButton = buttons[0]; } for (int i = 0; i < count; i++) { ObjectUtil.invokeMethod(rightButton, "simulatePush"); } } }
1a6a2c785f7d97e5e1a9f7a5fbee63f86c5e1647
f3ec391704c9c418d70808a38231ca66d16ab607
/SchoolProject/2ndFall2020/week1/httpServer/src/gk/company/Main.java
d5af930383bff753be528891404fa9e864348ff7
[]
no_license
gkwazy/SchoolProjects
efc457056fde56c9539b4f1d287396784ec80d5d
30068f02ad6291ee250dd43e981a2f656886ff98
refs/heads/master
2023-07-09T20:48:50.900596
2021-08-09T17:20:30
2021-08-09T17:20:30
394,379,015
0
0
null
null
null
null
UTF-8
Java
false
false
1,107
java
package gk.company; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.*; public class Main { private static ServerSocket server; public static void main(String[] args) throws IOException { server = new ServerSocket(8080); System.out.println("Listening for connection on port 8080 ...."); while(true) { Socket clientSocket = server.accept(); Thread serverThread = new Thread(() -> { System.out.println("started thread ... " + Thread.currentThread().getId()); try { HTTPRequest httpRequest = new HTTPRequest(); HTTPResponse httpResponse = new HTTPResponse(); String[] request = httpRequest.parseRequest(clientSocket); httpResponse.sendInfo(clientSocket, request); // clientSocket.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }); serverThread.start(); } } }
20b4dd8bbcae6e83d252031e39b66f46023984e9
2dfada3a7c42b541b7af3da7e6f9cc3d87c424ec
/src/main/java/com/code/service/impl/CategoryServiceImp.java
c26b3d3d0c899f071742095a00c4c1af8a1064df
[ "Apache-2.0" ]
permissive
yanchhuong/WESERVDEV
a37993d976aa15e3e0f697ff05c4ddd5dc9fad61
727ceb61578f8185b690505fbbce16b2c0a640cf
refs/heads/master
2021-09-13T14:10:33.773601
2018-05-01T02:55:18
2018-05-01T02:55:18
113,276,071
0
0
null
null
null
null
UTF-8
Java
false
false
2,457
java
package com.code.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.code.dao.ICategoryRepository; import com.code.model.CategoryBean; import com.code.model.CategoryBean_R001; import com.code.service.ICategoryService; @Service(value = "categoryService") public class CategoryServiceImp implements ICategoryService{ private ICategoryRepository iCategoryRepo; @Autowired(required = true) public CategoryServiceImp(ICategoryRepository iCategory){ this.iCategoryRepo = iCategory; } @Transactional(readOnly = true) @Override public List<CategoryBean_R001> findAll() { return this.iCategoryRepo.findAlls(); } @Transactional(readOnly = false) @Override public void saveCategoryBean(CategoryBean input) { if(input.getCatgid() > 0) { this.iCategoryRepo.updateCategory(input); }else { this.iCategoryRepo.insertCategory(input); } } @Override public void delete(long CategoryBeanId) { this.iCategoryRepo.delete(CategoryBeanId); } @Override public long getCatgidCount() { return this.iCategoryRepo.getCatidCount(); } @Override public void removeMenuTree(int rootid) { this.iCategoryRepo.removeMenuTree(rootid); } @Override public List<CategoryBean> findByCategoryBeanFirstName(String CategoryBeanFirstName) { // TODO Auto-generated method stub return null; } @Override public List<CategoryBean> findByCategoryBeanNameAndSalary(String CategoryBeanFirstName, long CategoryBeanSalary) { // TODO Auto-generated method stub return null; } @Override public List<CategoryBean> findBySalary(long salary) { // TODO Auto-generated method stub return null; } @Override public List<CategoryBean> findByPriceRange(long price1, long price2) { // TODO Auto-generated method stub return null; } @Override public List<CategoryBean> findByNameMatch(String name) { // TODO Auto-generated method stub return null; } @Override public List<CategoryBean> findByNamedParam(String name, String author, long price) { // TODO Auto-generated method stub return null; } @Override public CategoryBean findOne(long CategoryBeanId) { // TODO Auto-generated method stub return null; } @Override public void updateMenu(long pid, String usercd, long catgid) { // TODO Auto-generated method stub } }
23b9beb09658d4dea3fb05b0f0a5b8e98195aa09
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/29/147.java
e2d7982cd52f59677e39e2caaceac10c2bde6932
[ "MIT" ]
permissive
qiuchili/ggnn_graph_classification
c2090fefe11f8bf650e734442eb96996a54dc112
291ff02404555511b94a4f477c6974ebd62dcf44
refs/heads/master
2021-10-18T14:54:26.154367
2018-10-21T23:34:14
2018-10-21T23:34:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
763
java
package <missing>; public class GlobalMembers { public static int k(int n) { int i; int k1 = 1; int k2 = 2; int a; if (n > 1) { for (i = 1;i < n;i++) { a = k2; k2 = k1 + k2; k1 = a; } } else if (n = 1) { k2 = 2; } return k2; } public static int Main() { int n; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { n = Integer.parseInt(tempVar); } int i; int j; for (i = 0;i < n;i++) { int num; String tempVar2 = ConsoleInput.scanfRead(); if (tempVar2 != null) { num = Integer.parseInt(tempVar2); } double sum = 2; for (j = 2;j <= num;j++) { sum = sum + ((double)k(j) / (double)k(j - 1)); } System.out.printf("%.3lf\n",sum); } } }
9baccd17d79fbe041b3a6a96b617ebb77054eab1
5dc8faa95699b22cd4b564ea2ee20aa2977bf8fd
/src/org/openelis/ui/widget/table/event/FilterHandler.java
e094c44a528517d53a91ac7871ffb41651530a00
[]
no_license
mbielicke/OpenELIS-UI
0b47cde80cb73edce965b402708923040c3ca9f6
32dcf69b17d419b877cd68a6cc7d1408729b1fad
refs/heads/master
2021-01-11T00:44:51.796516
2016-08-10T18:19:42
2016-08-10T18:19:42
70,498,177
0
0
null
null
null
null
UTF-8
Java
false
false
195
java
package org.openelis.ui.widget.table.event; import com.google.gwt.event.shared.EventHandler; public interface FilterHandler extends EventHandler { public void onFilter(FilterEvent event); }
2c50cf961e76a3facae00a034236afb23c2e0eaf
a8e6cb7b256f8a2d7cef8100dcda91ef2eacbbd0
/reservation-api/src/main/java/ca/ulaval/glo4002/reservation/exceptions/RestException.java
2a70cee3a785f7ef3bcabe6a851257b7905c8d2a
[]
no_license
bigpkd/glo-4002-maitre-T
9354d9622cd5129ba2f339a2320c04f072a7136a
614699edac8f1969ddd0ad2321765275de063f34
refs/heads/master
2023-02-15T13:25:29.023813
2021-01-14T13:03:24
2021-01-14T13:03:24
329,617,060
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package ca.ulaval.glo4002.reservation.exceptions; public abstract class RestException extends RuntimeException { public RestException(String message) { super(message); } public abstract String getError(); }
21c00bc5105bb9242f27808dadd67493d413a4f7
4119b75e437c7dbccab677e98b5c00918abf5ed1
/svn-webapp/src/main/java/com/tusia/dto/PieChartCommits.java
6b3a4eccf5ea23b309837280d8d836cd448720c4
[]
no_license
qulith/svn-stats
9b97a2f6bb7fab15cf4f547f9c73e467868c6b10
4e2ca7e7b8739570858c5cc9c025220ec5e419b0
refs/heads/master
2020-04-06T03:34:08.898088
2011-11-13T00:32:04
2011-11-13T00:32:04
2,753,850
0
0
null
null
null
null
UTF-8
Java
false
false
496
java
package com.tusia.dto; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class PieChartCommits { protected String name; protected int y = 0; public JSONArray getJson() { JSONArray retVal = new JSONArray(); retVal.add(name); retVal.add(y); return retVal; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
af77e52677ef2a64bb41f52f43a3c343a6a0038a
f69976ab2b2f80d76c08f1d0001045321c2f93ec
/app/src/main/java/com/shoppay/wyoilnew/modle/InterfaceWeixinPay.java
07be87f7e6e0e5938d5ec3bc1656f0281b5d6096
[]
no_license
yy471101598/chuanfooilnew
632ac7bee9c078385da7969fe8c7d5fb9c97efd8
5761ed60b0026f8e2b998f1285ba954f0baa6d4b
refs/heads/master
2020-04-06T14:54:26.427759
2019-01-15T09:53:23
2019-01-15T09:53:23
157,558,712
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
package com.shoppay.wyoilnew.modle; import android.content.Context; public interface InterfaceWeixinPay { public void weixinPay(Context context,String moeny,String orderNo,String pName, InterfaceMVC interf); }
4f6983536af3911a9a200e0bde18042354500b14
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/4/4_8fde77a843431037fde796c92b22f699bd28953f/ReactorTarget/4_8fde77a843431037fde796c92b22f699bd28953f_ReactorTarget_t.java
5d79d549d4b2c95cd6b85d1919eaf7f6cf5d425d
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
930
java
package openccsensors.common.sensors.industrialcraft; import ic2.api.IReactor; import ic2.api.IC2Reactor; import java.util.HashMap; import java.util.Map; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.api.ISensorTarget; import openccsensors.common.sensors.TileSensorTarget; public class ReactorTarget extends TileSensorTarget implements ISensorTarget { ReactorTarget(TileEntity targetEntity) { super(targetEntity); } public Map getDetailInformation(World world) { HashMap retMap = new HashMap(); IReactor reactor = (IReactor) world.getBlockTileEntity(xCoord, yCoord, zCoord); retMap.put("Heat", reactor.getHeat()); retMap.put("MaxHeat", reactor.getMaxHeat()); retMap.put("Output", reactor.getOutput() * new IC2Reactor().getEUOutput()); retMap.put("Active", reactor.produceEnergy()); return retMap; } }
1e0d24cdb7a416ff20218662212a250e0926151f
f60d91838cc2471bcad3784a56be2aeece101f71
/spring-framework-4.3.15.RELEASE/spring-websocket/src/main/java/org/springframework/web/socket/server/support/package-info.java
33b4aec1832186c90212574e15ad6bfbf78eb8a3
[ "Apache-2.0" ]
permissive
fisher123456/spring-boot-1.5.11.RELEASE
b3af74913eb1a753a20c3dedecea090de82035dc
d3c27f632101e8be27ea2baeb4b546b5cae69607
refs/heads/master
2023-01-07T04:12:02.625478
2019-01-26T17:44:05
2019-01-26T17:44:05
167,649,054
0
0
Apache-2.0
2022-12-27T14:50:58
2019-01-26T04:21:05
Java
UTF-8
Java
false
false
162
java
/** * Server-side support classes including container-specific strategies * for upgrading a request. */ package org.springframework.web.socket.server.support;
a42749e2ff2bf641ec45289d2fcee6b1f763fb04
cc47da9d0dd0d0686b6e8f3dd8ad23305e9191a6
/src/main/java/de/uniks/se19/team_g/project_rbsg/ingame/model/Selectable.java
6189bf767fcdb14a7cc820cdcc166eefcf0b5b0e
[]
no_license
DerYeger/Project_RBSG
01f700b846ffc74c8b9875efb7d6d08bf23ba0e2
d92afb6c75fe7d6e48d8b5ae95241825d4310776
refs/heads/master
2023-03-14T04:42:24.022708
2021-02-27T17:29:37
2021-02-27T17:29:37
342,914,268
1
0
null
null
null
null
UTF-8
Java
false
false
361
java
package de.uniks.se19.team_g.project_rbsg.ingame.model; import javafx.beans.value.ObservableBooleanValue; import org.springframework.lang.Nullable; public interface Selectable { boolean isSelected(); void setSelectedIn(@Nullable Game game); ObservableBooleanValue selectedProperty(); default void clearSelection() {setSelectedIn(null);} }
a2e26dd9710d4fd2391aa588e640e950f74c6357
b69ac8ef168bfb98f1567315d1afbed7ab60c8c0
/src/com/mg_movie/adapter/RadioType.java
30d634d103fbef7aa66ac04f06a0f14f73f60cf8
[]
no_license
rockchow2002/MG_MOVIE
5d9e91492b41a11314d5aeabb82d7e2f34cd1b40
63816dc568793fa77b5c72588dfbd11acfa8f215
refs/heads/master
2021-01-21T06:00:43.426875
2013-09-30T09:33:08
2013-09-30T09:33:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,024
java
package com.mg_movie.adapter; import android.os.Parcel; import android.os.Parcelable; public class RadioType implements Parcelable { private String url; private String name; @Override public int describeContents() { return 0; } public RadioType() { } private RadioType(Parcel in) { readFromParcel(in); } public void readFromParcel(Parcel in) { url = in.readString(); name = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(url); dest.writeString(name); } public static final Creator<RadioType> CREATOR = new Creator<RadioType>() { @Override public RadioType createFromParcel(Parcel source) { return new RadioType(source); } @Override public RadioType[] newArray(int size) { return new RadioType[size]; } }; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
56fadd4a5f21601dcf02b72282021e6de8d67b1a
2bbb2449d4fff005bc66da6b21b6a0a2ed554400
/FriendzzHutMiddleWare/src/main/java/com/config/WebAppDispatcherConfig.java
f5e5bbec19f6427d3753cae601e7b98151a0370a
[]
no_license
chetnapadiya13/FriendzzzHutMiddleWare
4213b4ebc977a6a97994c3db1fd7cbcfcf1afd83
9d2012c53c00f022b25aedd77faeb27a54df88c5
refs/heads/master
2020-03-06T22:54:58.986841
2018-03-29T03:40:51
2018-03-29T03:40:51
127,117,807
0
0
null
null
null
null
UTF-8
Java
false
false
866
java
package com.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages="com.configer") public class WebAppDispatcherConfig { @Bean public ViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
20c1ce3ee38d60a4b650486b97bafe9022166d36
11b248bd386d5354a13903eff3c90a2e397c2d82
/app/src/main/java/cn/ac/iie/RPMod/fidouafclient/util/Preferences.java
ea547bb0672dbfcf7886fb28572cb1a6a6fcb824
[]
no_license
JKRm/EBY_CHG_RP
cb4bdcb32ff97012129a7bf53c2ec4f5650d9528
5e067db18275917cec737163bc555af8b59164b4
refs/heads/master
2021-01-17T13:10:14.802233
2016-06-22T13:49:27
2016-06-22T13:49:27
59,728,609
0
0
null
null
null
null
UTF-8
Java
false
false
1,009
java
package cn.ac.iie.RPMod.fidouafclient.util; import android.content.SharedPreferences; public class Preferences { private static String PREFERANCES = "Preferances"; public static String getSettingsParam(String paramName) { SharedPreferences settings = getPrefferences(); return settings.getString(paramName, ""); } public static SharedPreferences getPrefferences() { SharedPreferences settings = ApplicationContextProvider.getContext() .getSharedPreferences(PREFERANCES, 0); return settings; } public static void setSettingsParam(String paramName, String paramValue) { SharedPreferences settings = getPrefferences(); SharedPreferences.Editor editor = settings.edit(); editor.putString(paramName, paramValue); editor.commit(); } public static void setSettingsParamLong(String paramName, long paramValue) { SharedPreferences settings = getPrefferences(); SharedPreferences.Editor editor = settings.edit(); editor.putLong(paramName, paramValue); editor.commit(); } }
6d65a248cd06438384d52e8d391738212e9e1aaf
b01df13858b253323428438451f75ffbd82b068a
/src/main/java/com/jerait/lifecontrol/desktop/MainPreloader.java
88bb9315cefec9768bf6d17bb8c16f1cb9ddc014
[]
no_license
sbobrov85/lifecontrol-desktop
37a4574e8c35216f35a7191c26653f3019d68d0f
a25e42e11d64587802f9ddd182a56f6c619e9fa5
refs/heads/master
2021-01-12T04:53:53.037333
2017-05-02T03:22:47
2017-05-02T03:22:47
77,807,702
0
0
null
null
null
null
UTF-8
Java
false
false
1,033
java
package com.jerait.lifecontrol.desktop; import com.jerait.lifecontrol.desktop.utils.GUI; import javafx.application.Preloader; import javafx.application.Preloader.StateChangeNotification.Type; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.StageStyle; /** * Main preloader class. */ public class MainPreloader extends Preloader { /** * Contain preloader stage object. */ private Stage preloaderStage; /** * {@inheritDoc} */ @Override public void start(Stage primaryStage) throws Exception { preloaderStage = primaryStage; preloaderStage.initStyle(StageStyle.UNDECORATED); Scene mainPreloader = GUI.getScene("MainPreloader"); preloaderStage.setScene(mainPreloader); preloaderStage.show(); } /** * {@inheritDoc} */ @Override public void handleStateChangeNotification( StateChangeNotification stateChangeNotification ) { if (stateChangeNotification.getType() == Type.BEFORE_START) { preloaderStage.hide(); } } }
8f660102cd6b1920b83d378116606289879e87e9
680f7d92cc608cc6850cd5c150226aacbb419c06
/andEngineLib/src/main/java/org/andengine/entity/particle/initializer/GravityParticleInitializer.java
1273061c3649dfac2f32e1b5c65d737cbc1b6090
[]
no_license
mnafian/IsometricMapExample
e002b3e165abb5e52ec13fb4f541de155688bbc0
9dc08b462f5ad02cf70eab16328437fe5c8ad141
refs/heads/master
2021-01-22T06:58:51.347531
2015-08-19T08:27:05
2015-08-19T08:27:05
35,424,784
1
0
null
null
null
null
UTF-8
Java
false
false
1,569
java
package org.andengine.entity.particle.initializer; import org.andengine.entity.IEntity; import android.hardware.SensorManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:04:00 - 15.03.2010 */ public class GravityParticleInitializer<T extends IEntity> extends AccelerationParticleInitializer<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public GravityParticleInitializer() { super(0, SensorManager.GRAVITY_EARTH); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
83954e8da4438cf0a51b7925337592326d969ee7
a57ae3aec49e11b5977c80907d632fde5497da87
/algorithm1/src/jianzhioffer/T23.java
a532c4344d899b9060843f698e5f8742165a0ba1
[]
no_license
sy1121/algorithm1
39348239c900e5cfc1c2a09d1ac871088add5a04
49703f03f6262b49de8537374d88483dc4f8ace3
refs/heads/master
2021-01-17T18:11:04.283952
2019-07-04T09:54:18
2019-07-04T09:54:18
71,196,479
0
0
null
null
null
null
UTF-8
Java
false
false
517
java
package jianzhioffer; import java.util.LinkedList; import java.util.Queue; import algorithm.TreeNode; /** * 从上到下打印二叉树 * @author sy * */ public class T23 { public void printTree(TreeNode head){ if(head==null) return ; Queue<TreeNode> q=new LinkedList<TreeNode>(); q.add(head); while(!q.isEmpty()){ TreeNode cur=q.poll(); System.out.print(cur.val); if(cur.left!=null) q.offer(cur.left); if(cur.right!=null) q.offer(cur.right); } } }
47a8c35f564b046d1a14cc4cd0654c726a37f9ae
7a5587180170ca83beed60dc24115aac734bbc24
/app/src/main/java/com/example/blockcertify_manufacturerapp/Register/RegisterDistributor.java
1194cc5b171c146e53db18cbb98b17d218b0147e
[]
no_license
JollyJohhny/FYP-App-1
dc6656c1844903642857955c21ea7519d1dfca60
8a4869c803ed8d1c49e8d659a9575f8fee0b4ab6
refs/heads/master
2020-12-01T13:56:41.659608
2019-12-28T18:58:20
2019-12-28T18:58:20
230,650,960
1
0
null
null
null
null
UTF-8
Java
false
false
4,435
java
package com.example.blockcertify_manufacturerapp.Register; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.blockcertify_manufacturerapp.ChangePasswords.ChangePassword; import com.example.blockcertify_manufacturerapp.Extra.LoadingDialog; import com.example.blockcertify_manufacturerapp.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; public class RegisterDistributor extends AppCompatActivity { private LoadingDialog loadingDialog; EditText txtName,txtEmail,txtPassword,txtCnic,txtCompId,txtCnfrmPwd; DatabaseReference databaseReference; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_distributor); loadingDialog = new LoadingDialog(this, R.style.DialogLoadingTheme); txtEmail = findViewById(R.id.txtEmail); txtPassword = findViewById(R.id.txtPassword); txtCnfrmPwd = findViewById(R.id.txtCnfrmPwd); firebaseAuth = FirebaseAuth.getInstance(); } public void Register(View v){ final String Email = txtEmail.getText().toString(); String Password = txtPassword.getText().toString(); boolean flag = true; if(TextUtils.isEmpty(Email)){ Toast.makeText(this, "Please Enter Email!", Toast.LENGTH_LONG).show(); flag = false; } if(TextUtils.isEmpty(Password)){ Toast.makeText(this, "Please Enter Password!", Toast.LENGTH_LONG).show(); flag = false; } if(!Patterns.EMAIL_ADDRESS.matcher(Email).matches()){ Toast.makeText(this, "Please Enter Valid Blockcertify Email!", Toast.LENGTH_LONG).show(); flag = false; } if(txtPassword.getText().toString().equals(txtCnfrmPwd.getText().toString())){ } else{ flag = false; Toast.makeText(RegisterDistributor.this, "Password does not match!", Toast.LENGTH_SHORT).show(); } // Check for correct Register panel if(flag == true){ String[] splitted = Email.split("@"); if(splitted.length >0){ if(!splitted[1].equals("blockcertify.distributor.com")){ flag = false; Toast.makeText(this, "Use blockcertify.distributor.com after @ to Register the Distributor!", Toast.LENGTH_LONG).show(); } } } if(flag){ loadingDialog.show(); firebaseAuth.createUserWithEmailAndPassword(Email, Password) .addOnCompleteListener(RegisterDistributor.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { loadingDialog.dismiss(); Toast.makeText(RegisterDistributor.this, "Distributor Registered!", Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(RegisterDistributor.this, "Distributor already registered!", Toast.LENGTH_SHORT).show(); Log.i("failed", "createUserWithEmail:failure", task.getException()); loadingDialog.dismiss(); } // ... } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingDialog.dismiss(); } }); } } }
44f169e6c1a2eb9e5bfa7f9662c5f57d0f6e2920
7fd5f572169a7e50d10ed0d5e5966a43a8293be4
/JavaProject/src/main/java/com/danner/java/jvm/memory/RuntimeConstantPoolOOM.java
214e7dc4ec151a84d5c6758cd6f08cfe59019840
[]
no_license
vendanner/program-language
0f57dfe1ec24ad2fe53fc2832ecc4265f830d50b
bafbeade9cde1da9f21dc927cc493961feb5df30
refs/heads/master
2023-08-05T07:04:04.536507
2022-04-26T01:11:01
2022-04-26T01:11:01
202,111,639
1
0
null
2023-07-22T14:26:51
2019-08-13T09:33:55
Python
UTF-8
Java
false
false
465
java
package com.danner.java.jvm.memory; import java.util.ArrayList; import java.util.List; /** * Java8 VM Args:-Xms10m -Xmx10m -XX:-UseGCOverheadLimit * JDK 8 运行时常量池在 heap 中,设置对大小10M */ public class RuntimeConstantPoolOOM { public static void main(String[] args) { List<String> list = new ArrayList<String>(); long i = 0L; while(true) { list.add(String.valueOf(i++).intern()); } } }
a4f37fc4c0f8b250656e2ae42c86231571f74ba4
13d66b82be95244fe3ee28136c78ce08076a6ec1
/src/main/java/com/labafrique/creporter/controller/ReportController.java
52f0331af0d81825b18da428e7533f7abd1d78b1
[]
no_license
lukmanjaji/CReporterServer
74b8e623902f0deda564962cd6f985525c0ca2ea
29b329128c3790b02aa239de5ffb982ff275b2d5
refs/heads/master
2022-12-04T13:08:00.385216
2020-08-15T15:07:55
2020-08-15T15:07:55
287,761,882
0
0
null
null
null
null
UTF-8
Java
false
false
8,380
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.labafrique.creporter.controller; import com.google.gson.Gson; import com.labafrique.creporter.model.ReportModel; import com.labafrique.creporter.service.FileStorageService; import com.labafrique.creporter.ws.SocketHandler; import com.labafrique.creporter.repository.ReportRepository; import java.io.File; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * * @author Javalove */ @Component @RestController @RequestMapping("/creporter/listener") public class ReportController { @Autowired private ReportRepository caseRepo; @Autowired private FileStorageService fileStorageService; @Autowired SocketHandler handler; private static final Logger logger = LoggerFactory.getLogger(ReportController.class); public ReportController() { } @GetMapping(path="/getLatest") @ResponseBody public String getLatest(@RequestParam("t") String type, @RequestParam("x") String x) { x = x.replace(".0", ""); int a = Integer.parseInt(x); return URLDecoder.decode(new Gson().toJson(caseRepo.findByCaseType(type, a))); } @GetMapping(path="/getCases") @ResponseBody public String getCases(@RequestParam("t") String type) { return URLDecoder.decode(new Gson().toJson(caseRepo.findAllCases())); } @GetMapping(path="/getSent") @ResponseBody public String getSent(@RequestParam("sender") String sender, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("type") String type) { try { email = URLEncoder.encode(email, "utf-8"); sender = URLEncoder.encode(sender, "utf-8"); phone = URLEncoder.encode(phone, "utf-8"); type = URLEncoder.encode(type, "utf-8"); }catch(Exception er){} return URLDecoder.decode(new Gson().toJson(caseRepo.getSent(sender, email, phone, type))); } public int countAll() { return caseRepo.findAllCases().size(); } @PostMapping(path="/add") @ResponseBody public String save(@RequestParam("code") String code, @RequestParam("category") String category, @RequestParam("details") String details, @RequestParam("audio") String audio, @RequestParam("video") String video, @RequestParam("photo") String photo, @RequestParam("address") String address, @RequestParam("rtype") String rtype, @RequestParam("caseLocation") String caseLocation, @RequestParam("userLocation") String userLocation, @RequestParam("photoFile") MultipartFile photoFile, @RequestParam("videoFile") MultipartFile videoFile, @RequestParam ("audioFile") MultipartFile audioFile, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("sender") String sender, @RequestParam("thumb") String thumb) { String uploadingDir = System.getProperty("user.dir")+"/CReporterUploads/"; System.out.println(uploadingDir); String result = "error"; ReportModel model = new ReportModel(); model.setAddress(address); model.setCaseLocation(caseLocation); model.setCategory(category); model.setCode(code); model.setAudio(audio); model.setVideo(video); model.setPhoto(photo); model.setDetails(details); model.setRtype(rtype); model.setEmail(email); model.setSender(sender); model.setPhone(phone); model.setThumb(Integer.parseInt(thumb)); model.setUserLocation(userLocation); model.setStatus("In Review"); if(audio.equals("true") ) { doUpload(uploadingDir, audioFile, code); } if(video.equals("true") ) { doUpload(uploadingDir, videoFile, code); } if(photo.equals("true") ) { doUpload(uploadingDir, photoFile, code); } ReportModel md = caseRepo.save(model); /* if(attachment != null && attachment.length > 0) { logger.info("i'm in bro"); uploadM(attachment, code); } */ try {handler.broadcast("broadcast##newCase##"+URLDecoder.decode(new Gson().toJson(md), "utf-8")); }catch(Exception er){} return "saved##"+getSent(sender, email, phone, "cor"); } @PostMapping(path = "/thmbUp") public void vote(@RequestParam("code") String code) { caseRepo.ThumbUp(code); } public String search(String param) { String r =""; try{ r = URLDecoder.decode(new Gson().toJson(caseRepo.search(param)), "utf-8"); }catch(Exception er){} return r; } public String getVoteCount(String code) { return caseRepo.getVoteCount(code)+""; } public boolean doUpload(String uploadingDir, MultipartFile uploadedFile, String code) { System.out.println("about to upload photo"); boolean done = false; File f = new File(uploadingDir +code + "/"); if(!f.exists()) { f.mkdirs(); } try { File file = new File(uploadingDir + "/"+code + "/" +uploadedFile.getOriginalFilename()); uploadedFile.transferTo(file); } catch(IOException er) { er.printStackTrace(); } return done; } @GetMapping(path = "/test") public String test() { try{ String uploadingDir1 = System.getProperty("user.dir") + "/creporter/"; Path path = Paths.get(uploadingDir1); if (!Files.exists(path)) { Files.createDirectory(path); return("Directory created"); } else { return("Directory already exists"); } }catch(Exception er){return er.getMessage();} } @GetMapping("/getFile/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) { // Load file as Resource String a[] = fileName.split("_"); Resource resource = fileStorageService.loadFileAsResource(a[1], a[0]); // Try to determine file's content type String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) { logger.info("Could not determine file type."); } // Fallback to the default content type if type could not be determined if(contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } }
77150fff00cdfa5f400472cb68148bc6bb29fcb8
5bac73779fcd921b4e56e629593bbe7c0c83b049
/src/automatizedocumentation/AutomatizeDocumentation.java
864fb2d890abbdc5518daef8ec47f1729f42f472
[]
no_license
danianepg/automatize-documentation-gitlab
38a285c170ad85b14de7401fa3a676116bb2415a
896fab3bdecb4a1871ee04ce7c601cc2dc764d33
refs/heads/master
2022-11-15T07:01:36.473688
2020-07-14T21:50:41
2020-07-14T21:50:41
279,690,263
3
0
null
null
null
null
UTF-8
Java
false
false
6,819
java
package automatizedocumentation; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.gitlab4j.api.GitLabApi; import org.gitlab4j.api.GitLabApiException; import org.gitlab4j.api.models.CommitAction; import org.gitlab4j.api.models.CommitAction.Action; import org.gitlab4j.api.models.Issue; import org.gitlab4j.api.models.Milestone; import org.gitlab4j.api.models.Note; import org.gitlab4j.api.models.Project; import org.gitlab4j.api.models.RepositoryFile; import automatizedocumentation.utils.DateUtils; /** * Automatize documentation for GitLab * * @author Daniane P. Gomes * */ public class AutomatizeDocumentation { private final String url = "https://gitlab.com/"; private final String token = "PLACE_YOUR_TOKEN_HERE"; private final String projectRepository = "danianepg/automatize-documentation"; private final String changelogFilePath = "README.md"; private final String branch = "master"; private final String commitEmail = "[email protected]"; private final String commitName = "Daniane P. Gomes"; private final GitLabApi gitLabApi; public AutomatizeDocumentation() { this.gitLabApi = new GitLabApi(this.url, this.token); } /** * Finds all issues on a project related to the most recent milestone and write * its descriptions and comments on a file on repository and on the project * Wiki. */ public void generateDocumentation() { try { final Integer projectId = this.getProject(this.gitLabApi).getId(); final Milestone milestone = this.getMostRecentMilestone(this.gitLabApi, projectId); final Integer mostRecentMilestoneId = milestone.getId(); final List<Issue> issues = this.gitLabApi.getIssuesApi().getIssues(projectId); System.out.println("Number of issues found: " + issues.size()); final StringBuilder changelogMessages = new StringBuilder(); final LocalDate from = DateUtils.toLocalDate(milestone.getStartDate()); final LocalDate to = DateUtils.toLocalDate(milestone.getDueDate()); final StringBuilder sprintTitle = new StringBuilder(); sprintTitle.append(milestone.getTitle()); sprintTitle.append(": from "); sprintTitle.append(from.format(DateUtils.getDateFormat())); sprintTitle.append(" to "); sprintTitle.append(to.format(DateUtils.getDateFormat())); changelogMessages.append("## " + sprintTitle.toString() + "\n\n"); this.getChangelogMessagesFromIssues(projectId, mostRecentMilestoneId, issues, changelogMessages); this.createCommit(this.gitLabApi, projectId, changelogMessages); this.createWiki(projectId, changelogMessages, sprintTitle.toString()); } catch (final Exception e) { e.printStackTrace(); } } /** * Create the wiki page. * * @param projectId * @param changelogMessages * @param sprintTitle * @throws GitLabApiException */ private void createWiki(final Integer projectId, final StringBuilder changelogMessages, final String sprintTitle) throws GitLabApiException { System.out.println("Creating wiki"); this.gitLabApi.getWikisApi().createPage(projectId, sprintTitle, changelogMessages.toString()); } /** * Get the content of an issue * * @param projectId * @param mostRecentMilestoneId * @param issues * @param changelogMessages * @throws GitLabApiException */ private void getChangelogMessagesFromIssues(final Integer projectId, final Integer mostRecentMilestoneId, final List<Issue> issues, final StringBuilder changelogMessages) throws GitLabApiException { issues.stream().forEach(i -> { System.out.println("Issue: " + i.getIid()); if (i.getMilestone() != null && i.getMilestone().getId().equals(mostRecentMilestoneId)) { // Get only solution from description final String description = i.getDescription(); changelogMessages.append("Issue " + i.getIid() + ": "); changelogMessages.append(description + "\n\n"); this.printIssuesLabels(i); changelogMessages.append(this.printIssuesNotes(projectId, i)); } }); } /** * Print the labels of an issue * * @param issue */ private void printIssuesLabels(final Issue issue) { System.out.println("Issue labels: "); issue.getLabels().stream().forEach(System.out::println); } /** * * @param projectId * @param i */ private StringBuilder printIssuesNotes(final Integer projectId, final Issue i) { final StringBuilder notes = new StringBuilder(); try { final List<Note> notesLst = this.gitLabApi.getNotesApi().getIssueNotes(projectId, i.getIid()); System.out.println("Number of notes found: " + notesLst.size()); final boolean isClosed = notesLst.stream().filter(n -> n.getBody().contains("closed")).findAny() .isPresent(); if (isClosed) { notesLst.stream().forEach(n -> { System.out.println("\t" + n.getBody()); notes.append("\n* " + n.getBody()); }); } } catch (final GitLabApiException e) { e.printStackTrace(); } return notes; } /** * * @param gitLabApi * @param projectId * @param changelogMessages * @throws GitLabApiException */ private void createCommit(final GitLabApi gitLabApi, final Integer projectId, final StringBuilder changelogMessages) throws GitLabApiException { System.out.println("Creating commit"); final RepositoryFile file = gitLabApi.getRepositoryFileApi().getFile(projectId, this.changelogFilePath, this.branch); final StringBuilder content = new StringBuilder(file.getDecodedContentAsString()); final CommitAction ca = new CommitAction(); ca.setFilePath(this.changelogFilePath); final Action action = Action.UPDATE; ca.setAction(action); content.append("\n\n"); content.append(changelogMessages.toString()); ca.setContent(content.toString()); final List<CommitAction> commitLst = new ArrayList<>(); commitLst.add(ca); gitLabApi.getCommitsApi().createCommit(projectId, this.branch, "My awesome commit", null, this.commitEmail, this.commitName, commitLst); } /** * * @param gitLabApi * @return * @throws GitLabApiException */ private Project getProject(final GitLabApi gitLabApi) throws GitLabApiException { return gitLabApi.getProjectApi().getProject(this.projectRepository); } /** * Get the most recent milestone * * @param gitLabApi * @param projectId * @return * @throws GitLabApiException */ private Milestone getMostRecentMilestone(final GitLabApi gitLabApi, final Integer projectId) throws GitLabApiException { final List<Milestone> milestones = gitLabApi.getMilestonesApi().getMilestones(projectId); System.out.println("Number of milestones found:" + milestones.size()); return milestones.get(0); } public static void main(final String[] args) { final AutomatizeDocumentation generateChangelog = new AutomatizeDocumentation(); generateChangelog.generateDocumentation(); } }
946c4a30b4df9d13f6804c91b7c1896bf1a052a9
b879055f377e3dc23f2af4247623c601d4257742
/aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/transform/v20160408/DescribeClusterServiceConfigForAdminResponseUnmarshaller.java
f03f6f506d94dbf21fe3993f70522cd14f6ee0bf
[ "Apache-2.0" ]
permissive
pp6563/aliyun-openapi-java-sdk
d9b73462e8b2cb55855571d7309564b572e87a71
a9527a5ceda4eaffe32323879d28deb92a333e03
refs/heads/master
2020-07-11T17:55:17.535632
2019-08-27T02:11:25
2019-08-27T02:11:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,999
java
/* * 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.aliyuncs.emr.transform.v20160408; import java.util.ArrayList; import java.util.List; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.ConfigValue; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.ConfigValue.ConfigItemValue; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfo; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfo.EffectWay; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfo.PropertyValueAttributes; import com.aliyuncs.emr.model.v20160408.DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfo.PropertyValueAttributes.ValueEntryInfo; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeClusterServiceConfigForAdminResponseUnmarshaller { public static DescribeClusterServiceConfigForAdminResponse unmarshall(DescribeClusterServiceConfigForAdminResponse describeClusterServiceConfigForAdminResponse, UnmarshallerContext _ctx) { describeClusterServiceConfigForAdminResponse.setRequestId(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.RequestId")); Config config = new Config(); config.setServiceName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ServiceName")); config.setConfigVersion(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigVersion")); config.setApplied(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.Applied")); config.setCreateTime(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.CreateTime")); config.setAuthor(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.Author")); config.setComment(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.Comment")); List<ConfigValue> configValueList = new ArrayList<ConfigValue>(); for (int i = 0; i < _ctx.lengthValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList.Length"); i++) { ConfigValue configValue = new ConfigValue(); configValue.setConfigName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigName")); configValue.setAllowCustom(_ctx.booleanValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].AllowCustom")); List<ConfigItemValue> configItemValueList = new ArrayList<ConfigItemValue>(); for (int j = 0; j < _ctx.lengthValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigItemValueList.Length"); j++) { ConfigItemValue configItemValue = new ConfigItemValue(); configItemValue.setItemName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigItemValueList["+ j +"].ItemName")); configItemValue.setValue(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigItemValueList["+ j +"].Value")); configItemValue.setIsCustom(_ctx.booleanValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigItemValueList["+ j +"].IsCustom")); configItemValue.setDescription(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.ConfigValueList["+ i +"].ConfigItemValueList["+ j +"].Description")); configItemValueList.add(configItemValue); } configValue.setConfigItemValueList(configItemValueList); configValueList.add(configValue); } config.setConfigValueList(configValueList); List<PropertyInfo> propertyInfoList = new ArrayList<PropertyInfo>(); for (int i = 0; i < _ctx.lengthValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList.Length"); i++) { PropertyInfo propertyInfo = new PropertyInfo(); propertyInfo.setName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].Name")); propertyInfo.setValue(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].Value")); propertyInfo.setDescription(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].Description")); propertyInfo.setFileName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].FileName")); propertyInfo.setDisplayName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].DisplayName")); propertyInfo.setServiceName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].ServiceName")); propertyInfo.setComponent(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].Component")); List<String> propertyTypes = new ArrayList<String>(); for (int j = 0; j < _ctx.lengthValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyTypes.Length"); j++) { propertyTypes.add(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyTypes["+ j +"]")); } propertyInfo.setPropertyTypes(propertyTypes); PropertyValueAttributes propertyValueAttributes = new PropertyValueAttributes(); propertyValueAttributes.setType(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Type")); propertyValueAttributes.setMaximum(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Maximum")); propertyValueAttributes.setMimimum(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Mimimum")); propertyValueAttributes.setUnit(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Unit")); propertyValueAttributes.setReadOnly(_ctx.booleanValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.ReadOnly")); propertyValueAttributes.setHidden(_ctx.booleanValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Hidden")); propertyValueAttributes.setIncrememtStep(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.IncrememtStep")); List<ValueEntryInfo> entries = new ArrayList<ValueEntryInfo>(); for (int j = 0; j < _ctx.lengthValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Entries.Length"); j++) { ValueEntryInfo valueEntryInfo = new ValueEntryInfo(); valueEntryInfo.setValue(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Entries["+ j +"].Value")); valueEntryInfo.setLabel(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Entries["+ j +"].Label")); valueEntryInfo.setDescription(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].PropertyValueAttributes.Entries["+ j +"].Description")); entries.add(valueEntryInfo); } propertyValueAttributes.setEntries(entries); propertyInfo.setPropertyValueAttributes(propertyValueAttributes); EffectWay effectWay = new EffectWay(); effectWay.setEffectType(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].EffectWay.EffectType")); effectWay.setInvokeServiceName(_ctx.stringValue("DescribeClusterServiceConfigForAdminResponse.Config.PropertyInfoList["+ i +"].EffectWay.InvokeServiceName")); propertyInfo.setEffectWay(effectWay); propertyInfoList.add(propertyInfo); } config.setPropertyInfoList(propertyInfoList); describeClusterServiceConfigForAdminResponse.setConfig(config); return describeClusterServiceConfigForAdminResponse; } }
216c453e64473423d09fcdb996a7e420a6876572
a9ef8a52f7465482a3d85382397a5ede688e770b
/web/src/main/java/cn/dunn/controller/ChatGroupController.java
5b96dd079cb8badab44cadc0a19ac2efc0b51579
[ "Apache-2.0" ]
permissive
weimeittx/im-server
d81906c19eca6ed0a6eaa52e287996757fc1087e
71dcfc01b421f2678499452bfde584186c301d98
refs/heads/master
2021-01-11T03:35:11.436861
2016-09-30T09:03:31
2016-09-30T09:03:31
68,942,422
0
0
null
null
null
null
UTF-8
Java
false
false
1,613
java
package cn.dunn.controller; import cn.dunn.mode.ChatGroup; import cn.dunn.mode.GroupMember; import cn.dunn.mode.HttpResult; import cn.dunn.mode.User; import cn.dunn.mongo.ChatGroupRepository; import cn.dunn.mongo.GroupMemberRepository; import cn.dunn.util.WebUtil; import org.bson.types.ObjectId; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; @Controller @RequestMapping("/chatGroup") public class ChatGroupController { @Resource private ChatGroupRepository chatGroupRepository; @Resource private GroupMemberRepository groupMemberRepository; @Resource private MongoTemplate mongoTemplate; @RequestMapping("/getChatGroup") @ResponseBody public HttpResult getChatGroup(HttpServletRequest request) { List<ChatGroup> result = mongoTemplate.find(Query.query(Criteria.where("members").elemMatch(Criteria.where("$id").is(new ObjectId(WebUtil.loginUser(request).getId())))), ChatGroup.class); return new HttpResult(result); } @RequestMapping("getChatGroupMembers") @ResponseBody public HttpResult getChatGroupMembers(String id) { ChatGroup chatGroup = chatGroupRepository.findOne(id); return new HttpResult(chatGroup); } }
ab16dac8a543e7e00376dfb27b6f6b7fa600aed4
1eb65f3192a246da6b0bb67a9e7f5f12fded3002
/src/main/java/net/tridentsdk/api/docs/InternalUseOnly.java
e4af85883a20d2d3b4c06248722db165cd8da505
[ "Apache-2.0" ]
permissive
BeYkeRYkt/TridentSDK
ad3c0d077b8026943f3afc0a7bbe2e7fc72dd02d
a1b8c150c9656cf1c17f6f7de67367f98a6bcbfa
refs/heads/master
2021-01-14T10:59:50.568492
2015-01-16T12:28:15
2015-01-16T12:28:15
23,748,881
1
0
null
2015-01-16T12:28:15
2014-09-07T00:25:52
null
UTF-8
Java
false
false
993
java
/* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.api.docs; import java.lang.annotation.Documented; /** * Marks a member of the API or implementation that is designed to be used internally only. * * <p>The behavior of callers on those members marked by this annotation is unspecified and left undocumented.</p> */ @Documented public @interface InternalUseOnly { }
474f8c698708dcc8ca46c28a017f57af0cdd3ed5
565597ad168ef4f419f573da46947db4c1650c77
/app/src/main/java/com/example/sirisha/moviecopy/Pojo.java
d20ca4260b811d1b51d916893ab4ff9932c8c435
[]
no_license
Sirishamiriyala/MovieApp
0b683476ace1a9b35fa7086dbead3184ed276578
69fcd60c2610e414607fedd1574745bf40f922d8
refs/heads/master
2020-03-25T08:24:41.888538
2018-08-05T12:29:39
2018-08-05T12:29:39
143,610,977
0
0
null
null
null
null
UTF-8
Java
false
false
3,219
java
package com.example.sirisha.moviecopy; import com.google.gson.annotations.SerializedName; /** * Created by sirisha on 15-05-2018. */ class Pojo { String poster2,Poster,title,analysis,rel_date,lang,mtitle; String vote_count; String vote_avg; String Ident; String popularity; boolean video,adult; public Pojo(String poster2, String poster, String title, String analysis, String rel_date, String vote_avg, String vote_count,String popularity, boolean video, String ident, boolean adult, String mtitle, String lang) { this.poster2=poster2; this.Poster=poster; this.title=title; this.analysis=analysis; this.rel_date=rel_date; this.lang=lang; this.mtitle=mtitle; this.vote_count=vote_count; this.vote_avg=vote_avg; this.Ident=ident; this.popularity=popularity; this.video=video; this.adult=adult; } public Pojo(String ident, String poster2,String poster, String vote_avg, String analysis, String rel_date, String mtitle) { this.Ident=ident; this.poster2=poster2; this.Poster=poster; this.vote_avg=vote_avg; this.analysis=analysis; this.rel_date=rel_date; this.mtitle=mtitle; } public String getPoster2() { return poster2; } public void setPoster2(String poster2) { this.poster2 = poster2; } public String getPoster() { return Poster; } public void setPoster(String poster) { Poster = poster; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAnalysis() { return analysis; } public void setAnalysis(String analysis) { this.analysis = analysis; } public String getRel_date() { return rel_date; } public void setRel_date(String rel_date) { this.rel_date = rel_date; } public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } public String getMtitle() { return mtitle; } public void setMtitle(String mtitle) { this.mtitle = mtitle; } public String getVote_count() { return vote_count; } public void setVote_count(String vote_count) { this.vote_count = vote_count; } public String getVote_avg() { return vote_avg; } public void setVote_avg(String vote_avg) { this.vote_avg = vote_avg; } public String getIdent() { return Ident; } public void setIdent(String ident) { Ident = ident; } public String getPopularity() { return popularity; } public void setPopularity(String popularity) { this.popularity = popularity; } public boolean isVideo() { return video;} public void setVideo(boolean video) { this.video = video; } public boolean isAdult() { return adult; } public void setAdult(boolean adult) { this.adult = adult; } }
f5d5dcc2859dbb06112eba92b159808db24112ef
3fc13b4068f552b502e04b1c26553592a446d7ac
/api/src/main/java/mb/resource/hierarchical/walk/ResourceWalker.java
7fb70a5b507bdcdab18ed71c8f33720848e48bc9
[ "Apache-2.0" ]
permissive
metaborg/resource
5240772d3b5b3bc58c23dfd233697fdaebc14133
197057fb397b49663bee8e1a0bbcac2452ed4276
refs/heads/master
2022-05-25T05:27:36.397559
2022-05-11T13:41:09
2022-05-11T13:41:09
179,507,450
0
4
Apache-2.0
2021-08-24T09:35:45
2019-04-04T13:53:57
Java
UTF-8
Java
false
false
1,857
java
package mb.resource.hierarchical.walk; import mb.resource.hierarchical.HierarchicalResource; import mb.resource.hierarchical.match.path.PathMatcher; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; @FunctionalInterface public interface ResourceWalker extends Serializable { boolean traverse(HierarchicalResource directory, HierarchicalResource rootDirectory) throws IOException; static TrueResourceWalker ofTrue() { return new TrueResourceWalker(); } static FalseResourceWalker ofFalse() { return new FalseResourceWalker(); } static AllResourceWalker ofAll(ResourceWalker... walkers) { return new AllResourceWalker(walkers); } static AnyResourceWalker ofAny(ResourceWalker... walkers) { return new AnyResourceWalker(walkers); } static NotResourceWalker ofNot(ResourceWalker walkers) { return new NotResourceWalker(walkers); } static PathResourceWalker ofPath(PathMatcher matcher) { return new PathResourceWalker(matcher); } default NotResourceWalker not() { return new NotResourceWalker(this); } default AllResourceWalker and(ResourceWalker... walkers) { final ArrayList<ResourceWalker> allWalkers = new ArrayList<>(walkers.length + 1); allWalkers.add(this); Collections.addAll(allWalkers, walkers); return new AllResourceWalker(allWalkers); } default AnyResourceWalker or(ResourceWalker... walkers) { final ArrayList<ResourceWalker> anyWalkers = new ArrayList<>(walkers.length + 1); anyWalkers.add(this); Collections.addAll(anyWalkers, walkers); return new AnyResourceWalker(anyWalkers); } static PathResourceWalker ofNoHidden() {return ofPath(PathMatcher.ofNoHidden());} }
bea60c2880d148c43f2fa4deef483a8824184581
238c4e1bf0f53cea29e1ca5430af38dccb076632
/app/src/main/java/com/williamgdev/example/googleplaceapi/dto/AddressComponent.java
30df0ee2355b626a06d4bbf89d7150abf9c3b484
[]
no_license
williamgdev/GooglePlaceApi
885e7953c702cc7488784fcf1df38ddeefb52372
7b25be194bfcc1d553397917cb4c0ef990a25f01
refs/heads/master
2020-04-07T06:18:04.466056
2018-03-08T22:35:33
2018-03-08T22:35:33
124,188,223
0
0
null
null
null
null
UTF-8
Java
false
false
897
java
package com.williamgdev.example.googleplaceapi.dto; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class AddressComponent { @SerializedName("long_name") @Expose private String longName; @SerializedName("short_name") @Expose private String shortName; @SerializedName("types") @Expose private List<String> types = null; public String getLongName() { return longName; } public void setLongName(String longName) { this.longName = longName; } public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public List<String> getTypes() { return types; } public void setTypes(List<String> types) { this.types = types; } }
bda94afcf0069e1aa47c2f6c59acecbd9ee5b2d6
7e35e4dbbee5abaa7c28f8aae1b053c5cf1e4157
/TriveraFarm/src/trivera/farm/location/Structure.java
dbbdf923d6a23847078e9fa79d22fcca0550a941
[]
no_license
Razia1630/JAVA
1b8b623bf12fc0eb0612b21b773dc31f827ddb29
2d945e4718cac38fef7ac84ee3814f17cda15483
refs/heads/master
2023-09-05T20:19:46.499673
2018-11-06T22:30:40
2018-11-06T22:30:40
426,099,138
0
0
null
null
null
null
UTF-8
Java
false
false
2,086
java
package trivera.farm.location; import java.util.Arrays; /* * Trivera Farm application - Structure * <p> * This component and its source code representation are copyright protected * and proprietary to The Trivera Group, Inc., Worldwide D/B/A Trivera Technologies * * This component and source code may be used for instructional and * evaluation purposes only. No part of this component or its source code * may be sold, transferred, or publicly posted, nor may it be used in a * commercial or production environment, without the express written consent * of the Trivera Group, Inc. * * Copyright (c) 2018 The Trivera Group, Inc. * http://www.triveratech.com http://www.triveragroup.com * </p> * @author The Trivera Group Tech Team. */ public class Structure extends Location { // constructors public Structure () { super(); } public Structure (String name) { super(name); } public Structure (Location[] loc) { super(loc); } public Structure (String name, Location[] loc) { super(name, loc); } // getState - name plus count of rooms public String getState() { Room[] rooms = this.getRooms(); return getName() + ": contains " + ((rooms == null || rooms.length == 0) ? "NO" : childLocations.length) + " rooms"; } // getFullState - return getState() plus enumerated rooms, if any public String getFullState() { Room[] rooms = this.getRooms(); return getState() + ((rooms == null || rooms.length == 0) ? "." : ":\n\t" + this.getChildState()); } // get rooms public Room[] getRooms() { Room[] rooms = null; for (int i=0, j=childLocations.length; i<j; i++) { if (childLocations[i] == null) { continue; } // see if first if (rooms == null) { rooms = new Room[1]; rooms[0] = (Room) childLocations[i]; } else { rooms = Arrays.copyOf(rooms, (rooms.length + 1)); rooms[rooms.length-1] = (Room) childLocations[i]; } } return rooms; } // determine if Location subtype is valid protected boolean isLocationValid (Location loc) { // a Structure may only contain Rooms return (loc instanceof Room); } }
dab52a908cdd7b610ec3e3017c05b26d6d73fe47
119aa59e3f6ff8ea5b66227d6e1d77be51ee892d
/app/src/main/java/rchat/info/yourday_new/adapters/NamesAdapter.java
76f0bf728828681dea20574864964c553a4f58b5
[]
no_license
IAmProgrammist/YourDayAndroidClient
975ed8dd0f3ed24e37322920478fb858cbecc874
ce539a96ebfc9d091c7bfb74048614f760ad5623
refs/heads/master
2021-01-01T21:35:38.129653
2020-12-08T10:57:23
2020-12-08T10:57:23
239,349,930
0
0
null
null
null
null
UTF-8
Java
false
false
3,247
java
package rchat.info.yourday_new.adapters; import android.content.Context; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import rchat.info.yourday_new.R; import rchat.info.yourday_new.containers.Names; public class NamesAdapter extends BaseAdapter { Names names; Context ctx; public NamesAdapter(Context ctx, Names names) { this.names = names; this.ctx = ctx; } @Override public int getCount() { return 4; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup parent) { if (position == 0) { DisplayMetrics display = ctx.getResources().getDisplayMetrics(); int height = display.heightPixels; View v = View.inflate(ctx, R.layout.empty, null); v.setEnabled(false); v.setClickable(false); v.setPadding(0, 0, 0, ((int) height / 6)); return v; } else if (position == 1) { View va = View.inflate(ctx, R.layout.names_header, null); va.setEnabled(false); va.setClickable(false); return va; } else if (position == 3) { View vs = View.inflate(ctx, R.layout.empty, null); vs.setEnabled(false); vs.setClickable(false); vs.setPadding(0, 0, 0, 100); return vs; } else { view = View.inflate(ctx, R.layout.names_end, null); String boys = ""; for (String a : names.boys) { boys += "• " + a + ";" + "\n"; } try { boys = boys.substring(0, boys.length() - 2); } catch (Exception e) { } String girls = ""; for (String a : names.girls) { girls += "• " + a + ";" + "\n"; } try { girls = girls.substring(0, girls.length() - 2); } catch (Exception e) { } if (boys.equals("")) { view.findViewById(R.id.presentName).setVisibility(View.GONE); view.findViewById(R.id.boys).setVisibility(View.GONE); view.findViewById(R.id.imageView10).setVisibility(View.GONE); ((TextView) view.findViewById(R.id.girls)).setText(girls); } else if (girls.equals("")) { view.findViewById(R.id.presentName2).setVisibility(View.GONE); view.findViewById(R.id.girls).setVisibility(View.GONE); view.findViewById(R.id.imageView10).setVisibility(View.GONE); ((TextView) view.findViewById(R.id.boys)).setText(boys); } else { ((TextView) view.findViewById(R.id.girls)).setText(girls); ((TextView) view.findViewById(R.id.boys)).setText(boys); } return view; } } }
4a2cec2ffb7ec3cb821726f705afe037e4c6241d
c66d06321d8cd77b533444c770e5e00bf7730725
/Engan Actions/src/dao/daoEmpresa.java
62ec6a007a19d584df8dd7f607a21ecd8b2b260d
[]
no_license
franciswagner/Engan
4743bde21059d4648901ed4bce0883efe60bfb06
224d8cda06afaf009d3ba0b867e10af2d5713a28
refs/heads/master
2022-02-12T09:35:33.888043
2016-10-03T18:38:12
2016-10-03T18:38:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,080
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.ArrayList; import java.util.List; import model.Empresa; /** * * @author victor */ public class daoEmpresa { private static List<Empresa> empresas= new ArrayList(); public static void adicionar(Empresa empresa) { empresas.add(empresa); } public static void remover(Empresa empresa) { empresas.remove(empresa); } public static List<Empresa> getEmpresas() { return empresas; } // O motivo de utilizar esse for , é converter o a lista em String ; // porém não funciona jajajajaj. @Override public String toString(){ String retornadado = "vazio"; for(int i=0;this.empresas.get(i) != null;i++){ retornadado = this.empresas.get(i).getNome() + " " +this.empresas.get(i).getCNPJ() +";"; } return retornadado; } }
1e81360a40c00ce38c47d671619f251f359cc4a0
501f10009f6c3f2c2698eb7f51f5eabfd3ff777d
/src/main/java/com/example/OnlineQueueSS/Bootstrap/BootFillialDepartment.java
7aa97c53067423add099f55e41d96ba70eb4a2a1
[]
no_license
Turdubaeverkin/OnlineQueueSS
23ba07fba2faab70b8524656818d9cf394df0085
d8a5235c03c88e8f55d6b96a615297a4fc7202ff
refs/heads/master
2020-05-18T07:58:13.269014
2019-04-30T14:58:45
2019-04-30T14:58:45
184,282,442
0
0
null
null
null
null
UTF-8
Java
false
false
1,238
java
package com.example.OnlineQueueSS.Bootstrap; import com.example.OnlineQueueSS.Entity.Category; import com.example.OnlineQueueSS.Entity.Department; import com.example.OnlineQueueSS.Entity.Fillial; import com.example.OnlineQueueSS.Services.DepartmentService; import com.example.OnlineQueueSS.Services.FillialService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class BootFillialDepartment implements CommandLineRunner { @Autowired private FillialService fillialService; @Autowired private DepartmentService departmentService; @Override public void run(String... args) throws Exception { Category category = new Category("BANKS"); Department department1 = new Department("DemiBank", category); Department department2 = new Department("Optima", category); Department department3 = new Department("PCK", category); Fillial fillial1 = new Fillial("HEAD", "BishkekPark", department1); Fillial fillial2 = new Fillial("HEAD", "Ala Archa", department2); Fillial fillial3 = new Fillial("HEAD", "Asia Mall", department3); } }
fa46d2f9d27704624f80482efce0c33df8064f9f
4ac7a5a92e5b51bcc5904ff78366585eb62945c3
/src/com/controller/FormController.java
5ae3232773889c1576f6c64c47f1d634984eeab1
[]
no_license
lizhaoyang888/mybook-server
7f183e6e173e850d9445e9d3783aea09507baff9
c52bc2a8b65088be73682eaf421d9afc7964bcbc
refs/heads/master
2020-03-24T03:41:57.901278
2018-07-26T11:08:23
2018-07-26T11:08:23
142,429,382
0
0
null
null
null
null
UTF-8
Java
false
false
741
java
package com.controller; import com.bean.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /* * 动态页面跳转控制器 */ @Controller public class FormController { @RequestMapping(value="/{formName}") public String loginForm(@PathVariable String formName){ // 动态跳转页面 return formName; } @RequestMapping(value = "/addUser") public ModelAndView addUser(ModelAndView mv){ User user = new User(); mv.addObject("user",user); mv.setViewName("insertForm"); return mv; } }
6e1fd47183431b42fdd5d4ea394fe32fb14ecb6a
4e27d369f1f83d5ddb45a617460cbf0bed40265c
/src/LAB8/ILight.java
943982ca75e24eca6dcfb59c1089e882ae003764
[]
no_license
wararat12/OOP_2563_362211760011
7e2b81a6a37702461a9f92388e8e473de4d0e4f1
189339825c544eb50c1b23d3c6883eb727f7edbe
refs/heads/master
2023-03-14T10:47:50.422585
2021-03-09T04:16:17
2021-03-09T04:16:17
319,521,363
0
0
null
null
null
null
UTF-8
Java
false
false
176
java
package LAB8; public interface ILight extends extreamILight{ public void turnOn(); public void turnOff(); } interface extreamILight { public void autoHiBeam(); }
6a0eb2d89d791b5a52f14f00e55bfe04fdeefbb4
60239bb1ae7ecc2ce30738db51ad97688c4a669a
/src/main/java/juli/domain/User.java
1d54da1a5b9e23a1681e134a5587f48a80e9eaa7
[]
no_license
pangfei0/MyWeb
f4a62c3685fb177d27041e28dc70367c00e527e5
45e5d9690cff9af944da04d9f69c26b41afadf08
refs/heads/master
2020-09-21T20:27:54.334975
2016-10-03T02:43:52
2016-10-03T02:43:52
67,504,913
0
0
null
null
null
null
UTF-8
Java
false
false
3,683
java
package juli.domain; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity public class User extends BaseEntity { @Column(nullable = false) private String userName; @Column(nullable = false) private String password; @Column private String nick; @Column private String email; @Column private String telephone; //添加公司 @Column private String companyId; //添加公司类型 @Column private String companyType; //添加人员状态 0代表不在用,1代表在用 @Column private String inUse; //添加申请状态 0代表已审核通过,1代表正在申请 @Column private String isDemand; /** * 经度 */ @Column private Double lng; /** * 纬度 */ @Column private Double lat; //代表用户与微信端绑定的唯一标示openid @Column private String openid; @ManyToOne private Organization organization; @ManyToMany(fetch = FetchType.LAZY) private List<Role> roles = new ArrayList<>(); public String getIsDemand() { return isDemand; } public void setIsDemand(String isDemand) { this.isDemand = isDemand; } public String getInUse() { return inUse; } public void setInUse(String inUse) { this.inUse = inUse; } public String getCompanyType() { return companyType; } public void setCompanyType(String companyType) { this.companyType = companyType; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getCompanyId() { return companyId; } public User() { } public User(String userName, String password) { this.userName = userName; this.password = password; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } @Override public int hashCode() { return this.getId().length(); } @Override public boolean equals(Object obj) { if (!(obj instanceof User)) { return false; } if (obj == this) { return true; } return this.getId().equals(((User) obj).getId()); } }
42664f3d37c1757f72e9e92c2e695806069aac2f
03772edd7913eb319d5a9e409c75c303d5378a37
/src/unspc/net/webservicex/package-info.java
012652e4301edb1ce01d6df066f637babd0f29ff
[]
no_license
npgarcia/CloudMSC
e247c98b13c4bc3e69bef8380fe75d8b39f668a5
8cfbbd088b3480e0045b36f1590e0219bae7c225
refs/heads/master
2021-01-22T03:05:37.698512
2015-02-10T01:30:59
2015-02-10T01:30:59
30,568,608
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
/** * The United Nations Standard Products and Services Code® (UNSPSC®) provides an open, global multi-sector standard for efficient, accurate classification of products and services. Search the code on this website to locate commodity codes that can be used by your company. The UNSPSC offers a single global classification system that can be used for: Company-wide visibility of spend analysis,Cost-effective procurement optimization, Full exploitation of electronic commerce capabilities * */ @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.webservicex.net/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package unspc.net.webservicex;
c2989eae8aca6b67de00d130dc4504d0d508580d
380c988212649b021021b90e1fd5c1f548c5bfbb
/src/com/prepare/java8/streams/filter_foreach/DataBase.java
18a09f2f1c5444c6b88a26116046e3a81ac78224
[]
no_license
asksharmadeepak/prepare-java
1342b1f9d5d029db1b403aecd46a11137159bb79
b41ddda9fc6ceae8512a302617f14dff6b5f14c1
refs/heads/master
2023-08-20T16:07:59.442016
2021-10-30T18:22:19
2021-10-30T18:22:19
94,667,758
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
package com.prepare.java8.streams.filter_foreach; import java.util.ArrayList; import java.util.List; //DAO layer public class DataBase { public static List<Employee> getEmployees() { List<Employee> list = new ArrayList<>(); list.add(new Employee(176, "Roshan", "IT", 600000)); list.add(new Employee(388, "Bikash", "CIVIL", 900000)); list.add(new Employee(470, "Bimal", "DEFENCE", 500000)); list.add(new Employee(624, "Sourav", "CORE", 400000)); list.add(new Employee(176, "Prakash", "SOCIAL", 1200000)); return list; } }
[ "“[email protected]”" ]
a8ae794b0b3be1b6de151dbb4afb97112bdfd951
675358377f9ce65223ff625b070c59bfa29844da
/src/com/swingfrog/summer/client/ClientCluster.java
be7574b7b21f75b179b474f880799f27b5bb4127
[]
no_license
langtoutieji/Summer
7e0cc59104b6ac85cd7574f4b44d74c5885d97cf
da718509ad7943a2fa6b4cdada4745de5e0a73ff
refs/heads/master
2020-05-30T21:05:48.557601
2018-12-07T03:21:07
2018-12-07T03:21:07
189,963,862
1
0
null
2019-06-03T08:18:33
2019-06-03T08:18:32
null
UTF-8
Java
false
false
1,260
java
package com.swingfrog.summer.client; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class ClientCluster { private int next = -1; private List<ClientGroup> clientGroupList; private Map<String, ClientGroup> nameToClientGroup; public ClientCluster() { clientGroupList = new ArrayList<>(); nameToClientGroup = new HashMap<>(); } public void addClient(String name, ClientGroup clientGroup) { clientGroupList.add(clientGroup); nameToClientGroup.put(name, clientGroup); } public Client getClientByName(String name) { return nameToClientGroup.get(name).getClientWithNext(); } public Client getClientWithNext() { int size = clientGroupList.size(); if (size > 0) { if (size == 1) { return clientGroupList.get(0).getClientWithNext(); } next ++; next = next % size; return clientGroupList.get(next % size).getClientWithNext(); } return null; } public List<Client> listClients() { List<Client> list = new ArrayList<>(); Iterator<ClientGroup> ite = clientGroupList.iterator(); while (ite.hasNext()) { list.addAll(ite.next().listClients()); } return list; } }
9ff0ffe7876c5d786d6dc75786fc015cb8539fb4
305d851706549dfa30471682d642bb862d5b6af6
/src/main/java/be/vdab/TableServlet.java
3041988831a09113c42c84da7c5032e73b1dcac2
[]
no_license
JonathanPeypops/servlets-ex
8ed04d720f67b775cb59865bd8d562b7c78a396a
4c9d2cae228fb4d4c02322d4eb774c4ea66f8696
refs/heads/master
2020-04-05T23:19:24.664500
2015-06-25T09:25:50
2015-06-25T09:25:50
37,909,152
0
1
null
null
null
null
UTF-8
Java
false
false
1,233
java
package be.vdab; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(urlPatterns = "/multiply") public class TableServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head><title>Multiply</title><link href=\"style.css\"/></head>"); out.println("<meta charset=\"UTF-8\">"); out.println("<body>"); out.println("<h1>Table</h1>"); printTable(out); out.println("</body></html>"); } private void printTable(PrintWriter out){ out.println("<table>"); for(int x=1; x<=25;x++){ out.println("<tr>"); for( int y=1; y<=25;y++){ out.println("<td>" + x * y + "</td>"); } out.println("</tr>"); } out.println("</table>"); } }
27103d4ec1c20d077b21ef97285169647330b8c8
9b08be559eee78c3d564c5c4dc50dbc6c0d8b2e7
/telenet/src/main/java/cn/dyt/service/OrderServiceImpl.java
01425cfe41b924665f296040d635ad5829f8701d
[]
no_license
zhangymeng/telenetwork
7944e95e87b66c7c0fc34a83f2a8fea3b7f6796b
939e7160c6e1810060a2afbe7aec4d88a10e9892
refs/heads/master
2021-04-28T04:45:06.553932
2018-02-25T08:51:54
2018-02-25T08:51:54
122,166,795
0
0
null
null
null
null
UTF-8
Java
false
false
3,825
java
package cn.dyt.service; import java.sql.Timestamp; import java.text.ParseException; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.dyt.dao.CustomerDao; import cn.dyt.dao.OrderDao; import cn.dyt.dao.PreferentialDao; import cn.dyt.po.Customer; import cn.dyt.po.Order; import cn.dyt.po.Preferential; import cn.dyt.util.Tools; import cn.dyt.vo.IndexVo; import cn.dyt.vo.OrderVo; @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; @Autowired private CustomerDao customerDao; @Autowired private PreferentialDao preferentialDao; @Override public List<Order> findAll(IndexVo vo) { List<Order> list = orderDao.findAll(vo); for(Order o:list){ o.setName(o.getCustomer().getName()); if(o.getCustomer().getSex()==1){ o.setSex("男"); }else{ o.setSex("女"); } o.setPhone(o.getCustomer().getPhone()); if(o.getPrefId()!=0){ o.setTitle(o.getPreferential().getTitle()); if(o.getPreferential().getType()==1){ o.setType("抵扣"); }else if(o.getPreferential().getType()==2){ o.setType("折扣"); } o.setPref(o.getPreferential().getPref()); } } return list; } @Override public Map<String, Object> del(IndexVo vo) { boolean result = false; String reason = ""; Order order = orderDao.getById(vo.getId()); Timestamp createDate = new Timestamp(System.currentTimeMillis());//当前时间 if(Timestamp.valueOf(order.getEndDate()+"-01 00:00:00").getTime()>createDate.getTime()){ reason = "订单未结束,请勿删除"; }else{ orderDao.del(vo); result = true; } return Tools.resultMap(result, reason); } public void addOrder(OrderVo vo){ vo.setMoney(vo.getMoney()*vo.getNum()); //减去优惠券 Preferential preferential = preferentialDao.getById(vo.getPrefId()); if(preferential!=null){ if(preferential.getType()==1){ vo.setMoney(vo.getMoney()-preferential.getPref()); }else{ double mon = vo.getMoney()*((double)preferential.getPref()/10); int money = (int) mon; vo.setMoney(money); } } orderDao.add(vo); } @Override public Map<String, Object> add(OrderVo vo) { boolean result = false; String reason = ""; Customer cu = customerDao.getByPhone(vo.getPhone()); if(cu!=null){ vo.setcId(cu.getId()); //查询最后一条订单 Timestamp createDate = new Timestamp(System.currentTimeMillis());//当前时间 vo.setCreateDate(createDate); Order order = orderDao.getNew(cu.getId()); if(order!=null){ if(Timestamp.valueOf(order.getEndDate()+"-01 00:00:00").getTime()>createDate.getTime()){ try { vo.setStartDate(Tools.mathTimetamp(Timestamp.valueOf(order.getEndDate()+"-01 00:00:00"), 1)); vo.setEndDate(Tools.mathTimetamp(vo.getStartDate(),vo.getNum())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ try { vo.setStartDate(Tools.addAndSubtractDaysByCalendarTimetamp(1)); vo.setEndDate(Tools.mathTimetamp(vo.getStartDate(),vo.getNum())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ try { vo.setStartDate(Tools.addAndSubtractDaysByCalendarTimetamp(1)); vo.setEndDate(Tools.mathTimetamp(vo.getStartDate(),vo.getNum())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } addOrder(vo); result = true; }else{ reason = "该客户不存在"; } return Tools.resultMap(result, reason); } }
88bbe7de87e1a7b28661cc7529826aa442aedbf2
538c3f1f0a3709b861eb348a0d0acce9b58a32f2
/ClusterWrapper.java
ecac27857019a470936424b93388ca3bc2bb26b6
[]
no_license
gasstim/CSC365-B-Tree
6238bb64bc03263a2e0c54e70e74d973041e9a08
3084070569390e6d9bbbe003d76277a68ff7a1e4
refs/heads/master
2020-04-13T13:27:33.973384
2018-12-27T01:13:54
2018-12-27T01:13:54
163,231,154
0
1
null
null
null
null
UTF-8
Java
false
false
1,303
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package csc365lab2; import java.io.Serializable; import java.util.ArrayList; /** * * @author tim */ public class ClusterWrapper implements Serializable{ private ArrayList<Point> points; private ArrayList<Cluster> clusters; public ClusterWrapper() { points = new ArrayList<>(); clusters = new ArrayList<>(); } public void addPoints(Point p) { points.add(p); } public int getNumClusters() { return clusters.size(); } public ArrayList<Cluster> getClusters() { return clusters; } public void makeCluster(String centerKey, int in, Review cen) { Cluster cluster = new Cluster(); Point centroid = new Point(centerKey, 350, 350, in); cluster.center = centroid; cluster.cent=cen; clusters.add(cluster); } private ArrayList<Point> getCenters() { ArrayList<Point> centers = new ArrayList<>(); for (Cluster cluster : clusters) { Point point = cluster.center; centers.add(point); } return centers; } }
7fd12f7b8db4e5dc2d934202a07ea3009b504adf
977e4cdedd721264cfeeeb4512aff828c7a69622
/ares.standard/src/test/java/cz/stuchlikova/ares/application/connector/AresRzpClientTestImpl.java
2f8cf50890de333770626c8f9c3c3670e93057c7
[]
no_license
PavlaSt/ares.standard
ed5b177ca7ca71173b7fa7490cf939f8c3e050fb
1d3a50fa4397a490cfb4414f7bd94d5dcac1a45e
refs/heads/main
2023-05-08T02:28:09.921215
2021-05-27T10:03:07
2021-05-27T10:03:07
346,669,475
0
0
null
null
null
null
UTF-8
Java
false
false
906
java
package cz.stuchlikova.ares.application.connector; import cz.stuchlikova.ares.application.stub.rzp.AresDotazy; import cz.stuchlikova.ares.application.stub.rzp.AresOdpovedi; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import javax.xml.bind.JAXB; import java.io.InputStream; @Component @Primary public class AresRzpClientTestImpl extends ClientBaseTest<AresOdpovedi> implements AresClient<AresOdpovedi, AresDotazy> { @Override public AresOdpovedi getAresResponse(AresDotazy dotazy) { String ico = dotazy.getDotaz().get(0).getICO(); String url = "src/test/resources/getDtoRzpResponseByIco/ico=" + ico + ".xml"; return openXmlFileUnmarshalToObject(url); } @Override AresOdpovedi unmarshalStringToObject(InputStream xmlResult) { return JAXB.unmarshal(xmlResult, AresOdpovedi.class); } }
0fe62e6b2eaf5231b3be4ff536779f7494436c26
0bd31201e543a28e5b6d55db3441f5c65173b08a
/client/src/main/java/ru/alex/st/messanger/stub/TCPServerSelector.java
d14c2e987bd0e059b0841ad539fd4e6eab14c666
[]
no_license
Alexst1989/Socket-train
fa161f855043f114209ef6e31c6ea44762d92bf2
ae0838fea8ce93d87b05c15320af89a97aa34b83
refs/heads/master
2020-03-07T20:48:48.793620
2019-09-07T07:33:54
2019-09-07T07:33:54
127,707,508
0
0
null
null
null
null
UTF-8
Java
false
false
2,800
java
package ru.alex.st.messanger.stub; import ru.alex.st.messanger.example.EchoSelectorProtocol; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.Iterator; public class TCPServerSelector { private static final int BUFSIZE = 256; // Buffer size (bytes) private static final int TIMEOUT = 3000; // Wait timeout (milliseconds) public static void main( String[] args ) throws IOException { args = new String[]{ "9887" }; if ( args.length < 1 ) { // Test for correct # of args throw new IllegalArgumentException( "Parameter(s): <Port> ..." ); } // Create a selector to multiplex listening sockets and connections Selector selector = Selector.open(); // Create listening socket channel for each port and register selector for ( String arg : args ) { ServerSocketChannel listnChannel = ServerSocketChannel.open(); listnChannel.socket().bind( new InetSocketAddress( Integer.parseInt( arg ) ) ); listnChannel.configureBlocking( false ); // must be nonblocking to register // Register selector with channel. The returned key is ignored listnChannel.register( selector, SelectionKey.OP_ACCEPT ); } // Create a handler that will implement the protocol EchoSelectorProtocol protocol = new EchoSelectorProtocol( BUFSIZE ); while ( true ) { // Run forever, processing available I/O operations // Wait for some channel to be ready (or timeout) if ( selector.select( TIMEOUT ) == 0 ) { // returns # of ready chans System.out.print( "." ); continue; } // Get iterator on set of keys with I/O to process Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while ( keyIter.hasNext() ) { SelectionKey key = keyIter.next(); // Key is bit mask // Server socket channel has pending connection requests? if ( key.isAcceptable() ) { protocol.handleAccept( key ); } // Client socket channel has pending data? if ( key.isReadable() ) { protocol.handleRead( key ); } // Client socket channel is available for writing and // key is valid (i.e., channel not closed)? if ( key.isValid() && key.isWritable() ) { protocol.handleWrite( key ); } keyIter.remove(); // remove from set of selected keys } } } }
74f9edf848aa3abc4cfd38d979a6077c45d83d39
0b414778ce42c2cfe4f212eaf5a185ac08569279
/src/CountAndSay_38.java
a24e0f7276497fc3f42db95f539c786e396156f3
[]
no_license
xiazhixuanc/LeetCode
25416f361a83a4a20d5de17284617cef47f23747
983d2222e8c1252a98f477f585293af314bbe65f
refs/heads/master
2021-08-30T18:32:20.813604
2017-12-19T01:17:38
2017-12-19T01:17:38
114,699,871
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
public class CountAndSay_38 { public String countAndSay(int n){ if(n <= 0){ return null; } String s = "1"; StringBuilder sb = new StringBuilder(); sb.append("1"); int count = 0; for(int i = 1; i < n; i++){ s = sb.toString(); sb.setLength(0); count = 1; char c = s.charAt(0); for(int j = 1; j < s.length(); j++){ if(s.charAt(j) == c){ count++; } else{ sb.append(count); sb.append(c); c = s.charAt(j); count = 1; } } sb.append(count); sb.append(c); } return sb.toString(); } }
06e7b7a7d7d0081016dfa4158bd8ef4b620fab79
56ed96236b8efed3a9f26df1a07d938792b095d5
/app/src/main/java/com/spacECE/spaceceedu/VideoLibrary/VideoLibrary_Free.java
8112b127237ee2d850d2b89ce872f299d059bd9f
[]
no_license
sachin-mohite/SpacECEedu_Android
4d91fb116fb39c6ca6f4c2d60d841939d8726f3a
ef632d3076f4749bd1ff76a003d5a1182d46a4f2
refs/heads/master
2023-07-15T22:41:38.432816
2021-08-30T11:58:29
2021-08-30T11:58:29
401,426,977
0
1
null
null
null
null
UTF-8
Java
false
false
5,166
java
package com.spacECE.spaceceedu.VideoLibrary; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.spacECE.spaceceedu.R; import java.util.ArrayList; public class VideoLibrary_Free extends Fragment { private ArrayList<Topic> list= new ArrayList<>(); private ArrayList<Topic> rlist= new ArrayList<>(); private TextView tv_recentlyViewed; private RecyclerView recyclerView; private RecyclerView recentRecyclerView; VideoLibrary_RecyclerViewAdapter_Free.RecyclerViewClickListener listener; private VideoLibrary_RecyclerViewAdapter_recent.RecyclerViewClickListener rListener; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v= inflater.inflate(R.layout.fragment_video_library__free, container, false); list = new ArrayList<>(VideoLibrary_Activity.freeTopicList); rlist = new ArrayList<>(VideoLibrary_Activity.recentTopicList); // Bundle extras = getIntent().getExtras(); // if(extras!= null){account_id=extras.getString("account_id");} tv_recentlyViewed=v.findViewById(R.id.VL_Free_TextView_recentlyViewed); recyclerView= v.findViewById(R.id.VL_free_RecycleView); recentRecyclerView=v.findViewById(R.id.VL_recent_RecyclerView); setAdapter(list); if(!VideoLibrary_Activity.recentTopicList.isEmpty()){ setRAdapter(rlist); tv_recentlyViewed.setVisibility(View.VISIBLE); } return v; } private void setRAdapter(ArrayList<Topic> topicList) { Log.i("SetAdapter:","Working"); setOnRClickListener(); VideoLibrary_RecyclerViewAdapter_recent adapter = new VideoLibrary_RecyclerViewAdapter_recent(topicList,rListener); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getContext(),LinearLayoutManager.HORIZONTAL,false); recentRecyclerView.setLayoutManager(layoutManager); recentRecyclerView.setItemAnimator(new DefaultItemAnimator()); recentRecyclerView.setAdapter(adapter); Log.i("Adapter", "Executed"); } private void setOnRClickListener() { rListener = new VideoLibrary_RecyclerViewAdapter_recent.RecyclerViewClickListener() { @Override public void onClick(View v, int position) { Intent intent = new Intent(getContext(), TopicActivity.class); intent.putExtra("topic_name", rlist.get(position).getTitle()); intent.putExtra("v_url", rlist.get(position).getV_URL()); intent.putExtra("discrp", rlist.get(position).getDesc()); intent.putExtra("status",rlist.get(position).getStatus()); intent.putExtra("v_id",rlist.get(position).getV_id()); intent.putExtra("comments", rlist.get(position).getCntcomment()); intent.putExtra("views", rlist.get(position).getViews()); intent.putExtra("like_count", rlist.get(position).getCntlike()); intent.putExtra("dislike_count", rlist.get(position).getCntdislike()); startActivity(intent); } }; } private void setAdapter(ArrayList<Topic> myList) { Log.i("SetAdapter:","Working"); setOnClickListener(); VideoLibrary_RecyclerViewAdapter_Free adapter = new VideoLibrary_RecyclerViewAdapter_Free(myList,listener); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); Log.i("Adapter", "Executed"); } private void setOnClickListener() { listener = new VideoLibrary_RecyclerViewAdapter_Free.RecyclerViewClickListener() { @Override public void onClick(View v, int position) { Intent intent = new Intent(getContext(), TopicActivity.class); intent.putExtra("topic_name", list.get(position).getTitle()); intent.putExtra("v_url", list.get(position).getV_URL()); intent.putExtra("discrp", list.get(position).getDesc()); intent.putExtra("status",list.get(position).getStatus()); intent.putExtra("v_id",list.get(position).getV_id()); intent.putExtra("comments", list.get(position).getCntcomment()); intent.putExtra("views", list.get(position).getViews()); intent.putExtra("like_count", list.get(position).getCntlike()); intent.putExtra("dislike_count", list.get(position).getCntdislike()); startActivity(intent); } }; } }
f2f519651464966837efd1699876980a3a2905e8
c1539b5c1f5874dbb23d3cf5a93c5c2b6cc929e1
/app/src/main/java/com/example/shivang/contacts/MainActivity.java
d6b74347007bb7bc565c3a36a5d18ac8c3d68d10
[]
no_license
shivangchopra11/Contacts_App
f3c80cad0b601fafae21f9310429eb324d8952c4
34f22787df89c21d0bad5074e581664cbb7a2359
refs/heads/master
2020-12-02T16:12:56.987192
2017-07-10T00:36:38
2017-07-10T00:36:38
96,519,164
1
0
null
null
null
null
UTF-8
Java
false
false
8,407
java
package com.example.shivang.contacts; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.provider.SyncStateContract; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView listView; ArrayList<Contact> contactList; CustomArrayAdapter contactAdapter; //static int ctr = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); listView = (ListView)findViewById(R.id.listview); contactList = new ArrayList<>(); // for(int i=0;i<5;i++) { // Contact c = new Contact(); // c.name = "SHIVANG"; // c.category = "WORK"; // c.number = "7838826129"; // contactList.add(c); // } listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view,final int position, long id) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("DELETE"); builder.setMessage("Are you sure you want to delete ??"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i("TAG", "Removing position " + position); // contactList.remove(position); // contactAdapter.notifyDataSetChanged(); String name = contactList.get(position).name; ContactOpenHelper contactOpenHelper = ContactOpenHelper.getOpenHelperInstance(MainActivity.this); SQLiteDatabase database = contactOpenHelper.getWritableDatabase(); String whereClause = ContactOpenHelper.CONTACT_NAME + "=?"; String[] whereArgs = new String[] {name}; database.delete(contactOpenHelper.CONTACT_TABLE_NAME, whereClause, whereArgs); updateExpenseList(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); return true; } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(); i.setClass(MainActivity.this,Edit_Contact.class); i.putExtra("name",contactList.get(position).name); i.putExtra("mail",contactList.get(position).email); i.putExtra("number",contactList.get(position).number); i.putExtra("category",contactList.get(position).category); i.putExtra("id",contactList.get(position).id); i.putExtra("pos",position); Log.i("TAG","Sent numbers" + contactList.get(position).name + contactList.get(position).id); MainActivity.this.startActivityForResult(i,1); //MainActivity.this.startActivity(i); } }); contactAdapter = new CustomArrayAdapter(this,contactList); listView.setAdapter(contactAdapter); updateExpenseList(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(); i.setClass(MainActivity.this,Add_Contact.class); MainActivity.this.startActivityForResult(i,2); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent i = new Intent(this,SettingsActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode==1) { if (resultCode == RESULT_OK) { //startActivity(new Intent(data)); // int pos = data.getIntExtra("pos",0); // // Contact c1 = new Contact(); // c1.name = data.getStringExtra("name"); // c1.email = data.getStringExtra("mail"); // c1.number = data.getStringExtra("number"); // c1.category = data.getStringExtra("category"); // // contactList.set(pos,c1); // contactAdapter.notifyDataSetChanged(); updateExpenseList(); } } if(requestCode==2) { if (resultCode == RESULT_OK) { //startActivity(new Intent(data)); // Contact c1 = new Contact(); // c1.name = data.getStringExtra("name"); // c1.email = data.getStringExtra("mail"); // c1.number = data.getStringExtra("number"); // c1.category = data.getStringExtra("category"); // Log.i("TAG1", "Editing position " + c1.name); // contactList.add(c1); // contactAdapter.notifyDataSetChanged(); updateExpenseList(); } } } private void updateExpenseList() { ContactOpenHelper contactOpenHelper = ContactOpenHelper.getOpenHelperInstance(this); contactList.clear(); SQLiteDatabase database = contactOpenHelper.getReadableDatabase(); Cursor cursor = database.query(ContactOpenHelper.CONTACT_TABLE_NAME,null,null,null,null, null, null); Log.i("TAG1", "Found Querry "); if(cursor != null) { while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex(contactOpenHelper.CONTACT_NAME)); String number = cursor.getString(cursor.getColumnIndex(contactOpenHelper.CONTACT_NUMBER)); int id = cursor.getInt(cursor.getColumnIndex(contactOpenHelper.CONTACT_ID)); String email = cursor.getString(cursor.getColumnIndex(contactOpenHelper.CONTACT_EMAIL)); String category = cursor.getString(cursor.getColumnIndex(contactOpenHelper.CONTACT_CATEGORY)); Log.i("TAG1", "Found Querry " + name + number + email + id); Contact e = new Contact(); e.name = name; e.number = number; e.email = email; e.category = category; e.id =id; contactList.add(e); } contactAdapter.notifyDataSetChanged(); } } }
fee41ffe1caba6b315ace474aed3fa2ab65bdf96
fedb78a8f3505182cc42eab982834fb58c8cb7e3
/JuegoWarlux/src/main/java/com/warlux/domain/objetos/items/ITunelMeta.java
fa9a82a6c393e8d9198eb575536e3f19271d12c0
[]
no_license
warlux/repWarlux
c9fe01b09d50d37db8ace9294225236829bbe7b2
2ce8ef70f53cdfb6664c53c12b62a53d042f35c1
refs/heads/master
2016-09-05T10:29:28.577838
2012-12-27T20:37:31
2012-12-27T20:37:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
700
java
package com.warlux.domain.objetos.items; import javax.swing.ImageIcon; import com.warlux.domain.objetos.ItemEfecto; public class ITunelMeta extends Item { public ITunelMeta() { super(); imagen = new ImageIcon("src/main/resources/modeloObjetos/iTunelMeta.png"); permanente = true; nombre = "tunelMeta"; efecto = new ItemEfecto(); efecto.setRestringirAcceso(true); } @Override public void cambiarImagenActivada() { imagen = new ImageIcon( "src/main/resources/modeloObjetos/iTunelMeta.png"); } @Override public void cambiarImagenCondicional() { imagen = new ImageIcon( "src/main/resources/modeloObjetos/iTunelMetaAbierto.png"); } }
[ "Warlux@Leviathan" ]
Warlux@Leviathan