blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
06169ac9e661b16fef9485e5417706d0587e1f3e
fc933056c6a3ba3bd759fc71258d94db12419134
/src/main/java/com/elmakers/mine/bukkit/plugins/spells/builtin/InvincibleSpell.java
925278525a9a83b378002a3deb761be26137f1b6
[]
no_license
elBukkit/Spells
d98200839fed94bbe96ecf126dc53b4488ae893b
7bbdebf91ec6a94ecaf4bb74ad29b83035ff5367
refs/heads/master
2020-05-18T10:49:28.057838
2011-07-10T16:14:59
2011-07-10T16:14:59
1,782,030
0
0
null
null
null
null
UTF-8
Java
false
false
1,695
java
package com.elmakers.mine.bukkit.plugins.spells.builtin; import org.bukkit.Material; import com.elmakers.mine.bukkit.plugins.spells.Spell; public class InvincibleSpell extends Spell { public InvincibleSpell() { addVariant("ironskin", Material.IRON_CHESTPLATE, getCategory(), "Protect you from damage", "99"); addVariant("leatherskin", Material.LEATHER_CHESTPLATE, getCategory(), "Protect you from some damage", "50"); } @Override public boolean onCast(String[] parameters) { int amount = 100; if (parameters.length > 0) { try { amount = Integer.parseInt(parameters[0]); } catch (NumberFormatException ex) { amount = 100; } } Float currentAmount = spells.invincibleAmount(player); if (currentAmount != null) { sendMessage(player, "You feel ... normal."); spells.setInvincible(player, 0); } else { spells.setInvincible(player, (float)amount / 100); if (amount >= 100) { sendMessage(player, "You feel invincible!"); } else { sendMessage(player, "You feel strong!"); } } return true; } @Override public String getName() { return "invincible"; } @Override public String getCategory() { return "help"; } @Override public String getDescription() { return "Makes you impervious to damage"; } @Override public Material getMaterial() { return Material.GOLDEN_APPLE; } }
[ "nathan@spookycool.com" ]
nathan@spookycool.com
845d51f63f6fcb650018cdb99b8eeafb9f83c0a2
0ba544b316d64f2dda3e3dc25d5e652293fb52d7
/fir/app/fengfei/ucm/service/cmd/PingCommand.java
02075677491055d28e4bc804d5dd081709e9e388
[]
no_license
wing1000/test_sp
47c28340aef138dc08dad3ecdbd091675a498f16
2e2956c58f6a2a8d48a5734ace7295fd32d28859
refs/heads/master
2016-09-15T17:53:39.658653
2014-02-13T10:04:46
2014-02-13T10:04:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
217
java
package fengfei.ucm.service.cmd; import java.io.Writer; public class PingCommand implements Command { @Override public void execute(Writer writer) throws Exception { writer.write("pong"); } }
[ "wttloon@126.com" ]
wttloon@126.com
cd894e0bb0f3bcb31a69f3b3c4f94bd2102f536f
524de9066b9b7a62e87d24300db1f54030142767
/app/src/main/java/com/example/horo/model/service/pojo/daily/Pisces.java
b8a3e4b39ed278f0fbba356bea1a4a51c978b7d5
[]
no_license
max-android/Horo
f486fe241bae82352e24acff295b7a30667858e6
866807b311bad0212afbaebb80eba829fc6d3245
refs/heads/master
2021-08-07T06:43:07.791459
2017-11-07T18:12:15
2017-11-07T18:12:15
109,879,182
0
0
null
null
null
null
UTF-8
Java
false
false
1,215
java
package com.example.horo.model.service.pojo.daily; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; /** * Created by Максим on 19.10.2017. */ @Root(name = "pisces") public class Pisces { private String yesterday; private String today; private String tomorrow; private String tomorrow02; @Element(name = "yesterday") public String getYesterday() { return yesterday; } @Element(name = "today") public String getToday() { return today; } @Element(name = "tomorrow") public String getTomorrow() { return tomorrow; } @Element(name = "tomorrow02") public String getTomorrow02() { return tomorrow02; } @Element(name = "yesterday") public void setYesterday(String yesterday) { this.yesterday = yesterday; } @Element(name = "today") public void setToday(String today) { this.today = today; } @Element(name = "tomorrow") public void setTomorrow(String tomorrow) { this.tomorrow = tomorrow; } @Element(name = "tomorrow02") public void setTomorrow02(String tomorrow02) { this.tomorrow02 = tomorrow02; } }
[ "preferenceLEAD111@yandex.ru" ]
preferenceLEAD111@yandex.ru
70083da26ba0bcf6705967ee1d8de37e073a4855
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipsejdt_cluster/22610/src_1.java
0afb506ae7fcdcd5a72f27701b46f37a84035383
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
46,795
java
/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core.search; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jdt.core.*; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.core.search.*; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.compiler.ast.*; import org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.eclipse.jdt.internal.compiler.env.AccessRuleSet; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.*; import org.eclipse.jdt.internal.compiler.parser.Parser; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.core.*; import org.eclipse.jdt.internal.core.search.indexing.*; import org.eclipse.jdt.internal.core.search.matching.*; import org.eclipse.jdt.internal.core.util.Messages; import org.eclipse.jdt.internal.core.util.Util; /** * Search basic engine. Public search engine (see {@link org.eclipse.jdt.core.search.SearchEngine} * for detailed comment), now uses basic engine functionalities. * Note that serch basic engine does not implement deprecated functionalities... */ public class BasicSearchEngine { /* * A default parser to parse non-reconciled working copies */ private Parser parser; private CompilerOptions compilerOptions; /* * A list of working copies that take precedence over their original * compilation units. */ private ICompilationUnit[] workingCopies; /* * A working copy owner whose working copies will take precedent over * their original compilation units. */ private WorkingCopyOwner workingCopyOwner; /** * For tracing purpose. */ public static boolean VERBOSE = false; /* * Creates a new search basic engine. */ public BasicSearchEngine() { // will use working copies of PRIMARY owner } /** * @see SearchEngine#SearchEngine(ICompilationUnit[]) for detailed comment. */ public BasicSearchEngine(ICompilationUnit[] workingCopies) { this.workingCopies = workingCopies; } char convertTypeKind(int typeDeclarationKind) { switch(typeDeclarationKind) { case TypeDeclaration.CLASS_DECL : return IIndexConstants.CLASS_SUFFIX; case TypeDeclaration.INTERFACE_DECL : return IIndexConstants.INTERFACE_SUFFIX; case TypeDeclaration.ENUM_DECL : return IIndexConstants.ENUM_SUFFIX; case TypeDeclaration.ANNOTATION_TYPE_DECL : return IIndexConstants.ANNOTATION_TYPE_SUFFIX; default : return IIndexConstants.TYPE_SUFFIX; } } /** * @see SearchEngine#SearchEngine(WorkingCopyOwner) for detailed comment. */ public BasicSearchEngine(WorkingCopyOwner workingCopyOwner) { this.workingCopyOwner = workingCopyOwner; } /** * @see SearchEngine#createHierarchyScope(IType) for detailed comment. */ public static IJavaSearchScope createHierarchyScope(IType type) throws JavaModelException { return createHierarchyScope(type, DefaultWorkingCopyOwner.PRIMARY); } /** * @see SearchEngine#createHierarchyScope(IType,WorkingCopyOwner) for detailed comment. */ public static IJavaSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaModelException { return new HierarchyScope(type, owner); } /** * @see SearchEngine#createJavaSearchScope(IJavaElement[]) for detailed comment. */ public static IJavaSearchScope createJavaSearchScope(IJavaElement[] elements) { return createJavaSearchScope(elements, true); } /** * @see SearchEngine#createJavaSearchScope(IJavaElement[], boolean) for detailed comment. */ public static IJavaSearchScope createJavaSearchScope(IJavaElement[] elements, boolean includeReferencedProjects) { int includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES; if (includeReferencedProjects) { includeMask |= IJavaSearchScope.REFERENCED_PROJECTS; } return createJavaSearchScope(elements, includeMask); } /** * @see SearchEngine#createJavaSearchScope(IJavaElement[], int) for detailed comment. */ public static IJavaSearchScope createJavaSearchScope(IJavaElement[] elements, int includeMask) { JavaSearchScope scope = new JavaSearchScope(); HashSet visitedProjects = new HashSet(2); for (int i = 0, length = elements.length; i < length; i++) { IJavaElement element = elements[i]; if (element != null) { try { if (element instanceof JavaProject) { scope.add((JavaProject)element, includeMask, visitedProjects); } else { scope.add(element); } } catch (JavaModelException e) { // ignore } } } return scope; } /** * @see SearchEngine#createWorkspaceScope() for detailed comment. */ public static IJavaSearchScope createWorkspaceScope() { return JavaModelManager.getJavaModelManager().getWorkspaceScope(); } /** * Searches for matches to a given query. Search queries can be created using helper * methods (from a String pattern or a Java element) and encapsulate the description of what is * being searched (for example, search method declarations in a case sensitive way). * * @param scope the search result has to be limited to the given scope * @param requestor a callback object to which each match is reported */ void findMatches(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); /* initialize progress monitor */ if (monitor != null) monitor.beginTask(Messages.engine_searching, 100); if (VERBOSE) { Util.verbose("Searching for pattern: " + pattern.toString()); //$NON-NLS-1$ Util.verbose(scope.toString()); } if (participants == null) { if (VERBOSE) Util.verbose("No participants => do nothing!"); //$NON-NLS-1$ return; } IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); try { requestor.beginReporting(); for (int i = 0, l = participants.length; i < l; i++) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); SearchParticipant participant = participants[i]; SubProgressMonitor subMonitor= monitor==null ? null : new SubProgressMonitor(monitor, 1000); if (subMonitor != null) subMonitor.beginTask("", 1000); //$NON-NLS-1$ try { if (subMonitor != null) subMonitor.subTask(Messages.bind(Messages.engine_searching_indexing, new String[] {participant.getDescription()})); participant.beginSearching(); requestor.enterParticipant(participant); PathCollector pathCollector = new PathCollector(); indexManager.performConcurrentJob( new PatternSearchJob(pattern, participant, scope, pathCollector), IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, subMonitor); if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); // locate index matches if any (note that all search matches could have been issued during index querying) if (subMonitor != null) subMonitor.subTask(Messages.bind(Messages.engine_searching_matching, new String[] {participant.getDescription()})); String[] indexMatchPaths = pathCollector.getPaths(); if (indexMatchPaths != null) { pathCollector = null; // release int indexMatchLength = indexMatchPaths.length; SearchDocument[] indexMatches = new SearchDocument[indexMatchLength]; for (int j = 0; j < indexMatchLength; j++) { indexMatches[j] = participant.getDocument(indexMatchPaths[j]); } SearchDocument[] matches = MatchLocator.addWorkingCopies(pattern, indexMatches, getWorkingCopies(), participant); participant.locateMatches(matches, pattern, scope, requestor, subMonitor); } } finally { requestor.exitParticipant(participant); participant.doneSearching(); } } } finally { requestor.endReporting(); if (monitor != null) monitor.done(); } } /** * Returns a new default Java search participant. * * @return a new default Java search participant * @since 3.0 */ public static SearchParticipant getDefaultSearchParticipant() { return new JavaSearchParticipant(); } /** * @param matchRule */ public static String getMatchRuleString(final int matchRule) { if (matchRule == 0) { return "R_EXACT_MATCH"; //$NON-NLS-1$ } StringBuffer buffer = new StringBuffer(); for (int i=1; i<=8; i++) { int bit = matchRule & (1<<(i-1)); if (bit != 0 && buffer.length()>0) buffer.append(" | "); //$NON-NLS-1$ switch (bit) { case SearchPattern.R_PREFIX_MATCH: buffer.append("R_PREFIX_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_CASE_SENSITIVE: buffer.append("R_CASE_SENSITIVE"); //$NON-NLS-1$ break; case SearchPattern.R_EQUIVALENT_MATCH: buffer.append("R_EQUIVALENT_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_ERASURE_MATCH: buffer.append("R_ERASURE_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_FULL_MATCH: buffer.append("R_FULL_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_PATTERN_MATCH: buffer.append("R_PATTERN_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_REGEXP_MATCH: buffer.append("R_REGEXP_MATCH"); //$NON-NLS-1$ break; case SearchPattern.R_CAMELCASE_MATCH: buffer.append("R_CAMELCASE_MATCH"); //$NON-NLS-1$ break; } } return buffer.toString(); } /** * Return kind of search corresponding to given value. * * @param searchFor */ public static String getSearchForString(final int searchFor) { switch (searchFor) { case IJavaSearchConstants.TYPE: return ("TYPE"); //$NON-NLS-1$ case IJavaSearchConstants.METHOD: return ("METHOD"); //$NON-NLS-1$ case IJavaSearchConstants.PACKAGE: return ("PACKAGE"); //$NON-NLS-1$ case IJavaSearchConstants.CONSTRUCTOR: return ("CONSTRUCTOR"); //$NON-NLS-1$ case IJavaSearchConstants.FIELD: return ("FIELD"); //$NON-NLS-1$ case IJavaSearchConstants.CLASS: return ("CLASS"); //$NON-NLS-1$ case IJavaSearchConstants.INTERFACE: return ("INTERFACE"); //$NON-NLS-1$ case IJavaSearchConstants.ENUM: return ("ENUM"); //$NON-NLS-1$ case IJavaSearchConstants.ANNOTATION_TYPE: return ("ANNOTATION_TYPE"); //$NON-NLS-1$ case IJavaSearchConstants.CLASS_AND_ENUM: return ("CLASS_AND_ENUM"); //$NON-NLS-1$ case IJavaSearchConstants.CLASS_AND_INTERFACE: return ("CLASS_AND_INTERFACE"); //$NON-NLS-1$ } return "UNKNOWN"; //$NON-NLS-1$ } private Parser getParser() { if (this.parser == null) { this.compilerOptions = new CompilerOptions(JavaCore.getOptions()); ProblemReporter problemReporter = new ProblemReporter( DefaultErrorHandlingPolicies.proceedWithAllProblems(), this.compilerOptions, new DefaultProblemFactory()); this.parser = new Parser(problemReporter, true); } return this.parser; } /* * Returns the underlying resource of the given element. */ private IResource getResource(IJavaElement element) { if (element instanceof IMember) { ICompilationUnit cu = ((IMember)element).getCompilationUnit(); if (cu != null) { return cu.getResource(); } } return element.getResource(); } /* * Returns the list of working copies used by this search engine. * Returns null if none. */ private ICompilationUnit[] getWorkingCopies() { ICompilationUnit[] copies; if (this.workingCopies != null) { if (this.workingCopyOwner == null) { copies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false/*don't add primary WCs a second time*/); if (copies == null) { copies = this.workingCopies; } else { HashMap pathToCUs = new HashMap(); for (int i = 0, length = copies.length; i < length; i++) { ICompilationUnit unit = copies[i]; pathToCUs.put(unit.getPath(), unit); } for (int i = 0, length = this.workingCopies.length; i < length; i++) { ICompilationUnit unit = this.workingCopies[i]; pathToCUs.put(unit.getPath(), unit); } int length = pathToCUs.size(); copies = new ICompilationUnit[length]; pathToCUs.values().toArray(copies); } } else { copies = this.workingCopies; } } else if (this.workingCopyOwner != null) { copies = JavaModelManager.getJavaModelManager().getWorkingCopies(this.workingCopyOwner, true/*add primary WCs*/); } else { copies = JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false/*don't add primary WCs a second time*/); } if (copies == null) return null; // filter out primary working copies that are saved ICompilationUnit[] result = null; int length = copies.length; int index = 0; for (int i = 0; i < length; i++) { CompilationUnit copy = (CompilationUnit)copies[i]; try { if (!copy.isPrimary() || copy.hasUnsavedChanges() || copy.hasResourceChanged()) { if (result == null) { result = new ICompilationUnit[length]; } result[index++] = copy; } } catch (JavaModelException e) { // copy doesn't exist: ignore } } if (index != length && result != null) { System.arraycopy(result, 0, result = new ICompilationUnit[index], 0, index); } return result; } /* * Returns the list of working copies used to do the search on the given Java element. */ private ICompilationUnit[] getWorkingCopies(IJavaElement element) { if (element instanceof IMember) { ICompilationUnit cu = ((IMember)element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { ICompilationUnit[] copies = getWorkingCopies(); int length = copies == null ? 0 : copies.length; if (length > 0) { ICompilationUnit[] newWorkingCopies = new ICompilationUnit[length+1]; System.arraycopy(copies, 0, newWorkingCopies, 0, length); newWorkingCopies[length] = cu; return newWorkingCopies; } return new ICompilationUnit[] {cu}; } } return getWorkingCopies(); } boolean match(char patternTypeSuffix, int modifiers) { switch(patternTypeSuffix) { case IIndexConstants.CLASS_SUFFIX : return (modifiers & (Flags.AccAnnotation | Flags.AccInterface | Flags.AccEnum)) == 0; case IIndexConstants.CLASS_AND_INTERFACE_SUFFIX: return (modifiers & (Flags.AccAnnotation | Flags.AccEnum)) == 0; case IIndexConstants.CLASS_AND_ENUM_SUFFIX: return (modifiers & (Flags.AccAnnotation | Flags.AccInterface)) == 0; case IIndexConstants.INTERFACE_SUFFIX : return (modifiers & Flags.AccInterface) != 0; case IIndexConstants.ENUM_SUFFIX : return (modifiers & Flags.AccEnum) != 0; case IIndexConstants.ANNOTATION_TYPE_SUFFIX : return (modifiers & Flags.AccAnnotation) != 0; } return true; } boolean match(char patternTypeSuffix, char[] patternPkg, char[] patternTypeName, int matchRule, int typeKind, char[] pkg, char[] typeName) { switch(patternTypeSuffix) { case IIndexConstants.CLASS_SUFFIX : if (typeKind != TypeDeclaration.CLASS_DECL) return false; break; case IIndexConstants.CLASS_AND_INTERFACE_SUFFIX: if (typeKind != TypeDeclaration.CLASS_DECL && typeKind != TypeDeclaration.INTERFACE_DECL) return false; break; case IIndexConstants.CLASS_AND_ENUM_SUFFIX: if (typeKind != TypeDeclaration.CLASS_DECL && typeKind != TypeDeclaration.ENUM_DECL) return false; break; case IIndexConstants.INTERFACE_SUFFIX : if (typeKind != TypeDeclaration.INTERFACE_DECL) return false; break; case IIndexConstants.ENUM_SUFFIX : if (typeKind != TypeDeclaration.ENUM_DECL) return false; break; case IIndexConstants.ANNOTATION_TYPE_SUFFIX : if (typeKind != TypeDeclaration.ANNOTATION_TYPE_DECL) return false; break; case IIndexConstants.TYPE_SUFFIX : // nothing } boolean isCaseSensitive = (matchRule & SearchPattern.R_CASE_SENSITIVE) != 0; if (patternPkg != null && !CharOperation.equals(patternPkg, pkg, isCaseSensitive)) return false; if (patternTypeName != null) { boolean isCamelCase = (matchRule & SearchPattern.R_CAMELCASE_MATCH) != 0; int matchMode = matchRule & JavaSearchPattern.MATCH_MODE_MASK; if (!isCaseSensitive && !isCamelCase) { patternTypeName = CharOperation.toLowerCase(patternTypeName); } boolean matchFirstChar = !isCaseSensitive || patternTypeName[0] == typeName[0]; if (isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(patternTypeName, typeName)) { return true; } switch(matchMode) { case SearchPattern.R_EXACT_MATCH : if (!isCamelCase) { return matchFirstChar && CharOperation.equals(patternTypeName, typeName, isCaseSensitive); } // fall through next case to match as prefix if camel case failed case SearchPattern.R_PREFIX_MATCH : return matchFirstChar && CharOperation.prefixEquals(patternTypeName, typeName, isCaseSensitive); case SearchPattern.R_PATTERN_MATCH : return CharOperation.match(patternTypeName, typeName, isCaseSensitive); case SearchPattern.R_REGEXP_MATCH : // TODO (frederic) implement regular expression match break; } } return true; } /** * Searches for matches of a given search pattern. Search patterns can be created using helper * methods (from a String pattern or a Java element) and encapsulate the description of what is * being searched (for example, search method declarations in a case sensitive way). * * @see SearchEngine#search(SearchPattern, SearchParticipant[], IJavaSearchScope, SearchRequestor, IProgressMonitor) * for detailed comment */ public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { if (VERBOSE) { Util.verbose("BasicSearchEngine.search(SearchPattern, SearchParticipant[], IJavaSearchScope, SearchRequestor, IProgressMonitor)"); //$NON-NLS-1$ } findMatches(pattern, participants, scope, requestor, monitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package or a type name * prefix and match modes). * * @see SearchEngine#searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, TypeNameRequestor, int, IProgressMonitor) * for detailed comment */ public void searchAllTypeNames( final char[] packageName, final char[] typeName, final int matchRule, int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: "+(packageName==null?"null":new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type name: "+(typeName==null?"null":new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - match rule: "+getMatchRuleString(matchRule)); //$NON-NLS-1$ Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$ Util.verbose(" - scope: "+scope); //$NON-NLS-1$ } // Return on invalid combination of package and type names if (packageName == null || packageName.length == 0) { if (typeName != null && typeName.length == 0) { if (VERBOSE) { Util.verbose(" => return no result due to invalid empty values for package and type names!"); //$NON-NLS-1$ } return; } } IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); final char typeSuffix; switch(searchFor){ case IJavaSearchConstants.CLASS : typeSuffix = IIndexConstants.CLASS_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_INTERFACE : typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_ENUM : typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX; break; case IJavaSearchConstants.INTERFACE : typeSuffix = IIndexConstants.INTERFACE_SUFFIX; break; case IJavaSearchConstants.ENUM : typeSuffix = IIndexConstants.ENUM_SUFFIX; break; case IJavaSearchConstants.ANNOTATION_TYPE : typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; break; default : typeSuffix = IIndexConstants.TYPE_SUFFIX; break; } final TypeDeclarationPattern pattern = new TypeDeclarationPattern( packageName, null, // do find member types typeName, typeSuffix, matchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord; if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // fliter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1; int nameLength = record.simpleName==null ? 0 : record.simpleName.length; char[] path = new char[pkgLength+nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.pkg, 0, path, pos, pkgLength-1); CharOperation.replace(path, '.', '/'); path[pkgLength-1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } if (match(record.typeSuffix, record.modifiers)) { nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); } return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 100); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, getDefaultSearchParticipant(), // Java search only scope, searchRequestor), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); // add type names from working copies if (copies != null) { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; if (!scope.encloses(workingCopy)) continue; final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; IJavaElement parent = type.getParent(); char[][] enclosingTypeNames; if (parent instanceof IType) { char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); } else { enclosingTypeNames = CharOperation.NO_CHAR_CHAR; } char[] simpleName = type.getElementName().toCharArray(); int kind; if (type.isEnum()) { kind = TypeDeclaration.ENUM_DECL; } else if (type.isAnnotation()) { kind = TypeDeclaration.ANNOTATION_TYPE_DECL; } else if (type.isClass()) { kind = TypeDeclaration.CLASS_DECL; } else /*if (type.isInterface())*/ { kind = TypeDeclaration.INTERFACE_DECL; } if (match(typeSuffix, packageName, typeName, matchRule, kind, packageDeclaration, simpleName)) { nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllTypeDeclarationsVisitor extends ASTVisitor { public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; // no local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { if (match(typeSuffix, packageName, typeName, matchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) { nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); } return true; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { if (match(typeSuffix, packageName, typeName, matchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) { // compute encloising type names TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } // report nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); } return true; } } parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); } } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package or a type name * prefix and match modes). * */ public void searchAllSecondaryTypeNames( IPackageFragmentRoot[] sourceFolders, final IRestrictedAccessTypeRequestor nameRequestor, boolean waitForIndexes, IProgressMonitor progressMonitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchAllSecondaryTypeNames(IPackageFragmentRoot[], IRestrictedAccessTypeRequestor, boolean, IProgressMonitor)"); //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(" - source folders: "); //$NON-NLS-1$ int length = sourceFolders.length; for (int i=0; i<length; i++) { if (i==0) { buffer.append('['); } else { buffer.append(','); } buffer.append(sourceFolders[i].getElementName()); } buffer.append("]\n - waitForIndexes: "); //$NON-NLS-1$ buffer.append(waitForIndexes); Util.verbose(buffer.toString()); } IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); final TypeDeclarationPattern pattern = new SecondaryTypeDeclarationPattern(); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord; if (!record.secondary) { return true; // filter maint types } if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // fliter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1; int nameLength = record.simpleName==null ? 0 : record.simpleName.length; char[] path = new char[pkgLength+nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.pkg, 0, path, pos, pkgLength-1); CharOperation.replace(path, '.', '/'); path[pkgLength-1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); return true; } }; // add type names from indexes if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 100); } try { indexManager.performConcurrentJob( new PatternSearchJob( pattern, getDefaultSearchParticipant(), // Java search only createJavaSearchScope(sourceFolders), searchRequestor), waitForIndexes ? IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH : IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); } catch (OperationCanceledException oce) { // do nothing } } /** * Searches for all top-level types and member types in the given scope using a case sensitive exact match * with the given qualified names and type names. * * @see SearchEngine#searchAllTypeNames(char[][], char[][], IJavaSearchScope, TypeNameRequestor, int, IProgressMonitor) * for detailed comment */ public void searchAllTypeNames( final char[][] qualifications, final char[][] typeNames, final int matchRule, int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: "+(qualifications==null?"null":new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type name: "+(typeNames==null?"null":new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - match rule: "+matchRule); //$NON-NLS-1$ Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$ Util.verbose(" - scope: "+scope); //$NON-NLS-1$ } IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); final char typeSuffix; switch(searchFor){ case IJavaSearchConstants.CLASS : typeSuffix = IIndexConstants.CLASS_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_INTERFACE : typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_ENUM : typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX; break; case IJavaSearchConstants.INTERFACE : typeSuffix = IIndexConstants.INTERFACE_SUFFIX; break; case IJavaSearchConstants.ENUM : typeSuffix = IIndexConstants.ENUM_SUFFIX; break; case IJavaSearchConstants.ANNOTATION_TYPE : typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; break; default : typeSuffix = IIndexConstants.TYPE_SUFFIX; break; } final MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames, typeSuffix, matchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // fliter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) indexRecord; AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0 : record.qualification.length + 1; int nameLength = record.simpleName == null ? 0 : record.simpleName.length; char[] path = new char[qualificationLength + nameLength]; int pos = 0; if (qualificationLength > 0) { System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1); CharOperation.replace(path, '.', '/'); path[qualificationLength-1] = '/'; pos += qualificationLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } nameRequestor.acceptType(record.modifiers, record.getPackageName(), record.simpleName, record.getEnclosingTypeNames(), documentPath, accessRestriction); return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 100); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, getDefaultSearchParticipant(), // Java search only scope, searchRequestor), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); // add type names from working copies if (copies != null) { for (int i = 0, length = copies.length; i < length; i++) { ICompilationUnit workingCopy = copies[i]; final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; IJavaElement parent = type.getParent(); char[][] enclosingTypeNames; char[] qualification = packageDeclaration; if (parent instanceof IType) { char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); qualification = CharOperation.concat(qualification, parentQualifiedName); } else { enclosingTypeNames = CharOperation.NO_CHAR_CHAR; } char[] simpleName = type.getElementName().toCharArray(); char suffix = IIndexConstants.TYPE_SUFFIX; if (type.isClass()) { suffix = IIndexConstants.CLASS_SUFFIX; } else if (type.isInterface()) { suffix = IIndexConstants.INTERFACE_SUFFIX; } else if (type.isEnum()) { suffix = IIndexConstants.ENUM_SUFFIX; } else if (type.isAnnotation()) { suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; } if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification, simpleName, suffix, matchRule))) { nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllTypeDeclarationsVisitor extends ASTVisitor { public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; // no local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(packageDeclaration, typeDeclaration.name, convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)), matchRule); if (pattern.matchesDecodedKey(decodedPattern)) { nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); } return true; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { // compute encloising type names char[] qualification = packageDeclaration; TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { qualification = CharOperation.concat(qualification, enclosing.name, '.'); enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern(qualification, memberTypeDeclaration.name, convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)), matchRule); if (pattern.matchesDecodedKey(decodedPattern)) { nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); } return true; } } parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); } } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } } public void searchDeclarations(IJavaElement enclosingElement, SearchRequestor requestor, SearchPattern pattern, IProgressMonitor monitor) throws JavaModelException { if (VERBOSE) { Util.verbose(" - java element: "+enclosingElement); //$NON-NLS-1$ } IJavaSearchScope scope = createJavaSearchScope(new IJavaElement[] {enclosingElement}); IResource resource = this.getResource(enclosingElement); try { if (resource instanceof IFile) { try { requestor.beginReporting(); if (VERBOSE) { Util.verbose("Searching for " + pattern + " in " + resource.getFullPath()); //$NON-NLS-1$//$NON-NLS-2$ } SearchParticipant participant = getDefaultSearchParticipant(); SearchDocument[] documents = MatchLocator.addWorkingCopies( pattern, new SearchDocument[] {new JavaSearchDocument(enclosingElement.getPath().toString(), participant)}, getWorkingCopies(enclosingElement), participant); participant.locateMatches( documents, pattern, scope, requestor, monitor); } finally { requestor.endReporting(); } } else { search( pattern, new SearchParticipant[] {getDefaultSearchParticipant()}, scope, requestor, monitor); } } catch (CoreException e) { if (e instanceof JavaModelException) throw (JavaModelException) e; throw new JavaModelException(e); } } /** * Searches for all declarations of the fields accessed in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the field declarations using the given requestor. * * @see SearchEngine#searchDeclarationsOfAccessedFields(IJavaElement, SearchRequestor, IProgressMonitor) * for detailed comment */ public void searchDeclarationsOfAccessedFields(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchDeclarationsOfAccessedFields(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$ } SearchPattern pattern = new DeclarationOfAccessedFieldsPattern(enclosingElement); searchDeclarations(enclosingElement, requestor, pattern, monitor); } /** * Searches for all declarations of the types referenced in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the type declarations using the given requestor. * * @see SearchEngine#searchDeclarationsOfReferencedTypes(IJavaElement, SearchRequestor, IProgressMonitor) * for detailed comment */ public void searchDeclarationsOfReferencedTypes(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchDeclarationsOfReferencedTypes(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$ } SearchPattern pattern = new DeclarationOfReferencedTypesPattern(enclosingElement); searchDeclarations(enclosingElement, requestor, pattern, monitor); } /** * Searches for all declarations of the methods invoked in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the method declarations using the given requestor. * * @see SearchEngine#searchDeclarationsOfSentMessages(IJavaElement, SearchRequestor, IProgressMonitor) * for detailed comment */ public void searchDeclarationsOfSentMessages(IJavaElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaModelException { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchDeclarationsOfSentMessages(IJavaElement, SearchRequestor, SearchPattern, IProgressMonitor)"); //$NON-NLS-1$ } SearchPattern pattern = new DeclarationOfReferencedMethodsPattern(enclosingElement); searchDeclarations(enclosingElement, requestor, pattern, monitor); } }
[ "375833274@qq.com" ]
375833274@qq.com
1d1deb88337894849f608cf9e6354f9da220b2b9
9f1b560f7f7dc488859e42398b8045d62ec5dd0b
/src/main/java/com/movit/rwe/modules/act/web/ActProcessController.java
91183f26e1838bd95ee56a342e963e40c9b4a81c
[ "Apache-2.0" ]
permissive
qingshui5555/azrwebi
f471c45f9ddb4e2afa0d705ed15feb891a4d92bc
d5aad86dc17b24ae88d5b0418ece3a84f3fd63e1
refs/heads/master
2020-03-28T03:31:11.989441
2018-09-27T07:12:31
2018-09-27T07:12:31
147,651,355
0
0
null
null
null
null
UTF-8
Java
false
false
7,106
java
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.movit.rwe.modules.act.web; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.XMLStreamException; import org.activiti.engine.runtime.ProcessInstance; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.movit.rwe.common.persistence.Page; import com.movit.rwe.common.utils.StringUtils; import com.movit.rwe.common.web.BaseController; import com.movit.rwe.modules.act.service.ActProcessService; /** * 流程定义相关Controller * @author ThinkGem * @version 2013-11-03 */ @Controller @RequestMapping(value = "${adminPath}/act/process") public class ActProcessController extends BaseController { @Autowired private ActProcessService actProcessService; /** * 流程定义列表 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = {"list", ""}) public String processList(String category, HttpServletRequest request, HttpServletResponse response, Model model) { /* * 保存两个对象,一个是ProcessDefinition(流程定义),一个是Deployment(流程部署) */ Page<Object[]> page = actProcessService.processList(new Page<Object[]>(request, response), category); model.addAttribute("page", page); model.addAttribute("category", category); return "modules/act/actProcessList"; } /** * 运行中的实例列表 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "running") public String runningList(String procInsId, String procDefKey, HttpServletRequest request, HttpServletResponse response, Model model) { Page<ProcessInstance> page = actProcessService.runningList(new Page<ProcessInstance>(request, response), procInsId, procDefKey); model.addAttribute("page", page); model.addAttribute("procInsId", procInsId); model.addAttribute("procDefKey", procDefKey); return "modules/act/actProcessRunningList"; } /** * 读取资源,通过部署ID * @param processDefinitionId 流程定义ID * @param processInstanceId 流程实例ID * @param resourceType 资源类型(xml|image) * @param response * @throws Exception */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "resource/read") public void resourceRead(String procDefId, String proInsId, String resType, HttpServletResponse response) throws Exception { InputStream resourceAsStream = actProcessService.resourceRead(procDefId, proInsId, resType); byte[] b = new byte[1024]; int len = -1; while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { response.getOutputStream().write(b, 0, len); } } /** * 部署流程 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "/deploy", method=RequestMethod.GET) public String deploy(Model model) { return "modules/act/actProcessDeploy"; } /** * 部署流程 - 保存 * @param file * @return */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "/deploy", method=RequestMethod.POST) public String deploy(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir, String category, MultipartFile file, RedirectAttributes redirectAttributes) { String fileName = file.getOriginalFilename(); if (StringUtils.isBlank(fileName)){ redirectAttributes.addFlashAttribute("message", "请选择要部署的流程文件"); }else{ String message = actProcessService.deploy(exportDir, category, file); redirectAttributes.addFlashAttribute("message", message); } return "redirect:" + adminPath + "/act/process"; } /** * 设置流程分类 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "updateCategory") public String updateCategory(String procDefId, String category, RedirectAttributes redirectAttributes) { actProcessService.updateCategory(procDefId, category); return "redirect:" + adminPath + "/act/process"; } /** * 挂起、激活流程实例 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "update/{state}") public String updateState(@PathVariable("state") String state, String procDefId, RedirectAttributes redirectAttributes) { String message = actProcessService.updateState(state, procDefId); redirectAttributes.addFlashAttribute("message", message); return "redirect:" + adminPath + "/act/process"; } /** * 将部署的流程转换为模型 * @param procDefId * @param redirectAttributes * @return * @throws UnsupportedEncodingException * @throws XMLStreamException */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "convert/toModel") public String convertToModel(String procDefId, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException, XMLStreamException { org.activiti.engine.repository.Model modelData = actProcessService.convertToModel(procDefId); redirectAttributes.addFlashAttribute("message", "转换模型成功,模型ID="+modelData.getId()); return "redirect:" + adminPath + "/act/model"; } /** * 导出图片文件到硬盘 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "export/diagrams") @ResponseBody public List<String> exportDiagrams(@Value("#{APP_PROP['activiti.export.diagram.path']}") String exportDir) throws IOException { List<String> files = actProcessService.exportDiagrams(exportDir);; return files; } /** * 删除部署的流程,级联删除流程实例 * @param deploymentId 流程部署ID */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "delete") public String delete(String deploymentId) { actProcessService.deleteDeployment(deploymentId); return "redirect:" + adminPath + "/act/process"; } /** * 删除流程实例 * @param procInsId 流程实例ID * @param reason 删除原因 */ @RequiresPermissions("act:process:edit") @RequestMapping(value = "deleteProcIns") public String deleteProcIns(String procInsId, String reason, RedirectAttributes redirectAttributes) { if (StringUtils.isBlank(reason)){ addMessage(redirectAttributes, "请填写删除原因"); }else{ actProcessService.deleteProcIns(procInsId, reason); addMessage(redirectAttributes, "删除流程实例成功,实例ID=" + procInsId); } return "redirect:" + adminPath + "/act/process/running/"; } }
[ "253515173@qq.com" ]
253515173@qq.com
fdda74eb9fe9ee23832d908359fabb60213da639
915bc4b49660b21068cded065306d6d60e1532f2
/src/main/java/org/snpeff/snpEffect/testCases/unity/TestCasesApplyIns.java
8ec5119cf12abd8a6ecd8cd47d6382d92cee0633
[]
no_license
smith-chem-wisc/SnpEff
4b12d0c187eba4ad472f0e9bc5580b6c003eb5c2
ac911a9433995b4cba17bb90054eab2286437759
refs/heads/master
2023-01-21T11:06:31.745348
2023-01-12T21:35:46
2023-01-12T21:35:46
132,474,093
2
3
null
2023-01-12T21:35:48
2018-05-07T14:40:12
Java
UTF-8
Java
false
false
6,763
java
package org.snpeff.snpEffect.testCases.unity; import org.junit.Test; import org.snpeff.interval.Variant; import org.snpeff.util.Gpr; /** * Test cases: apply a variant (INS) to a transcript * */ public class TestCasesApplyIns extends TestCasesBaseApply { public TestCasesApplyIns() { super(); } /** * Variant before exon */ @Test public void test_apply_variant_01() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 290, "", "ACG"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 303, 402); } /** * Variant before exon */ @Test public void test_apply_variant_02() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 297, "", "ACG"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 303, 402); } /** * Variant overlapping exon start */ @Test public void test_apply_variant_03() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 299, "", "ACG"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 303, 402); } /** * Variant at exon start */ @Test public void test_apply_variant_04() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 300, "", "ACG"); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + "ACGtgtttgggaattcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacg".toLowerCase() // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 402); } /** * Variant in exon */ @Test public void test_apply_variant_05() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 310, "", "ACG"); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + "tgtttgggaaACGttcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacg".toLowerCase() // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 402); } /** * Variant in exon */ @Test public void test_apply_variant_06() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 399, "", "ACG"); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + "tgtttgggaattcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacACGg".toLowerCase() // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 402); } /** * Variant overlapping exon end */ @Test public void test_apply_variant_07() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 399, "", "ACG"); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + "tgtttgggaattcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacACGg".toLowerCase() // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 402); } /** * Variant right after exon end */ @Test public void test_apply_variant_08() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 400, "", "ACG"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 300, 399); } /** * Variant after exon end */ @Test public void test_apply_variant_09() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 410, "", "ACG"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 300, 399); } /** * Variant over exon: variant is larger than exon, starts before exon and overlaps the whole exon */ @Test public void test_apply_variant_10() { Gpr.debug("Test"); Variant variant = new Variant(transcript.getParent(), 290, "", "ATTGGCTCGACGCTCATTCACTCCAACAGCCCGGGACCCCCGCTCAATTATTTCACTCACCGGGAAAATTGTACCGATTGTCCGTGCCTTACTTCAAATGACATCCGCAGGTGAAGGCAT"); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 420, 519); } /** * Variant over exon: variant is larger than exon and starts right at exons start and ends after exon end */ @Test public void test_apply_variant_11() { Gpr.debug("Test"); String seq = "ATTGGCTCGACGCTCATTCACTCCAACAGCCCGGGACCCCCGCTCAATTATTTCACTCACCGGGAAAATTGTACCGATTGTCCGTGCCTTACTTCAAATGACATCCGCAGGTGAAGGCAT"; Variant variant = new Variant(transcript.getParent(), 300, "", seq); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + seq.toLowerCase() + "tgtttgggaattcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacg" // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 519); } /** * Variant over exon: variant is larger than exon, starts before exon start and end right at exon end */ @Test public void test_apply_variant_12() { Gpr.debug("Test"); String seq = "ATTGGCTCGACGCTCATTCACTCCAACAGCCCGGGACCCCCGCTCAATTATTTCACTCACCGGGAAAATTGTACCGATTGTCCGTGCCTTACTTCAAATGACATCCGCAG"; Variant variant = new Variant(transcript.getParent(), 290, "", seq); checkApplyIns(variant, transcript.cds(), transcript.protein(), 1, 410, 509); } /** * Variant over exon: variant is on the same coordiantes as exon */ @Test public void test_apply_variant_13() { Gpr.debug("Test"); String seq = "ATTGGCTCGACGCTCATTCACTCCAACAGCCCGGGACCCCCGCTCAATTATTTCACTCACCGGGAAAATTGTACCGATTGTCCGTGCCTTACTTCAAATG"; Variant variant = new Variant(transcript.getParent(), 300, "", seq); String expectedCds = "atgtccgcaggtgaaggcatacacgctgcgcgtatactgatgttacctcgatggattttgtcagaaatatggtgcccaggacgcgaagggcatattatgg" // Exon[0] + seq.toLowerCase() + "tgtttgggaattcacgggcacggttctgcagcaagctgaattggcagctcggcataaatcccgaccccatcgtcacgcacggatcaattcatcctcaacg" // Exon[1] + "ggtagaggaaaagcacctaacccccattgagcaggatctctttcgtaatactctgtatcgattaccgatttatttgattccccacatttatttcatcggg" // Exon[2] ; checkApplyIns(variant, expectedCds, null, 1, 300, 499); } }
[ "pablo.e.cingolani@gmail.com" ]
pablo.e.cingolani@gmail.com
391d83157c6e8d9dea208d0b2f6821f7a0ae7128
e4880bbca1969bba7f1aa73fd268510e5118ad5a
/src/main/java/me/prosl3nderman/proeverything/commands/DelhomeCommand.java
6341d8c40a61aa1c7290f26fe0d4243b4876d985
[]
no_license
ProSl3nderMan/ProEverything
583fac392baf6076687d4b6e3ee5608cbe579e33
2431b7e8c5b2b85fd2fb1ad2ba3445c88371bfbd
refs/heads/main
2023-02-18T22:20:11.758961
2021-01-17T19:34:54
2021-01-17T19:34:54
330,470,638
0
0
null
null
null
null
UTF-8
Java
false
false
2,455
java
package me.prosl3nderman.proeverything.commands; import me.prosl3nderman.proeverything.HomeConfig; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; public class DelhomeCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if (!(commandSender instanceof Player)) { commandSender.sendMessage("Must be sent by a player."); return true; } Player p = (Player) commandSender; String uuid = p.getUniqueId().toString(); HomeConfig HC = new HomeConfig(); if (!HC.getConfig().contains(uuid)) { p.sendMessage(ChatColor.RED + "You do not have a home! Do " + ChatColor.WHITE + "/sethome " + ChatColor.RED + "to set your home!"); return true; } List<String> homes = new ArrayList<String>(); for (String home : HC.getConfig().getConfigurationSection(uuid).getKeys(false)) homes.add(home); if (args.length == 0) { if (!homes.contains("home")) { p.sendMessage(ChatColor.RED + "You do not have a default home! Do " + ChatColor.WHITE + "/sethome " + ChatColor.RED + "to set your default home!"); return true; } p.sendMessage(ChatColor.RED + "Do " + ChatColor.WHITE + "/delhome home" + ChatColor.RED + " to delete your default home."); return true; } if (!homes.contains(args[0])) { p.sendMessage(ChatColor.RED + "Invalid home name " + ChatColor.WHITE + args[0] + ChatColor.RED + "! Homes: " + homesInStringForm(homes)); return true; } HC.getConfig().set(uuid + "." + args[0], null); if (HC.getConfig().getConfigurationSection(uuid).getKeys(false).size() == 0) HC.getConfig().set(uuid, null); HC.srConfig(); p.sendMessage(ChatColor.GOLD + "Your home " + ChatColor.WHITE + args[0] + ChatColor.GOLD + " has now been deleted!"); return true; } private String homesInStringForm(List<String> homes) { String dummy = homes.get(0); for (int i = 1; i < homes.size(); i++) dummy = dummy + ", " + homes.get(i); return dummy; } }
[ "austinbworkin@gmail.com" ]
austinbworkin@gmail.com
d9eed42dcd72490d20387449ea5f41bb4fa009f4
af7c8e493be053d600d21a6b7eaba55844e2269e
/Westwinglife/app/src/main/java/com/bentudou/westwinglife/fragment/FourFragment.java
d6b61f670f108f5dbfba186b89986cdb3773452f
[]
no_license
wutianchi/Tudou-android
fa8cb86d33ecef0ed3bdddcaf2069a55efb0bff1
d73db454eeb26ac7c85090778097add0bc7a9271
refs/heads/master
2021-01-09T06:04:15.980455
2017-02-04T04:42:35
2017-02-04T04:42:35
80,893,685
5
3
null
null
null
null
UTF-8
Java
false
false
20,365
java
package com.bentudou.westwinglife.fragment; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.bentudou.westwinglife.R; import com.bentudou.westwinglife.activity.AboutBentudouActivity; import com.bentudou.westwinglife.activity.GiveUsMessageActivity; import com.bentudou.westwinglife.activity.GrowLogActivity; import com.bentudou.westwinglife.activity.LoginActivity; import com.bentudou.westwinglife.activity.MyAddressActivity; import com.bentudou.westwinglife.activity.MyCouponActivity; import com.bentudou.westwinglife.activity.MyInviteCodeActivity; import com.bentudou.westwinglife.activity.MyMessageListActivity; import com.bentudou.westwinglife.activity.MyNewCollectionListActivity; import com.bentudou.westwinglife.activity.NewOrderListActivity; import com.bentudou.westwinglife.activity.SetActivity; import com.bentudou.westwinglife.activity.ShareBentudouActivity; import com.bentudou.westwinglife.activity.WebDetailActivity; import com.bentudou.westwinglife.backend.PotatoService; import com.bentudou.westwinglife.config.Constant; import com.bentudou.westwinglife.json.CheckSign; import com.bentudou.westwinglife.json.PayNumber; import com.bentudou.westwinglife.json.UnReadMessage; import com.bentudou.westwinglife.json.UserInfo; import com.bentudou.westwinglife.json.UserSign; import com.bentudou.westwinglife.utils.FileImageUpload; import com.bentudou.westwinglife.utils.SharePreferencesUtils; import com.bentudou.westwinglife.utils.ToastUtils; import com.bentudou.westwinglife.utils.UploadUtil; import com.bentudou.westwinglife.utils.VerifitionUtil; import com.gunlei.app.ui.view.ProgressHUD; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Random; import common.retrofit.RTHttpClient; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Created by lzz on 2016/3/2. */ public class FourFragment extends Fragment implements View.OnClickListener,UploadUtil.OnUploadProcessListener { /** * 去上传文件 */ protected static final int TO_UPLOAD_FILE = 1; /** * 上传文件响应 */ protected static final int UPLOAD_FILE_DONE = 2; // /** * 选择文件 */ public static final int TO_SELECT_PHOTO = 3; /** * 上传初始化 */ private static final int UPLOAD_INIT_PROCESS = 4; /** * 上传中 */ private static final int UPLOAD_IN_PROCESS = 5; /*** * 这里的这个URL是我服务器的javaEE环境URL */ private static String requestURL = Constant.URL_BASE_TEST+"/UploadImage/uploadIDImage.htm"; private String picPath = "/sdcard/startimg.png"; private ImageView iv_my_message,iv_level; private SwipeRefreshLayout srl_fresh; private TextView tv_my_phone,tv_new_message,tv_is_sign,tv_pay_num; private LinearLayout llt_my_order,llt_my_address,llt_my_tudou,llt_my_yaoqing, llt_my_share,llt_my_set,llt_my_collection, llt_qiandao,llt_grow,llt_bg_img, llt_no_pay,llt_have_pay,llt_no_use_order; ProgressHUD progressHUD = null; private String inviteCode; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_four,null); initView(view); return view; } private void initView(View view) { iv_my_message = (ImageView) view.findViewById(R.id.iv_my_message); iv_level = (ImageView) view.findViewById(R.id.iv_level); srl_fresh = (SwipeRefreshLayout) view.findViewById(R.id.srl_fresh); tv_my_phone = (TextView) view.findViewById(R.id.tv_my_phone); llt_my_order = (LinearLayout) view.findViewById(R.id.llt_my_order); llt_no_pay = (LinearLayout) view.findViewById(R.id.llt_no_pay); llt_have_pay = (LinearLayout) view.findViewById(R.id.llt_have_pay); llt_no_use_order = (LinearLayout) view.findViewById(R.id.llt_no_use_order); llt_my_address = (LinearLayout) view.findViewById(R.id.llt_my_address); llt_my_tudou = (LinearLayout) view.findViewById(R.id.llt_my_tudou); llt_my_yaoqing = (LinearLayout) view.findViewById(R.id.llt_my_yaoqing); llt_my_share = (LinearLayout) view.findViewById(R.id.llt_my_share); llt_my_set = (LinearLayout) view.findViewById(R.id.llt_my_set); llt_my_collection = (LinearLayout) view.findViewById(R.id.llt_my_collection); llt_qiandao = (LinearLayout) view.findViewById(R.id.llt_qiandao); llt_grow = (LinearLayout) view.findViewById(R.id.llt_grow); llt_bg_img = (LinearLayout) view.findViewById(R.id.llt_bg_img); tv_new_message = (TextView) view.findViewById(R.id.tv_new_message); tv_is_sign = (TextView) view.findViewById(R.id.tv_is_sign); tv_pay_num = (TextView) view.findViewById(R.id.tv_pay_num); iv_my_message.setOnClickListener(this); llt_qiandao.setOnClickListener(this); llt_grow.setOnClickListener(this); llt_my_order.setOnClickListener(this); llt_no_pay.setOnClickListener(this); llt_have_pay.setOnClickListener(this); llt_no_use_order.setOnClickListener(this); llt_my_address.setOnClickListener(this); llt_my_tudou.setOnClickListener(this); llt_my_yaoqing.setOnClickListener(this); llt_my_share.setOnClickListener(this); llt_my_set.setOnClickListener(this); llt_my_collection.setOnClickListener(this); srl_fresh.setColorSchemeResources(R.color.color_select, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); srl_fresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { toRefresh(); isNewMessage(); isCheckSign(); initNoPayNum(); } }); isNewMessage(); isCheckSign(); initNoPayNum(); initBgImg(); } private void initNoPayNum() { final PotatoService service = RTHttpClient.create(PotatoService.class); service.findOrderNumberUnpaid(SharePreferencesUtils.getBtdToken(getActivity()),new Callback<PayNumber>() { @Override public void success(PayNumber payNumber, Response response) { if (payNumber.getStatus().equals("1")){ if (payNumber.getData().getOrderNumber()>0){ tv_pay_num.setVisibility(View.VISIBLE); tv_pay_num.setText(String.valueOf(payNumber.getData().getOrderNumber())); }else { tv_pay_num.setVisibility(View.GONE); } } } @Override public void failure(RetrofitError error) { } }); } private void initBgImg() { switch (SharePreferencesUtils.getBgImg(getActivity())){ case 1: llt_bg_img.setBackgroundResource(R.drawable.bg1); break; case 2: llt_bg_img.setBackgroundResource(R.drawable.bg2); break; case 3: llt_bg_img.setBackgroundResource(R.drawable.bg3); break; case 4: llt_bg_img.setBackgroundResource(R.drawable.bg4); break; case 5: llt_bg_img.setBackgroundResource(R.drawable.bg5); break; case 6: llt_bg_img.setBackgroundResource(R.drawable.bg6); break; case 7: llt_bg_img.setBackgroundResource(R.drawable.bg7); break; case 8: llt_bg_img.setBackgroundResource(R.drawable.bg8); break; case 9: llt_bg_img.setBackgroundResource(R.drawable.bg9); break; case 10: llt_bg_img.setBackgroundResource(R.drawable.bg10); break; case 11: llt_bg_img.setBackgroundResource(R.drawable.bg11); break; } } private void isCheckSign() { final PotatoService service = RTHttpClient.create(PotatoService.class); service.checkUserSign(SharePreferencesUtils.getBtdToken(getActivity()),new Callback<CheckSign>() { @Override public void success(CheckSign checkSign, Response response) { if (checkSign.getStatus().equals("1")){ if (checkSign.getData().isUserSign()){ tv_is_sign.setText("已签到"); }else { tv_is_sign.setText("签到"); } switch (checkSign.getData().getUserGrade()){ case 0: iv_level.setImageResource(R.drawable.v0); break; case 1: iv_level.setImageResource(R.drawable.v1); break; case 2: iv_level.setImageResource(R.drawable.v2); break; case 3: iv_level.setImageResource(R.drawable.v3); break; case 4: iv_level.setImageResource(R.drawable.v4); break; case 5: iv_level.setImageResource(R.drawable.v5); break; case 6: iv_level.setImageResource(R.drawable.v6); break; } } } @Override public void failure(RetrofitError error) { } }); } //是否有新消息 private void isNewMessage() { final PotatoService service = RTHttpClient.create(PotatoService.class); service.getUnReadCount(SharePreferencesUtils.getBtdToken(getActivity()),new Callback<UnReadMessage>() { @Override public void success(UnReadMessage userInfo, Response response) { if (userInfo.getStatus().equals("1")){ if (userInfo.getData().getUnreadMessageCount()>0){ tv_new_message.setVisibility(View.VISIBLE); }else { tv_new_message.setVisibility(View.GONE); } } } @Override public void failure(RetrofitError error) { } }); } public void toRefresh(){ final PotatoService service = RTHttpClient.create(PotatoService.class); service.getUserInfo(SharePreferencesUtils.getBtdToken(getActivity()),new Callback<UserInfo>() { @Override public void success(UserInfo userInfo, Response response) { srl_fresh.setRefreshing(false); if (null!=userInfo.getData()){ inviteCode =userInfo.getData().getUserInviteCode(); tv_my_phone.setText(userInfo.getData().getUserName()); }else { startActivity(new Intent(getActivity(), LoginActivity.class)); } } @Override public void failure(RetrofitError error) { srl_fresh.setRefreshing(false); } }); } private void initData() { inviteCode = SharePreferencesUtils.getInviteCode(getActivity()); tv_my_phone.setText(SharePreferencesUtils.getMobile(getActivity())); // progressHUD = ProgressHUD.show(getActivity(), "读取中", true, null); // final PotatoService service = RTHttpClient.create(PotatoService.class); // service.getUserInfo(SharePreferencesUtils.getBtdToken(getActivity()),new CallbackSupport<UserInfo>(progressHUD, getActivity()) { // @Override // public void success(UserInfo userInfo, Response response) { // progressHUD.dismiss(); // if (null!=userInfo.getData()){ // inviteCode =userInfo.getData().getUserInviteCode(); // tv_my_phone.setText(userInfo.getData().getUserName()); // tv_my_yaoqing.setText("我的邀请码 "+inviteCode); // }else { // startActivity(new Intent(getActivity(), LoginActivity.class)); // } // // } // // @Override // public void failure(RetrofitError error) { // super.failure(error); // } // }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.llt_my_set: startActivity(new Intent(getActivity(), SetActivity.class)); break;//去设置 case R.id.iv_my_message: startActivity(new Intent(getActivity(), MyMessageListActivity.class)); break;//去消息列表 case R.id.llt_my_order: startActivity(new Intent(getActivity(), NewOrderListActivity.class).putExtra("tagid",1)); // startActivity(new Intent(getActivity(), OrderListActivity.class)); break;//去我的订单 case R.id.llt_no_pay: startActivity(new Intent(getActivity(), NewOrderListActivity.class).putExtra("tagid",2)); break;//去待付款的订单 case R.id.llt_have_pay: startActivity(new Intent(getActivity(), NewOrderListActivity.class).putExtra("tagid",3)); break;//去已付款的订单 case R.id.llt_no_use_order: startActivity(new Intent(getActivity(), NewOrderListActivity.class).putExtra("tagid",4)); break;//去失效的订单 case R.id.llt_my_collection: startActivity(new Intent(getActivity(), MyNewCollectionListActivity.class)); break;//去我的收藏 case R.id.llt_my_address: startActivity(new Intent(getActivity(), MyAddressActivity.class)); break;//去我的地址 case R.id.llt_my_tudou: startActivity(new Intent(getActivity(), MyCouponActivity.class)); break;//去我的土豆条 case R.id.llt_my_yaoqing: startActivity(new Intent(getActivity(), MyInviteCodeActivity.class).putExtra("invite_code",inviteCode)); break;//去我的邀请码 // handler.sendEmptyMessage(TO_UPLOAD_FILE); // new Thread(new Runnable() { // @Override // public void run() { // String result; // result= FileImageUpload.uploadFile(SharePreferencesUtils.getBtdToken(getActivity()),new File("/sdcard/startimg.png"),"iDImg",Constant.URL_BASE_TEST+"/UploadImage/uploadIDImage.htm"); // if (result.equals("1")){ // Log.d("result","-----上传成功!"); // }else { // Log.d("result","-----上传失败!"); // } // } // }).start(); // VerifitionUtil.uploadImg(SharePreferencesUtils.getBtdToken(getActivity()),"/sdcard/startimg.png"); case R.id.llt_my_share: startActivity(new Intent(getActivity(), ShareBentudouActivity.class)); break;//去分享 case R.id.llt_qiandao: if (tv_is_sign.getText().toString().equals("已签到")){ ToastUtils.showToastCenter(getActivity(),"今天您已经签到过了哟"); break; } toSign(); break;//去签到 case R.id.llt_grow: startActivity(new Intent(getActivity(), GrowLogActivity.class)); break;//去成长记录 } } private void toUploadFile() { String fileKey = "iDImg"; UploadUtil uploadUtil = UploadUtil.getInstance();; uploadUtil.setOnUploadProcessListener(this); //设置监听器监听上传状态 Map<String, String> params = new HashMap<String, String>(); params.put("BtdToken", SharePreferencesUtils.getBtdToken(getActivity())); uploadUtil.uploadFile( picPath,fileKey, requestURL,params); } //签到接口 private void toSign() { final PotatoService service = RTHttpClient.create(PotatoService.class); service.createUserSign(SharePreferencesUtils.getBtdToken(getActivity()),new Callback<UserSign>() { @Override public void success(UserSign userSign, Response response) { if (userSign.getStatus().equals("1")){ if (userSign.isData()){ tv_is_sign.setText("已签到"); ToastUtils.showToastCenter(getActivity(),"签到成功"); // DialogUtils.showToast(getActivity().getLayoutInflater(),getActivity(),"签到成功","获取积分15"); }else { ToastUtils.showToastCenter(getActivity(),"服务器小憩中"); } } } @Override public void failure(RetrofitError error) { } }); } @Override public void onStart() { super.onStart(); // Constant.push_value=4; // if (SharePreferencesUtils.getBtdToken(getActivity()).isEmpty()){ // startActivity(new Intent(getActivity(), LoginActivity.class)); // }else { initData(); isNewMessage(); initNoPayNum(); isCheckSign(); // } } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case TO_UPLOAD_FILE: toUploadFile(); break; case UPLOAD_INIT_PROCESS: Log.d("UPLOAD_INIT_PROCESS","-----"+msg.arg1); break; case UPLOAD_IN_PROCESS: Log.d("UPLOAD_IN_PROCESS","-----"+msg.arg1); break; case UPLOAD_FILE_DONE: String result = "响应码:"+msg.arg1+"\n响应信息:"+msg.obj+"\n耗时:"+UploadUtil.getRequestTime()+"秒"; Log.d("UPLOAD_FILE_DONE","-----"+result); break; default: break; } super.handleMessage(msg); } }; /** * 上传服务器响应回调 */ @Override public void onUploadDone(int responseCode, String message) { Message msg = Message.obtain(); msg.what = UPLOAD_FILE_DONE; msg.arg1 = responseCode; msg.obj = message; handler.sendMessage(msg); } @Override public void onUploadProcess(int uploadSize) { Message msg = Message.obtain(); msg.what = UPLOAD_IN_PROCESS; msg.arg1 = uploadSize; handler.sendMessage(msg ); } @Override public void initUpload(int fileSize) { Message msg = Message.obtain(); msg.what = UPLOAD_INIT_PROCESS; msg.arg1 = fileSize; handler.sendMessage(msg ); } }
[ "admin@example.com" ]
admin@example.com
e8f48fba0e949c22766631f430e7a43b9e4d9837
f4bae0caded5c190e9873f7376a0f632a9f21dd2
/src/test/java/de/doubleslash/microprofileconfig/test/smallrye_config_example/PropertiesEnvFileTest.java
91709ecc7d72abc748d73b1417f57744019b8376
[ "Apache-2.0" ]
permissive
andyglick/smallrye_config_example
391421974502b0c39c59a8a949d8d54d266f28c3
48c6214f4369c2250a25f78ad9b40b36a4b6ddfe
refs/heads/main
2023-07-16T22:44:27.839149
2021-08-26T02:13:06
2021-08-26T02:13:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
971
java
package de.doubleslash.microprofileconfig.test.smallrye_config_example; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterEach; import static org.assertj.core.api.Assertions.assertThat; import static de.doubleslash.microprofileconfig.test.smallrye_config_example.DotEnvFile.writeDotEnvFile; import static de.doubleslash.microprofileconfig.test.smallrye_config_example.DotEnvFile.clearDotEnvFile; class PropertiesEnvFileTest { @AfterEach void teardown() { clearDotEnvFile(); } @Test void readFromEnvFile() { writeDotEnvFile("NONE_LOCALHOST"); Config config = ConfigProvider.getConfig(); assertThat(config.getValue("smallrye.test.hostoverwrite", String.class)).isEqualTo("NONE_LOCALHOST"); assertThat(config.getValue("smallrye.test.host", String.class)).isEqualTo("localhost"); } }
[ "Michael.Goldschmidt@doubleSlash.de" ]
Michael.Goldschmidt@doubleSlash.de
4ea3615c6787f1bf412c84ce229825e32250f279
225011bbc304c541f0170ef5b7ba09b967885e95
/mf/org/w3c/dom/ls/LSLoadEvent.java
7a451ea0d6982971a9f9b1bd7500ea9475e4109d
[]
no_license
sebaudracco/bubble
66536da5367f945ca3318fecc4a5f2e68c1df7ee
e282cda009dfc9422594b05c63e15f443ef093dc
refs/heads/master
2023-08-25T09:32:04.599322
2018-08-14T15:27:23
2018-08-14T15:27:23
140,444,001
1
1
null
null
null
null
UTF-8
Java
false
false
200
java
package mf.org.w3c.dom.ls; import mf.org.w3c.dom.Document; import mf.org.w3c.dom.events.Event; public interface LSLoadEvent extends Event { LSInput getInput(); Document getNewDocument(); }
[ "sebaudracco@gmail.com" ]
sebaudracco@gmail.com
e92226422949f2eed9cbb43bc552b6e75e3bafbf
39e13fe3ce8ce8731519cbb7cc3ae95d2b5d8c21
/src/H10/Opdr10_1.java
f488a9d4c063a69a4dfa25322dd39aa982d31d69
[]
no_license
Rohit1320/inleiding-java
c2abe19f2c26ef340d4416f3772adbaf64fb216a
7c2e64119da657e6d9664ceb5dd7027181e69e68
refs/heads/master
2020-06-04T12:09:34.161836
2017-04-10T14:40:04
2017-04-10T14:40:04
68,289,090
0
0
null
null
null
null
UTF-8
Java
false
false
1,235
java
package H10; import java.awt.*; import java.applet.*; import java.awt.event.*; public class Opdr10_1 extends Applet { int getal; int getal2; TextField tekstvak2; TextField tekstvak; Label label; String tekst; public void init() { tekstvak = new TextField("", 5); tekstvak.addActionListener(new VakListener()); tekst = ""; tekstvak2 = new TextField("", 5); tekstvak2.addActionListener(new VakListener()); label = new Label("Type twee getallen naar keuze"); add(label); add(tekstvak); add(tekstvak2); } public void paint(Graphics g) { g.drawString(tekst, 50, 45); } class VakListener implements ActionListener { public void actionPerformed(ActionEvent e) { String s; String l; s = tekstvak.getText(); l = tekstvak2.getText(); getal = Integer.parseInt(s); getal2 = Integer.parseInt(l); if (getal > getal2) { tekst = "Grootste getal." + getal; } if (getal2 > getal) { tekst = "Grootste getal." + getal2; } repaint(); } } }
[ "rkashyap@roc-dev.com" ]
rkashyap@roc-dev.com
1d6e9566bbac8af279f3870f2d534b686a8a68ac
806f76edfe3b16b437be3eb81639d1a7b1ced0de
/src/com/huawei/p029c/C4333a.java
8cef34cb2a05b834ce0173b77812dbce4f1287d6
[]
no_license
magic-coder/huawei-wear-re
1bbcabc807e21b2fe8fe9aa9d6402431dfe3fb01
935ad32f5348c3d8c8d294ed55a5a2830987da73
refs/heads/master
2021-04-15T18:30:54.036851
2018-03-22T07:16:50
2018-03-22T07:16:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
112
java
package com.huawei.p029c; /* compiled from: IExerciseAdviceForTrackDataCallback */ public interface C4333a { }
[ "lebedev1537@gmail.com" ]
lebedev1537@gmail.com
9c386ebcb813e8047f19ae3bfcc9f44a38794b31
8b2e046fd839fddfc596cda345dee9e7549346e9
/src/main/java/it/polimi/se2018/exception/gameboard_exception/tool_exception/RoundTrackIndexException.java
8812ee19efcf75688bacdf3982b3ab01913a7dee
[]
no_license
MatteoFormentin/ing-sw-2018-formentin-genoni
13b81aaf83e53d4f7a8cfb781a5e99dad86bdd2e
c85d9ffcec885a5d06bf8d6bb4643cdb0cc022bf
refs/heads/master
2020-03-09T18:24:27.688260
2019-02-28T15:55:46
2019-02-28T15:55:46
128,931,687
3
0
null
null
null
null
UTF-8
Java
false
false
673
java
package it.polimi.se2018.exception.gameboard_exception.tool_exception; import it.polimi.se2018.exception.gameboard_exception.player_state_exception.PlayerException; /** * The class {@code CurrentPlayerException} is a subclass of {@code Exception} * <p> * So it's a checked exceptions and it need to be declared in a * method or constructor's {@code throws} clause if they can be thrown * by the execution of the method or constructor and propagate outside * the method or constructor boundary. */ public class RoundTrackIndexException extends PlayerException { public RoundTrackIndexException() { super("Il round non può essere selezionato"); } }
[ "36886380+LucaGenoni@users.noreply.github.com" ]
36886380+LucaGenoni@users.noreply.github.com
ef701c375794636ae9221efea5bba9fd03a95448
c9b9efe729b677fea0ac4876efb587dddb1bc165
/src/main/java/de/mh/jba/entity/Item.java
ae9b3c507ee60f5e242fb0e1b1988a1f6adc1ce0
[]
no_license
Bato/myjba
1753cdb4a7e99f343fc88f20bd14efdcab3d2a1b
e76cf413f16911269714dd9a274e8432b8c481cf
refs/heads/master
2020-05-29T23:11:06.456837
2014-06-11T15:36:08
2014-06-11T15:36:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,482
java
package de.mh.jba.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import org.hibernate.annotations.Type; @Entity public class Item { @Id @GeneratedValue private Integer id; @Column(length = 1000) private String title; @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(length = Integer.MAX_VALUE) private String description; @Column(length = 1000) private String link; @Column(name = "published_date") private Date publishedDate; @ManyToOne @JoinColumn(name="blog_id") private Blog blog; public Blog getBlog() { return blog; } public void setBlog(Blog blog) { this.blog = blog; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getPublishedDate() { return publishedDate; } public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } }
[ "mh.bato@googlemail.com" ]
mh.bato@googlemail.com
d8a661b2741e52cc0464c253c4bdfbfc1b735ad5
86505462601eae6007bef6c9f0f4eeb9fcdd1e7b
/bin/modules/commerce-services/commerceservices/testsrc/de/hybris/platform/commerceservices/spring/config/MultipleListMergeBean.java
d2e38028e98124ba477b3f879baed8f8b205bc10
[]
no_license
jp-developer0/hybrisTrail
82165c5b91352332a3d471b3414faee47bdb6cee
a0208ffee7fee5b7f83dd982e372276492ae83d4
refs/heads/master
2020-12-03T19:53:58.652431
2020-01-02T18:02:34
2020-01-02T18:02:34
231,430,332
0
4
null
2020-08-05T22:46:23
2020-01-02T17:39:15
null
UTF-8
Java
false
false
752
java
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.commerceservices.spring.config; import java.util.ArrayList; import java.util.List; public class MultipleListMergeBean { private List<MergeTestBean> propertyList; private List<MergeTestBean> fieldList; public MultipleListMergeBean() { this.propertyList = new ArrayList<MergeTestBean>(); this.fieldList = new ArrayList<MergeTestBean>(); } public List<MergeTestBean> getPropertyList() { return propertyList; } public void setPropertyList(final List<MergeTestBean> propertyList) { this.propertyList = propertyList; } public void setFieldList(final List<MergeTestBean> fieldList) { this.fieldList = fieldList; } }
[ "juan.gonzalez.working@gmail.com" ]
juan.gonzalez.working@gmail.com
1ac35d49effa5ac0080e27254f2c2ecdb5c60169
d176db251052bfaf481898fec206559775427b6c
/Reto10/app/src/main/java/unal/edu/co/reto10/SelectOnItemSelectedListener.java
c254a6c867e81579115e55546aa0376fb7fce966
[]
no_license
buildtheui/movilesunal20172
2dd164e358c76a6a6b0cb5d524f1e3df4e64aaa7
ab6d915e73a4777b618731eec12a17f6545ca379
refs/heads/master
2022-10-14T06:56:04.833383
2017-11-27T18:10:53
2017-11-27T18:10:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package unal.edu.co.reto10; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; /** * Created by FABIAN on 13/11/2017. */ public class SelectOnItemSelectedListener implements AdapterView.OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
[ "fabtics@gmail.com" ]
fabtics@gmail.com
9d88b24aa1b989258a4ce7df7318f2ed0af9fd41
0c42803ddc58d18d82c894325715cf3d252e872b
/java/src/test/java/Lab5.java
25e11d62fe5301afd7e004b2a04dc89af241994d
[]
no_license
kostya05983/eltex_school
591d34458c160155f424e091d9dad5172d03267c
c76f4ee96455945dd32e516ba087fe670250240b
refs/heads/master
2020-04-25T20:26:10.213019
2018-04-08T14:54:21
2018-04-08T14:54:21
173,050,084
0
0
null
null
null
null
UTF-8
Java
false
false
2,798
java
import Baskets.Credentials; import Baskets.Order; import Baskets.Orders; import Baskets.ShoppingCart; import DataHandler.ManagerOrderJSON; import Goods.BuildingMaterials; import Goods.Paints; import java.util.UUID; public class Lab5 { public static void main(String[] args) { Orders orders=new Orders(); Credentials credentials=new Credentials(); credentials.setId(UUID.randomUUID()); credentials.setName("Граф"); credentials.setSurname("Дуку"); credentials.setPatronymic("Графович"); credentials.setEmail("graph@imperiamail.com"); ShoppingCart shoppingCart=new ShoppingCart(); UUID uuidGraph=credentials.getId(); shoppingCart.add(new BuildingMaterials()); shoppingCart.add(new Paints()); Order order=new Order(); order.setCredentials(credentials); order.setShoppingCart(shoppingCart); orders.addOrder(order); orders.makeDeal(order); Baskets.Credentials credentialsDart=new Baskets.Credentials(); credentialsDart.setId(UUID.randomUUID()); credentialsDart.setName("Энакин"); credentialsDart.setSurname("Скайуокер"); credentialsDart.setPatronymic("Вейдер"); credentialsDart.setEmail("dart@imperialmail.com"); UUID uuidDart=credentialsDart.getId(); ShoppingCart shoppingCart1=new ShoppingCart(); shoppingCart1.add(new BuildingMaterials()); shoppingCart1.add(new Paints()); Order order1=new Order(); order1.setCredentials(credentialsDart); order1.setShoppingCart(shoppingCart); orders.addOrder(order1); orders.makeDeal(order1); // ManagerOrderFile managerOrderFile=new ManagerOrderFile("/home/kostya05983/IdeaProjects/Eltex_School/src/main/resources/test"); // // managerOrderFile.saveAll(orders); // // managerOrderFile.openOutput(); // //// Orders orders1; //// orders1=managerOrderFile.readAll(); // // //orders1.showOrdersList(); // // //System.out.println(managerOrderFile.readById(uuidDart).toString()); // // // orders=managerOrderFile.readAll(); // orders.showOrdersList(); ManagerOrderJSON managerOrderJSON=new ManagerOrderJSON("src/test"); managerOrderJSON.saveAll(orders); managerOrderJSON.closeOutput(); managerOrderJSON.openInput(); System.out.println( managerOrderJSON.readById(uuidDart)); // managerOrderJSON.openBufferedWriter(); // managerOrderJSON.saveById(uuidDart,order); // managerOrderJSON.closeBufferedWriter(); managerOrderJSON.openInput(); // orders=managerOrderJSON.readAll(); // orders.showOrdersList(); } // }
[ "kostya05983@gmail.com" ]
kostya05983@gmail.com
fa386c6298826ba2683be2d36b53afed9c975cf6
bdd294ca5e591e299d449b30e75daad193e5e7c5
/Strategic pattern/SimUDuck_App/ducks/RubberDuck.java
3fba851f264400fff4248d6995fe058dceb78064
[]
no_license
lbches/Design-patterns
b82941205969783d5457d657922f7d021aaa57c9
7e1f845c0fda0b19d13d39dcee47c288bffffd19
refs/heads/master
2021-04-13T02:45:43.859975
2020-03-22T07:15:08
2020-03-22T07:15:08
249,130,264
0
0
null
null
null
null
UTF-8
Java
false
false
446
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 SimUDuck_App.ducks; /** * * @author checos */ public class RubberDuck extends SimUDuck_App.Duck{ public void display(){ //dsplay } public void fly(){ //fly } public void quack(){ //quack } }
[ "37570157+lbches@users.noreply.github.com" ]
37570157+lbches@users.noreply.github.com
c2e9184c44c103c049eabb7ad9675e41200dc986
2dc7e6c88af1762aaa49a12247e2fc067ba7c422
/app/src/main/java/com/zgdj/djframe/adapter/MessageHistoryAdapter.java
ad1d6c071970f828f818518529b4e38f5aa5e791
[]
no_license
jhj24/MyFrame
dd5fde33141b09f74001098d36e3f69e99f16f4c
a205c60b74ee4b133cc270090c954e514184d415
refs/heads/master
2020-06-28T11:21:20.812088
2019-11-06T06:56:04
2019-11-06T06:56:04
200,218,653
0
0
null
null
null
null
UTF-8
Java
false
false
2,228
java
package com.zgdj.djframe.adapter; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.widget.TextView; import com.zgdj.djframe.R; import com.zgdj.djframe.base.rv.BaseViewHolder; import com.zgdj.djframe.base.rv.adapter.SingleAdapter; import com.zgdj.djframe.model.MessageHistoryModel; import com.zgdj.djframe.utils.Utils; import java.util.List; /** * description: 消息历史列表Adapter * author: Created by Mr.Zhang on 2018/6/26 */ public class MessageHistoryAdapter extends SingleAdapter<MessageHistoryModel.DataBean> { public MessageHistoryAdapter(List<MessageHistoryModel.DataBean> list, int layoutId) { super(list, layoutId); } @Override protected void bind(BaseViewHolder holder, MessageHistoryModel.DataBean data) { TextView user = holder.getView(R.id.item_message_history_tv_user); //审批人 TextView date = holder.getView(R.id.item_message_history_tv_date); //审批日期 TextView result = holder.getView(R.id.item_message_history_tv_result); //审批结果 TextView suggest = holder.getView(R.id.item_message_history_tv_suggestion); //审批意见 // set if (!TextUtils.isEmpty(data.getNickname())) user.setText(data.getNickname()); if (!TextUtils.isEmpty(data.getCreate_time())) { long time = Long.valueOf(data.getCreate_time()); date.setText(Utils.getTime2Date(time)); } if (!TextUtils.isEmpty(data.getResult())) { result.setText(data.getResult()); //设置状态颜色 if (data.getResult().equals("未通过")) { result.setTextColor(ContextCompat.getColor(mContext, R.color.red)); } else if (data.getResult().equals("待提交")) { result.setTextColor(ContextCompat.getColor(mContext, R.color.qualified)); } else if (data.getResult().equals("完成")) { result.setTextColor(ContextCompat.getColor(mContext, R.color.bids_4)); } } if (!TextUtils.isEmpty(data.getMark())) { suggest.setText(data.getMark()); } else { suggest.setText("无"); } } }
[ "1406929846@qq.com" ]
1406929846@qq.com
1fd36a78a92daacaa4995d5f6139fd60297a8a28
960a75c2dca3f4dcbe94c346877ae173375ca216
/ExCELIenceAnimator/src/cs3500/animator/model/AnimatableShape.java
4608253f2abdad21245a3a1d28ba984faecc2d48
[]
no_license
anirudh723/ExCELIence-Animation-Project
47a519c2d41fcd92deb8aef89b58192ef97df845
fd3901e0d7071c5265116f4f918c03cedd241dd5
refs/heads/master
2020-06-01T05:51:43.361142
2019-11-07T19:51:53
2019-11-07T19:51:53
190,664,858
0
0
null
null
null
null
UTF-8
Java
false
false
4,086
java
package cs3500.animator.model; import java.awt.Dimension; import java.awt.Color; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; /** * Represents an Animatable Shape, which is a shape with a list of motions for that particular * shape. These shapes are more applicable to the controller and view. We thought it was a good idea * to have just a normal shape, which is the AbstractShape class, and then an Animatable shape, * which is that shape but with it's motions. */ public class AnimatableShape implements IAnimatableShape { private IShape shape; private ArrayList<IMotion> motions; /** * Constructs an Animatable shape. * * @param shape the Shape. * @param motions the list of Motions that correspond with the given Shape. * @throws IllegalArgumentException if the given Shape is null. * @throws IllegalArgumentException if the given list of Motions is null. * @throws IllegalArgumentException if the list of motions are not in order by tick. * @throws IllegalArgumentException if motions are not in order by their tick. */ public AnimatableShape(IShape shape, ArrayList<IMotion> motions) { if (shape == null) { throw new IllegalArgumentException("Given Shape is null."); } this.shape = shape; if (motions == null) { throw new IllegalArgumentException("Given list of Motions is null."); } this.motions = motions; this.ensureMotionsInOrder(); } @Override public String getType() { return this.shape.getType(); } @Override public Color getColor() { return this.shape.getColor(); } @Override public List<IMotion> getMotions() { ArrayList<IMotion> copy = new ArrayList<>(); for (IMotion m : this.motions) { copy.add(new Motion(m.getTick(), m.getPosition(), m.getDimension(), m.getColor())); } return copy; } @Override public Point2D getPosition() { return this.shape.getPosition(); } @Override public Dimension getDimension() { return this.shape.getDimension(); } @Override public void addMotionInShape(IMotion m) { if (m == null) { throw new IllegalArgumentException("Given Motion is null"); } if (motions.size() == 0) { motions.add(m); putShapeAtInitialMotion(); return; } else if (motions.size() == 1) { if (motions.get(0).getTick() > m.getTick()) { motions.add(0, m); putShapeAtInitialMotion(); return; } else if (motions.get(0).getTick() < m.getTick()) { motions.add(m); putShapeAtInitialMotion(); return; } } else { for (int i = 0; i < motions.size() - 1; i++) { if (motions.get(i).getTick() == m.getTick()) { System.out.println("Cannot add motion at a tick that already had a motion"); } else if (motions.get(i).getTick() < m.getTick() && motions.get(i + 1).getTick() > m .getTick()) { motions.add(i + 1, m); putShapeAtInitialMotion(); return; } } if (motions.get(motions.size() - 1).getTick() < m.getTick()) { motions.add(m); putShapeAtInitialMotion(); } } } private void putShapeAtInitialMotion() { this.shape.assignInitialMotion(this.motions.get(0).getDimension(), this.motions.get(0).getPosition(), this.motions.get(0).getColor()); } @Override public void removeMotionInShape(IMotion m) { if (m == null) { throw new IllegalArgumentException("Given Motion is null"); } for (int i = 0; i < motions.size(); i++) { if (motions.get(i).getTick() == m.getTick()) { motions.remove(i); return; } } throw new IllegalArgumentException("Trying to remove a Motion that doesn't exist"); } @Override public void ensureMotionsInOrder() { for (int i = 0; i < motions.size() - 1; i++) { if (motions.get(i).getTick() >= motions.get(i + 1).getTick()) { throw new IllegalArgumentException("Motions must be in order by their tick."); } } } }
[ "anirudh.s723@gmail.com" ]
anirudh.s723@gmail.com
e03bab82390f35cb9c27d0de80db14d88ef9fe13
9662b17b14af31d6b0f3e2fba73c275a0fe03c2f
/src/main/java/org/jboss/set/assistant/evaluator/impl/pullrequest/RepositoryEvaluator.java
9b5674c5469eee2e70da48e33a2a5a976cd8f3b4
[]
no_license
jboss-set/assistant
1b99d62776ae0c5c939c5c4b886d92254ee60c37
083143781d19d0ab0a612d67b669d7dcb4dec5da
refs/heads/master
2020-05-21T23:38:27.440476
2019-05-22T02:24:21
2019-05-22T02:24:21
61,617,310
1
4
null
2017-02-22T09:48:09
2016-06-21T08:43:02
Java
UTF-8
Java
false
false
2,901
java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.set.assistant.evaluator.impl.pullrequest; import static org.jboss.set.assistant.Util.convertURLtoURI; import org.jboss.set.aphrodite.Aphrodite; import org.jboss.set.aphrodite.domain.PullRequest; import org.jboss.set.aphrodite.domain.Repository; import org.jboss.set.aphrodite.domain.StreamComponent; import org.jboss.set.aphrodite.spi.NotFoundException; import org.jboss.set.assistant.Constants; import org.jboss.set.assistant.data.LinkData; import org.jboss.set.assistant.evaluator.Evaluator; import org.jboss.set.assistant.evaluator.EvaluatorContext; import java.net.URI; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; /** * @author egonzalez * */ public class RepositoryEvaluator implements Evaluator { private static Logger logger = Logger.getLogger(RepositoryEvaluator.class.getCanonicalName()); @Override public String name() { return "Repository evaluator"; } @Override public void eval(EvaluatorContext context, Map<String, Object> data) { Repository repository = context.getRepository(); Aphrodite aphrodite = context.getAphrodite(); PullRequest pullRequest = context.getPullRequest(); StreamComponent streamComponent; Optional<String> componentName = Optional.of(Constants.NOTAPPLICABLE); URI uri = convertURLtoURI(pullRequest.getRepository().getURL()); if (uri != null) { try { streamComponent = aphrodite.getComponentBy(uri, pullRequest.getCodebase()); componentName = Optional.of(streamComponent.getName()); } catch (NotFoundException e) { logger.log(Level.WARNING, e.getMessage(), e); } data.put("repository", new LinkData(componentName.get(), repository.getURL())); } } }
[ "chaowan@redhat.com" ]
chaowan@redhat.com
e979d9053967dbff4eed64de253143ffef9ce061
699ce67139c5e50e67769b5f96638178ba2d66d5
/calcu/src/calcu/Calcu.java
f54b2f2a449e6f16d67da581e412f78b0a30a6cb
[]
no_license
SnehaTri/CALCULATOR
85da0ccbd9fcf992c6a2a0b75005cba326f4b4c3
a5f181a78d6043e5807bc51a62b0cdc83b6f664d
refs/heads/master
2020-03-19T02:38:28.959370
2018-06-02T01:13:06
2018-06-02T01:13:06
135,646,895
0
0
null
null
null
null
UTF-8
Java
false
false
2,860
java
package calcu; import java.util.Scanner; /** * the main class displays the menu for the user and also takes input the choice of the user and depending on the input given by the user * it moves the pointer to the respective functions defined in the switch statements */ public class Calcu { public static void main(String[] args) { Scanner s=new Scanner(System.in); float number1,number2; int choice; operations c1=new operations(); System.out.println("Enter two numbers"); number1=s.nextFloat(); number2=s.nextFloat(); System.out.println("Enter your choice\n"); System.out.println("1:Add\n"); System.out.println("2:Subtract\n"); System.out.println("3:Multiply\n"); System.out.println("4:Divide\n"); choice=s.nextInt(); switch(choice) { case 1:System.out.print(c1.add(number1,number2)); break; case 2:System.out.print(c1.sub(number1,number2)); break; case 3:System.out.print(c1.mul(number1,number2)); break; case 4:if(number2==0) System.out.println("Cannot divide by zero\n"); else System.out.print(c1.div(number1,number2)); break; default:System.out.println("You entered an invalid choice\n"); } } } /** * * @author Inspi */ class operations { /** * Adds two floating point numbers * @param number1 First operand * @param number2 Second operand * @return Result of addition of two parameter values */ float add(float number1,float number2) { return (number1+number2); } /** * Subtracts two floating point numbers * @param number1 First operand * @param number2 Second operand * @return Result of subtraction of two parameter values */ float sub(float number1,float number2) { return (number1-number2); } /** * Multiplies two floating point numbers * @param number1 First operand * @param number2 Second operand * @return Result of multiplication of two parameter values */ float mul(float number1,float number2) { return (number1*number2); } /** * Divides two floating point numbers * @param number1 First operand * @param number2 Second operand * @return Result of division of two parameter values */ float div(float number1,float number2) { if(number2 == 0) throw new ArithmeticException(); return (number1/number2); } }
[ "Inspi@S3R1" ]
Inspi@S3R1
bda27584d2fd27481014050b233fb45b2ed31d60
2034a5924be653dda6ffbead4ff4cb8996f43a1d
/app/src/main/java/com/jsd/jsdweinxin/app/entity/request/SetPortraitRequest.java
409d19739a8efeeae223790f82bfe86dfcbe2eb0
[]
no_license
jsd01/JSDweixin
fb109d689a5fd8c17714602025e5537d8651c426
e19d3afc24606871f0d7f91a890882a51bc30481
refs/heads/master
2020-03-23T09:15:06.172719
2018-07-19T10:42:37
2018-07-19T10:42:37
141,376,656
0
0
null
null
null
null
UTF-8
Java
false
false
450
java
package com.jsd.jsdweinxin.app.entity.request; /** * Created by AMing on 16/1/13. * Company RongCloud */ public class SetPortraitRequest { private String portraitUri; public SetPortraitRequest(String portraitUri) { this.portraitUri = portraitUri; } public String getPortraitUri() { return portraitUri; } public void setPortraitUri(String portraitUri) { this.portraitUri = portraitUri; } }
[ "jacyffamily@163.com" ]
jacyffamily@163.com
d2f2bec6ee2c048b5adf8816b688d73110b82c2f
8ae4a635a21942ba9d27393060f5bb0011665b56
/app/src/main/java/com/example/studentkits/appInfo.java
83453263a7bc7877333ddebf8bb62ee6b778afa2
[]
no_license
ainshahirahh/Student-Kits
2ef179405f9da620cecd9533a524ad3d83ca5732
24a2b5cbcd322b696094bf66ba1d53c627614bf0
refs/heads/master
2023-06-04T00:05:07.928977
2021-06-21T05:15:33
2021-06-21T05:15:33
378,812,000
0
0
null
null
null
null
UTF-8
Java
false
false
837
java
package com.example.studentkits; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; public class appInfo extends AppCompatActivity { ImageButton infoBack; View view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_info); infoBack = (ImageButton) findViewById(R.id.infoBack); infoBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentLoadNewActivity = new Intent(appInfo.this, MainActivity.class); startActivity(intentLoadNewActivity); } }); } }
[ "ainshahirahh89@gmail.com" ]
ainshahirahh89@gmail.com
55769f0d9004fafffc30b15dcd0061a75f107db8
573d4bd2fbda83e4b067804659446ba75df4b72b
/project/android/MiiReader/app/src/main/java/com/moses/miiread/view/adapter/base/IViewHolder.java
68d067f5abff56046e939cdedd745161218e9c37
[]
no_license
chang1157/openmiiread
d98c1565d4e3b56f12f49e0ea135647b112c2cc2
06e12e0afa38346a6cda7f5dc8eb1451e82ba36b
refs/heads/master
2021-06-18T08:58:38.678645
2021-03-30T13:41:47
2021-03-30T13:41:47
194,989,400
17
2
null
null
null
null
UTF-8
Java
false
false
303
java
package com.moses.miiread.view.adapter.base; import android.view.View; import android.view.ViewGroup; /** * Created by origin on 17-5-17. */ public interface IViewHolder<T> { View createItemView(ViewGroup parent); void initView(); void onBind(T data, int pos); void onClick(); }
[ "234531164@qq.com" ]
234531164@qq.com
b579935ceff1159fd0bb55703c4d63998a2e638b
0c2e6e3d2bf9de720a457c368e702eb016800430
/src/main/java/com/miaoshaproject/dataobject/SequenceDO.java
0ecc8481ddc01a20c8507f37d0ae82090add81e2
[]
no_license
SkironYong/miaosha
903a7fdb0f60370c3ae040e9518bd3877d369108
4da6be09221e9a2460020223fdf6658bba66c5b6
refs/heads/master
2022-07-03T12:05:38.184872
2020-07-04T15:49:49
2020-07-04T15:49:49
244,345,503
1
0
null
2020-03-02T10:42:53
2020-03-02T10:42:52
null
UTF-8
Java
false
false
2,931
java
package com.miaoshaproject.dataobject; public class SequenceDO { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column sequence_info.name * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column sequence_info.current_value * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ private Integer currentValue; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column sequence_info.step * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ private Integer step; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column sequence_info.name * * @return the value of sequence_info.name * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column sequence_info.name * * @param name the value for sequence_info.name * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column sequence_info.current_value * * @return the value of sequence_info.current_value * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public Integer getCurrentValue() { return currentValue; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column sequence_info.current_value * * @param currentValue the value for sequence_info.current_value * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public void setCurrentValue(Integer currentValue) { this.currentValue = currentValue; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column sequence_info.step * * @return the value of sequence_info.step * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public Integer getStep() { return step; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column sequence_info.step * * @param step the value for sequence_info.step * * @mbg.generated Sun Mar 08 16:58:50 GMT+08:00 2020 */ public void setStep(Integer step) { this.step = step; } }
[ "553645886@qq.com" ]
553645886@qq.com
062d889402103de27a925fc4756ce8cd85f7d772
2adcceae12f84a4c16c36f7321636b13bdf19951
/src/com/iweb/servlet/classroom/ClassroomListServlet.java
2541e43465641ccc8bc9a0b8acc1135286cc1ffe
[]
no_license
zhoudalu10/TeachingManagementSystem
edc47e8aa0ae9891900ebc54fb56713cc32c8b39
46f5ed4a863325df056273aa14d4469910ce8199
refs/heads/master
2020-09-06T11:03:17.691872
2019-11-08T07:02:24
2019-11-08T07:02:24
220,406,410
1
0
null
null
null
null
UTF-8
Java
false
false
1,096
java
package com.iweb.servlet.classroom; import java.io.IOException; import java.util.List; 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 com.iweb.DAO.ClassroomDAO; import com.iweb.entity.Classroom; /** * Servlet implementation class ClassroomListServlet */ @WebServlet("/ClassroomListServlet") public class ClassroomListServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); List<Classroom> classrooms = ClassroomDAO.all(); request.setAttribute("classrooms", classrooms); request.getRequestDispatcher("/page/ClassroomList.jsp").forward(request, response); } }
[ "yexin_@Macintosh.local" ]
yexin_@Macintosh.local
abe5d0eee74ba333a94096d7516006d79c9dac27
b1f51f8ba05ad83ecfbd80e6e7f140e70850bf01
/ACE_ERP/src/sales/org/util/entity/ITypeConverter.java
c1fcc4ce99660e69463d1c8f0aa947475f909361
[]
no_license
hyundaimovex-asanwas/asanwas-homepage
27e0ba1ed7b41313069e732f3dc9df20053caddd
75e30546f11258d8b70159cfbe8ee36b18371bd0
refs/heads/master
2023-06-07T03:41:10.170367
2021-07-01T10:23:54
2021-07-01T10:23:54
376,739,168
1
1
null
null
null
null
UHC
Java
false
false
227
java
/* * 작성자 : 이동연 * 파일명 : ITypeConverter.java * 작성일 : 2004. 6. 10. * [파일 설명] * */ package sales.org.util.entity; public interface ITypeConverter { public Object convert(Object objValue); }
[ "86274611+evnmoon@users.noreply.github.com" ]
86274611+evnmoon@users.noreply.github.com
68a1adc5a3c7185746596b4086871867152d6715
089ab3d42d6fde9efb56498e32aa74cec3a16e83
/src/org/lqc/jxc/il/Branch.java
93e7256716f017d763b9b4c0340f2e5b2aba1285
[]
no_license
lqc/jxc
9585f254fa288b246a0dc837259dde6c4bab3cd7
0e3c7cd4ac7956f5ffc2b35002d71fafbb3c96a7
refs/heads/master
2021-09-08T14:59:00.233687
2010-11-03T22:39:41
2010-11-03T22:39:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
843
java
package org.lqc.jxc.il; import org.lqc.jxc.transform.ILVisitor; import org.lqc.jxc.types.Type; public class Branch extends Operation { public Branch(StaticContainer cont, int line, Expression<? extends Type> c, Operation a, Operation b) { super(cont, line); condition = c; opA = a; opB = b; } /** Branch condition. */ protected Expression<? extends Type> condition; /** Branch A. */ protected Operation opA; /** Branch B. */ protected Operation opB; /** * @return the condition */ public Expression<? extends Type> getCondition() { return condition; } /** * @return the opA */ public Operation getOperationA() { return opA; } /** * @return the opB */ public Operation getOperationB() { return opB; } @Override public <T> void visit(ILVisitor<T> v) { v.process(this); } }
[ "lrekucki@gmail.com" ]
lrekucki@gmail.com
86055d884cec4abf9cf87c44560db56a6d65f9a6
4dca9a246c16d6c75b36da660dc6b23152e6651b
/ycf/src/main/java/spring/mapper/MPermissionMxpandMapper.java
53a2ddacb5a08b540fc36b6baea10af9a559972b
[]
no_license
zhoubaojiang/test
5951100fce678226f33e2fabd66aa06e08b7ae02
c206d96c50d890768fe070a486121ca4a4cba976
refs/heads/master
2022-08-21T06:37:12.273564
2019-12-23T11:10:44
2019-12-23T11:10:44
227,252,836
1
0
null
2022-06-29T17:50:29
2019-12-11T01:52:14
Java
UTF-8
Java
false
false
995
java
package spring.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import spring.model.MPermissionMxpand; import spring.model.MPermissionMxpandExample; public interface MPermissionMxpandMapper { long countByExample(MPermissionMxpandExample example); int deleteByExample(MPermissionMxpandExample example); int deleteByPrimaryKey(Long permissionId); int insert(MPermissionMxpand record); int insertSelective(MPermissionMxpand record); List<MPermissionMxpand> selectByExample(MPermissionMxpandExample example); MPermissionMxpand selectByPrimaryKey(Long permissionId); int updateByExampleSelective(@Param("record") MPermissionMxpand record, @Param("example") MPermissionMxpandExample example); int updateByExample(@Param("record") MPermissionMxpand record, @Param("example") MPermissionMxpandExample example); int updateByPrimaryKeySelective(MPermissionMxpand record); int updateByPrimaryKey(MPermissionMxpand record); }
[ "838888921@qq.com" ]
838888921@qq.com
aba0beb49c7768309cd7fb94174d058a7a893f59
91a1799b8270f2ffbe63905107be95c547d3b39e
/java-jvm/src/main/java/pers/nebo/jvm/jstack/JstackStudy.java
985808df20fdcb9006e37585531f91dbbe234884
[]
no_license
nebofeng/java-study
25b0f1eab8622c35d40919b54e639d8cae8769f9
4ff027de0fd39b8f0338dd1a5523fedba67a6cf2
refs/heads/master
2023-08-18T15:18:28.020587
2023-08-07T14:20:22
2023-08-07T14:20:22
138,743,262
4
1
null
2023-01-02T21:54:42
2018-06-26T13:37:19
Java
UTF-8
Java
false
false
319
java
package pers.nebo.jvm.jstack; import java.util.Map; /** * @auther nebofeng * @email nebofeng@gmail.com * @date 2018/10/21 * @des :jstack */ public class JstackStudy { public static void main(String[] args) { Map <Thread, StackTraceElement[]> m= Thread.getAllStackTraces(); // 遍历map } }
[ "nebofeng@gmail.com" ]
nebofeng@gmail.com
841ed5986bf669e41616f3f79dffe6cdb0cf697f
a8f94a595a9ba1e42adc14ec7e616d1896f4854d
/Final/Final/src/pkgfinal/hdgh.java
c22c54ad9cda98bcdce90c1b92a8ac8342329afc
[]
no_license
SETTYRAJESHWARRAO/Crime-Data-mining-
ff38b0703b71b5307e7862d9c5c22fefb4ae0004
23274a9d4929c410d60f39cab1533685ec43f00b
refs/heads/master
2021-05-29T17:56:10.461667
2015-10-26T18:04:36
2015-10-26T18:04:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,100
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pkgfinal; /** * * @author yatharth */ import java.io.*; import java.util.*; class p { String ccode,date,addres,crime,crimed,area,arrest,domes,beat; int x,y,year; float lat; float lon; public p() { this.ccode = ""; this.date = ""; this.addres = ""; this.crime =""; this.crimed = ""; this.area = ""; this.arrest = ""; this.domes = ""; this.beat = ""; this.x = 0; this.y = 0; this.year = 0; this.lat = (float)0.0; this.lon = (float)0.0; } } public class hdgh { class cen { float cx,cy; int size; String initial; } public void db(){ try{ FileInputStream fstream = new FileInputStream("e:/fclean2.csv"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); FileWriter fw = new FileWriter("e:/test/cen.csv"); FileWriter fwinner = new FileWriter("e:/test/core.csv"); int minpnts=50,x,y; String []temp; String input; int i=0,k=0,flag=0,ctr=0; float rad = (float) 0.14; String str; List inner=new LinkedList(); List outer=new LinkedList(); p p5=new p(); p p2=new p(); while ((str = br.readLine()) != null) { try { p p1=new p(); int innerctr=0; ctr++; // System.out.println(ctr); temp=str.split(","); p1.ccode=temp[0]; p1.date =temp[1]; p1.addres= temp[2]; p1.beat =temp[3]; p1.crime= temp[4]; p1.crimed= temp[5]; p1.area= temp[6]; p1.arrest=temp[7]; p1.domes=temp[8]; p1.x=Integer.parseInt(temp[9]); p1.y=Integer.parseInt(temp[10]); p1.year= Integer.parseInt(temp[11]); String lat =temp[12]; String lon =temp[13]; //System.out.println(temp[13]); p1.lat=Float.parseFloat(lat); p1.lon=Float.parseFloat(lon); // System.out.println("new value is : "+p1.lat+p1.lon); int size=inner.size(); /*for(k=0;k<size;k++) { p p2=new p(); p2 = (p)inner.get(k); System.out.println("values"+k+" ,"+p2.lat+p2.lon); }*/ if(i>0) { flag=0; for(int q=0;q<outer.size();q++) { inner=(List)outer.get(q); innerctr=0; for(int e=0;e<inner.size();e++) { p2=(p)inner.get(e); // System.out.println("lat"+p1.lat+p2.lat); float diff= (float) Math.sqrt(Math.pow((p1.lat-p2.lat),2)+Math.pow((p1.lon-p2.lon),2)); // System.out.println("diff"+diff); if(diff<.3) { innerctr++; } else{ break; } } if(innerctr==inner.size()) { inner.add(p1); outer.remove(q); outer.add(inner); flag=1; break; // fwinner.write(temp[0]+","); } } if(flag==0) {System.out.println("f0"); inner=new LinkedList(); inner.add(p1); outer.add(inner); } } else { inner.add(p1); outer.add(inner); // fwinner.write(temp[0]+","); // p5.lon=p1.lon; // p5.lat=p1.lat; i++; } } catch(Exception e) {System.out.println(e); } } for(int q=0;q<outer.size();q++) { inner=(List)outer.get(q); for(int e=0;e<inner.size();e++) { p2=(p)inner.get(e); fwinner.write(p2.ccode+","); } fwinner.write("\n"); } } catch(Exception e) { System.out.println(e); } System.out.println("dbover"); } public static void main(String[] args) throws IOException { hdgh db1 =new hdgh(); db1.db(); // db1.finalcluster(); // db1.read(); // db1.readout(); // db1.plotl(); //db1.plotvialink(); } }
[ "yatharth.sharma@gmail.com" ]
yatharth.sharma@gmail.com
34f9adbd2e64219a61f9ccd1610356437ca2ccf0
f5b7c557f80d899fa482fe208bdfb858fe790672
/shoppingcartUpdated/src/main/java/com/vw/runtime/VWSwiftHelper.java
6e32b96246df35e16e0ed9beafbcb80e14e80f00
[]
no_license
sharath079/HTS
dcd0c52c18604ab5b0beb4adaff27775c6a0c23d
b6f6fb095c92ae00fb9bc11a06397b41ecfc51b3
refs/heads/master
2023-03-23T14:29:00.463956
2021-03-17T09:05:18
2021-03-17T09:05:18
330,579,188
0
0
null
null
null
null
UTF-8
Java
false
false
16,496
java
package com.vw.runtime; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import com.google.gson.JsonObject; //import com.re.bean.MessageQueue; //import com.shoppingcart.controller.forms.base.MessageQueueLabel; /** * * @author Srikanth Brahmadevara: Harivara Technology Solutions, CODE GENERATED */ @SuppressWarnings( {"unchecked", "rawtypes","unused"}) public class VWSwiftHelper extends MessageGenieController { private static final String SWIFT_MESSAGE_END = "-}"; private static final String EMPTY_STRING = ""; private static final String FORWARD_SLASH = "/"; private static final String SWIFT_TAG79 = ":79:"; //private static final String SWIFT_TAG79_RIGHT_COLON = "79:"; private static final String SWIFT_FIELD_SEPARATOR = ":"; private static final String SWIFT_DECIMAL_SEPARATOR = ","; private static final String DECIMAL_SEPARATOR = "."; String sFileContent = ""; String sParseErr = ""; String[] sParams = null; public VWSwiftHelper(Session session) { super(session); debugCode("Out VWSwiftHelper Constructor : With Session parameter"); } public VWSwiftHelper() { super(); debugCode("Out VWSwiftHelper Constructor : With Session parameter"); } public String getParseErrors() { return sParseErr; } public void setFileContent(String sContent) { System.out.println("*****************BEGIN*****************"); this.sFileContent = sContent; System.out.println("*****************END*****************"); } public String getFileContent() { return this.sFileContent; } public String getTagValue(String sEntityName, String sTag, String isCompositeField, String sTotalParts, String sPart, String sBIndex, String sEIndex, String sSeparator, String isMandatoryField) { if (!isExists(sTag)) { return EMPTY_STRING; } String sTagValue = EMPTY_STRING; sTag = handleHeaderTags(sTag); sTagValue = handleSingleField(sFileContent, sTag); sTagValue = handleCompositeField(sEntityName, sTag, isCompositeField, sTotalParts, sPart, sBIndex, sEIndex, sSeparator, isMandatoryField, sTagValue); return sTagValue; } public String handleHeaderTags(String sTag) { if(sTag.matches(":1:")) { return "{1:"; } if(sTag.matches(":2:")) { return "{2:"; } if(sTag.matches(":5:")) { return "{5:"; } if(sTag.matches(":6:")) { return "{6:"; } return sTag; } public void setTagValuetoSwiftMessage(String sTag,String sTagValue, String isCompositeField, String sTotalParts, String sPart, String sBIndex, String sEIndex, String sSeparator) { if(!isExists(sTag)) { return; } if (!isExists(sTagValue)) { if(!Boolean.valueOf(isCompositeField)) { return; } } if (StringUtils.contains(sFileContent,sTag)) { String sCurrentTagValue = handleSingleField(sFileContent,sTag); String sCurrentTagBackup = sCurrentTagValue; if (Boolean.valueOf(isCompositeField)) { if (isExists(sSeparator)) { if (sSeparator.matches(NEW_LINE_CHAR)) { sCurrentTagValue = sCurrentTagValue + NEW_LINE_CHAR + sTagValue; } if (sSeparator.matches(FORWARD_SLASH)) { sCurrentTagValue = sCurrentTagValue + FORWARD_SLASH + sTagValue; } }else { sCurrentTagValue = StringUtils.overlay(sCurrentTagValue, sTagValue, Integer.parseInt(sBIndex), Integer.parseInt(sBIndex)+ Integer.parseInt(sEIndex)); } } sFileContent = StringUtils.replace(sFileContent, sTag + sCurrentTagBackup, sTag + sCurrentTagValue); }else { //sFileContent = sFileContent + sTag + sTagValue + NEW_LINE_CHAR; String sTagNewLine = NEW_LINE_CHAR; if(!isExists(sTagValue)) { if(!Boolean.valueOf(isCompositeField)) { sTagNewLine = ""; } } sFileContent = sFileContent + sTag + sTagValue + sTagNewLine; } handleLastCompositeField(sTag,isCompositeField,sTotalParts,sPart,sSeparator); } private void handleLastCompositeField(String sTag, String isCompositeField, String sTotalParts, String sPart, String sSeparator) { if (Boolean.valueOf(isCompositeField)) { if ((sTotalParts==sPart) || (sSeparator.matches("@REPEAT@"))) // NG: the last part of a subfields is being addressed here { String sAllPartsOfTagBackup = handleSingleFieldCore(sFileContent, sTag, false); if ((isExists(sSeparator) && (!sSeparator.matches("@REPEAT@")))) { String sAllPartsOfTagAfterTrim = StringUtils.replaceChars(sAllPartsOfTagBackup, sSeparator,""); if (!isExists(sAllPartsOfTagAfterTrim)) { sFileContent = StringUtils.replace(sFileContent, sTag + sAllPartsOfTagBackup,""); }else { if (sTag.contains(":39A:")) { String s=""; } String sAllPartsOfTag =stripRight(sAllPartsOfTagBackup, sSeparator); if(isExists(sAllPartsOfTag)) { sFileContent = StringUtils.replace(sFileContent, sTag + sAllPartsOfTagBackup, sTag + sAllPartsOfTag); }else { sFileContent = StringUtils.replace(sFileContent, sTag + sAllPartsOfTagBackup, ""); } } }else { if (sAllPartsOfTagBackup.matches(NEW_LINE_CHAR)) { sFileContent = StringUtils.replace(sFileContent, sTag + sAllPartsOfTagBackup,""); } } } } } private String stripRight(String sStr, String sSeparator) { String sAfterTrimString = ""; if (sSeparator.contains(NEW_LINE_CHAR)) { sAfterTrimString = StringUtils.replace(sStr, NEW_LINE_CHAR, "@NEW@"); sAfterTrimString = sStr.replaceAll(sSeparator + "+$", ""); sAfterTrimString = sAfterTrimString + NEW_LINE_CHAR; }else { String[] allLines = sStr.split("\\" + NEW_LINE_CHAR,-1); for(String item: allLines) { String sTemp = item; sTemp = StringUtils.removeEnd(sTemp," "); sTemp = sTemp.replaceAll(sSeparator + "+$", ""); if(isExists(sAfterTrimString)) { sAfterTrimString = sAfterTrimString + NEW_LINE_CHAR + sTemp; }else { sAfterTrimString = sTemp ; } } } return sAfterTrimString; } @SuppressWarnings("deprecation") private String handleCompositeField(String sEntityName, String sTag, String isCompositeField, String sTotalParts, String sPart, String sBIndex, String sEIndex, String sSeparator, String isMandatoryField, String sTagValue) { if (Boolean.valueOf(isCompositeField)) { Integer iParts = Integer.parseInt(sPart); Integer iTotalParts = Integer.parseInt(sTotalParts); if (isExists(sSeparator)) { if (sSeparator.contains("@REPEAT@")) { if (sPart.contains("0")) { int maxTimes = StringUtils.countMatches(sFileContent, sTag); String[] sAllRepeatTags = StringUtils.substringsBetween(sFileContent, sTag , SWIFT_FIELD_SEPARATOR); if (isExists(sAllRepeatTags)) { int maxArrayTimes = sAllRepeatTags.length; if (maxTimes > iTotalParts) { sParseErr = sParseErr + handleErrors("C71", sTag, sTotalParts); }else { sTagValue = StringUtils.concatenate(sAllRepeatTags); if (maxTimes != maxArrayTimes) { String sRemaining = StringUtils.substringAfter(sFileContent, sAllRepeatTags[maxArrayTimes - 1]); sTagValue = sTagValue + handleSingleField(sRemaining, sTag); } } } //} } } else { //Changed from StringUtils to regex to get blank values also in the array String sTagValues[] = sTagValue.split("\\" + sSeparator,-1); if ((sTagValues.length - 1) >= iParts - 1) { sTagValue = sTagValues[iParts - 1]; sTagValue = extractFixedLength(sTag, sBIndex, sEIndex, sTagValue, iTotalParts, iParts); } else { sTagValue = EMPTY_STRING; } } } else { sTagValue = extractFixedLength(sTag, sBIndex, sEIndex, sTagValue, iTotalParts, iParts); } } return sTagValue; } private String handleSingleField(String sFileContent, String sTag) { return handleSingleFieldCore(sFileContent,sTag,true); } private String handleSingleFieldCore(String sFileContent, String sTag, boolean bRemoveUnwanted) { String sTagValue = EMPTY_STRING; sTagValue = StringUtils.substringBetween(sFileContent, sTag, SWIFT_FIELD_SEPARATOR); // Begin Last Field Handling if (!isExists(sTagValue)) { if (isExists(sFileContent,sTag)) { sTagValue = StringUtils.substringBetween(sFileContent, sTag, SWIFT_MESSAGE_END); } } if (StringUtils.contains(sTagValue, SWIFT_MESSAGE_END)) { sTagValue = StringUtils.substringBefore(sTagValue,SWIFT_MESSAGE_END); } String sRemaining = EMPTY_STRING; Integer iCount = 0; if (!isExists(sTagValue)) { sRemaining = StringUtils.substringAfter(sFileContent, sTag); iCount = StringUtils.countMatches(sRemaining, SWIFT_FIELD_SEPARATOR); if (iCount == 0) { sTagValue = sRemaining; } } // End Last Field Handling if (bRemoveUnwanted) { sTagValue = removeUnwanted(sTagValue); } return sTagValue; } private String extractFixedLength(String sTag, String sBIndex, String sEIndex, String sTagValue, Integer iTotalParts, Integer iParts) { if (!sBIndex.contains("0") || !sEIndex.contains("0")) { if (isExists(sTagValue)) { String sPartValue = EMPTY_STRING; String sCleanTagValue = StringUtils.replace(sTagValue,FORWARD_SLASH,EMPTY_STRING); Integer iBIndex = Integer.parseInt(sBIndex); Integer iEIndex = Integer.parseInt(sEIndex); sPartValue = StringUtils.mid(sCleanTagValue , iBIndex, iEIndex); sCleanTagValue = EMPTY_STRING; if (isExists(sPartValue)) { sTagValue = sPartValue; }else { sTagValue=""; } if (iTotalParts == iParts) // Length Handling { if (sTagValue.length() > (iEIndex)) { sParseErr = sParseErr + handleErrors("SWIFT_FIELD_LENGTH_ERROR", sTag, sTagValue); } } } } return sTagValue; } // Begin Data Type Handling public Byte getValue(Byte bByte, String sTag, String str) { if (isExists(str)) { return Byte.parseByte(str); } return bByte; } public Integer getValue(Integer iInteger, String sTag, String str) { try { str = removeUnwanted(str); if (isExists(str)) { return Integer.parseInt(str); } } catch (Exception e) { sParseErr = sParseErr + handleErrors("VWT_INTEGER", sTag, str); } return 0; } public String getValue(Integer iInteger) { if (isExists(iInteger)) { return iInteger.toString(); } return ""; } public Long getValue(Long lLong, String sTag, String str) { try { if (isExists(str)) { str = removeUnwanted(str); return Long.parseLong(str); } } catch (Exception e) { sParseErr = sParseErr + handleErrors("VWT_LONG", sTag, str); } return (long) 0; } public String getValue(Long lLong) { if (isExists(lLong)) { return lLong.toString(); } return ""; } public Float getValue(Float fFloat, String sTag, String str) { try { if (isExists(str)) { str = removeUnwanted(str); return Float.parseFloat(str); } } catch (Exception e) { sParseErr = sParseErr + handleErrors("VWT_FLOAT", sTag, str); } return (float) 0; } public String getValue(Float fFloat) { if (isExists(fFloat)) { return StringUtils.replace(fFloat.toString(),DECIMAL_SEPARATOR,SWIFT_DECIMAL_SEPARATOR); } return ""; } public Double getValue(Double dDouble, String sTag, String str) { try { if (isExists(str)) { if (!str.contains(SWIFT_DECIMAL_SEPARATOR)) { throw new Exception(); } str = removeUnwanted(str); str = StringUtils.replace(str, SWIFT_DECIMAL_SEPARATOR, DECIMAL_SEPARATOR); return Double.parseDouble(str); } } catch (Exception e) { sParseErr = sParseErr + handleErrors("T43", sTag, str); } return 0.0; } public String getValue(Double dDouble) { if (isExists(dDouble)) { return StringUtils.replace(dDouble.toString(),DECIMAL_SEPARATOR,SWIFT_DECIMAL_SEPARATOR); } return ""; } public BigDecimal getValue(BigDecimal dbBigDecimal, String sTag, String str) { if (isExists(str)) { try { if (!str.contains(",")) { throw new Exception(); } dbBigDecimal = convertSwiftAmtToBigDecimal(str); } catch (Exception e) { sParseErr = sParseErr + handleErrors("T40", sTag, str); } } return dbBigDecimal; } public String getValue(BigDecimal dbBigDecimal) { if (isExists(dbBigDecimal)) { String sAmtinString = dbBigDecimal.toPlainString(); sAmtinString = StringUtils.replace(sAmtinString,DECIMAL_SEPARATOR,SWIFT_DECIMAL_SEPARATOR); String sAfterDecimal = StringUtils.substringAfter(sAmtinString,SWIFT_DECIMAL_SEPARATOR); String sAfterDecimalNew = StringUtils.replace(sAfterDecimal,"0",""); return StringUtils.replace(sAmtinString,sAfterDecimal,sAfterDecimalNew); } return ""; } public Boolean getValue(Boolean bBoolean, String sTag, String str) { try { if (isExists(str)) { str = removeUnwanted(str); return Boolean.parseBoolean(str); } } catch (Exception e) { sParseErr = sParseErr + handleErrors("VW_BOOLEAN", sTag, str); } return bBoolean; } public String getValue(Boolean bBoolean) { if (isExists(bBoolean)) { return bBoolean.toString(); } return ""; } public String getValue(String bString, String sTag, String str) { if (isExists(str)) { str = removeUnwanted(str); return str; } return EMPTY_STRING; } public String getValue(String bString) { if (isExists(bString)) { return bString; } return ""; } public Date getValue(Date dDate, String sTag, String str) { Date date = dDate; SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); formatter.setLenient(false); if (isExists(str)) { try { str = removeUnwanted(str); date = formatter.parse(str); } catch (ParseException e) { sParseErr = sParseErr + handleErrors("T50", sTag, str); } return date; } return dDate; } public String getValue(Date dDate) { String sDate=""; SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); if (isExists(dDate)) { sDate = formatter.format(dDate); return sDate; } return ""; } public Object getValue(Object bObj, String sTag, String str) { if (isExists(str)) { return Byte.parseByte(str); } return bObj; } // End Data Type Handling protected boolean isExists(String sStr) { if (StringUtils.contains(sStr, NEW_LINE_CHAR)) { return true; } if (sStr != null && sStr.trim().length() > 0) { return true; } else { return false; } } public void doValidations() { } public void doEnrichValues(Boolean doUpdateRules, JsonObject paramsInfoObj) { } public void doAfterEnrichValues() { } public HashMap getSearchParams() { return null; } public String getLabel(String sResponseField) { return null; } public Class<?> setBeanClass() { return this.getClass(); // return MessageQueue.class; } public String getManagedBeanName() { return null; } public void setValues(Object sourceBean, Object targetBean, Boolean bSetAsManagedBean) { } public Class<?> setBeanLabelClass() { return this.getClass(); // return MessageQueueLabel.class; } public String getManagedBeanNameLabel() { return null; } public void setPKValue(Object entityObj) { } public void doAfterSelectRow() { } public void afterCreateTransaction(JsonObject paramsInfoObj) { } public void beforeCreateTransaction(JsonObject paramsInfoObj) { } public void afterCreateTransactionCommitted() { } public void afterUpdateTransaction(JsonObject paramsInfoObj) { } public void beforeUpdateTransaction(JsonObject paramsInfoObj) { } public void afterUpdateTransactionCommitted() { } public String getPkFieldName() { return ""; } @Override public Object getFieldValue(Object entityBean, String sFieldName) { // TODO Auto-generated method stub return null; } @Override public void validateRepeatLine(String sRepeatTagName, String string, int iCurrIndex) { // TODO Auto-generated method stub } @Override protected void setTxnStatus(String sStatus) { // TODO Auto-generated method stub } @Override protected void doEnrichSystemValues(String sAction, String sNextStatus) { // TODO Auto-generated method stub } @Override protected void doEnrichSystemValues(String sAction) { // TODO Auto-generated method stub } }
[ "sharathchandra079@gmail.com" ]
sharathchandra079@gmail.com
3aabed0ab792acff41c36be082ffb10ba58eba83
4d948dbb5d1434883ba6f292b5b41f0e381b45fb
/Demo.java
d7b575d9d7c9f169ad16998ac6029cdfd5c9380a
[]
no_license
akavic/Ca213_stuff
a01c2196b0e59fd02027050d3b648ac6aacc6bab
eecbf27e1c88d4a55eec1a194fad9a7209d31baa
refs/heads/master
2021-04-30T02:46:40.460554
2018-03-10T16:21:29
2018-03-10T16:21:29
121,506,400
0
0
null
null
null
null
UTF-8
Java
false
false
2,968
java
import java.lang.reflect.Array; import java.util.Arrays; /** * Created by bobby_000 on 08/03/2018. */ public class Demo { public static void main(String[] args) { Fan fan = new Fan(); Light light =new Light(); Switch mswitch =new Switch(); mswitch.turnonState(fan); mswitch.turnoffState(fan); int [] arr={9,8,7,6,5,4,3,2,1}; System.out.print(Arrays.toString(arr)); } public static void quickSort(int[] arr, int low, int high) { //https://www.programcreek.com/2012/11/quicksort-array-in-java/ if (arr == null || arr.length == 0) return; if (low >= high) return; // pick the pivot int middle = low + (high - low) / 2; int pivot = arr[middle]; // make left < pivot and right > pivot int i = low, j = high; while (i <= j) { while (arr[i] < pivot) { i++; } while (arr[j] > pivot) { j--; } if (i <= j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } // recursively sort two sub parts if (low < j) quickSort(arr, low, j); if (high > i) quickSort(arr, i, high); } } /* Date default_date =new Date(); PrintDetails dt = new PrintDetails(); Date comparsion_date = new Date(); while(!Console.EndOfFile()) { comparsion_date.get(); default_date.latestDate(comparsion_date); } default_date.put(); */ /*Point p1=new Point(); Point p2 = new Point(); p1.get(); p2.get(); p1.midpoint(p2).midpoint_print(); */ /*Period p1=new Period(); Period p2=new Period(); p1.get(); p2.get(); if(p1.overlaps(p2)) System.out.print("They overlaps"); else System.out.print("doesn't overlap"); */ /* Rational r1 = new Rational(13,3); Rational r2 = new Rational(4,6); Rational r3 = new Rational(2,3); System.out.println(r1 + "+" + r2 + " = " + r1.add(r2)); System.out.println(r1 + "-" + r2 + " = " + r1.subtract(r2)); System.out.println(r1 + "*" + r2 + " = " + r1.multiply(r2)); System.out.println(r1 + " / " + r2 + " = " + r1.divide(r2)); System.out.println(r2 + "==" + r3 + " = " + r2.equals(r3)); // todo may need to create own equal method System.out.println(r1 + " as double = " + r1.doubleValue()); */ /* Pair<String,Integer> phoneNumber = new Pair<>("Bill's number", 1324); System.out.println(phoneNumber); Pair<Double,Double> point = new Pair<>(3.14, 2.32); System.out.println(point);*/
[ "vakinla.va@gmail.com" ]
vakinla.va@gmail.com
42658802409fbee8e80a4f39cce50a9fee7e6c53
b493134139615c7480cfded00b9840288469ec7b
/SimplePath/SimulationFramework/Marker.java
3dfbdfc1ba72069450a63dc5427e8f41cbe83c65
[ "MIT" ]
permissive
Hranz/Projects
6f8eca5fc1276465e72fee492e23b833cf5b6ace
d1ededcf9727f89da0eb0a53c98f1149cc963855
refs/heads/master
2016-09-05T19:20:25.489727
2014-05-10T04:01:38
2014-05-10T04:01:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,656
java
/* Marker.java Mike Barnes 8/12/2013 */ package SimulationFramework; // CLASSPATH = ... /282projects/SimulationFrameworkV3 // PATH = ... /282projects/SimulationFrameworkV3/SimulationFramework import java.awt.*; import java.util.ArrayList; import java.util.Iterator; /** Markers are used to represent position on the canvas that Bot's can use for path finding. In algorithm simulation Markers can be either temporary or permanent. Permanent markers are only cleared when the simulation's "Reset" option is selected. Temporary markers are cleared when the simulation's "Clear" option is selected. Marker's size has a default value of 2. Can be changed with int getSize() and void setSize(int size). <p> Marker UML class diagram <p> <Img align left src = "../../UML/Marker.png"> @since 8/12/2013 @version 3.0 @author G. M. Barnes */ public class Marker implements Drawable { /** marker's position */ private Point point; /** marker's color */ private Color color; /** marker's size */ private int size; /** marker's label */ private String label; /** when true Marker's label is drawn */ private boolean drawLabel; /** Make a Marker @param x marker's horizontal screen position @param y marker's vertical screen position @param colorValue marker's color */ public Marker(int x, int y, Color colorValue) { point = new Point(x, y); color = colorValue; size = 2; drawLabel = false; } /** Make a Marker @param x marker's horizontal screen position @param y marker's vertical screen position @param colorValue marker's color @param ptSize marker's size */ public Marker(int x, int y, Color colorValue, int ptSize) { point = new Point(x, y); color = colorValue; size = ptSize; drawLabel = false; } /** Make a Marker @param pt marker's horizontal screen position @param colorValue marker's color */ public Marker(Point pt, Color colorValue) { point = pt; color = colorValue; size = 2; drawLabel = false; } /** Make a Marker @param pt marker's horizontal screen position @param colorValue marker's color @param ptSize marker's size */ public Marker(Point pt, Color colorValue, int ptSize) { point = pt; color = colorValue; size = ptSize; drawLabel = false; } /** Make a Marker, copy constructor @param m Marker to copy values for new Marker from */ public Marker(Marker m) { point = m.getPoint(); color = m.getColor(); size = m.getSize(); drawLabel = false; } /** @return the marker's color */ public Color getColor() { return color; } /** @return the marker's label */ public String getLabel() { return label; } /** @return the marker's position */ public Point getPoint() { return point; } /** @return the marker's size */ public int getSize() { return size; } /** change marker's color */ public void setColor(Color c) { color = c; } /** change marker's label */ public void setLabel(String l) { drawLabel = true; label = l; } /** change marker's size */ public void setSize(int s) { size = s; } /** Draw the marker on the simulation's canvas */ public void draw(Graphics g) { Color tColor; tColor = g.getColor(); // save exisiting color g.setColor(color); g.fillRect((int) point.getX() - size, (int) point.getY() - size, 2 * size, 2 * size); g.setColor(tColor); // restore previous color if (drawLabel) g.drawString(label, (int) point.getX() - 2 * size, (int) point.getY() - 2 * size); } }
[ "larson.kristoffert@gmail.com" ]
larson.kristoffert@gmail.com
e47f93c419902f030a248a9815b88983b7171462
81463ceab90dd9ab0ab6c5dc5e35cb7d282fae37
/storyline/src/main/java/com/example/lovestory/util/test/SumTowDigital.java
c606cb6394c49f7d87a3dda2fee8e799ff39a4d0
[]
no_license
Tobeawiser/studyInterstingThings
225038d8caec297d08cd440139cbf2076ff55c83
104550aa0b662e2dde0e03c1fea2b63bec3f43aa
refs/heads/main
2023-07-06T19:59:32.305120
2023-06-26T07:52:51
2023-06-26T07:52:51
343,432,581
0
1
null
null
null
null
UTF-8
Java
false
false
1,548
java
package com.example.lovestory.util.test; public class SumTowDigital { public static void main(String[] args) { } //Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode newNode = new ListNode(); boolean flagAdd = false; int value = l1.val + l2.val; if (value >= 10) { value = value % 10; flagAdd = true; } else { flagAdd = false; } newNode.val = value; while (l1.next != null && l2.next != null) { value = l1.next.val + l2.next.val; if (value >= 10) { value = value % 10; flagAdd = true; } else { flagAdd = false; } if (flagAdd) { newNode.next.val = value + 1; } else { newNode.next.val = value; } } if (l1.next == null) { if (flagAdd) { newNode.next.val = value + 1; } } return new ListNode(); } } }
[ "473255514@qq.com" ]
473255514@qq.com
863600db475f9907941c61a932d2eb5079d81862
2f6a1bed14f36780aba30716cfa1b53e302c047c
/app/src/main/java/com/waymaps/util/MapProvider.java
eba2f660424f797a0a40a4796764726cbc251050
[]
no_license
stashes/WayMaps
0c7aedb7da493b95e1c929b6f3b4487cb7ccdbf8
5b318765223d4634e84057daa6dd670f5db3d0b5
refs/heads/master
2021-04-27T10:02:23.465991
2018-06-30T14:06:57
2018-06-30T14:06:57
122,518,272
0
0
null
null
null
null
UTF-8
Java
false
false
102
java
package com.waymaps.util; public enum MapProvider { Google,OSM,GOOGLE_HYBRID, GOOGLE_SATELLITE }
[ "stas.hess@gmail.com" ]
stas.hess@gmail.com
45b000e380b37cb331d2f3e074cbad4123ee3ce8
bfc676cb91b28b07940827b68991884c4308c94a
/backend/delivery/src/main/java/com/sddeliver/delivery/repositories/ProductRepository.java
6e9c4aa1a2fa56db343ec2125bfaa057b5e42ec8
[]
no_license
GiovaneOliveiraTI/dsdeliver-sw2
8266a6543481a6303caad630eff8c7e1acc930dc
9effe7577a3efceb5b5ec1713fd3b5da7441c881
refs/heads/main
2023-02-14T19:36:35.144677
2021-01-10T20:19:40
2021-01-10T20:19:40
327,092,004
1
0
null
null
null
null
UTF-8
Java
false
false
303
java
package com.sddeliver.delivery.repositories; import com.sddeliver.delivery.entities.Product; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ProductRepository extends JpaRepository<Product, Long> { List<Product> findAllByOrderByNameAsc(); }
[ "giovaneoliveira_ti@hotmail.com" ]
giovaneoliveira_ti@hotmail.com
62040ebd9c0d5770f35d93ceea85a6f5405f79d4
8113295ad201cefc33299fe663f51117b5365467
/spring-boot-ehCache-CacheManager/src/test/java/com/javaResource/ehcache/api/SpringBootEhCacheCacheManagerApplicationTests.java
dd0731f03f1691102d974da2b9cfe0c7bf3bcf04
[]
no_license
rama292087/springboot-microservices
f90e8d6ad519fabce03194e7185ecaaf42f529be
d057d630e98819b0ff6c721728ade3a1c77109ef
refs/heads/main
2022-12-27T12:28:52.416402
2020-10-12T17:45:09
2020-10-12T17:45:09
303,455,092
0
0
null
null
null
null
UTF-8
Java
false
false
243
java
package com.javaResource.ehcache.api; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringBootEhCacheCacheManagerApplicationTests { @Test void contextLoads() { } }
[ "reddy@LAPTOP-7M8NVEQ2" ]
reddy@LAPTOP-7M8NVEQ2
b4a1a63efc0d149974a3a1783ec297bec8865eec
80a87ea063eb609d9faab6a69a2aa14ed12319c4
/app/src/main/java/com/example/administrator/chaoshen/bean/PayOrderSuccess.java
29f2e77a10438ccb7c5e54c39ad218d4987bb489
[]
no_license
tunder19/Chaoshen814
12d0fe04054461991bb6ecfd4bb5c25cbb9c815c
75f37f3f54d73e8522b24e00944e9b5c178b06c4
refs/heads/master
2020-03-28T20:17:33.760025
2018-09-17T01:57:54
2018-09-17T01:57:54
149,056,554
0
0
null
null
null
null
UTF-8
Java
false
false
83
java
package com.example.administrator.chaoshen.bean; public class PayOrderSuccess { }
[ "381120944.com" ]
381120944.com
32c1dd54591becd6bf2ad0bcf468b305893000a2
6c9aac925a043b3e76083f107f9147e011ff5413
/src/main/java/com/blog/springboot/util/Data.java
a0b81b74287a10b8ad8c72255dd9cfe171b64a65
[]
no_license
wyf2215087636/myBlog
d7a90e553a758e130b1c92be10da8d2dd4c39e6c
446bc6ceb2a502206492849c88d7e0e8549a3634
refs/heads/master
2020-04-15T15:59:45.592715
2019-03-10T13:15:32
2019-03-10T13:15:32
164,814,651
1
0
null
null
null
null
UTF-8
Java
false
false
556
java
package com.blog.springboot.util; public class Data { private int code; private String message; public Data(int code, String message) { super(); this.code = code; this.message = message; } public void init(int code, String message) { this.code = code; this.message = message; } public Data() { super(); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
[ "2215087636@qq.com" ]
2215087636@qq.com
a49bd0b428f2710534047171df4c479d67f74337
fc52c45a05977e69d8decd028b3f2755c3f29ad0
/MyApp/app/src/main/java/com/example/akshaygudi/myapp/CustomSpinnerListener.java
c7318c15730ccec3a52751cedf9830da61fa9142
[]
no_license
AkshayGudi/APPS
432b11b6743c7ec43e79374217c418c3418b3b0f
80acc55d35ee40cf8988367b196e243d64da902c
refs/heads/master
2021-04-26T22:20:35.462754
2018-03-06T12:29:18
2018-03-06T12:29:18
124,075,088
0
0
null
null
null
null
UTF-8
Java
false
false
661
java
package com.example.akshaygudi.myapp; import android.content.Intent; import android.view.View; import android.widget.AdapterView; /** * Created by Akshay.Gudi on 20-01-2018. */ public class CustomSpinnerListener implements AdapterView.OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getItemAtPosition(position) == "Date" || parent.getItemAtPosition(position) == "Time" ) { Intent newIntent = new Intent(parent.getContext(),MainActivity.class); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
[ "akshaygudi1993@gmail.com" ]
akshaygudi1993@gmail.com
b91ca9a13eef73219556090efdf661e3015b3de6
3ecb8981d81d7211aaa9cf7d4d82d4ce043ab89c
/app/build/generated/source/r/debug/android/support/graphics/drawable/R.java
085c0f139d02fd7c601a2ea00e42b8b82a49e657
[]
no_license
pritul2/Android-ICT-query-generator
c4e24377e8b4a688beacf363e7c239ebfaeec372
98af7c27a76e2a87888a94bdf7ffc1e03c1dd84f
refs/heads/master
2020-04-16T04:01:28.990805
2019-03-27T17:15:07
2019-03-27T17:15:07
165,252,607
0
0
null
null
null
null
UTF-8
Java
false
false
12,121
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.graphics.drawable; public final class R { public static final class attr { public static final int alpha = 0x7f030027; public static final int coordinatorLayoutStyle = 0x7f030064; public static final int font = 0x7f03007f; public static final int fontProviderAuthority = 0x7f030081; public static final int fontProviderCerts = 0x7f030082; public static final int fontProviderFetchStrategy = 0x7f030083; public static final int fontProviderFetchTimeout = 0x7f030084; public static final int fontProviderPackage = 0x7f030085; public static final int fontProviderQuery = 0x7f030086; public static final int fontStyle = 0x7f030087; public static final int fontVariationSettings = 0x7f030088; public static final int fontWeight = 0x7f030089; public static final int keylines = 0x7f030099; public static final int layout_anchor = 0x7f03009d; public static final int layout_anchorGravity = 0x7f03009e; public static final int layout_behavior = 0x7f03009f; public static final int layout_dodgeInsetEdges = 0x7f0300c9; public static final int layout_insetEdge = 0x7f0300d2; public static final int layout_keyline = 0x7f0300d3; public static final int statusBarBackground = 0x7f030112; public static final int ttcIndex = 0x7f030145; } public static final class color { public static final int notification_action_color_filter = 0x7f05003f; public static final int notification_icon_bg_color = 0x7f050040; public static final int ripple_material_light = 0x7f05004a; public static final int secondary_text_default_material_light = 0x7f05004c; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f06004b; public static final int compat_button_inset_vertical_material = 0x7f06004c; public static final int compat_button_padding_horizontal_material = 0x7f06004d; public static final int compat_button_padding_vertical_material = 0x7f06004e; public static final int compat_control_corner_material = 0x7f06004f; public static final int compat_notification_large_icon_max_height = 0x7f060050; public static final int compat_notification_large_icon_max_width = 0x7f060051; public static final int notification_action_icon_size = 0x7f060062; public static final int notification_action_text_size = 0x7f060063; public static final int notification_big_circle_margin = 0x7f060064; public static final int notification_content_margin_start = 0x7f060065; public static final int notification_large_icon_height = 0x7f060066; public static final int notification_large_icon_width = 0x7f060067; public static final int notification_main_column_padding_top = 0x7f060068; public static final int notification_media_narrow_margin = 0x7f060069; public static final int notification_right_icon_size = 0x7f06006a; public static final int notification_right_side_padding_top = 0x7f06006b; public static final int notification_small_icon_background_padding = 0x7f06006c; public static final int notification_small_icon_size_as_large = 0x7f06006d; public static final int notification_subtext_size = 0x7f06006e; public static final int notification_top_pad = 0x7f06006f; public static final int notification_top_pad_large_text = 0x7f060070; } public static final class drawable { public static final int notification_action_background = 0x7f07005e; public static final int notification_bg = 0x7f07005f; public static final int notification_bg_low = 0x7f070060; public static final int notification_bg_low_normal = 0x7f070061; public static final int notification_bg_low_pressed = 0x7f070062; public static final int notification_bg_normal = 0x7f070063; public static final int notification_bg_normal_pressed = 0x7f070064; public static final int notification_icon_background = 0x7f070065; public static final int notification_template_icon_bg = 0x7f070066; public static final int notification_template_icon_low_bg = 0x7f070067; public static final int notification_tile_bg = 0x7f070068; public static final int notify_panel_notification_icon_bg = 0x7f070069; } public static final class id { public static final int action_container = 0x7f09000e; public static final int action_divider = 0x7f090010; public static final int action_image = 0x7f090011; public static final int action_text = 0x7f090017; public static final int actions = 0x7f090018; public static final int async = 0x7f09001e; public static final int blocking = 0x7f090021; public static final int bottom = 0x7f090022; public static final int chronometer = 0x7f09002b; public static final int end = 0x7f09003b; public static final int forever = 0x7f090041; public static final int icon = 0x7f090048; public static final int icon_group = 0x7f090049; public static final int info = 0x7f090051; public static final int italic = 0x7f090056; public static final int left = 0x7f090059; public static final int line1 = 0x7f09005a; public static final int line3 = 0x7f09005b; public static final int none = 0x7f09006d; public static final int normal = 0x7f09006e; public static final int notification_background = 0x7f09006f; public static final int notification_main_column = 0x7f090070; public static final int notification_main_column_container = 0x7f090071; public static final int right = 0x7f09007a; public static final int right_icon = 0x7f09007b; public static final int right_side = 0x7f09007c; public static final int start = 0x7f090098; public static final int tag_transition_group = 0x7f09009c; public static final int tag_unhandled_key_event_manager = 0x7f09009d; public static final int tag_unhandled_key_listeners = 0x7f09009e; public static final int text = 0x7f09009f; public static final int text2 = 0x7f0900a0; public static final int time = 0x7f0900a4; public static final int title = 0x7f0900a5; public static final int top = 0x7f0900a9; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f0a0005; } public static final class layout { public static final int notification_action = 0x7f0b0024; public static final int notification_action_tombstone = 0x7f0b0025; public static final int notification_template_custom_big = 0x7f0b0026; public static final int notification_template_icon_group = 0x7f0b0027; public static final int notification_template_part_chronometer = 0x7f0b0028; public static final int notification_template_part_time = 0x7f0b0029; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f0e0035; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f0f00ee; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f00ef; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f00f0; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f00f1; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f00f2; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f015a; public static final int Widget_Compat_NotificationActionText = 0x7f0f015b; public static final int Widget_Support_CoordinatorLayout = 0x7f0f015c; } public static final class styleable { public static final int[] ColorStateListItem = { 0x010101a5, 0x0101031f, 0x7f030027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] CoordinatorLayout = { 0x7f030099, 0x7f030112 }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x010100b3, 0x7f03009d, 0x7f03009e, 0x7f03009f, 0x7f0300c9, 0x7f0300d2, 0x7f0300d3 }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f030081, 0x7f030082, 0x7f030083, 0x7f030084, 0x7f030085, 0x7f030086 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x0101056f, 0x01010570, 0x7f03007f, 0x7f030087, 0x7f030088, 0x7f030089, 0x7f030145 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x0101019d, 0x0101019e, 0x010101a1, 0x010101a2, 0x010101a3, 0x010101a4, 0x01010201, 0x0101020b, 0x01010510, 0x01010511, 0x01010512, 0x01010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x010101a5, 0x01010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "pritul.dave@gmail.com" ]
pritul.dave@gmail.com
c4d2720dfd414a5f74ca53851e0debb863885b32
9858a4144c15d9805b8bf8d30bb03410f1006175
/freshobackend/src/main/java/com/niit/daoImpl/CategoryDAOImpl.java
5c3798d844d7ffe453deb1e07eb2ed53d5703dd0
[]
no_license
Suriyababu15/Ecommerce-Project
be14c1cf530729d301ff3ed0d4488a499d1288c9
7073fd9fd53d92190f6d01413aa33372f65a7420
refs/heads/master
2022-12-23T13:36:01.405724
2020-03-02T11:12:04
2020-03-02T11:12:04
243,993,444
0
0
null
2022-12-16T12:01:51
2020-02-29T15:31:25
Java
UTF-8
Java
false
false
2,128
java
package com.niit.daoImpl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.niit.dao.CategoryDAO; import com.niit.model.Category; @Repository("CategoryDAO") @Transactional public class CategoryDAOImpl implements CategoryDAO { @Autowired private SessionFactory sessionFactory; public CategoryDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public List<Category> list() { @SuppressWarnings({ "unchecked" }) List<Category> listCategory = (List<Category>) sessionFactory.getCurrentSession().createCriteria(Category.class) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return listCategory; } public Category getByCategoryId(int categoryid) { String hql = "from Category where CategoryId ='" + categoryid + "'"; Query query = (Query) sessionFactory.getCurrentSession().createQuery(hql); @SuppressWarnings("unchecked") List<Category> listCategory = (List<Category>) (query).list(); if (listCategory != null && !listCategory.isEmpty()) { return listCategory.get(0); } return null; } public Category getByCategoryName(String categoryname) { String hql = "from Category where CategoryName ='" + categoryname + "'"; Query query = (Query) sessionFactory.getCurrentSession().createQuery(hql); @SuppressWarnings("unchecked") List<Category> listCategory = (List<Category>) (query).list(); if (listCategory != null && !listCategory.isEmpty()) { return listCategory.get(0); } return null; } public void saveOrUpdate(Category category) { sessionFactory.getCurrentSession().saveOrUpdate(category); } public void delete(int categoryId) { Category categoryToDelete = new Category(); categoryToDelete.setCategoryId(categoryId); sessionFactory.getCurrentSession().delete(categoryToDelete); } }
[ "NEW@DESKTOP-J73QT47" ]
NEW@DESKTOP-J73QT47
8a2bd24105c75b82669292e17c09d7556df223d2
03fdd696927d2e78c2ae08fd6ccf8ba142c22c9e
/threads/RoundRobinScheduler.java
c820567a552c369c70d6b2e444c558b2c27fc252
[ "MIT-Modern-Variant" ]
permissive
MemorySlices/nachos
ab932e118038fdc078b7145d6f162897e8acfe18
36b0cb888db87da0e09a3f97130bee56c1847689
refs/heads/master
2023-02-16T17:08:22.302621
2021-01-16T07:55:33
2021-01-16T07:55:33
308,321,767
1
0
null
2020-11-18T06:24:15
2020-10-29T12:30:23
Java
UTF-8
Java
false
false
2,292
java
package nachos.threads; import nachos.machine.*; import java.util.LinkedList; import java.util.Iterator; /** * A round-robin scheduler tracks waiting threads in FIFO queues, implemented * with linked lists. When a thread begins waiting for access, it is appended * to the end of a list. The next thread to receive access is always the first * thread in the list. This causes access to be given on a first-come * first-serve basis. */ public class RoundRobinScheduler extends Scheduler { /** * Allocate a new round-robin scheduler. */ public RoundRobinScheduler() { } /** * Allocate a new FIFO thread queue. * * @param transferPriority ignored. Round robin schedulers have * no priority. * @return a new FIFO thread queue. */ public ThreadQueue newThreadQueue(boolean transferPriority) { return new FifoQueue(); } private class FifoQueue extends ThreadQueue { /** * Add a thread to the end of the wait queue. * * @param thread the thread to append to the queue. */ public void waitForAccess(KThread thread) { Lib.assertTrue(Machine.interrupt().disabled()); waitQueue.add(thread); } /** * Remove a thread from the beginning of the queue. * * @return the first thread on the queue, or <tt>null</tt> if the * queue is * empty. */ public KThread nextThread() { Lib.assertTrue(Machine.interrupt().disabled()); if (waitQueue.isEmpty()) return null; return (KThread) waitQueue.removeFirst(); } /** * The specified thread has received exclusive access, without using * <tt>waitForAccess()</tt> or <tt>nextThread()</tt>. Assert that no * threads are waiting for access. */ public void acquire(KThread thread) { Lib.assertTrue(Machine.interrupt().disabled()); Lib.assertTrue(waitQueue.isEmpty()); } /** * Print out the contents of the queue. */ public void print() { Lib.assertTrue(Machine.interrupt().disabled()); for (Iterator i=waitQueue.iterator(); i.hasNext(); ) System.out.print((KThread) i.next() + " "); } private LinkedList<KThread> waitQueue = new LinkedList<KThread>(); } }
[ "MemorySlices@foxmail.com" ]
MemorySlices@foxmail.com
2095090a497411be2166d3601c14c1d6ef7aa501
4067562d7f89389d8615359164875a93f146f69f
/src/main/java/com/youotech/service/DevicesRackServices.java
652f841f28d029a0754c14658e4b8813ecec48e9
[]
no_license
582496630/sdjftz
9804e0bed5e018b11952b808ef56b1301f97eac3
a60cb83433164ee6d9db6da96f059ac9967c3852
refs/heads/master
2020-03-10T21:26:00.568339
2018-04-15T09:23:07
2018-04-15T09:23:07
129,594,230
0
0
null
null
null
null
UTF-8
Java
false
false
803
java
package com.youotech.service; import java.util.List; import java.util.Map; import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl; import com.github.pagehelper.PageInfo; import com.youotech.entity.DevicesRackModel; import com.youotech.entity.EngineRoomModel; import com.youotech.entity.dto.TreeDTO; public interface DevicesRackServices { public PageInfo<DevicesRackModel> getDevicesRack(Integer pageNumber, Integer pageSize, Map<String, Object> map); public List<TreeDTO> getDeviceRackLeftTreeInfo(); public List<TreeDTO> getEngineRoomTree(); public EngineRoomModel getEngineRoomOne(Integer roomId); public Integer insertInfo(EngineRoomModel eModel); public Integer deleteEngineRooms(Long[] roomIds); public List<DevicesRackModel> getDevicesRack2(Map<String, Object> map); }
[ "582496630@qq.com" ]
582496630@qq.com
b79ca835a53779d49ca0b405c6014e5e1b9f4096
9bcd755a6d83c04a739f53924d42737dfc2b8b58
/src/server/ClientHandler.java
c92bcd97120db2953e434b11cd167d11b26bb1d0
[]
no_license
DevBorisElkin/ServerForSN
9ef93d096ad23783824917deec0df49cd097e0ee
6567b860aed8b9f1e429894032a3a919535db7d7
refs/heads/master
2020-04-19T06:24:59.909388
2019-03-16T17:34:19
2019-03-16T17:34:19
168,017,076
0
0
null
null
null
null
UTF-8
Java
false
false
7,662
java
package server; import database.Database; import support.Message; import support.UserData; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ClientHandler { private Server server; private Socket socket; private DataOutputStream out; private DataInputStream in; private String nick; String str; List<String> blackList; public String getNick() { return nick; } public ClientHandler(Server server, Socket socket) { try { this.socket = socket; this.server = server; this.in = new DataInputStream(socket.getInputStream()); this.out = new DataOutputStream(socket.getOutputStream()); this.blackList = new ArrayList<>(); new Thread(() -> { try { while (true) { str = in.readUTF(); if(str.startsWith("/check")) { sendMsg("/online"); }else if (str.startsWith("/auth")) { // /auth login72 pass72 String[] tokens = str.split(" "); String newNick = Database.getNickByLoginAndPass(tokens[1], tokens[2]); if (newNick != null) { if (!server.isNickBusy(newNick)) { sendMsg("/auth_ok "+newNick); System.out.println("Пользователь "+newNick+" авторизовался."); nick = newNick; server.subscribe(this); Database.updateUserStatus(newNick,"online"); break; } else { sendMsg("Учетная запись уже используется"); } } else { sendMsg("/wrong login/password"); } }else if(str.startsWith("/add_user")){ String[] tokens = str.split(" "); Database.addUser(tokens[1],tokens[2],tokens[3]); sendMsg("user_was_added"+" "+tokens[1]+" "+tokens[2]+" "+tokens[3]); break; //TODO: доделать регистрацию }else{ sendMsg("/unknown command"); } } while (true) { str = in.readUTF(); if (str.startsWith("/")) { if(str.startsWith("/check")) { sendMsg("/online"); }else if (str.equals("/end")) { out.writeUTF("/serverclosed"); break; } if(str.startsWith("/get_main_info")){ String[] tokens = str.split(" "); List<String>data=Database.getCompleteData(tokens[1]); StringBuilder output= new StringBuilder("/compl_data"); for(String e: data) output.append(e).append(" "); out.writeUTF(output.toString()); } if (str.startsWith("/w ")) { // /w nick3 lsdfhldf sdkfjhsdf wkerhwr String[] tokens = str.split(" ", 3); String m = str.substring(tokens[1].length() + 4); server.sendPersonalMsg(this, tokens[1], tokens[2]); } if (str.startsWith("/blacklist ")) { // /blacklist nick3 String[] tokens = str.split(" "); blackList.add(tokens[1]); sendMsg("Вы добавили пользователя " + tokens[1] + " в черный список"); } if(str.startsWith("/get_all_users")){ List<UserData>list=Database.getAllUsersData(); StringBuilder builder=new StringBuilder("/all_users_data@"); for(UserData a:list){ builder.append(a.toStr()+"@"); } //builder.append(list.get(0).toStr()+"@"); // replace this line with line above sendMsg(builder.toString()); } if(str.startsWith("/online_push ")){ String[] tokens = str.split(" "); Database.updateUserStatus(tokens[1], "online"); } if(str.startsWith("/update_user ")){ String[] tokens = str.split(" "); Database.updateUserData(tokens[1],tokens[2]); } } else { server.broadcastMsg(this, nick + ": " + str); } //System.out.println("Client: " + str); } } catch (IOException e) { //e.printStackTrace(); } finally { Database.updateUserStatus(nick, "offline"); if(nick!=null){ System.out.println("Пользователь "+nick+" отключился"); } System.out.println("Клиент отключился"); sendMsg("offline"); try { in.close(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } server.unsubscribe(this); } }).start(); } catch (Exception e) { //e.printStackTrace(); } } public boolean checkBlackList(String nick) { return blackList.contains(nick); } public void sendMsg(String msg) { try { out.writeUTF(msg); } catch (IOException e) { //e.printStackTrace(); } } public void sendAllData(){ List<UserData>list=Database.getAllUsersData(); StringBuilder builder=new StringBuilder("/all_users_data@"); for(UserData a:list){ builder.append(a.toStr()+"@"); } sendMsg(builder.toString()); } public void sendMessages(){ List<Message>list=Database.getAllMessages(); StringBuilder builder = new StringBuilder("/all_messages"); for(Message a:list){builder.append(a.toString()); } sendMsg(builder.toString()); } }
[ "ea.foreverrr@gmail.com" ]
ea.foreverrr@gmail.com
ff5de9ce47754fa2506dc60be79b311758c9cb2b
8c08005ec63143d7e666ea3ece3bc6a4947f8cfd
/src/application/Controller.java
c010acadf424955b67e8bc164b250aeedecd3953
[]
no_license
Robin-LESAOUT/ET3_TPGraphicalEditor_LE_SAOUT_Robin
0aea193eb0b5c428b4cddbcfc62ee7007e464e27
e26b5cc05df1154d391005ae74887e33ff539c2d
refs/heads/master
2022-11-11T07:49:09.553982
2020-05-29T21:09:54
2020-05-29T21:09:54
275,011,441
0
0
null
null
null
null
ISO-8859-1
Java
false
false
9,168
java
package application; import javafx.scene.control.ToggleGroup; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import java.util.ArrayList; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ColorPicker; import javafx.scene.control.RadioButton; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// PENSEZ A LIRE LE READ ME SVP //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Controller { //Declaration des attributs avec la balise FXML pour faire le lien avec sample.fxml private Modele model; @FXML private RadioButton selectBtn; @FXML private RadioButton ellipseBtn; @FXML private RadioButton rectangleBtn; @FXML private RadioButton lineBtn; @FXML private Button deleteBtn; @FXML private Button cloneBtn; @FXML private ColorPicker colorPicker; @FXML private ToggleGroup group; @FXML private Pane Pane; Rectangle rectangle; Ellipse ellipse; Line ligne; private Color Couleur; //constructeur public Controller() { model= new Modele(this,false,false,false,false); } //fonction qui permet de dessiner un rectangle et l'ajoute à l'Arraylist qui contient tous les rectangles public Rectangle createRectangle(double x,double y, ArrayList<Rectangle> array) { Rectangle r = new Rectangle(x,y,100,100); r.setStroke(Color.BLACK); r.setFill(colorPicker.getValue()); array.add(r); return r; } //Focntion qui permet de redimensionner un rectangle (notamment pour le fait de bouger les figures dans le canvas correctment) public Rectangle setRectangle(Rectangle r, double X, double Y) { r.setWidth(X); r.setHeight(Y); return r; } public Ellipse createEllipse(double x, double y, ArrayList<Ellipse> array) { Ellipse e = new Ellipse(x,y,75,40); e.setStroke(Color.BLACK); e.setFill(colorPicker.getValue()); array.add(e); return e; } public Ellipse setEllipse(Ellipse e, double X, double Y) { e.setRadiusX(X); e.setRadiusY(Y); return e; } public Line createLine (double x,double y,double a, double b) { Line l= new Line(); l.setStartX(a); l.setStartY(b); l.setEndX(x); l.setEndY(y); return l; } //permet d'initialiser correctment les attribts en fonction du RadioButton qui a été cliqué public void clicEllipse(MouseEvent event) { model.setEl(true); model.setRec(false); model.setLi(false); model.setSelect(false); } public void clicRectangle(MouseEvent event) { model.setEl(false); model.setRec(true); model.setLi(false); model.setSelect(false); } public void clicSelect(MouseEvent event) { model.setEl(false); model.setRec(false); model.setLi(false); model.setSelect(true); } public void clicLigne(MouseEvent event) { model.setEl(false); model.setRec(false); model.setLi(true); model.setSelect(false); } public void clicColor(MouseEvent event) { model.setEl(false); model.setRec(false); model.setLi(false); model.setSelect(false); model.setCouleur(colorPicker.getValue()); } public void initialize() { //Creation des array listes qui conserve les figures ArrayList<Rectangle> arrayR = new ArrayList<Rectangle>(); ArrayList<Ellipse> arrayE = new ArrayList<Ellipse>(); ArrayList<Line> arrayL = new ArrayList<Line>(); // Ces arrayLists permettent de conserver les coordonnées ArrayList<Double> listeX = new ArrayList<Double>(); ArrayList<Double> listeY = new ArrayList<Double>(); // Events handlers qui permettent de définir si un radio button a été clique rectangleBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { clicRectangle(event); } }); ellipseBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { clicEllipse(event); } }); lineBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { clicLigne(event); } }); selectBtn.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { clicSelect(event); } }); Pane.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(model.isEl()) { createEllipse(event.getX(),event.getY(),arrayE).addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(model.isSelect()) { boolean sel=false; if(!sel) { arrayE.get(arrayE.size()-1).setRadiusX(arrayE.get(arrayE.size()-1).getRadiusX()+10); arrayE.get(arrayE.size()-1).setRadiusY(arrayE.get(arrayE.size()-1).getRadiusY()+10); arrayE.get(arrayE.size()-1).setFill(colorPicker.getValue()); sel=true; } } } }); Pane.getChildren().add(arrayE.get(arrayE.size()-1)); listeX.add(event.getX()); listeY.add(event.getY()); } else if (model.isRec()) { createRectangle(event.getX(),event.getY(),arrayR).addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(model.isSelect()) { arrayR.get(arrayR.size()-1).setWidth(arrayR.get(arrayR.size()-1).getWidth()+10); arrayR.get(arrayR.size()-1).setHeight(arrayR.get(arrayR.size()-1).getHeight()+10); arrayR.get(arrayR.size()-1).setFill(colorPicker.getValue()); } } }); Pane.getChildren().add(arrayR.get(arrayR.size()-1)); listeX.add(event.getX()); listeY.add(event.getY()); } } }); Pane.addEventHandler(MouseEvent.MOUSE_DRAGGED,new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { if (model.isEl()) { setEllipse(arrayE.get(arrayE.size()-1), event.getX() - (listeX.get(listeX.size()-1)), event.getY() - ((listeY.get(listeY.size()-1)))); arrayE.get(arrayE.size()-1).addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(model.isSelect()) { arrayE.get(arrayE.size()-1).setCenterX(event.getX()); arrayE.get(arrayE.size()-1).setCenterY(event.getY()); } } }); }else if(model.isRec()) { setRectangle(arrayR.get(arrayR.size()-1),event.getX() - (listeX.get(listeX.size()-1)),event.getY()- ((listeY.get(listeY.size()-1)))); arrayR.get(arrayR.size()-1).addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if(model.isSelect()) { arrayR.get(arrayR.size()-1).setX(event.getX()); arrayR.get(arrayR.size()-1).setY(event.getY()); } } }); } } }); //Fonction de deletion des figures (qq bugs) deleteBtn.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { if(model.isSelect()) { Pane.getChildren().remove(arrayE.get(arrayE.size()-1)); Pane.getChildren().remove(arrayR.get(arrayR.size()-1)); } } }); //Tentative de clone button mais problème de out of bonds... /* cloneBtn.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { if(model.isSelect()) { if(model.isRec()) { createRectangle(event.getX()+10, event.getY(), arrayR); Pane.getChildren().add(arrayR.get(arrayR.size()-1)); } else if(model.isEl()) { createEllipse(event.getX()+10, event.getY(), arrayE); Pane.getChildren().add(arrayE.get(arrayE.size()-1)); } } } }); */ // Tentattive d'évènement qui permet de déselectionner le texte en réduisant le feedback /* arrayE.get(arrayE.size()-1).addEventHandler(MouseEvent.MOUSE_RELEASED,new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { if(model.isSelect()) { arrayE.get(arrayE.size()-1).setRadiusX(arrayE.get(arrayE.size()-1).getRadiusX()-10); arrayE.get(arrayE.size()-1).setRadiusY(arrayE.get(arrayE.size()-1).getRadiusY()-10); arrayR.get(arrayR.size()-1).setX(arrayR.get(arrayR.size()-1).getX()-10); arrayR.get(arrayR.size()-1).setY(arrayR.get(arrayR.size()-1).getY()-10); } } }); */ } }
[ "65037222+Robin-LESAOUT@users.noreply.github.com" ]
65037222+Robin-LESAOUT@users.noreply.github.com
6241601f8cabcff15986323e60c89d02e4c7eb5f
11bc2c26ba2c3e8cfb58e5dd7ab430ec0e16a375
/ACORD_PC_JAXB/src/org/acord/standards/pc_surety/acord1/xml/PCBASICWATERCRAFT.java
16395b2c14cd571b5d71047e9e01ee4bcc2448f2
[]
no_license
TimothyDH/neanderthal
b295b3e3401ab403fb89950f354c83f3690fae38
1444b21035e3a846d85ea1bf32638a1e535bca67
refs/heads/master
2021-05-04T10:25:54.675556
2019-09-05T13:49:14
2019-09-05T13:49:14
45,859,747
0
0
null
null
null
null
UTF-8
Java
false
false
1,993
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.02.24 at 10:20:12 PM EST // package org.acord.standards.pc_surety.acord1.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for PCBASICWATERCRAFT complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PCBASICWATERCRAFT"> * &lt;complexContent> * &lt;extension base="{http://www.ACORD.org/standards/PC_Surety/ACORD1/xml/}PCBASICWATERCRAFT_NoID"> * &lt;attribute name="id" type="{http://www.ACORD.org/standards/PC_Surety/ACORD1/xml/}ID" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PCBASICWATERCRAFT") public class PCBASICWATERCRAFT extends PCBASICWATERCRAFTNoID { @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
[ "Bryan.Bringle@3f59fb54-24d0-11df-be41-57e7d1eefd51" ]
Bryan.Bringle@3f59fb54-24d0-11df-be41-57e7d1eefd51
55cedaaa22dc66760064384b90bd5c77dda1b031
065cc40929ae266e422b3c5cd94eec0c440e82cc
/src/main/java/com/guge/spring/beans/entity/Property.java
24f641975de8107555b640fc3d3c863d402cf00b
[]
no_license
yue907/simple-spring
bd7ddd21c52f972be7f66c06a7c9f796cae8ef6e
f76c60b51a170170fffa84e0e6b3bdb39c7f70e3
refs/heads/master
2020-07-01T19:24:09.447171
2017-04-17T07:22:39
2017-04-17T07:22:39
74,261,982
0
0
null
null
null
null
UTF-8
Java
false
false
572
java
package com.guge.spring.beans.entity; /** * Created by google on 17/4/15. */ public class Property { private String name; private String value; private String ref; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } }
[ "songbo.yue@dianping.com" ]
songbo.yue@dianping.com
7553a03c032fa75d7bb12b02a2be5a714776334d
fbe8771084b9333f743a82cc6344d872e917310b
/src/main/java/com/app/model/Category.java
00c857653759722582cb7e2b93a9df3510605ea1
[]
no_license
AlekPrz/ProductShopOrder_App
b0cfc7bdb313d99d34b6844999639a9685ed1817
cfc96f263bc873b003522432aeb047ed7eae554c
refs/heads/master
2021-06-21T12:38:22.775673
2021-03-18T07:23:09
2021-03-18T07:23:09
201,101,442
0
0
null
2020-07-02T00:18:34
2019-08-07T17:55:44
Java
UTF-8
Java
false
false
476
java
package com.app.model; import lombok.*; import javax.persistence.*; import java.util.LinkedHashSet; import java.util.Set; @Data @AllArgsConstructor @NoArgsConstructor @Builder @Entity @Table(name = "categories") public class Category { @Id @GeneratedValue private Long id; //@Column(unique = true) private String name; @ToString.Exclude @EqualsAndHashCode.Exclude @OneToMany(mappedBy = "category") private Set<Product> products; }
[ "alekprzybysz@gmail.com" ]
alekprzybysz@gmail.com
fc4792593f4891c1670f664240ca05c0f62173a2
b522d8db178621ab6ca8b230f4dee9ce1cfbd333
/kdc-tool/token-tool/src/main/java/org/apache/kerby/token/TokenCache.java
51e359344ad151def0b2b5a89c42aea9ee860c75
[ "Apache-2.0" ]
permissive
HazelChen/directory-kerby
491ff75d3e2281ae0096c5b9cd53684548471687
1ca0d98e962825ffd53b3a83019c924673d9b557
refs/heads/master
2021-01-17T21:34:31.337558
2015-03-19T06:13:57
2015-03-19T06:13:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,928
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.kerby.token; import java.io.*; public class TokenCache { private static final String DEFAULT_TOKEN_CACHE_PATH = ".tokenauth"; private static final String TOKEN_CACHE_FILE = ".tokenauth.token"; public static String readToken(String tokenCacheFile) { File cacheFile = null; if (tokenCacheFile != null && ! tokenCacheFile.isEmpty()) { cacheFile = new File(tokenCacheFile); if (!cacheFile.exists()) { throw new RuntimeException("Invalid token cache specified: " + tokenCacheFile); }; } else { cacheFile = getDefaultTokenCache(); if (!cacheFile.exists()) { throw new RuntimeException("No token cache available by default"); }; } String token = null; try { BufferedReader reader = new BufferedReader(new FileReader(cacheFile)); String line = reader.readLine(); reader.close(); if (line != null) { token = line; } } catch (IOException ex) { //NOP } return token; } public static void writeToken(String token) { File cacheFile = getDefaultTokenCache(); try { Writer writer = new FileWriter(cacheFile); writer.write(token.toString()); writer.close(); // sets read-write permissions to owner only cacheFile.setReadable(false, false); cacheFile.setReadable(true, true); cacheFile.setWritable(true, true); } catch (IOException ioe) { // if case of any error we just delete the cache, if user-only // write permissions are not properly set a security exception // is thrown and the file will be deleted. cacheFile.delete(); } } public static File getDefaultTokenCache() { String homeDir = System.getProperty("user.home", DEFAULT_TOKEN_CACHE_PATH); return new File(homeDir, TOKEN_CACHE_FILE); } }
[ "drankye@gmail.com" ]
drankye@gmail.com
d76652905c1d2ceddd95b9d94b0aa751643c27ba
87d1c544100613cfd6a2ef1477bb022859188578
/apps/Mms/src/com/android/mms/ui/ComposeMessageActivity.java
b8aa6db045d147ef4a6dd8a14efec80dc7ea30ce
[ "Apache-2.0" ]
permissive
ioz9/lewa_code_packages
7d2151c3e4838b11dd7566b1d4e8660d9fee8b4c
cbe0eee43c61c9c953df7290e97ccf9e1866cc60
refs/heads/master
2020-03-29T14:06:25.894000
2012-05-08T17:28:56
2012-05-08T17:28:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
152,491
java
/* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import static android.content.res.Configuration.KEYBOARDHIDDEN_NO; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START; import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION; import static com.android.mms.ui.MessageListAdapter.COLUMN_ID; import static com.android.mms.ui.MessageListAdapter.COLUMN_MMS_LOCKED; import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE; import static com.android.mms.ui.MessageListAdapter.PROJECTION; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnClickListener; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SqliteWrapper; import android.drm.mobile1.DrmException; import android.drm.mobile1.DrmRawContent; import android.gesture.Gesture; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import android.gesture.Prediction; import android.graphics.drawable.Drawable; import android.media.CamcorderProfile; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.os.SystemProperties; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.CommonDataKinds.Website; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContactsEntity; import android.provider.DrmStore; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.provider.MediaStore.Video; import android.provider.Telephony.Mms; import android.provider.Telephony.Sms; import android.provider.Settings; import android.telephony.SmsMessage; import android.text.ClipboardManager; import android.text.Editable; import android.text.InputFilter; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.TextKeyListener; import android.text.style.AbsoluteSizeSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.util.Config; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewStub; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnKeyListener; import android.view.inputmethod.InputMethodManager; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.CursorAdapter; import android.widget.TextView; import android.widget.Toast; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.TelephonyProperties; import com.android.mms.LogTag; import com.android.mms.MmsConfig; import com.android.mms.R; import com.android.mms.data.Contact; import com.android.mms.data.ContactList; import com.android.mms.data.Conversation; import com.android.mms.data.WorkingMessage; import com.android.mms.data.WorkingMessage.MessageStatusListener; import com.google.android.mms.ContentType; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.MmsException; import com.google.android.mms.pdu.PduBody; import com.google.android.mms.pdu.PduPart; import com.google.android.mms.pdu.PduPersister; import com.google.android.mms.pdu.SendReq; import com.android.mms.model.SlideModel; import com.android.mms.model.SlideshowModel; import com.android.mms.templates.TemplateGesturesLibrary; import com.android.mms.templates.TemplatesDb; import com.android.mms.transaction.MessagingNotification; import com.android.mms.ui.MessageUtils.ResizeImageResultCallback; import com.android.mms.ui.MessagingPreferenceActivity; import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo; import com.android.mms.util.SendingProgressTokenManager; import com.android.mms.util.SmileyParser; import android.text.InputFilter.LengthFilter; /** * This is the main UI for: * 1. Composing a new message; * 2. Viewing/managing message history of a conversation. * * This activity can handle following parameters from the intent * by which it's launched. * thread_id long Identify the conversation to be viewed. When creating a * new message, this parameter shouldn't be present. * msg_uri Uri The message which should be opened for editing in the editor. * address String The addresses of the recipients in current conversation. * exit_on_sent boolean Exit this activity after the message is sent. */ public class ComposeMessageActivity extends Activity implements View.OnClickListener, TextView.OnEditorActionListener, MessageStatusListener, Contact.UpdateListener, OnGesturePerformedListener { // Phone Goggles block created for compatibility and demonstration to // to external developers private static Method phoneGoggles; static { try { Class phoneGogglesClass = Class.forName("android.util.PhoneGoggles"); phoneGoggles = phoneGogglesClass.getMethod("processCommunication", new Class[] {Context.class, int.class, String[].class, Runnable.class, Runnable.class, int.class, int.class, int.class, int.class, int.class, int.class}); } catch (ClassNotFoundException e) { } catch (SecurityException e) { } catch (NoSuchMethodException e) { } } public static final int REQUEST_CODE_ATTACH_IMAGE = 10; public static final int REQUEST_CODE_TAKE_PICTURE = 11; public static final int REQUEST_CODE_ATTACH_VIDEO = 12; public static final int REQUEST_CODE_TAKE_VIDEO = 13; public static final int REQUEST_CODE_ATTACH_SOUND = 14; public static final int REQUEST_CODE_RECORD_SOUND = 15; public static final int REQUEST_CODE_ATTACH_CONTACT = 16; public static final int REQUEST_CODE_CREATE_SLIDESHOW = 17; public static final int REQUEST_CODE_ECM_EXIT_DIALOG = 18; public static final int REQUEST_CODE_ADD_CONTACT = 19; private static final String TAG = "Mms/compose"; private static final boolean DEBUG = false; private static final boolean TRACE = false; private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV; // Menu ID private static final int MENU_ADD_SUBJECT = 0; private static final int MENU_DELETE_THREAD = 1; private static final int MENU_ADD_ATTACHMENT = 2; private static final int MENU_DISCARD = 3; private static final int MENU_SEND = 4; private static final int MENU_CALL_RECIPIENT = 5; private static final int MENU_CONVERSATION_LIST = 6; // Context menu ID private static final int MENU_VIEW_CONTACT = 12; private static final int MENU_ADD_TO_CONTACTS = 13; private static final int MENU_EDIT_MESSAGE = 14; private static final int MENU_VIEW_SLIDESHOW = 16; private static final int MENU_VIEW_MESSAGE_DETAILS = 17; private static final int MENU_DELETE_MESSAGE = 18; private static final int MENU_SEARCH = 19; private static final int MENU_DELIVERY_REPORT = 20; private static final int MENU_FORWARD_MESSAGE = 21; private static final int MENU_CALL_BACK = 22; private static final int MENU_SEND_EMAIL = 23; private static final int MENU_COPY_MESSAGE_TEXT = 24; private static final int MENU_COPY_TO_SDCARD = 25; private static final int MENU_INSERT_SMILEY = 26; private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27; private static final int MENU_LOCK_MESSAGE = 28; private static final int MENU_UNLOCK_MESSAGE = 29; private static final int MENU_COPY_TO_DRM_PROVIDER = 30; private static final int MENU_INSERT_TEMPLATE = 31; private static final int RECIPIENTS_MAX_LENGTH = 312; private static final int MESSAGE_LIST_QUERY_TOKEN = 9527; private static final int DELETE_MESSAGE_TOKEN = 9700; private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10; private static final long NO_DATE_FOR_DIALOG = -1L; private static final String EXIT_ECM_RESULT = "exit_ecm_result"; private static final int DIALOG_TEMPLATE_SELECT = 0; private static final int DIALOG_TEMPLATE_NOT_AVAILABLE = 1; private ContentResolver mContentResolver; private BackgroundQueryHandler mBackgroundQueryHandler; private Conversation mConversation; // Conversation we are working in private boolean mExitOnSent; // Should we finish() after sending a message? private boolean mSendOnEnter; // Send on Enter private boolean mBlackBackground; // Option for switch background from white to black private boolean mBackToAllThreads; // Always return to all threads list private View mTopPanel; // View containing the recipient and subject editors private View mBottomPanel; // View containing the text editor, send button, ec. private EditText mTextEditor; // Text editor to type your message into private TextView mTextCounter; // Shows the number of characters used in text editor private Button mSendButton; // Press to detonate private EditText mSubjectTextEditor; // Text editor for MMS subject private AttachmentEditor mAttachmentEditor; private MessageListView mMsgListView; // ListView for messages in this conversation public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter private RecipientsEditor mRecipientsEditor; // UI control for editing recipients private boolean mIsKeyboardOpen; // Whether the hardware keyboard is visible private boolean mIsLandscape; // Whether we're in landscape mode private boolean mPossiblePendingNotification; // If the message list has changed, we may have // a pending notification to deal with. private boolean mToastForDraftSave; // Whether to notify the user that a draft is being saved private boolean mSentMessage; // true if the user has sent a message while in this // activity. On a new compose message case, when the first // message is sent is a MMS w/ attachment, the list blanks // for a second before showing the sent message. But we'd // think the message list is empty, thus show the recipients // editor thinking it's a draft message. This flag should // help clarify the situation. private WorkingMessage mWorkingMessage; // The message currently being composed. private AlertDialog mSmileyDialog; private boolean mWaitingForSubActivity; private int mLastRecipientCount; // Used for warning the user on too many recipients. private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter; private boolean mSendingMessage; // Indicates the current message is sending, and shouldn't send again. private Intent mAddContactIntent; // Intent used to add a new contact private String mDebugRecipients; private GestureLibrary mLibrary; private TemplatesDb mTemplatesDb; private String[] mTemplatesText; @SuppressWarnings("unused") private static void log(String logMsg) { Thread current = Thread.currentThread(); long tid = current.getId(); StackTraceElement[] stack = current.getStackTrace(); String methodName = stack[3].getMethodName(); // Prepend current thread ID and name of calling method to the message. logMsg = "[" + tid + "] [" + methodName + "] " + logMsg; Log.d(TAG, logMsg); } //========================================================== // Inner classes //========================================================== private void editSlideshow() { Uri dataUri = mWorkingMessage.saveAsMms(false); Intent intent = new Intent(this, SlideshowEditActivity.class); intent.setData(dataUri); startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW); } private final Handler mAttachmentEditorHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case AttachmentEditor.MSG_EDIT_SLIDESHOW: { editSlideshow(); break; } case AttachmentEditor.MSG_SEND_SLIDESHOW: { if (isPreparedForSending()) { ComposeMessageActivity.this.confirmSendMessageIfNeeded(); } break; } case AttachmentEditor.MSG_VIEW_IMAGE: case AttachmentEditor.MSG_PLAY_VIDEO: case AttachmentEditor.MSG_PLAY_AUDIO: case AttachmentEditor.MSG_PLAY_SLIDESHOW: MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this, mWorkingMessage); break; case AttachmentEditor.MSG_REPLACE_IMAGE: case AttachmentEditor.MSG_REPLACE_VIDEO: case AttachmentEditor.MSG_REPLACE_AUDIO: showAddAttachmentDialog(true); break; case AttachmentEditor.MSG_REMOVE_ATTACHMENT: mWorkingMessage.setAttachment(WorkingMessage.TEXT, null, false); break; default: break; } } }; private final Handler mMessageListItemHandler = new Handler() { @Override public void handleMessage(Message msg) { String type; switch (msg.what) { case MessageListItem.MSG_LIST_EDIT_MMS: type = "mms"; break; case MessageListItem.MSG_LIST_EDIT_SMS: type = "sms"; break; default: Log.w(TAG, "Unknown message: " + msg.what); return; } MessageItem msgItem = getMessageItem(type, (Long) msg.obj, false); if (msgItem != null) { editMessageItem(msgItem); drawBottomPanel(); } } }; private final OnKeyListener mSubjectKeyListener = new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } // When the subject editor is empty, press "DEL" to hide the input field. if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) { showSubjectEditor(false); mWorkingMessage.setSubject(null, true); return true; } return false; } }; /** * Return the messageItem associated with the type ("mms" or "sms") and message id. * @param type Type of the message: "mms" or "sms" * @param msgId Message id of the message. This is the _id of the sms or pdu row and is * stored in the MessageItem * @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's * cache and the code can create a new MessageItem based on the position of the current cursor. * If false, the function returns null if the MessageItem isn't in the cache. * @return MessageItem or null if not found and createFromCursorIfNotInCache is false */ private MessageItem getMessageItem(String type, long msgId, boolean createFromCursorIfNotInCache) { return mMsgListAdapter.getCachedMessageItem(type, msgId, createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null); } private boolean isCursorValid() { // Check whether the cursor is valid or not. Cursor cursor = mMsgListAdapter.getCursor(); if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) { Log.e(TAG, "Bad cursor.", new RuntimeException()); return false; } return true; } private void resetCounter() { mTextCounter.setText(""); mTextCounter.setVisibility(View.GONE); } private void updateCounter(CharSequence text, int start, int before, int count) { WorkingMessage workingMessage = mWorkingMessage; if (workingMessage.requiresMms()) { // If we're not removing text (i.e. no chance of converting back to SMS // because of this change) and we're in MMS mode, just bail out since we // then won't have to calculate the length unnecessarily. final boolean textRemoved = (before > count); if (!textRemoved) { setSendButtonText(workingMessage.requiresMms()); return; } } int[] params = SmsMessage.calculateLength(text, false); /* SmsMessage.calculateLength returns an int[4] with: * int[0] being the number of SMS's required, * int[1] the number of code units used, * int[2] is the number of code units remaining until the next message. * int[3] is the encoding type that should be used for the message. */ int msgCount = params[0]; int remainingInCurrentMessage = params[2]; if (!MmsConfig.getMultipartSmsEnabled()) { mWorkingMessage.setLengthRequiresMms( msgCount >= MmsConfig.getSmsToMmsTextThreshold(), true); } // Show the counter only if: // - We are not in MMS mode // - We are going to send more than one message OR we are getting close boolean showCounter = false; if (!workingMessage.requiresMms() && (msgCount > 1 || remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) { showCounter = true; } // Show the counter if the pref_key_show_counter_always preference is TRUE SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if(prefs.getBoolean("pref_key_show_counter_always",false)== true){ showCounter = true; } setSendButtonText(workingMessage.requiresMms()); if (showCounter) { // Update the remaining characters and number of messages required. String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount : String.valueOf(remainingInCurrentMessage); mTextCounter.setText(counterText); mTextCounter.setVisibility(View.VISIBLE); } else { mTextCounter.setVisibility(View.GONE); } } @Override public void startActivityForResult(Intent intent, int requestCode) { // requestCode >= 0 means the activity in question is a sub-activity. if (requestCode >= 0) { mWaitingForSubActivity = true; } super.startActivityForResult(intent, requestCode); } private void toastConvertInfo(boolean toMms) { final int resId = toMms ? R.string.converting_to_picture_message : R.string.converting_to_text_message; Toast.makeText(this, resId, Toast.LENGTH_SHORT).show(); } private class DeleteMessageListener implements OnClickListener { private final Uri mDeleteUri; private final boolean mDeleteLocked; public DeleteMessageListener(Uri uri, boolean deleteLocked) { mDeleteUri = uri; mDeleteLocked = deleteLocked; } public DeleteMessageListener(long msgId, String type, boolean deleteLocked) { if ("mms".equals(type)) { mDeleteUri = ContentUris.withAppendedId(Mms.CONTENT_URI, msgId); } else { mDeleteUri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgId); } mDeleteLocked = deleteLocked; } public void onClick(DialogInterface dialog, int whichButton) { mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN, null, mDeleteUri, mDeleteLocked ? null : "locked=0", null); dialog.dismiss(); } } private class DiscardDraftListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { mWorkingMessage.discard(); dialog.dismiss(); finish(); } } private class SendIgnoreInvalidRecipientListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { sendMessage(true); dialog.dismiss(); } } private class CancelSendingListener implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { if (isRecipientsEditorVisible()) { mRecipientsEditor.requestFocus(); } dialog.dismiss(); } } private void confirmSendMessageIfNeeded() { if (!isRecipientsEditorVisible()) { sendMessage(true); return; } boolean isMms = mWorkingMessage.requiresMms(); if (mRecipientsEditor.hasInvalidRecipient(isMms)) { if (mRecipientsEditor.hasValidRecipient(isMms)) { String title = getResourcesString(R.string.has_invalid_recipient, mRecipientsEditor.formatInvalidNumbers(isMms)); new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(title) .setMessage(R.string.invalid_recipient_message) .setPositiveButton(R.string.try_to_send, new SendIgnoreInvalidRecipientListener()) .setNegativeButton(R.string.no, new CancelSendingListener()) .show(); } else { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.cannot_send_message) .setMessage(R.string.cannot_send_message_reason) .setPositiveButton(R.string.yes, new CancelSendingListener()) .show(); } } else { sendMessage(true); } } private final TextWatcher mRecipientsWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // This is a workaround for bug 1609057. Since onUserInteraction() is // not called when the user touches the soft keyboard, we pretend it was // called when textfields changes. This should be removed when the bug // is fixed. onUserInteraction(); } public void afterTextChanged(Editable s) { // Bug 1474782 describes a situation in which we send to // the wrong recipient. We have been unable to reproduce this, // but the best theory we have so far is that the contents of // mRecipientList somehow become stale when entering // ComposeMessageActivity via onNewIntent(). This assertion is // meant to catch one possible path to that, of a non-visible // mRecipientsEditor having its TextWatcher fire and refreshing // mRecipientList with its stale contents. if (!isRecipientsEditorVisible()) { IllegalStateException e = new IllegalStateException( "afterTextChanged called with invisible mRecipientsEditor"); // Make sure the crash is uploaded to the service so we // can see if this is happening in the field. Log.w(TAG, "RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor"); return; } mWorkingMessage.setWorkingRecipients(mRecipientsEditor.getNumbers()); mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true); checkForTooManyRecipients(); // Walk backwards in the text box, skipping spaces. If the last // character is a comma, update the title bar. for (int pos = s.length() - 1; pos >= 0; pos--) { char c = s.charAt(pos); if (c == ' ') continue; if (c == ',') { updateTitle(mConversation.getRecipients()); } break; } // If we have gone to zero recipients, disable send button. updateSendButtonState(); } }; private void checkForTooManyRecipients() { final int recipientLimit = MmsConfig.getRecipientLimit(); if (recipientLimit != Integer.MAX_VALUE) { final int recipientCount = recipientCount(); boolean tooMany = recipientCount > recipientLimit; if (recipientCount != mLastRecipientCount) { // Don't warn the user on every character they type when they're over the limit, // only when the actual # of recipients changes. mLastRecipientCount = recipientCount; if (tooMany) { String tooManyMsg = getString(R.string.too_many_recipients, recipientCount, recipientLimit); Toast.makeText(ComposeMessageActivity.this, tooManyMsg, Toast.LENGTH_LONG).show(); } } } } private final OnCreateContextMenuListener mRecipientsMenuCreateListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (menuInfo != null) { Contact c = ((RecipientContextMenuInfo) menuInfo).recipient; RecipientsMenuClickListener l = new RecipientsMenuClickListener(c); menu.setHeaderTitle(c.getName()); if (c.existsInDatabase()) { menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact) .setOnMenuItemClickListener(l); } else if (canAddToContacts(c)){ menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts) .setOnMenuItemClickListener(l); } } } }; private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener { private final Contact mRecipient; RecipientsMenuClickListener(Contact recipient) { mRecipient = recipient; } public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { // Context menu handlers for the recipients editor. case MENU_VIEW_CONTACT: { Uri contactUri = mRecipient.getUri(); Intent intent = new Intent(Intent.ACTION_VIEW, contactUri); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); return true; } case MENU_ADD_TO_CONTACTS: { mAddContactIntent = ConversationList.createAddContactIntent( mRecipient.getNumber()); ComposeMessageActivity.this.startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT); return true; } } return false; } } private boolean canAddToContacts(Contact contact) { // There are some kind of automated messages, like STK messages, that we don't want // to add to contacts. These names begin with special characters, like, "*Info". final String name = contact.getName(); if (!TextUtils.isEmpty(contact.getNumber())) { char c = contact.getNumber().charAt(0); if (isSpecialChar(c)) { return false; } } if (!TextUtils.isEmpty(name)) { char c = name.charAt(0); if (isSpecialChar(c)) { return false; } } if (!(Mms.isEmailAddress(name) || Mms.isPhoneNumber(name) || MessageUtils.isLocalNumber(contact.getNumber()))) { // Handle "Me" return false; } return true; } private boolean isSpecialChar(char c) { return c == '*' || c == '%' || c == '$'; } private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo"); return; } final int position = info.position; addUriSpecificMenuItems(menu, v, position); } private Uri getSelectedUriFromMessageList(ListView listView, int position) { // If the context menu was opened over a uri, get that uri. MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position); if (msglistItem == null) { // FIXME: Should get the correct view. No such interface in ListView currently // to get the view by position. The ListView.getChildAt(position) cannot // get correct view since the list doesn't create one child for each item. // And if setSelection(position) then getSelectedView(), // cannot get corrent view when in touch mode. return null; } TextView textView; CharSequence text = null; int selStart = -1; int selEnd = -1; //check if message sender is selected textView = (TextView) msglistItem.findViewById(R.id.text_view); if (textView != null) { text = textView.getText(); selStart = textView.getSelectionStart(); selEnd = textView.getSelectionEnd(); } if (selStart == -1) { //sender is not being selected, it may be within the message body textView = (TextView) msglistItem.findViewById(R.id.body_text_view); if (textView != null) { text = textView.getText(); selStart = textView.getSelectionStart(); selEnd = textView.getSelectionEnd(); } } // Check that some text is actually selected, rather than the cursor // just being placed within the TextView. if (selStart != selEnd) { int min = Math.min(selStart, selEnd); int max = Math.max(selStart, selEnd); URLSpan[] urls = ((Spanned) text).getSpans(min, max, URLSpan.class); if (urls.length == 1) { return Uri.parse(urls[0].getURL()); } } //no uri was selected return null; } private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) { Uri uri = getSelectedUriFromMessageList((ListView) v, position); if (uri != null) { Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE); menu.addIntentOptions(0, 0, 0, new android.content.ComponentName(this, ComposeMessageActivity.class), null, intent, 0, null); } } private final void addCallAndContactMenuItems( ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) { // Add all possible links in the address & message StringBuilder textToSpannify = new StringBuilder(); if (msgItem.mBoxId == Mms.MESSAGE_BOX_INBOX) { textToSpannify.append(msgItem.mAddress + ": "); } textToSpannify.append(msgItem.mBody); SpannableString msg = new SpannableString(textToSpannify.toString()); Linkify.addLinks(msg, Linkify.ALL); ArrayList<String> uris = MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class)); while (uris.size() > 0) { String uriString = uris.remove(0); // Remove any dupes so they don't get added to the menu multiple times while (uris.contains(uriString)) { uris.remove(uriString); } int sep = uriString.indexOf(":"); String prefix = null; if (sep >= 0) { prefix = uriString.substring(0, sep); uriString = uriString.substring(sep + 1); } boolean addToContacts = false; if ("mailto".equalsIgnoreCase(prefix)) { String sendEmailString = getString( R.string.menu_send_email).replace("%s", uriString); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:" + uriString)); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); menu.add(0, MENU_SEND_EMAIL, 0, sendEmailString) .setOnMenuItemClickListener(l) .setIntent(intent); addToContacts = !haveEmailContact(uriString); } else if ("tel".equalsIgnoreCase(prefix)) { String callBackString = getString( R.string.menu_call_back).replace("%s", uriString); Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + uriString)); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); menu.add(0, MENU_CALL_BACK, 0, callBackString) .setOnMenuItemClickListener(l) .setIntent(intent); addToContacts = !isNumberInContacts(uriString); } if (addToContacts) { Intent intent = ConversationList.createAddContactIntent(uriString); String addContactString = getString( R.string.menu_add_address_to_contacts).replace("%s", uriString); menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString) .setOnMenuItemClickListener(l) .setIntent(intent); } } } private boolean haveEmailContact(String emailAddress) { Cursor cursor = SqliteWrapper.query(this, getContentResolver(), Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)), new String[] { Contacts.DISPLAY_NAME }, null, null, null); if (cursor != null) { try { while (cursor.moveToNext()) { String name = cursor.getString(0); if (!TextUtils.isEmpty(name)) { return true; } } } finally { cursor.close(); } } return false; } private boolean isNumberInContacts(String phoneNumber) { return Contact.get(phoneNumber, false).existsInDatabase(); } private final OnCreateContextMenuListener mMsgListMenuCreateListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Cursor cursor = mMsgListAdapter.getCursor(); String type = cursor.getString(COLUMN_MSG_TYPE); long msgId = cursor.getLong(COLUMN_ID); addPositionBasedMenuItems(menu, v, menuInfo); MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor); if (msgItem == null) { Log.e(TAG, "Cannot load message item for type = " + type + ", msgId = " + msgId); return; } menu.setHeaderTitle(R.string.message_options); MsgListMenuClickListener l = new MsgListMenuClickListener(); if (msgItem.mLocked) { menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock) .setOnMenuItemClickListener(l); } else { menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock) .setOnMenuItemClickListener(l); } if (msgItem.isMms()) { switch (msgItem.mBoxId) { case Mms.MESSAGE_BOX_INBOX: break; case Mms.MESSAGE_BOX_OUTBOX: // Since we currently break outgoing messages to multiple // recipients into one message per recipient, only allow // editing a message for single-recipient conversations. if (getRecipients().size() == 1) { menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit) .setOnMenuItemClickListener(l); } break; } switch (msgItem.mAttachmentType) { case WorkingMessage.TEXT: break; case WorkingMessage.VIDEO: case WorkingMessage.IMAGE: if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard) .setOnMenuItemClickListener(l); } break; case WorkingMessage.SLIDESHOW: default: menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow) .setOnMenuItemClickListener(l); if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard) .setOnMenuItemClickListener(l); } if (haveSomethingToCopyToDrmProvider(msgItem.mMsgId)) { menu.add(0, MENU_COPY_TO_DRM_PROVIDER, 0, getDrmMimeMenuStringRsrc(msgItem.mMsgId)) .setOnMenuItemClickListener(l); } break; } } else { // Message type is sms. Only allow "edit" if the message has a single recipient if (getRecipients().size() == 1 && (msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX || msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) { menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit) .setOnMenuItemClickListener(l); } } addCallAndContactMenuItems(menu, l, msgItem); // Forward is not available for undownloaded messages. if (msgItem.isDownloaded()) { menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward) .setOnMenuItemClickListener(l); } // It is unclear what would make most sense for copying an MMS message // to the clipboard, so we currently do SMS only. if (msgItem.isSms()) { menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text) .setOnMenuItemClickListener(l); } menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details) .setOnMenuItemClickListener(l); menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message) .setOnMenuItemClickListener(l); if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) { menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report) .setOnMenuItemClickListener(l); } } }; private void editMessageItem(MessageItem msgItem) { if ("sms".equals(msgItem.mType)) { editSmsMessageItem(msgItem); } else { editMmsMessageItem(msgItem); } if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) { // For messages with bad addresses, let the user re-edit the recipients. initRecipientsEditor(); } } private void editSmsMessageItem(MessageItem msgItem) { // When the message being edited is the only message in the conversation, the delete // below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a // thread contains no messages and silently deletes the thread. Meanwhile, the mConversation // object still holds onto the old thread_id and code thinks there's a backing thread in // the DB when it really has been deleted. Here we try and notice that situation and // clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll // create a new thread if necessary. synchronized(mConversation) { if (mConversation.getMessageCount() <= 1) { mConversation.clearThreadId(); } } // Delete the old undelivered SMS and load its content. Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId); SqliteWrapper.delete(ComposeMessageActivity.this, mContentResolver, uri, null, null); mWorkingMessage.setText(msgItem.mBody); } private void editMmsMessageItem(MessageItem msgItem) { // Discard the current message in progress. mWorkingMessage.discard(); // Load the selected message in as the working message. mWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri); mWorkingMessage.setConversation(mConversation); mAttachmentEditor.update(mWorkingMessage); drawTopPanel(); // WorkingMessage.load() above only loads the slideshow. Set the // subject here because we already know what it is and avoid doing // another DB lookup in load() just to get it. mWorkingMessage.setSubject(msgItem.mSubject, false); if (mWorkingMessage.hasSubject()) { showSubjectEditor(true); } } private void copyToClipboard(String str) { ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); clip.setText(str); } private void forwardMessage(MessageItem msgItem) { Intent intent = createIntent(this, 0); intent.putExtra("exit_on_sent", true); intent.putExtra("forwarded_message", true); if (msgItem.mType.equals("sms")) { intent.putExtra("sms_body", msgItem.mBody); } else { SendReq sendReq = new SendReq(); String subject = getString(R.string.forward_prefix); if (msgItem.mSubject != null) { subject += msgItem.mSubject; } sendReq.setSubject(new EncodedStringValue(subject)); sendReq.setBody(msgItem.mSlideshow.makeCopy( ComposeMessageActivity.this)); Uri uri = null; try { PduPersister persister = PduPersister.getPduPersister(this); // Copy the parts of the message here. uri = persister.persist(sendReq, Mms.Draft.CONTENT_URI); } catch (MmsException e) { Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri, e); Toast.makeText(ComposeMessageActivity.this, R.string.cannot_save_message, Toast.LENGTH_SHORT).show(); return; } intent.putExtra("msg_uri", uri); intent.putExtra("subject", subject); } // ForwardMessageActivity is simply an alias in the manifest for ComposeMessageActivity. // We have to make an alias because ComposeMessageActivity launch flags specify // singleTop. When we forward a message, we want to start a separate ComposeMessageActivity. // The only way to do that is to override the singleTop flag, which is impossible to do // in code. By creating an alias to the activity, without the singleTop flag, we can // launch a separate ComposeMessageActivity to edit the forward message. intent.setClassName(this, "com.android.mms.ui.ForwardMessageActivity"); startActivity(intent); } /** * Context menu handlers for the message list view. */ private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem item) { if (!isCursorValid()) { return false; } Cursor cursor = mMsgListAdapter.getCursor(); String type = cursor.getString(COLUMN_MSG_TYPE); long msgId = cursor.getLong(COLUMN_ID); MessageItem msgItem = getMessageItem(type, msgId, true); if (msgItem == null) { return false; } switch (item.getItemId()) { case MENU_EDIT_MESSAGE: editMessageItem(msgItem); drawBottomPanel(); return true; case MENU_COPY_MESSAGE_TEXT: copyToClipboard(msgItem.mBody); return true; case MENU_FORWARD_MESSAGE: forwardMessage(msgItem); return true; case MENU_VIEW_SLIDESHOW: MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId), null); return true; case MENU_VIEW_MESSAGE_DETAILS: { String messageDetails = MessageUtils.getMessageDetails( ComposeMessageActivity.this, cursor, msgItem.mMessageSize); new AlertDialog.Builder(ComposeMessageActivity.this) .setTitle(R.string.message_details_title) .setMessage(messageDetails) .setPositiveButton(android.R.string.ok, null) .setCancelable(true) .show(); return true; } case MENU_DELETE_MESSAGE: { DeleteMessageListener l = new DeleteMessageListener( msgItem.mMessageUri, msgItem.mLocked); confirmDeleteDialog(l, msgItem.mLocked); return true; } case MENU_DELIVERY_REPORT: showDeliveryReport(msgId, type); return true; case MENU_COPY_TO_SDCARD: { int resId = copyMedia(msgId) ? R.string.copy_to_sdcard_success : R.string.copy_to_sdcard_fail; Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show(); return true; } case MENU_COPY_TO_DRM_PROVIDER: { int resId = getDrmMimeSavedStringRsrc(msgId, copyToDrmProvider(msgId)); Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show(); return true; } case MENU_LOCK_MESSAGE: { lockMessage(msgItem, true); return true; } case MENU_UNLOCK_MESSAGE: { lockMessage(msgItem, false); return true; } default: return false; } } } private void lockMessage(MessageItem msgItem, boolean locked) { Uri uri; if ("sms".equals(msgItem.mType)) { uri = Sms.CONTENT_URI; } else { uri = Mms.CONTENT_URI; } final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId); final ContentValues values = new ContentValues(1); values.put("locked", locked ? 1 : 0); new Thread(new Runnable() { public void run() { getContentResolver().update(lockUri, values, null, null); } }, "lockMessage").start(); } /** * Looks to see if there are any valid parts of the attachment that can be copied to a SD card. * @param msgId */ private boolean haveSomethingToCopyToSDCard(long msgId) { PduBody body = PduBodyCache.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); if (body == null) { return false; } boolean result = false; int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type); } if (ContentType.isImageType(type) || ContentType.isVideoType(type) || ContentType.isAudioType(type)) { result = true; break; } } return result; } /** * Looks to see if there are any drm'd parts of the attachment that can be copied to the * DrmProvider. Right now we only support saving audio (e.g. ringtones). * @param msgId */ private boolean haveSomethingToCopyToDrmProvider(long msgId) { String mimeType = getDrmMimeType(msgId); return isAudioMimeType(mimeType); } /** * Simple cache to prevent having to load the same PduBody again and again for the same uri. */ private static class PduBodyCache { private static PduBody mLastPduBody; private static Uri mLastUri; static public PduBody getPduBody(Context context, Uri contentUri) { if (contentUri.equals(mLastUri)) { return mLastPduBody; } try { mLastPduBody = SlideshowModel.getPduBody(context, contentUri); mLastUri = contentUri; } catch (MmsException e) { Log.e(TAG, e.getMessage(), e); return null; } return mLastPduBody; } }; /** * Copies media from an Mms to the DrmProvider * @param msgId */ private boolean copyToDrmProvider(long msgId) { boolean result = true; PduBody body = PduBodyCache.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); if (body == null) { return false; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isDrmType(type)) { // All parts (but there's probably only a single one) have to be successful // for a valid result. result &= copyPartToDrmProvider(part); } } return result; } private String mimeTypeOfDrmPart(PduPart part) { Uri uri = part.getDataUri(); InputStream input = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; DrmRawContent content = new DrmRawContent(fin, fin.available(), DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING); String mimeType = content.getContentType(); return mimeType; } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); } catch (DrmException e) { Log.e(TAG, "DrmException caught ", e); } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); } } } return null; } /** * Returns the type of the first drm'd pdu part. * @param msgId */ private String getDrmMimeType(long msgId) { PduBody body = PduBodyCache.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); if (body == null) { return null; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isDrmType(type)) { return mimeTypeOfDrmPart(part); } } return null; } private int getDrmMimeMenuStringRsrc(long msgId) { String mimeType = getDrmMimeType(msgId); if (isAudioMimeType(mimeType)) { return R.string.save_ringtone; } return 0; } private int getDrmMimeSavedStringRsrc(long msgId, boolean success) { String mimeType = getDrmMimeType(msgId); if (isAudioMimeType(mimeType)) { return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail; } return 0; } private boolean isAudioMimeType(String mimeType) { return mimeType != null && mimeType.startsWith("audio/"); } private boolean isImageMimeType(String mimeType) { return mimeType != null && mimeType.startsWith("image/"); } private boolean copyPartToDrmProvider(PduPart part) { Uri uri = part.getDataUri(); InputStream input = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; // Build a nice title byte[] location = part.getName(); if (location == null) { location = part.getFilename(); } if (location == null) { location = part.getContentLocation(); } // Depending on the location, there may be an // extension already on the name or not String title = new String(location); int index; if ((index = title.indexOf(".")) == -1) { String type = new String(part.getContentType()); } else { title = title.substring(0, index); } // transfer the file to the DRM content provider Intent item = DrmStore.addDrmFile(mContentResolver, fin, title); if (item == null) { Log.w(TAG, "unable to add file " + uri + " to DrmProvider"); return false; } } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); return false; } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } } return true; } /** * Copies media from an Mms to a directory on the SD card * @param msgId */ private boolean copyMedia(long msgId) { boolean result = true; PduBody body = PduBodyCache.getPduBody(this, ContentUris.withAppendedId(Mms.CONTENT_URI, msgId)); if (body == null) { return false; } int partNum = body.getPartsNum(); for(int i = 0; i < partNum; i++) { PduPart part = body.getPart(i); String type = new String(part.getContentType()); if (ContentType.isImageType(type) || ContentType.isVideoType(type) || ContentType.isAudioType(type)) { result &= copyPart(part, Long.toHexString(msgId)); // all parts have to be successful for a valid result. } } return result; } private boolean copyPart(PduPart part, String fallback) { Uri uri = part.getDataUri(); InputStream input = null; FileOutputStream fout = null; try { input = mContentResolver.openInputStream(uri); if (input instanceof FileInputStream) { FileInputStream fin = (FileInputStream) input; byte[] location = part.getName(); if (location == null) { location = part.getFilename(); } if (location == null) { location = part.getContentLocation(); } String fileName; if (location == null) { // Use fallback name. fileName = fallback; } else { fileName = new String(location); } // Depending on the location, there may be an // extension already on the name or not // Get Shared Preferences and User Defined Save Location for MMS SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String dir = Environment.getExternalStorageDirectory() + "/" + prefs.getString(MessagingPreferenceActivity.MMS_SAVE_LOCATION, "download") + "/"; String extension; int index; if ((index = fileName.indexOf(".")) == -1) { String type = new String(part.getContentType()); extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type); } else { extension = fileName.substring(index + 1, fileName.length()); fileName = fileName.substring(0, index); } File file = getUniqueDestination(dir + fileName, extension); // make sure the path is valid and directories created for this file. File parentFile = file.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!"); return false; } fout = new FileOutputStream(file); byte[] buffer = new byte[8000]; int size = 0; while ((size=fin.read(buffer)) != -1) { fout.write(buffer, 0, size); } // Notify other applications listening to scanner events // that a media file has been added to the sd card sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); } } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while opening or reading stream", e); return false; } finally { if (null != input) { try { input.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } if (null != fout) { try { fout.close(); } catch (IOException e) { // Ignore Log.e(TAG, "IOException caught while closing stream", e); return false; } } } return true; } private File getUniqueDestination(String base, String extension) { File file = new File(base + "." + extension); for (int i = 2; file.exists(); i++) { file = new File(base + "_" + i + "." + extension); } return file; } private void showDeliveryReport(long messageId, String type) { Intent intent = new Intent(this, DeliveryReportActivity.class); intent.putExtra("message_id", messageId); intent.putExtra("message_type", type); startActivity(intent); } private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION); private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) { long token = intent.getLongExtra("token", SendingProgressTokenManager.NO_TOKEN); if (token != mConversation.getThreadId()) { return; } int progress = intent.getIntExtra("progress", 0); switch (progress) { case PROGRESS_START: setProgressBarVisibility(true); break; case PROGRESS_ABORT: case PROGRESS_COMPLETE: setProgressBarVisibility(false); break; default: setProgress(100 * progress); } } } }; private int mGestureSensitivity; private static ContactList sEmptyContactList; private ContactList getRecipients() { // If the recipients editor is visible, the conversation has // not really officially 'started' yet. Recipients will be set // on the conversation once it has been saved or sent. In the // meantime, let anyone who needs the recipient list think it // is empty rather than giving them a stale one. if (isRecipientsEditorVisible()) { if (sEmptyContactList == null) { sEmptyContactList = new ContactList(); } return sEmptyContactList; } return mConversation.getRecipients(); } private void updateTitle(ContactList list) { String s; switch (list.size()) { case 0: { String recipient = ""; if (mRecipientsEditor != null) { recipient = mRecipientsEditor.getText().toString(); } s = recipient; break; } case 1: { s = list.get(0).getNameAndNumber(); break; } default: { // Handle multiple recipients s = list.formatNames(", "); break; } } mDebugRecipients = list.serialize(); getWindow().setTitle(s); } // Get the recipients editor ready to be displayed onscreen. private void initRecipientsEditor() { if (isRecipientsEditorVisible()) { return; } // Must grab the recipients before the view is made visible because getRecipients() // returns empty recipients when the editor is visible. ContactList recipients = getRecipients(); ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub); if (stub != null) { mRecipientsEditor = (RecipientsEditor) stub.inflate(); } else { mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor); mRecipientsEditor.setVisibility(View.VISIBLE); } mRecipientsEditor.setAdapter(new RecipientsAdapter(this)); mRecipientsEditor.populate(recipients); mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener); mRecipientsEditor.addTextChangedListener(mRecipientsWatcher); mRecipientsEditor.setFilters(new InputFilter[] { new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) }); mRecipientsEditor.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // After the user selects an item in the pop-up contacts list, move the // focus to the text editor if there is only one recipient. This helps // the common case of selecting one recipient and then typing a message, // but avoids annoying a user who is trying to add five recipients and // keeps having focus stolen away. if (mRecipientsEditor.getRecipientCount() == 1) { // if we're in extract mode then don't request focus final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputManager == null || !inputManager.isFullscreenMode()) { mTextEditor.requestFocus(); } } } }); mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { RecipientsEditor editor = (RecipientsEditor) v; ContactList contacts = editor.constructContactsFromInput(); updateTitle(contacts); } } }); mTopPanel.setVisibility(View.VISIBLE); } //========================================================== // Activity methods //========================================================== public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) { if (MessagingNotification.isFailedToDeliver(intent)) { // Cancel any failed message notifications MessagingNotification.cancelNotification(context, MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID); return true; } return false; } public static boolean cancelFailedDownloadNotification(Intent intent, Context context) { if (MessagingNotification.isFailedToDownload(intent)) { // Cancel any failed download notifications MessagingNotification.cancelNotification(context, MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID); return true; } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences((Context)ComposeMessageActivity.this); mBlackBackground = prefs.getBoolean(MessagingPreferenceActivity.BLACK_BACKGROUND, false); mBackToAllThreads = prefs.getBoolean(MessagingPreferenceActivity.BACK_TO_ALL_THREADS, false); mSendOnEnter = prefs.getBoolean(MessagingPreferenceActivity.SEND_ON_ENTER, true); mGestureSensitivity = prefs.getInt(MessagingPreferenceActivity.GESTURE_SENSITIVITY_VALUE, 3); boolean showGesture = prefs.getBoolean(MessagingPreferenceActivity.SHOW_GESTURE, false); int layout = R.layout.compose_message_activity; if (mBlackBackground) { layout = R.layout.compose_message_activity_black; } GestureOverlayView gestureOverlayView = new GestureOverlayView(this); View inflate = getLayoutInflater().inflate(layout, null); gestureOverlayView.addView(inflate); gestureOverlayView.setEventsInterceptionEnabled(true); gestureOverlayView.setGestureVisible(showGesture); gestureOverlayView.addOnGesturePerformedListener(this); setContentView(gestureOverlayView); setProgressBarVisibility(false); mLibrary = TemplateGesturesLibrary.getStore(this); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // Initialize members for UI elements. initResourceRefs(); mContentResolver = getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver); initialize(savedInstanceState, 0); if (TRACE) { android.os.Debug.startMethodTracing("compose"); } registerForContextMenu(mTextEditor); } @Override protected Dialog onCreateDialog(int id, Bundle args) { AlertDialog.Builder builder = new AlertDialog.Builder(this); switch (id) { case DIALOG_TEMPLATE_NOT_AVAILABLE: builder.setTitle(R.string.template_not_present_error_title); builder.setMessage(R.string.template_not_present_error); return builder.create(); case DIALOG_TEMPLATE_SELECT: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.template_select); builder.setItems(mTemplatesText, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mTextEditor.append(mTemplatesText[which]); } }); return builder.create(); } return super.onCreateDialog(id, args); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (v == mTextEditor) { menu.setHeaderTitle(R.string.template_insert_ctx_menu_title); menu.add(Menu.NONE, MENU_INSERT_TEMPLATE, Menu.NONE, R.string.template_insert); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == MENU_INSERT_TEMPLATE) { showInsertTemplateDialog(); } return super.onContextItemSelected(item); } private void showInsertTemplateDialog() { if (mTemplatesDb == null) { mTemplatesDb = new TemplatesDb(this); } mTemplatesDb.open(); mTemplatesText = mTemplatesDb.getAllTemplatesText(); mTemplatesDb.close(); if (mTemplatesText.length > 0) { showDialog(DIALOG_TEMPLATE_SELECT); } else { showDialog(DIALOG_TEMPLATE_NOT_AVAILABLE); } } public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { ArrayList<Prediction> predictions = mLibrary.recognize(gesture); for (Prediction prediction : predictions) { if (prediction.score > mGestureSensitivity) { if (mTemplatesDb == null) { mTemplatesDb = new TemplatesDb(ComposeMessageActivity.this); } mTemplatesDb.open(); String text = mTemplatesDb.getTemplateTextFromId(Long.parseLong(prediction.name)); mTemplatesDb.close(); mTextEditor.append(text); } } } private void showSubjectEditor(boolean show) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("" + show); } if (mSubjectTextEditor == null) { // Don't bother to initialize the subject editor if // we're just going to hide it. if (show == false) { return; } mSubjectTextEditor = (EditText)findViewById(R.id.subject); } mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null); if (show) { mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher); } else { mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher); } mSubjectTextEditor.setText(mWorkingMessage.getSubject()); mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE); hideOrShowTopPanel(); } private void hideOrShowTopPanel() { boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible()); mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE); } public void initialize(Bundle savedInstanceState, long originalThreadId) { Intent intent = getIntent(); // Create a new empty working message. mWorkingMessage = WorkingMessage.createEmpty(this); // Read parameters or previously saved state of this activity. This will load a new // mConversation initActivityState(savedInstanceState, intent); if (LogTag.SEVERE_WARNING && originalThreadId != 0 && originalThreadId == mConversation.getThreadId()) { LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " + " threadId didn't change from: " + originalThreadId, this); } log("savedInstanceState = " + savedInstanceState + " intent = " + intent + " mConversation = " + mConversation); if (cancelFailedToDeliverNotification(getIntent(), this)) { // Show a pop-up dialog to inform user the message was // failed to deliver. undeliveredMessageDialog(getMessageDate(null)); } cancelFailedDownloadNotification(getIntent(), this); // Set up the message history ListAdapter initMessageList(); // Load the draft for this thread, if we aren't already handling // existing data, such as a shared picture or forwarded message. boolean isForwardedMessage = false; if (!handleSendIntent(intent)) { isForwardedMessage = handleForwardedMessage(); if (!isForwardedMessage) { loadDraft(); } } // Let the working message know what conversation it belongs to mWorkingMessage.setConversation(mConversation); // Show the recipients editor if we don't have a valid thread. Hide it otherwise. if (mConversation.getThreadId() <= 0) { // Hide the recipients editor so the call to initRecipientsEditor won't get // short-circuited. hideRecipientEditor(); initRecipientsEditor(); // Bring up the softkeyboard so the user can immediately enter recipients. This // call won't do anything on devices with a hard keyboard. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } else { hideRecipientEditor(); } updateSendButtonState(); drawTopPanel(); drawBottomPanel(); mAttachmentEditor.update(mWorkingMessage); Configuration config = getResources().getConfiguration(); mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO; mIsLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE; onKeyboardStateChanged(mIsKeyboardOpen); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } updateTitle(mConversation.getRecipients()); if (isForwardedMessage && isRecipientsEditorVisible()) { // The user is forwarding the message to someone. Put the focus on the // recipient editor rather than in the message editor. mRecipientsEditor.requestFocus(); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); Conversation conversation = null; mSentMessage = false; // If we have been passed a thread_id, use that to find our // conversation. // Note that originalThreadId might be zero but if this is a draft and we save the // draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage // the thread will get a threadId behind the UI thread's back. long originalThreadId = mConversation.getThreadId(); long threadId = intent.getLongExtra("thread_id", 0); Uri intentUri = intent.getData(); boolean sameThread = false; if (threadId > 0) { conversation = Conversation.get(this, threadId, false); } else { if (mConversation.getThreadId() == 0) { // We've got a draft. See if the new intent's recipient is the same as // the draft's recipient. First make sure the working recipients are synched // to the conversation. mWorkingMessage.syncWorkingRecipients(); sameThread = mConversation.sameRecipient(intentUri); } if (!sameThread) { // Otherwise, try to get a conversation based on the // data URI passed to our intent. conversation = Conversation.get(this, intentUri, false); } } if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("data=" + intentUri + ", thread_id extra is " + threadId + ", new conversation=" + conversation + ", mConversation=" + mConversation); } if (conversation != null) { // Don't let any markAsRead DB updates occur before we've loaded the messages for // the thread. conversation.blockMarkAsRead(true); // this is probably paranoia to compare both thread_ids and recipient lists, // but we want to make double sure because this is a last minute fix for Froyo // and the previous code checked thread ids only. // (we cannot just compare thread ids because there is a case where mConversation // has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1), // even though the recipient lists are different) sameThread = (conversation.getThreadId() == mConversation.getThreadId() && conversation.equals(mConversation)); } if (sameThread) { log("same conversation"); } else { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("different conversation"); } saveDraft(); // if we've got a draft, save it first initialize(null, originalThreadId); loadMessageContent(); } } @Override protected void onRestart() { super.onRestart(); if (mWorkingMessage.isDiscarded()) { // If the message isn't worth saving, don't resurrect it. Doing so can lead to // a situation where a new incoming message gets the old thread id of the discarded // draft. This activity can end up displaying the recipients of the old message with // the contents of the new message. Recognize that dangerous situation and bail out // to the ConversationList where the user can enter this in a clean manner. if (mWorkingMessage.isWorthSaving()) { mWorkingMessage.unDiscard(); // it was discarded in onStop(). } else if (isRecipientsEditorVisible()) { goToConversationList(); } else { loadDraft(); mWorkingMessage.setConversation(mConversation); mAttachmentEditor.update(mWorkingMessage); } } } @Override protected void onStart() { super.onStart(); mConversation.blockMarkAsRead(true); initFocus(); // Register a BroadcastReceiver to listen on HTTP I/O process. registerReceiver(mHttpProgressReceiver, mHttpProgressFilter); loadMessageContent(); // Update the fasttrack info in case any of the recipients' contact info changed // while we were paused. This can happen, for example, if a user changes or adds // an avatar associated with a contact. mWorkingMessage.syncWorkingRecipients(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } updateTitle(mConversation.getRecipients()); } public void loadMessageContent() { startMsgListQuery(); updateSendFailedNotification(); drawBottomPanel(); } private void updateSendFailedNotification() { final long threadId = mConversation.getThreadId(); if (threadId <= 0) return; // updateSendFailedNotificationForThread makes a database call, so do the work off // of the ui thread. new Thread(new Runnable() { public void run() { MessagingNotification.updateSendFailedNotificationForThread( ComposeMessageActivity.this, threadId); } }, "updateSendFailedNotification").start(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("recipients", getRecipients().serialize()); mWorkingMessage.writeStateToBundle(outState); if (mExitOnSent) { outState.putBoolean("exit_on_sent", mExitOnSent); } } @Override protected void onResume() { super.onResume(); // OLD: get notified of presence updates to update the titlebar. // NEW: we are using ContactHeaderWidget which displays presence, but updating presence // there is out of our control. //Contact.startPresenceObserver(); addRecipientsListeners(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("update title, mConversation=" + mConversation.toString()); } // There seems to be a bug in the framework such that setting the title // here gets overwritten to the original title. Do this delayed as a // workaround. mMessageListItemHandler.postDelayed(new Runnable() { public void run() { ContactList recipients = isRecipientsEditorVisible() ? mRecipientsEditor.constructContactsFromInput() : getRecipients(); updateTitle(recipients); } }, 100); } @Override protected void onPause() { super.onPause(); // OLD: stop getting notified of presence updates to update the titlebar. // NEW: we are using ContactHeaderWidget which displays presence, but updating presence // there is out of our control. //Contact.stopPresenceObserver(); removeRecipientsListeners(); } @Override protected void onStop() { super.onStop(); // Allow any blocked calls to update the thread's read status. mConversation.blockMarkAsRead(false); if (mMsgListAdapter != null) { mMsgListAdapter.changeCursor(null); } if (mRecipientsEditor != null) { CursorAdapter recipientsAdapter = (CursorAdapter)mRecipientsEditor.getAdapter(); if (recipientsAdapter != null) { recipientsAdapter.changeCursor(null); } } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("save draft"); } saveDraft(); // Cleanup the BroadcastReceiver. unregisterReceiver(mHttpProgressReceiver); } @Override protected void onDestroy() { if (TRACE) { android.os.Debug.stopMethodTracing(); } super.onDestroy(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (LOCAL_LOGV) { Log.v(TAG, "onConfigurationChanged: " + newConfig); } mIsKeyboardOpen = newConfig.keyboardHidden == KEYBOARDHIDDEN_NO; boolean isLandscape = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE; if (mIsLandscape != isLandscape) { mIsLandscape = isLandscape; // Have to re-layout the attachment editor because we have different layouts // depending on whether we're portrait or landscape. mAttachmentEditor.update(mWorkingMessage); } onKeyboardStateChanged(mIsKeyboardOpen); } private void onKeyboardStateChanged(boolean isKeyboardOpen) { // If the keyboard is hidden, don't show focus highlights for // things that cannot receive input. if (isKeyboardOpen) { if (mRecipientsEditor != null) { mRecipientsEditor.setFocusableInTouchMode(true); } if (mSubjectTextEditor != null) { mSubjectTextEditor.setFocusableInTouchMode(true); } mTextEditor.setFocusableInTouchMode(true); mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send); } else { if (mRecipientsEditor != null) { mRecipientsEditor.setFocusable(false); } if (mSubjectTextEditor != null) { mSubjectTextEditor.setFocusable(false); } mTextEditor.setFocusable(false); mTextEditor.setHint(R.string.open_keyboard_to_compose_message); } } @Override public void onUserInteraction() { checkPendingNotification(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) { checkPendingNotification(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: if ((mMsgListAdapter != null) && mMsgListView.isFocused()) { Cursor cursor; try { cursor = (Cursor) mMsgListView.getSelectedItem(); } catch (ClassCastException e) { Log.e(TAG, "Unexpected ClassCastException.", e); return super.onKeyDown(keyCode, event); } if (cursor != null) { boolean locked = cursor.getInt(COLUMN_MMS_LOCKED) != 0; DeleteMessageListener l = new DeleteMessageListener( cursor.getLong(COLUMN_ID), cursor.getString(COLUMN_MSG_TYPE), locked); confirmDeleteDialog(l, locked); return true; } } break; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: if (isPreparedForSending()) { confirmSendMessageIfNeeded(); return true; } break; case KeyEvent.KEYCODE_BACK: exitComposeMessageActivity(new Runnable() { public void run() { //Always return to all threads if (mBackToAllThreads) { goToConversationList(); } else { finish(); } } }); return true; } return super.onKeyDown(keyCode, event); } private void exitComposeMessageActivity(final Runnable exit) { // If the message is empty, just quit -- finishing the // activity will cause an empty draft to be deleted. if (!mWorkingMessage.isWorthSaving()) { exit.run(); return; } if (isRecipientsEditorVisible() && !mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) { MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener()); return; } mToastForDraftSave = true; exit.run(); } private void goToConversationList() { finish(); startActivity(new Intent(this, ConversationList.class)); } private void hideRecipientEditor() { if (mRecipientsEditor != null) { mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher); mRecipientsEditor.setVisibility(View.GONE); hideOrShowTopPanel(); } } private boolean isRecipientsEditorVisible() { return (null != mRecipientsEditor) && (View.VISIBLE == mRecipientsEditor.getVisibility()); } private boolean isSubjectEditorVisible() { return (null != mSubjectTextEditor) && (View.VISIBLE == mSubjectTextEditor.getVisibility()); } public void onAttachmentChanged() { // Have to make sure we're on the UI thread. This function can be called off of the UI // thread when we're adding multi-attachments runOnUiThread(new Runnable() { public void run() { drawBottomPanel(); updateSendButtonState(); mAttachmentEditor.update(mWorkingMessage); } }); } public void onProtocolChanged(final boolean mms) { // Have to make sure we're on the UI thread. This function can be called off of the UI // thread when we're adding multi-attachments runOnUiThread(new Runnable() { public void run() { toastConvertInfo(mms); setSendButtonText(mms); } }); } private void setSendButtonText(boolean isMms) { Button sendButton = mSendButton; sendButton.setText(R.string.send); if (isMms) { // Create and append the "MMS" text in a smaller font than the "Send" text. sendButton.append("\n"); SpannableString spannable = new SpannableString(getString(R.string.mms)); int mmsTextSize = (int) (sendButton.getTextSize() * 0.75f); spannable.setSpan(new AbsoluteSizeSpan(mmsTextSize), 0, spannable.length(), 0); sendButton.append(spannable); mTextCounter.setText(""); } } Runnable mResetMessageRunnable = new Runnable() { public void run() { resetMessage(); } }; public void onPreMessageSent() { runOnUiThread(mResetMessageRunnable); } public void onMessageSent() { // If we already have messages in the list adapter, it // will be auto-requerying; don't thrash another query in. if (mMsgListAdapter.getCount() == 0) { startMsgListQuery(); } } public void onMaxPendingMessagesReached() { saveDraft(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms, Toast.LENGTH_LONG).show(); } }); } public void onAttachmentError(final int error) { runOnUiThread(new Runnable() { public void run() { handleAddAttachmentError(error, R.string.type_picture); onMessageSent(); // now requery the list of messages } }); } // We don't want to show the "call" option unless there is only one // recipient and it's a phone number. private boolean isRecipientCallable() { ContactList recipients = getRecipients(); return (recipients.size() == 1 && !recipients.containsEmail()); } private void dialRecipient() { String number = getRecipients().get(0).getNumber(); Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number)); startActivity(dialIntent); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (isRecipientCallable()) { menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call).setIcon( R.drawable.ic_menu_call); } // Only add the "View contact" menu item when there's a single recipient and that // recipient is someone in contacts. ContactList recipients = getRecipients(); if (recipients.size() == 1 && recipients.get(0).existsInDatabase()) { menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact).setIcon( R.drawable.ic_menu_contact); } if (MmsConfig.getMmsEnabled()) { if (!isSubjectEditorVisible()) { menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon( R.drawable.ic_menu_edit); } if (!mWorkingMessage.hasAttachment()) { menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment).setIcon( R.drawable.ic_menu_attachment); } } if (isPreparedForSending()) { menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send); } menu.add(0, MENU_INSERT_SMILEY, 0, R.string.menu_insert_smiley).setIcon( R.drawable.ic_menu_emoticons); if (mMsgListAdapter.getCount() > 0) { // Removed search as part of b/1205708 //menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon( // R.drawable.ic_menu_search); Cursor cursor = mMsgListAdapter.getCursor(); if ((null != cursor) && (cursor.getCount() > 0)) { menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon( android.R.drawable.ic_menu_delete); } } else { menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete); } menu.add(0, MENU_CONVERSATION_LIST, 0, R.string.all_threads).setIcon( R.drawable.ic_menu_friendslist); buildAddAddressToContactMenuItem(menu); return true; } private void buildAddAddressToContactMenuItem(Menu menu) { // Look for the first recipient we don't have a contact for and create a menu item to // add the number to contacts. for (Contact c : getRecipients()) { if (!c.existsInDatabase() && canAddToContacts(c)) { Intent intent = ConversationList.createAddContactIntent(c.getNumber()); menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts) .setIcon(android.R.drawable.ic_menu_add) .setIntent(intent); break; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD_SUBJECT: showSubjectEditor(true); mWorkingMessage.setSubject("", true); mSubjectTextEditor.requestFocus(); break; case MENU_ADD_ATTACHMENT: // Launch the add-attachment list dialog showAddAttachmentDialog(false); break; case MENU_DISCARD: mWorkingMessage.discard(); finish(); break; case MENU_SEND: if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } break; case MENU_SEARCH: onSearchRequested(); break; case MENU_DELETE_THREAD: confirmDeleteThread(mConversation.getThreadId()); break; case MENU_CONVERSATION_LIST: exitComposeMessageActivity(new Runnable() { public void run() { goToConversationList(); } }); break; case MENU_CALL_RECIPIENT: dialRecipient(); break; case MENU_INSERT_SMILEY: showSmileyDialog(); break; case MENU_VIEW_CONTACT: { // View the contact for the first (and only) recipient. ContactList list = getRecipients(); if (list.size() == 1 && list.get(0).existsInDatabase()) { Uri contactUri = list.get(0).getUri(); Intent intent = new Intent(Intent.ACTION_VIEW, contactUri); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } break; } case MENU_ADD_ADDRESS_TO_CONTACTS: mAddContactIntent = item.getIntent(); startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT); break; } return true; } private void confirmDeleteThread(long threadId) { Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler, threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN); } // static class SystemProperties { // TODO, temp class to get unbundling working // static int getInt(String s, int value) { // return value; // just return the default value or now // } // } private int getVideoCaptureDurationLimit() { return CamcorderProfile.get(CamcorderProfile.QUALITY_LOW).duration; } private void addAttachment(int type, boolean replace) { // Calculate the size of the current slide if we're doing a replace so the // slide size can optionally be used in computing how much room is left for an attachment. int currentSlideSize = 0; SlideshowModel slideShow = mWorkingMessage.getSlideshow(); if (replace && slideShow != null) { SlideModel slide = slideShow.get(0); currentSlideSize = slide.getSlideSize(); } switch (type) { case AttachmentTypeSelectorAdapter.ADD_IMAGE: MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE); break; case AttachmentTypeSelectorAdapter.TAKE_PICTURE: { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Mms.ScrapSpace.CONTENT_URI); startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE); break; } case AttachmentTypeSelectorAdapter.ADD_VIDEO: MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO); break; case AttachmentTypeSelectorAdapter.RECORD_VIDEO: { // Set video size limit. Subtract 1K for some text. long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP; if (slideShow != null) { sizeLimit -= slideShow.getCurrentMessageSize(); // We're about to ask the camera to capture some video which will // eventually replace the content on the current slide. Since the current // slide already has some content (which was subtracted out just above) // and that content is going to get replaced, we can add the size of the // current slide into the available space used to capture a video. sizeLimit += currentSlideSize; } if (sizeLimit > 0) { int durationLimit = getVideoCaptureDurationLimit(); Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); intent.putExtra("android.intent.extra.sizeLimit", sizeLimit); intent.putExtra("android.intent.extra.durationLimit", durationLimit); startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO); } else { Toast.makeText(this, getString(R.string.message_too_big_for_video), Toast.LENGTH_SHORT).show(); } } break; case AttachmentTypeSelectorAdapter.ADD_SOUND: MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND); break; case AttachmentTypeSelectorAdapter.RECORD_SOUND: MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND); break; case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW: editSlideshow(); break; case AttachmentTypeSelectorAdapter.ADD_CONTACT_INFO: final Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(intent, REQUEST_CODE_ATTACH_CONTACT); break; default: break; } } private void showAddAttachmentDialog(final boolean replace) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_dialog_attach); builder.setTitle(R.string.add_attachment); if (mAttachmentTypeSelectorAdapter == null) { mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter( this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW); } builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace); dialog.dismiss(); } }); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (DEBUG) { log("requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data); } mWaitingForSubActivity = false; // We're back! if (mWorkingMessage.isFakeMmsForDraft()) { // We no longer have to fake the fact we're an Mms. At this point we are or we aren't, // based on attachments and other Mms attrs. mWorkingMessage.removeFakeMmsForDraft(); } // If there's no data (because the user didn't select a picture and // just hit BACK, for example), there's nothing to do. if (requestCode != REQUEST_CODE_TAKE_PICTURE) { if (data == null) { return; } } else if (resultCode != RESULT_OK){ if (DEBUG) log("bail due to resultCode=" + resultCode); return; } switch(requestCode) { case REQUEST_CODE_CREATE_SLIDESHOW: if (data != null) { WorkingMessage newMessage = WorkingMessage.load(this, data.getData()); if (newMessage != null) { mWorkingMessage = newMessage; mWorkingMessage.setConversation(mConversation); mAttachmentEditor.update(mWorkingMessage); drawTopPanel(); updateSendButtonState(); } } break; case REQUEST_CODE_TAKE_PICTURE: { // create a file based uri and pass to addImage(). We want to read the JPEG // data directly from file (using UriImage) instead of decoding it into a Bitmap, // which takes up too much memory and could easily lead to OOM. File file = new File(Mms.ScrapSpace.SCRAP_FILE_PATH); Uri uri = Uri.fromFile(file); addImage(uri, false); break; } case REQUEST_CODE_ATTACH_IMAGE: { addImage(data.getData(), false); break; } case REQUEST_CODE_TAKE_VIDEO: case REQUEST_CODE_ATTACH_VIDEO: addVideo(data.getData(), false); break; case REQUEST_CODE_ATTACH_SOUND: { Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) { break; } addAudio(uri); break; } case REQUEST_CODE_RECORD_SOUND: addAudio(data.getData()); break; case REQUEST_CODE_ATTACH_CONTACT: showContactInfoDialog(data.getData()); break; case REQUEST_CODE_ECM_EXIT_DIALOG: boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false); if (outOfEmergencyMode) { sendMessage(false); } break; case REQUEST_CODE_ADD_CONTACT: // The user just added a new contact. We saved the contact info in // mAddContactIntent. Get the contact and force our cached contact to // get reloaded with the new info (such as contact name). After the // contact is reloaded, the function onUpdate() in this file will get called // and it will update the title bar, etc. if (mAddContactIntent != null) { String address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL); if (address == null) { address = mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE); } if (address != null) { Contact contact = Contact.get(address, false); if (contact != null) { contact.reload(); } } } break; default: // TODO break; } } private void showContactInfoDialog(Uri contactUri) { String contactId = null, displayName = null; Cursor contactCursor = getContentResolver().query(contactUri, new String[] {Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null); if(contactCursor.moveToFirst()){ contactId = contactCursor.getString(0); displayName = contactCursor.getString(1); } else { Toast.makeText(this, R.string.cannot_find_contact, Toast.LENGTH_SHORT).show(); return; } final Cursor entryCursor = getContentResolver().query(Data.CONTENT_URI, new String[] { Data._ID, Data.DATA1, Data.DATA2, Data.DATA3, Data.MIMETYPE }, Data.CONTACT_ID + "=? AND (" + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=?)", new String[] { contactId, CommonDataKinds.Phone.CONTENT_ITEM_TYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE, CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE, CommonDataKinds.Website.CONTENT_ITEM_TYPE }, Data.DATA2 ); ContactEntryAdapter adapter = new ContactEntryAdapter(this, entryCursor); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_dialog_attach); builder.setTitle(displayName); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { entryCursor.moveToPosition(which); String value = entryCursor.getString(entryCursor.getColumnIndex(Data.DATA1)); int start = mTextEditor.getSelectionStart(); int end = mTextEditor.getSelectionEnd(); mTextEditor.getText().replace(Math.min(start, end), Math.max(start, end), value); dialog.dismiss(); } }); builder.show(); } private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() { // TODO: make this produce a Uri, that's what we want anyway public void onResizeResult(PduPart part, boolean append) { if (part == null) { handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture); return; } Context context = ComposeMessageActivity.this; PduPersister persister = PduPersister.getPduPersister(context); int result; Uri messageUri = mWorkingMessage.saveAsMms(true); try { Uri dataUri = persister.persistPart(part, ContentUris.parseId(messageUri)); result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("ResizeImageResultCallback: dataUri=" + dataUri); } } catch (MmsException e) { result = WorkingMessage.UNKNOWN_ERROR; } handleAddAttachmentError(result, R.string.type_picture); } }; private void handleAddAttachmentError(final int error, final int mediaTypeStringId) { if (error == WorkingMessage.OK) { return; } runOnUiThread(new Runnable() { public void run() { Resources res = getResources(); String mediaType = res.getString(mediaTypeStringId); String title, message; switch(error) { case WorkingMessage.UNKNOWN_ERROR: message = res.getString(R.string.failed_to_add_media, mediaType); Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show(); return; case WorkingMessage.UNSUPPORTED_TYPE: title = res.getString(R.string.unsupported_media_format, mediaType); message = res.getString(R.string.select_different_media, mediaType); break; case WorkingMessage.MESSAGE_SIZE_EXCEEDED: title = res.getString(R.string.exceed_message_size_limitation, mediaType); message = res.getString(R.string.failed_to_add_media, mediaType); break; case WorkingMessage.IMAGE_TOO_LARGE: title = res.getString(R.string.failed_to_resize_image); message = res.getString(R.string.resize_image_error_information); break; default: throw new IllegalArgumentException("unknown error " + error); } MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message); } }); } private void addImage(Uri uri, boolean append) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("append=" + append + ", uri=" + uri); } int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append); if (result == WorkingMessage.IMAGE_TOO_LARGE || result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("resize image " + uri); } MessageUtils.resizeImageAsync(this, uri, mAttachmentEditorHandler, mResizeImageCallback, append); return; } handleAddAttachmentError(result, R.string.type_picture); } private void addVideo(Uri uri, boolean append) { if (uri != null) { int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append); handleAddAttachmentError(result, R.string.type_video); } } private void addAudio(Uri uri) { int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false); handleAddAttachmentError(result, R.string.type_audio); } private boolean handleForwardedMessage() { Intent intent = getIntent(); // If this is a forwarded message, it will have an Intent extra // indicating so. If not, bail out. if (intent.getBooleanExtra("forwarded_message", false) == false) { return false; } Uri uri = intent.getParcelableExtra("msg_uri"); if (Log.isLoggable(LogTag.APP, Log.DEBUG)) { log("" + uri); } if (uri != null) { mWorkingMessage = WorkingMessage.load(this, uri); mWorkingMessage.setSubject(intent.getStringExtra("subject"), false); } else { mWorkingMessage.setText(intent.getStringExtra("sms_body")); } // let's clear the message thread for forwarded messages mMsgListAdapter.changeCursor(null); return true; } private boolean handleSendIntent(Intent intent) { Bundle extras = intent.getExtras(); if (extras == null) { return false; } final String mimeType = intent.getType(); String action = intent.getAction(); if (Intent.ACTION_SEND.equals(action)) { if (extras.containsKey(Intent.EXTRA_STREAM)) { Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM); addAttachment(mimeType, uri, false); return true; } else if (extras.containsKey(Intent.EXTRA_TEXT)) { mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT)); return true; } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) { SlideshowModel slideShow = mWorkingMessage.getSlideshow(); final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM); int currentSlideCount = slideShow != null ? slideShow.size() : 0; int importCount = uris.size(); if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) { importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount, importCount); Toast.makeText(ComposeMessageActivity.this, getString(R.string.too_many_attachments, SlideshowEditor.MAX_SLIDE_NUM, importCount), Toast.LENGTH_LONG).show(); } // Attach all the pictures/videos off of the UI thread. // Show a progress alert if adding all the slides hasn't finished // within one second. // Stash the runnable for showing it away so we can cancel // it later if adding completes ahead of the deadline. final AlertDialog dialog = new AlertDialog.Builder(ComposeMessageActivity.this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.adding_attachments_title) .setMessage(R.string.adding_attachments) .create(); final Runnable showProgress = new Runnable() { public void run() { dialog.show(); } }; // Schedule it for one second from now. mAttachmentEditorHandler.postDelayed(showProgress, 1000); final int numberToImport = importCount; new Thread(new Runnable() { public void run() { for (int i = 0; i < numberToImport; i++) { Parcelable uri = uris.get(i); addAttachment(mimeType, (Uri) uri, true); } // Cancel pending show of the progress alert if necessary. mAttachmentEditorHandler.removeCallbacks(showProgress); dialog.dismiss(); } }, "addAttachment").start(); return true; } return false; } // mVideoUri will look like this: content://media/external/video/media private static final String mVideoUri = Video.Media.getContentUri("external").toString(); // mImageUri will look like this: content://media/external/images/media private static final String mImageUri = Images.Media.getContentUri("external").toString(); private void addAttachment(String type, Uri uri, boolean append) { if (uri != null) { // When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be // videos, and/or images, and/or some other unknown types we don't handle. When // a single attachment is "shared" the type will specify an image or video. When // there are multiple types, the type passed in is "*/*". In that case, we've got // to look at the uri to figure out if it is an image or video. boolean wildcard = "*/*".equals(type); if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) { addImage(uri, append); } else if (type.startsWith("video/") || (wildcard && uri.toString().startsWith(mVideoUri))) { addVideo(uri, append); } } } private String getResourcesString(int id, String mediaName) { Resources r = getResources(); return r.getString(id, mediaName); } private void drawBottomPanel() { // Reset the counter for text editor. resetCounter(); if (mWorkingMessage.hasSlideshow()) { mBottomPanel.setVisibility(View.GONE); mAttachmentEditor.requestFocus(); return; } mBottomPanel.setVisibility(View.VISIBLE); CharSequence text = mWorkingMessage.getText(); // TextView.setTextKeepState() doesn't like null input. if (text != null) { mTextEditor.setTextKeepState(text); } else { mTextEditor.setText(""); } } private void drawTopPanel() { showSubjectEditor(mWorkingMessage.hasSubject()); } //========================================================== // Interface methods //========================================================== public void onClick(View v) { if ((v == mSendButton) && isPreparedForSending()) { confirmSendMessageIfNeeded(); } } public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null) { // Send on Enter if (((event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) && !mSendOnEnter) { return false; } // if shift key is down, then we want to insert the '\n' char in the TextView; // otherwise, the default action is to send the message. if (!event.isShiftPressed()) { if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; } return false; } if (isPreparedForSending()) { confirmSendMessageIfNeeded(); } return true; } private final TextWatcher mTextEditorWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // This is a workaround for bug 1609057. Since onUserInteraction() is // not called when the user touches the soft keyboard, we pretend it was // called when textfields changes. This should be removed when the bug // is fixed. onUserInteraction(); mWorkingMessage.setText(s); updateSendButtonState(); updateCounter(s, start, before, count); ensureCorrectButtonHeight(); } public void afterTextChanged(Editable s) { } }; /** * Ensures that if the text edit box extends past two lines then the * button will be shifted up to allow enough space for the character * counter string to be placed beneath it. */ private void ensureCorrectButtonHeight() { int currentTextLines = mTextEditor.getLineCount(); if (currentTextLines <= 2) { mTextCounter.setVisibility(View.GONE); } else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) { // Making the counter invisible ensures that it is used to correctly // calculate the position of the send button even if we choose not to // display the text. mTextCounter.setVisibility(View.INVISIBLE); } } private final TextWatcher mSubjectEditorWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { mWorkingMessage.setSubject(s, true); } public void afterTextChanged(Editable s) { } }; //========================================================== // Private methods //========================================================== /** * Initialize all UI elements from resources. */ private void initResourceRefs() { mMsgListView = (MessageListView) findViewById(R.id.history); mMsgListView.setDivider(null); // no divider so we look like IM conversation. mBottomPanel = findViewById(R.id.bottom_panel); mTextEditor = (EditText) findViewById(R.id.embedded_text_editor); mTextEditor.setOnEditorActionListener(this); mTextEditor.addTextChangedListener(mTextEditorWatcher); mTextEditor.setFilters(new InputFilter[] { new LengthFilter(MmsConfig.getMaxTextLimit())}); mTextCounter = (TextView) findViewById(R.id.text_counter); mSendButton = (Button) findViewById(R.id.send_button); mSendButton.setOnClickListener(this); mTopPanel = findViewById(R.id.recipients_subject_linear); mTopPanel.setFocusable(false); mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor); mAttachmentEditor.setHandler(mAttachmentEditorHandler); } private void confirmDeleteDialog(OnClickListener listener, boolean locked) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(locked ? R.string.confirm_dialog_locked_title : R.string.confirm_dialog_title); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setCancelable(true); builder.setMessage(locked ? R.string.confirm_delete_locked_message : R.string.confirm_delete_message); builder.setPositiveButton(R.string.delete, listener); builder.setNegativeButton(R.string.no, null); builder.show(); } void undeliveredMessageDialog(long date) { String body; LinearLayout dialog = (LinearLayout) LayoutInflater.from(this).inflate( R.layout.retry_sending_dialog, null); if (date >= 0) { body = getString(R.string.undelivered_msg_dialog_body, MessageUtils.formatTimeStampString(this, date)); } else { // FIXME: we can not get sms retry time. body = getString(R.string.undelivered_sms_dialog_body); } ((TextView) dialog.findViewById(R.id.body_text_view)).setText(body); Toast undeliveredDialog = new Toast(this); undeliveredDialog.setView(dialog); undeliveredDialog.setDuration(Toast.LENGTH_LONG); undeliveredDialog.show(); } private void startMsgListQuery() { Uri conversationUri = mConversation.getUri(); if (conversationUri == null) { return; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("for " + conversationUri); } // Cancel any pending queries mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN); try { // Kick off the new query mBackgroundQueryHandler.startQuery( MESSAGE_LIST_QUERY_TOKEN, null, conversationUri, PROJECTION, null, null, null); } catch (SQLiteException e) { SqliteWrapper.checkSQLiteException(this, e); } } private void initMessageList() { if (mMsgListAdapter != null) { return; } String highlightString = getIntent().getStringExtra("highlight"); Pattern highlight = highlightString == null ? null : Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE); // Initialize the list adapter with a null cursor. mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight); mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener); mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler); mMsgListView.setAdapter(mMsgListAdapter); mMsgListView.setItemsCanFocus(false); mMsgListView.setVisibility(View.VISIBLE); mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener); mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view != null) { ((MessageListItem) view).onMessageListItemClick(); } } }); } private void loadDraft() { if (mWorkingMessage.isWorthSaving()) { Log.w(TAG, "called with non-empty working message"); return; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("call WorkingMessage.loadDraft"); } mWorkingMessage = WorkingMessage.loadDraft(this, mConversation); } private void saveDraft() { // TODO: Do something better here. Maybe make discard() legal // to call twice and make isEmpty() return true if discarded // so it is caught in the clause above this one? if (mWorkingMessage.isDiscarded()) { return; } if (!mWaitingForSubActivity && !mWorkingMessage.isWorthSaving()) { if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("not worth saving, discard WorkingMessage and bail"); } mWorkingMessage.discard(); return; } mWorkingMessage.saveDraft(); if (mToastForDraftSave) { Toast.makeText(this, R.string.message_saved_as_draft, Toast.LENGTH_SHORT).show(); } } private boolean isPreparedForSending() { int recipientCount = recipientCount(); return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() && (mWorkingMessage.hasAttachment() || mWorkingMessage.hasText()); } private int recipientCount() { int recipientCount; // To avoid creating a bunch of invalid Contacts when the recipients // editor is in flux, we keep the recipients list empty. So if the // recipients editor is showing, see if there is anything in it rather // than consulting the empty recipient list. if (isRecipientsEditorVisible()) { recipientCount = mRecipientsEditor.getRecipientCount(); } else { recipientCount = getRecipients().size(); } return recipientCount; } private void sendMessage(boolean bCheckEcmMode) { if (bCheckEcmMode) { // TODO: expose this in telephony layer for SDK build String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE); if (Boolean.parseBoolean(inEcm)) { try { startActivityForResult( new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_ECM_EXIT_DIALOG); return; } catch (ActivityNotFoundException e) { // continue to send message Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e); } } } if (!mSendingMessage) { if (LogTag.SEVERE_WARNING) { String sendingRecipients = mConversation.getRecipients().serialize(); if (!sendingRecipients.equals(mDebugRecipients)) { String workingRecipients = mWorkingMessage.getWorkingRecipients(); if (!mDebugRecipients.equals(workingRecipients)) { LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage recipients in " + "window: \"" + mDebugRecipients + "\" differ from recipients from conv: \"" + sendingRecipients + "\" and working recipients: " + workingRecipients, this); } } } final Runnable onRun = new Runnable() { public void run() { // send can change the recipients. Make sure we remove the listeners first and then add // them back once the recipient list has settled. removeRecipientsListeners(); mWorkingMessage.send(mDebugRecipients); mSentMessage = true; mSendingMessage = true; addRecipientsListeners(); // But bail out if we are supposed to exit after the message is sent. if (mExitOnSent) { finish(); } } }; final Runnable onCancel = new Runnable() { public void run() { finish(); } }; if (phoneGoggles != null) { try { phoneGoggles.invoke(null, this, 1, // 1 for phone numbers, 2 for email addresses, 0 otherwise mConversation.getRecipients().getNumbers(), onRun, onCancel, R.string.dialog_phone_goggles_title, R.string.dialog_phone_goggles_title_unlocked, R.string.dialog_phone_goggles_content, R.string.dialog_phone_goggles_unauthorized, R.string.dialog_phone_goggles_ok, R.string.dialog_phone_goggles_cancel); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // If the Phone Goggles API doesn't exist } else { onRun.run(); } } } private void resetMessage() { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log(""); } // Make the attachment editor hide its view. mAttachmentEditor.hideView(); // Hide the subject editor. showSubjectEditor(false); // Focus to the text editor. mTextEditor.requestFocus(); // We have to remove the text change listener while the text editor gets cleared and // we subsequently turn the message back into SMS. When the listener is listening while // doing the clearing, it's fighting to update its counts and itself try and turn // the message one way or the other. mTextEditor.removeTextChangedListener(mTextEditorWatcher); // Clear the text box. TextKeyListener.clear(mTextEditor.getText()); mWorkingMessage = WorkingMessage.createEmpty(this); mWorkingMessage.setConversation(mConversation); hideRecipientEditor(); drawBottomPanel(); // "Or not", in this case. updateSendButtonState(); // Our changes are done. Let the listener respond to text changes once again. mTextEditor.addTextChangedListener(mTextEditorWatcher); // Close the soft on-screen keyboard if we're in landscape mode so the user can see the // conversation. if (mIsLandscape) { InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0); } mLastRecipientCount = 0; mSendingMessage = false; } private void updateSendButtonState() { boolean enable = false; if (isPreparedForSending()) { // When the type of attachment is slideshow, we should // also hide the 'Send' button since the slideshow view // already has a 'Send' button embedded. if (!mWorkingMessage.hasSlideshow()) { enable = true; } else { mAttachmentEditor.setCanSend(true); } } else if (null != mAttachmentEditor){ mAttachmentEditor.setCanSend(false); } setSendButtonText(mWorkingMessage.requiresMms()); mSendButton.setEnabled(enable); mSendButton.setFocusable(enable); } private long getMessageDate(Uri uri) { if (uri != null) { Cursor cursor = SqliteWrapper.query(this, mContentResolver, uri, new String[] { Mms.DATE }, null, null, null); if (cursor != null) { try { if ((cursor.getCount() == 1) && cursor.moveToFirst()) { return cursor.getLong(0) * 1000L; } } finally { cursor.close(); } } } return NO_DATE_FOR_DIALOG; } private void initActivityState(Bundle bundle, Intent intent) { if (bundle != null) { String recipients = bundle.getString("recipients"); if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients); mConversation = Conversation.get(this, ContactList.getByNumbers(recipients, false /* don't block */, true /* replace number */), false); addRecipientsListeners(); mExitOnSent = bundle.getBoolean("exit_on_sent", false); mWorkingMessage.readStateFromBundle(bundle); return; } // If we have been passed a thread_id, use that to find our conversation. long threadId = intent.getLongExtra("thread_id", 0); if (threadId > 0) { if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId); mConversation = Conversation.get(this, threadId, false); } else { Uri intentData = intent.getData(); if (intentData != null) { // try to get a conversation based on the data URI passed to our intent. if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData); mConversation = Conversation.get(this, intentData, false); mWorkingMessage.setText(getBody(intentData)); } else { // special intent extra parameter to specify the address String address = intent.getStringExtra("address"); if (!TextUtils.isEmpty(address)) { if (LogTag.VERBOSE) log("get mConversation by address " + address); mConversation = Conversation.get(this, ContactList.getByNumbers(address, false /* don't block */, true /* replace number */), false); } else { if (LogTag.VERBOSE) log("create new conversation"); mConversation = Conversation.createNew(this); } } } addRecipientsListeners(); mExitOnSent = intent.getBooleanExtra("exit_on_sent", false); if (intent.hasExtra("sms_body")) { mWorkingMessage.setText(intent.getStringExtra("sms_body")); } mWorkingMessage.setSubject(intent.getStringExtra("subject"), false); } private void initFocus() { if (!mIsKeyboardOpen) { return; } // If the recipients editor is visible, there is nothing in it, // and the text editor is not already focused, focus the // recipients editor. if (isRecipientsEditorVisible() && TextUtils.isEmpty(mRecipientsEditor.getText()) && !mTextEditor.isFocused()) { mRecipientsEditor.requestFocus(); return; } // If we decided not to focus the recipients editor, focus the text editor. mTextEditor.requestFocus(); } private final MessageListAdapter.OnDataSetChangedListener mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() { public void onDataSetChanged(MessageListAdapter adapter) { mPossiblePendingNotification = true; } public void onContentChanged(MessageListAdapter adapter) { startMsgListQuery(); } }; private void checkPendingNotification() { if (mPossiblePendingNotification && hasWindowFocus()) { mConversation.markAsRead(); mPossiblePendingNotification = false; } } private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch(token) { case MESSAGE_LIST_QUERY_TOKEN: int newSelectionPos = -1; long targetMsgId = getIntent().getLongExtra("select_id", -1); if (targetMsgId != -1) { cursor.moveToPosition(-1); while (cursor.moveToNext()) { long msgId = cursor.getLong(COLUMN_ID); if (msgId == targetMsgId) { newSelectionPos = cursor.getPosition(); break; } } } mMsgListAdapter.changeCursor(cursor); if (newSelectionPos != -1) { mMsgListView.setSelection(newSelectionPos); } // Once we have completed the query for the message history, if // there is nothing in the cursor and we are not composing a new // message, we must be editing a draft in a new conversation (unless // mSentMessage is true). // Show the recipients editor to give the user a chance to add // more people before the conversation begins. if (cursor.getCount() == 0 && !isRecipientsEditorVisible() && !mSentMessage) { initRecipientsEditor(); } // FIXME: freshing layout changes the focused view to an unexpected // one, set it back to TextEditor forcely. mTextEditor.requestFocus(); mConversation.blockMarkAsRead(false); return; case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN: long threadId = (Long)cookie; ConversationList.confirmDeleteThreadDialog( new ConversationList.DeleteThreadListener(threadId, mBackgroundQueryHandler, ComposeMessageActivity.this), threadId == -1, cursor != null && cursor.getCount() > 0, ComposeMessageActivity.this); break; } } @Override protected void onDeleteComplete(int token, Object cookie, int result) { switch(token) { case DELETE_MESSAGE_TOKEN: case ConversationList.DELETE_CONVERSATION_TOKEN: // Update the notification for new messages since they // may be deleted. MessagingNotification.nonBlockingUpdateNewMessageIndicator( ComposeMessageActivity.this, false, false); // Update the notification for failed messages since they // may be deleted. updateSendFailedNotification(); // Return to message list if the last message on thread is being deleted if (mMsgListAdapter.getCount() == 1) { finish(); } break; } // If we're deleting the whole conversation, throw away // our current working message and bail. if (token == ConversationList.DELETE_CONVERSATION_TOKEN) { mWorkingMessage.discard(); Conversation.init(ComposeMessageActivity.this); finish(); } } } private void showSmileyDialog() { if (mSmileyDialog == null) { int[] icons = SmileyParser.DEFAULT_SMILEY_RES_IDS; String[] names = getResources().getStringArray( SmileyParser.DEFAULT_SMILEY_NAMES); final String[] texts = getResources().getStringArray( SmileyParser.DEFAULT_SMILEY_TEXTS); final int N = names.length; List<Map<String, ?>> entries = new ArrayList<Map<String, ?>>(); for (int i = 0; i < N; i++) { // We might have different ASCII for the same icon, skip it if // the icon is already added. boolean added = false; for (int j = 0; j < i; j++) { if (icons[i] == icons[j]) { added = true; break; } } if (!added) { HashMap<String, Object> entry = new HashMap<String, Object>(); entry. put("icon", icons[i]); entry. put("name", names[i]); entry.put("text", texts[i]); entries.add(entry); } } final SimpleAdapter a = new SimpleAdapter( this, entries, R.layout.smiley_menu_item, new String[] {"icon", "name", "text"}, new int[] {R.id.smiley_icon, R.id.smiley_name, R.id.smiley_text}); SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() { public boolean setViewValue(View view, Object data, String textRepresentation) { if (view instanceof ImageView) { Drawable img = getResources().getDrawable((Integer)data); ((ImageView)view).setImageDrawable(img); return true; } return false; } }; a.setViewBinder(viewBinder); AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(getString(R.string.menu_insert_smiley)); b.setCancelable(true); b.setAdapter(a, new DialogInterface.OnClickListener() { @SuppressWarnings("unchecked") public final void onClick(DialogInterface dialog, int which) { HashMap<String, Object> item = (HashMap<String, Object>) a.getItem(which); mTextEditor.append((String)item.get("text")); dialog.dismiss(); } }); mSmileyDialog = b.create(); } mSmileyDialog.show(); } public void onUpdate(final Contact updated) { // Using an existing handler for the post, rather than conjuring up a new one. mMessageListItemHandler.post(new Runnable() { public void run() { ContactList recipients = isRecipientsEditorVisible() ? mRecipientsEditor.constructContactsFromInput() : getRecipients(); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("[CMA] onUpdate contact updated: " + updated); log("[CMA] onUpdate recipients: " + recipients); } updateTitle(recipients); // The contact information for one (or more) of the recipients has changed. // Rebuild the message list so each MessageItem will get the last contact info. ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged(); if (mRecipientsEditor != null) { mRecipientsEditor.populate(recipients); } } }); } private void addRecipientsListeners() { Contact.addListener(this); } private void removeRecipientsListeners() { Contact.removeListener(this); } public static Intent createIntent(Context context, long threadId) { Intent intent = new Intent(context, ComposeMessageActivity.class); if (threadId > 0) { intent.setData(Conversation.getUri(threadId)); } return intent; } private String getBody(Uri uri) { if (uri == null) { return null; } String urlStr = uri.getSchemeSpecificPart(); if (!urlStr.contains("?")) { return null; } urlStr = urlStr.substring(urlStr.indexOf('?') + 1); String[] params = urlStr.split("&"); for (String p : params) { if (p.startsWith("body=")) { try { return URLDecoder.decode(p.substring(5), "UTF-8"); } catch (UnsupportedEncodingException e) { } } } return null; } }
[ "ioz9ioz9@gmail.com" ]
ioz9ioz9@gmail.com
c21231e9a8bfd37708668656dbfade31909edcfb
3c3e9fa6f13aead3eaef4c632366b9c14161b2b6
/src/main/java/br/ufpi/entidades/Endereco.java
1f0ce22c1987e125586c4e2e66c59b23d8ca3f2a
[]
no_license
katiacih/ufpi-treinamento
5c0fcfdce89c7dc8b259b794482f3d7d18ee1497
796df8db2d8bf0d0ff1b3f63450cb3b5aea94f5a
refs/heads/master
2021-01-10T09:39:51.622949
2015-03-07T14:40:27
2015-03-07T14:40:27
50,693,704
1
0
null
null
null
null
UTF-8
Java
false
false
815
java
package br.ufpi.entidades; import java.io.Serializable; import javax.persistence.Embeddable; @Embeddable public class Endereco implements Serializable { private static final long serialVersionUID = 1L; private String numero; private String logradouro; private String cep; private String bairro; public Endereco() { } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getLogradouro() { return logradouro; } public void setLogradouro(String logradouro) { this.logradouro = logradouro; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } }
[ "stanleymsn@gmail.com" ]
stanleymsn@gmail.com
5481b621a5901969e7b51e189ae5b7ef9a85a581
447520f40e82a060368a0802a391697bc00be96f
/apks/malware/app32/source/com/payeco/android/plugin/e.java
5ee1b9b70ce24185ce0d0e8888d162ef4e77b9af
[ "Apache-2.0" ]
permissive
iantal/AndroidPermissions
7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465
d623b732734243590b5f004d167e542e2e2ae249
refs/heads/master
2023-07-19T01:29:26.689186
2019-09-30T19:01:42
2019-09-30T19:01:42
107,239,248
0
0
Apache-2.0
2023-07-16T07:41:38
2017-10-17T08:22:57
null
UTF-8
Java
false
false
4,426
java
package com.payeco.android.plugin; import android.hardware.Camera.PictureCallback; final class e implements Camera.PictureCallback { e(b paramB) {} /* Error */ public final void onPictureTaken(byte[] paramArrayOfByte, android.hardware.Camera paramCamera) { // Byte code: // 0: new 24 java/io/FileOutputStream // 3: dup // 4: getstatic 30 com/payeco/android/plugin/b/a:b Ljava/lang/String; // 7: invokespecial 33 java/io/FileOutputStream:<init> (Ljava/lang/String;)V // 10: astore_3 // 11: aload_3 // 12: astore_2 // 13: aload_3 // 14: aload_1 // 15: invokevirtual 37 java/io/FileOutputStream:write ([B)V // 18: aload_3 // 19: astore_2 // 20: aload_0 // 21: getfield 12 com/payeco/android/plugin/e:a Lcom/payeco/android/plugin/b; // 24: invokestatic 42 com/payeco/android/plugin/b:a (Lcom/payeco/android/plugin/b;)Lcom/payeco/android/plugin/a; // 27: invokestatic 47 com/payeco/android/plugin/a:a (Lcom/payeco/android/plugin/a;)Lcom/payeco/android/plugin/PayecoCameraActivity; // 30: iconst_m1 // 31: invokevirtual 53 com/payeco/android/plugin/PayecoCameraActivity:setResult (I)V // 34: aload_3 // 35: invokevirtual 56 java/io/FileOutputStream:close ()V // 38: aload_0 // 39: getfield 12 com/payeco/android/plugin/e:a Lcom/payeco/android/plugin/b; // 42: invokestatic 42 com/payeco/android/plugin/b:a (Lcom/payeco/android/plugin/b;)Lcom/payeco/android/plugin/a; // 45: invokestatic 47 com/payeco/android/plugin/a:a (Lcom/payeco/android/plugin/a;)Lcom/payeco/android/plugin/PayecoCameraActivity; // 48: invokevirtual 59 com/payeco/android/plugin/PayecoCameraActivity:finish ()V // 51: return // 52: astore 4 // 54: aconst_null // 55: astore_1 // 56: aload_1 // 57: astore_2 // 58: ldc 61 // 60: ldc 63 // 62: aload 4 // 64: invokestatic 69 android/util/Log:e (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I // 67: pop // 68: aload_1 // 69: ifnull -18 -> 51 // 72: aload_1 // 73: invokevirtual 56 java/io/FileOutputStream:close ()V // 76: aload_0 // 77: getfield 12 com/payeco/android/plugin/e:a Lcom/payeco/android/plugin/b; // 80: invokestatic 42 com/payeco/android/plugin/b:a (Lcom/payeco/android/plugin/b;)Lcom/payeco/android/plugin/a; // 83: invokestatic 47 com/payeco/android/plugin/a:a (Lcom/payeco/android/plugin/a;)Lcom/payeco/android/plugin/PayecoCameraActivity; // 86: invokevirtual 59 com/payeco/android/plugin/PayecoCameraActivity:finish ()V // 89: return // 90: astore_1 // 91: aconst_null // 92: astore_2 // 93: aload_2 // 94: ifnull +20 -> 114 // 97: aload_2 // 98: invokevirtual 56 java/io/FileOutputStream:close ()V // 101: aload_0 // 102: getfield 12 com/payeco/android/plugin/e:a Lcom/payeco/android/plugin/b; // 105: invokestatic 42 com/payeco/android/plugin/b:a (Lcom/payeco/android/plugin/b;)Lcom/payeco/android/plugin/a; // 108: invokestatic 47 com/payeco/android/plugin/a:a (Lcom/payeco/android/plugin/a;)Lcom/payeco/android/plugin/PayecoCameraActivity; // 111: invokevirtual 59 com/payeco/android/plugin/PayecoCameraActivity:finish ()V // 114: aload_1 // 115: athrow // 116: astore_1 // 117: goto -41 -> 76 // 120: astore_2 // 121: goto -20 -> 101 // 124: astore_1 // 125: goto -87 -> 38 // 128: astore_1 // 129: goto -36 -> 93 // 132: astore 4 // 134: aload_3 // 135: astore_1 // 136: goto -80 -> 56 // Local variable table: // start length slot name signature // 0 139 0 this e // 0 139 1 paramArrayOfByte byte[] // 0 139 2 paramCamera android.hardware.Camera // 10 125 3 localFileOutputStream java.io.FileOutputStream // 52 11 4 localException1 Exception // 132 1 4 localException2 Exception // Exception table: // from to target type // 0 11 52 java/lang/Exception // 0 11 90 finally // 72 76 116 java/io/IOException // 97 101 120 java/io/IOException // 34 38 124 java/io/IOException // 13 18 128 finally // 20 34 128 finally // 58 68 128 finally // 13 18 132 java/lang/Exception // 20 34 132 java/lang/Exception } }
[ "antal.micky@yahoo.com" ]
antal.micky@yahoo.com
2ba8148790e8797a776b09f8f558304514a27cec
b00987f423ad64d9b8e47fd58cb7c0de81b74dbf
/src/main/java/com/carservice/application/data/entity/Warehouse.java
08a4d7159887cdac2d9efe3befeb70b0a00c0bf3
[]
no_license
STyulenev/CarService
d0d045604915a8ee0bee65d25f3209e2b9b68555
c5e08047a67c1f60ca05b58e426b539cfd6e4724
refs/heads/main
2023-08-23T13:43:02.829985
2021-10-23T08:53:47
2021-10-23T08:53:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,228
java
package com.carservice.application.data.entity; import javax.persistence.*; import java.util.List; @Entity @Table(name = "Warehouse", schema = "public") public class Warehouse { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name="office_id", nullable=false) private Office office; @Column(name = "quantity") private Integer quantity; @ManyToMany @JoinTable( name = "Detail_Warehouse", joinColumns = @JoinColumn(name = "warehouse_id"), inverseJoinColumns = @JoinColumn(name = "detail_id")) private List<Detail> details; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public List<Detail> getDetails() { return details; } public void setDetails(List<Detail> details) { this.details = details; } public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } }
[ "Tyulenev.i@yandex.ru" ]
Tyulenev.i@yandex.ru
eef665ad4917638d8fef4251d506525ab439d5eb
80adb15ab8807813caa7cc9f44e98e2f1ca51309
/app/src/main/java/richard/example/com/androidlearningdemo/fragment/TabLayout/TabLayoutFragment.java
f4ddfc1cd385f235f9e9224f023090c984d4e6f9
[]
no_license
richardxu/AndroidLearningDemo
8660f3e718de1449335a77eeeed5347596961c7d
e452d9c806786f2a9e7acd958b5ae6ca08144c01
refs/heads/master
2020-12-24T12:13:12.650808
2017-03-08T09:46:45
2017-03-08T09:46:45
73,066,196
0
0
null
null
null
null
UTF-8
Java
false
false
1,015
java
package richard.example.com.androidlearningdemo.fragment.TabLayout; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import richard.example.com.androidlearningdemo.R; /** * Created by Administrator on 2016/11/10. */ public class TabLayoutFragment extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.fragment_tabs_layout); // Get the ViewPager and set it's PagerAdapter so that is can display items ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(), TabLayoutFragment.this)); //Give the TabLayout the viewPager TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); tabLayout.setupWithViewPager(viewPager); } }
[ "xulican@gmail.com" ]
xulican@gmail.com
3e4f6d12202744d3b5efa7ed8b9ea0626a93377c
13c2d3db2d49c40c74c2e6420a9cd89377f1c934
/program_data/JavaProgramData/36/389.java
9a4bce42cb9fa457bd984c13d151dafb8e1af26e
[ "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
866
java
package <missing>; public class GlobalMembers { public static void Main() { String c = new String(new char[10]); String b = new String(new char[10]); int i; int j; int n; int k; int m; String tempVar = ConsoleInput.scanfRead(); if (tempVar != null) { c = tempVar.charAt(0); } String tempVar2 = ConsoleInput.scanfRead(" "); if (tempVar2 != null) { b = tempVar2.charAt(0); } n = c.length(); m = b.length(); if (m == n) { for (i = 0;i < n;i++) { for (j = 0;j < n;j++) { if (c.charAt(i) != ' ' && b.charAt(j) != ' ') { if (c.charAt(i) == b.charAt(j)) { c = tangible.StringFunctions.changeCharacter(c, i, b[j] = ' '); } } } } for (i = 0;i < n;i++) { if (c.charAt(i) != ' ' || b.charAt(i) != ' ') { System.out.print("NO"); break; } } if (i == n) { System.out.print("YES"); } } else { System.out.print("NO"); } } }
[ "y.yu@open.ac.uk" ]
y.yu@open.ac.uk
42fc8add593389a124aeeee7f5bb8c344890cda5
2135ba111249c6e87097e42c4a9d2db0b96be297
/prosolo-analytics/src/main/java/org/prosolo/bigdata/dal/cassandra/UserRecommendationsDBManager.java
4627c076fc0c040e43495978e64f5fded78ffe76
[ "BSD-3-Clause" ]
permissive
prosolotechnologies/prosolo
55742dda961359cfcd01231f3ae41de41eb73666
fb2058577002f9dce362375afb2ca72bb51deef7
refs/heads/master
2022-12-26T20:23:41.213375
2020-07-15T19:44:10
2020-07-15T19:44:10
239,235,647
3
0
BSD-3-Clause
2022-12-16T04:23:15
2020-02-09T02:35:26
Java
UTF-8
Java
false
false
743
java
package org.prosolo.bigdata.dal.cassandra;/** * Created by zoran on 20/07/16. */ import java.util.List; /** * zoran 20/07/16 */ public interface UserRecommendationsDBManager { // void insertStudentPreferenceRecord(Long student, String resourcetype, Long resourceid, Double preference, Long timestamp); void insertStudentPreferenceForDate(Long student, String resourcetype, Long resourceid, Double preference, Long dateEpoch); Double getStudentPreferenceForDate(Long student, String resourcetype, Long resourceid, Long dateEpoch); void insertClusterUsers(Long cluster, List<Long> users); void insertNewUser(Long userid, Long timestamp); Boolean isStudentNew(Long user); void deleteStudentNew(Long user); }
[ "zoran.jeremic@gmail.com" ]
zoran.jeremic@gmail.com
a11561119ada365b21904a0eeb1a2a59d998988f
26a165be16d17a624f8cfec920afa226bc420372
/第四次作业/product-api/product-api-boot/src/main/java/com/fh/util/Md5Util.java
eb7a54ba46e7f9d1d0e2268c07abd2d6215d3523
[]
no_license
Crush-sh/work
eb6f04f10ff804d0126d1ebd6b7a5f58c3efde4a
ef3a43effc5253d4481402a66a3e5e22882eae15
refs/heads/master
2022-07-02T18:13:11.016206
2020-02-09T12:00:16
2020-02-09T12:00:16
235,764,897
0
1
null
2022-06-29T18:19:46
2020-01-23T09:44:54
JavaScript
UTF-8
Java
false
false
805
java
package com.fh.util; import java.security.MessageDigest; public class Md5Util { public final static String md5(String s){ char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] strTemp = s.getBytes(); // 使用MD5创建MessageDigest对象 MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte b = md[i]; // 将没个数(int)b进行双字节加密 str[k++] = hexDigits[b >> 4 & 0xf]; str[k++] = hexDigits[b & 0xf]; } return new String(str); } catch (Exception e) { return null; } } public static void main(String[] args) { } }
[ "929677188@qq.com" ]
929677188@qq.com
88e5184acd4905f0ae61ff97196d960c11763f15
81f478a51b5733f09e484d0ae420154534906fa7
/Caso di studio/src/scuola/Insegnamento.java
bd6c1ea8c7d1a5837fb6f066984ab9f2bc323695
[]
no_license
ChristianDB99/Programmazione2
ea3ea44a4fd099f83fa1e4fde1e7ee12ce51d62f
49e5d2e9fc260a07d9e7600793d69a0065a62dbb
refs/heads/main
2023-08-26T08:57:31.241174
2021-10-26T10:21:46
2021-10-26T10:21:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
185
java
package scuola; public enum Insegnamento { INFORMATICA, MATEMATICA, ITALIANO, STORIA, MUSICA, EDUCAZIONE_FISICA, FISICA, TECNOLOGIA, RELIGIONE }
[ "christiandibrisco1999@gmail.com" ]
christiandibrisco1999@gmail.com
6e72f731fb4f7cd26bf7b5e7ca6981a6750fc451
9914d8322c1a201c1eba93718277d53f1e0069dc
/app/src/main/java/com/testadria/adriaalbumapp/interfaces/IPhotosView.java
84acb546a696d9402d7ea4e2d979f01021462bb7
[]
no_license
mob7/AdriaAlbumApp
13a18991916bacb370fb76d52295adc1a782e51f
62e0d1ca26cd082586a33fcc01290659ef0b759b
refs/heads/master
2021-05-10T14:52:35.521342
2018-01-23T17:52:43
2018-01-23T17:52:43
118,532,662
0
0
null
null
null
null
UTF-8
Java
false
false
222
java
package com.testadria.adriaalbumapp.interfaces; import com.facebook.GraphResponse; /** * Created by OUSSAMA on 23/01/2018. */ public interface IPhotosView { void GetAlbumImagesCompleted(GraphResponse response); }
[ "mohamed.elbelaidi@kindyinfomaroc.com" ]
mohamed.elbelaidi@kindyinfomaroc.com
6fdc471b9174b71a282bdf3e0b199d586f03e207
375113d527a97a4e141185db920291d3d4188f93
/DB2/app/src/main/java/com/example/hp/db2/MainActivity.java
4aabf2fd7836f95d851d3c86265bdcf23f986989
[]
no_license
Eve-wambui/AndroidStudioProjects
51b618dd5113db063c016c9732987beb377c0be4
cc87b86790eacec078aec1670fbfb2014231124e
refs/heads/master
2020-08-02T12:24:27.428221
2019-09-27T15:39:42
2019-09-27T15:39:42
211,351,672
0
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.example.hp.db2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "wambui17evelyne@gmail.com" ]
wambui17evelyne@gmail.com
121cc8fd905a036c31cc827b4f387fb6679c3a27
9c75035862a7e2b30b9f64b3c063d55ed355cbc3
/MyLibrary/src/PanelModifié/OffAdd.java
9f8213d714fc9c218eccfef7bdfd10a995dd9659
[]
no_license
FilRougeLibrairie/Librairie
469fb35e99328693bfc08115051062ca66086ee6
818b6e68c1703f350f2b5bb3a2d336ec518bcbcb
refs/heads/master
2021-01-23T07:27:25.384951
2017-10-10T08:52:13
2017-10-10T08:52:13
102,212,586
0
0
null
null
null
null
UTF-8
Java
false
false
17,263
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 PanelModifié; import ClassObjet.Offer; import SQLS.OfferDAO; import java.awt.Color; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.Vector; import javax.swing.DefaultComboBoxModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.jdatepicker.impl.JDatePanelImpl; import org.jdatepicker.impl.JDatePickerImpl; import org.jdatepicker.impl.UtilDateModel; import utils.DateLabelFormatter; /** * * @author cdi303 */ public class OffAdd extends javax.swing.JPanel { JDatePickerImpl datePicker, datePicker2; private JFileChooser jfc = new JFileChooser(); private String date, dateEnd; JOptionPane jop1, jop2 = new JOptionPane(); OfferDAO offerDAO = new OfferDAO(); Offer offer = new Offer(); Vector<Offer> offerList; OfferDAO vatDAO = new OfferDAO(); Vector v = new Vector(); Offer p = new Offer(); public OffAdd() { initComponents(); jComboBox1.setSelectedIndex(-1); UtilDateModel model = new UtilDateModel(); UtilDateModel mode2 = new UtilDateModel(); Properties p = new Properties(); p.put("text.today", "Today"); p.put("text.month", "Month"); p.put("text.year", "Year"); jComboBox1.setSelectedIndex(-1); JDatePanelImpl datePanel = new JDatePanelImpl(model, p); JDatePanelImpl datePanel1 = new JDatePanelImpl(mode2, p); datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter()); datePicker.setBackground(Color.WHITE); datePicker.setBounds(0, 0, 200, 30); datePicker.setVisible(true); datePicker2 = new JDatePickerImpl(datePanel1, new DateLabelFormatter()); datePicker2.setBackground(Color.WHITE); datePicker2.setBounds(0, 0, 200, 30); datePicker2.setVisible(true); panelDate.setSize(100, 100); panelDate.add(datePicker); panelDate1.setSize(100, 100); panelDate1.add(datePicker2); datePicker.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { datePickerActionPerformed(evt); } }); datePicker2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { datePicker2ActionPerformed(evt); } }); } private void datePickerActionPerformed(java.awt.event.ActionEvent evt) { Date selectedDate = (Date) datePicker.getModel().getValue(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); date = df.format(selectedDate); } private void datePicker2ActionPerformed(java.awt.event.ActionEvent evt) { Date selectedDate2 = (Date) datePicker2.getModel().getValue(); SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd"); dateEnd = df2.format(selectedDate2); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTName = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTDiscount = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jTLink = new javax.swing.JTextField(); panelDate1 = new javax.swing.JPanel(); panelDate = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTComment = new javax.swing.JTextArea(); jComboBox1 = new javax.swing.JComboBox(); setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Nom de l'offre:"); jLabel2.setText("Commentaire:"); jLabel4.setText("% de Remise:"); jButton2.setBackground(new java.awt.Color(0, 51, 255)); jButton2.setText("SELECTIONNER UNE IMAGE"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel3.setText("Lien de l'image "); jTLink.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTLinkActionPerformed(evt); } }); javax.swing.GroupLayout panelDate1Layout = new javax.swing.GroupLayout(panelDate1); panelDate1.setLayout(panelDate1Layout); panelDate1Layout.setHorizontalGroup( panelDate1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); panelDate1Layout.setVerticalGroup( panelDate1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 32, Short.MAX_VALUE) ); javax.swing.GroupLayout panelDateLayout = new javax.swing.GroupLayout(panelDate); panelDate.setLayout(panelDateLayout); panelDateLayout.setHorizontalGroup( panelDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); panelDateLayout.setVerticalGroup( panelDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 32, Short.MAX_VALUE) ); jLabel5.setText("Date de début:"); jLabel6.setText("Date de fin:"); jButton1.setBackground(new java.awt.Color(0, 51, 255)); jButton1.setText("VALIDER"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTComment.setColumns(20); jTComment.setRows(5); jScrollPane1.setViewportView(jTComment); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Actif", "Inactif" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(80, 80, 80) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelDate1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jTLink, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTName, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup() .addGap(133, 133, 133) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(283, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(74, 74, 74) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jTName, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(jTDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(panelDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(panelDate1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTLink, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(61, 61, 61)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38)) ); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed int returnval = jfc.showOpenDialog(jButton2); if (returnval == JFileChooser.APPROVE_OPTION) { //recuperation du chemin jTLink.setText(jfc.getSelectedFile().getAbsolutePath()); } }//GEN-LAST:event_jButton2ActionPerformed private void jTLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTLinkActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTLinkActionPerformed private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked }//GEN-LAST:event_jButton1MouseClicked int value = 0; private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (jComboBox1.getSelectedItem().equals("Actif")) { value = 0; } else{ value = 1; } Offer offer = new Offer(); offer.setOffStatus(value); offer.setOffName(jTName.getText()); offer.setOffText(jTComment.getText()); offer.setOffPicture(jTLink.getText()); offer.setOffDateStart(date); offer.setOffDateEnd(dateEnd); offer.setOffDiscount(Float.valueOf(jTDiscount.getText())); OfferDAO offerDAO = new OfferDAO(); offerDAO.create(offer); jop1.showMessageDialog(null, "L'offre a été ajoutée avec succès.", "Information", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_jButton1ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed }//GEN-LAST:event_jComboBox1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTComment; private javax.swing.JTextField jTDiscount; private javax.swing.JTextField jTLink; private javax.swing.JTextField jTName; private javax.swing.JPanel panelDate; private javax.swing.JPanel panelDate1; // End of variables declaration//GEN-END:variables }
[ "chrystelle.bihan@hotmail.fr" ]
chrystelle.bihan@hotmail.fr
ad4ce9924d6a486f2409e0fc65d23bc6056149e9
a7210128b2ae776ae197319767de4cfbab33f21b
/parser/src/main/java/com/onenetwork/util/SerialUtils.java
1bcd72e583b4bffbc3f269a2210e5b488c857927
[]
no_license
gigbat/onenetwork-parser
5c213e38bc76661df267ec44e59b650d9735ee10
cfb0aba33f8f06f846accc1b5031c3e0c8c9cbfb
refs/heads/master
2023-06-25T04:53:06.640903
2021-07-22T16:18:08
2021-07-22T16:18:08
387,429,454
0
0
null
null
null
null
UTF-8
Java
false
false
544
java
package com.onenetwork.util; import com.google.gson.Gson; import lombok.experimental.UtilityClass; @UtilityClass public class SerialUtils { public String serializeObject(Object o) { Gson gson = new Gson(); return gson.toJson(o); } public static Object unserializeObject(String s, Object o) { Gson gson = new Gson(); return gson.fromJson(s, o.getClass()); } public static Object cloneObject(Object o) { String s = serializeObject(o); return unserializeObject(s, o); } }
[ "b.kostevich@gmail.com" ]
b.kostevich@gmail.com
8bab9b155f1d46f4c81ab52e74b4bd2e09ec8958
9ef5f50f173f5f73792ee047ece613f03dbeb30f
/RandomNumber_AscendingDescending/SortingNumbers.java
e7c008259483e7a1b9088dee4bcc0e7d3392fb09
[]
no_license
devliang/DataStructurePractice
46adde29c3b33c83b8dbf73027f540c49c546875
eae901078634c47f5ea9fb89c215ce1183d04d88
refs/heads/master
2021-07-19T16:13:22.230591
2019-01-27T04:59:01
2019-01-27T04:59:01
151,512,973
1
1
null
2019-01-27T04:59:02
2018-10-04T03:20:40
Java
UTF-8
Java
false
false
857
java
public class SortingNumbers { private int[] arr; private int nElems; public SortingNumbers(int[] arr){ this.arr = arr; nElems = arr.length; } public void ascendingBubbleSort(){ int out, in; for(out = nElems - 1; out>1; out --){ for(in=0; in<out; in++){ if(arr[in] > arr[in+1]) swap(in, in+1); } } } public void descendingBubbleSort(){ int out, in; for(out = nElems - 1; out>1; out --){ for(in=0; in<out; in++){ if(arr[in] < arr[in+1]) swap(in, in+1); } } } public void swap(int a, int b){ int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } public void display(){ for(int i=0; i<arr.length;i++){ System.out.print(arr[i] + " "); } System.out.println(""); } }
[ "ryanfang0827@gmail.com" ]
ryanfang0827@gmail.com
36e6f5226a9e17ccc652579f5e858d523c281222
f5b75261f0c2123c68b3bf09b0319799147cc7b0
/struts-2.3.1/core/src/test/java/org/apache/struts2/dispatcher/ActionContextCleanUpTest.java
fd498e8f3d77c7af818c073e2d90028472f9f37f
[]
no_license
tangyong/struts2-osgi-plugin-glassfish
0ca477a11100dbef93831a0ee19a09b6f55a2d98
1a7ce57e2a4c8e439398bf9a4fef0b086b3b1b4a
refs/heads/master
2021-01-23T13:36:13.293775
2013-01-22T10:37:18
2013-01-22T10:37:18
7,551,994
1
0
null
null
null
null
UTF-8
Java
false
false
6,384
java
/* * $Id: ActionContextCleanUpTest.java 651946 2008-04-27 13:41:38Z apetrelli $ * * 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.struts2.dispatcher; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.dispatcher.mapper.ActionMapping; import org.springframework.mock.web.MockFilterConfig; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import com.mockobjects.servlet.MockFilterChain; import junit.framework.TestCase; /** * @version $Date: 2008-04-27 22:41:38 +0900 (日, 27 4 2008) $ $Id: ActionContextCleanUpTest.java 651946 2008-04-27 13:41:38Z apetrelli $ */ public class ActionContextCleanUpTest extends TestCase { protected MockFilterConfig filterConfig; protected MockHttpServletRequest request; protected MockHttpServletResponse response; protected MockFilterChain filterChain; protected MockFilterChain filterChain2; protected MockServletContext servletContext; protected Counter counter; protected Map<String, Integer> _tmpStore; protected InnerDispatcher _dispatcher; protected InnerDispatcher _dispatcher2; protected ActionContextCleanUp cleanUp; protected ActionContextCleanUp cleanUp2; @Override protected void tearDown() throws Exception { filterConfig = null; request = null; response = null; filterChain = null; filterChain2 = null; servletContext = null; counter = null; _tmpStore = null; _dispatcher = null; _dispatcher2 = null; cleanUp = null; cleanUp2 = null; } @Override protected void setUp() throws Exception { Dispatcher.setInstance(null); counter = new Counter(); _tmpStore = new LinkedHashMap<String, Integer>(); filterConfig = new MockFilterConfig(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); servletContext = new MockServletContext(); _dispatcher = new InnerDispatcher(servletContext) { @Override public String toString() { return "dispatcher"; } }; _dispatcher2 = new InnerDispatcher(servletContext){ @Override public String toString() { return "dispatcher2"; } }; filterChain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { _tmpStore.put("counter"+(counter.count++), (Integer) request.getAttribute("__cleanup_recursion_counter")); } }; cleanUp = new ActionContextCleanUp(); cleanUp2 = new ActionContextCleanUp(); filterChain2 = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { _tmpStore.put("counter"+(counter.count++), (Integer) request.getAttribute("__cleanup_recursion_counter")); cleanUp2.doFilter(request, response, filterChain); } }; } public void testSingle() throws Exception { assertNull(request.getAttribute("__cleanup_recursion_counter")); cleanUp.init(filterConfig); cleanUp.doFilter(request, response, filterChain); cleanUp.destroy(); assertEquals(_tmpStore.size(), 1); assertEquals(_tmpStore.get("counter0"), new Integer(1)); assertEquals(request.getAttribute("__cleanup_recursion_counter"), new Integer("0")); } public void testMultiple() throws Exception { assertNull(request.getAttribute("__cleanup_recursion_counter")); cleanUp.init(filterConfig); cleanUp2.init(filterConfig); cleanUp.doFilter(request, response, filterChain2); cleanUp2.destroy(); cleanUp.destroy(); assertEquals(_tmpStore.size(), 2); assertEquals(_tmpStore.get("counter0"), new Integer(1)); assertEquals(_tmpStore.get("counter1"), new Integer(2)); assertEquals(request.getAttribute("__cleanup_recursion_counter"), new Integer("0")); } class InnerDispatcher extends Dispatcher { public boolean prepare = false; public boolean wrapRequest = false; public boolean service = false; public InnerDispatcher(ServletContext servletContext) { super(servletContext, new HashMap<String,String>()); } @Override public void prepare(HttpServletRequest request, HttpServletResponse response) { prepare = true; } @Override public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext) throws IOException { wrapRequest = true; return request; } @Override public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { service = true; } } class Counter { public int count=0; } }
[ "tangyong@cn.fujitsu.com" ]
tangyong@cn.fujitsu.com
af3694d73fb17f1621c8c89bb8519e21ca5c3be1
2312f07ef2524597a00ac84c5537563f950690f7
/earth3d_pro_wallpaper/src/main/java/com/xmodpp/addons/wallpaper/XMODWallpaperService.java
3ef37526f93c07661be7bd9da906e915fee02ed0
[]
no_license
jinkg/ETW_Components
6cd1ed14c334779947f09d9e8609552cf9ecfbdd
b16fb28acd4b3e0c68ffd1dbeeb567b6c0371dbc
refs/heads/master
2021-05-07T06:29:01.507396
2018-09-26T12:44:26
2018-09-26T12:44:28
111,760,297
2
0
null
null
null
null
UTF-8
Java
false
false
2,950
java
package com.xmodpp.addons.wallpaper; import android.content.res.Configuration; import android.service.wallpaper.WallpaperService; import android.service.wallpaper.WallpaperService.Engine; import android.view.MotionEvent; import android.view.SurfaceHolder; import com.xmodpp.application.Application; public abstract class XMODWallpaperService extends WallpaperService { private static XMODWallpaperEngine activeEngine; public class XMODWallpaperEngine extends Engine { protected XMODWallpaperSurface surface = new XMODWallpaperSurface(); public XMODWallpaperEngine() { super(); } public void onConfigurationChanged(Configuration configuration) { this.surface.updateRotation(); } public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); this.surface.setID(isPreview() ? 2 : 1); surfaceHolder.addCallback(this.surface); } public void onDestroy() { super.onDestroy(); } public void onOffsetsChanged(float f, float f2, float f3, float f4, int i, int i2) { super.onOffsetsChanged(f, f2, f3, f4, i, i2); if (!isPreview()) { this.surface.onWallpaperOffsetsChanged(f, f2, f3, f4, i, i2); } } public void onTouchEvent(MotionEvent motionEvent) { super.onTouchEvent(motionEvent); this.surface.onTouch(null, motionEvent); } public void onVisibilityChanged(boolean z) { super.onVisibilityChanged(z); if (z) { XMODWallpaperService.setActiveEngine(this); this.surface.surfaceChanged(null, 0, getSurfaceHolder().getSurfaceFrame().width(), getSurfaceHolder().getSurfaceFrame().height()); this.surface.onResume(); return; } this.surface.onPause(); } } public static synchronized XMODWallpaperEngine getActiveEngine() { XMODWallpaperEngine xMODWallpaperEngine; synchronized (XMODWallpaperService.class) { xMODWallpaperEngine = activeEngine; } return xMODWallpaperEngine; } private static synchronized void setActiveEngine(XMODWallpaperEngine xMODWallpaperEngine) { synchronized (XMODWallpaperService.class) { activeEngine = xMODWallpaperEngine; } } public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); XMODWallpaperEngine activeEngine = getActiveEngine(); if (activeEngine != null) { activeEngine.onConfigurationChanged(configuration); } } public void onCreate() { super.onCreate(); Application.Init(getApplicationContext()); } public Engine onCreateEngine() { return new XMODWallpaperEngine(); } }
[ "jinyalin@baidu.com" ]
jinyalin@baidu.com
d3d46b0d7785c80ec59d80e48c072059a2ac4c55
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/17/17_5bdf3f1d61e2eca758fa1f76f90384fb7edafeee/GradientEditorPanel/17_5bdf3f1d61e2eca758fa1f76f90384fb7edafeee_GradientEditorPanel_t.java
da07db0f1933f4e6889147bda776475fcfe992a6
[]
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
11,837
java
/* Copyright (c) 2006, 2007, The Cytoscape Consortium (www.cytoscape.org) The Cytoscape Consortium is: - Institute for Systems Biology - University of California San Diego - Memorial Sloan-Kettering Cancer Center - Institut Pasteur - Agilent Technologies This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder is on an "as is" basis, and the Institute for Systems Biology and the Whitehead Institute have no obligations to provide maintenance, support, updates, enhancements or modifications. In no event shall the Institute for Systems Biology and the Whitehead Institute be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the Institute for Systems Biology and the Whitehead Institute have been advised of the possibility of such damage. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package cytoscape.visual.ui.editors.continuous; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JColorChooser; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import cytoscape.Cytoscape; import cytoscape.util.CyColorChooser; import cytoscape.visual.VisualPropertyType; import cytoscape.visual.mappings.BoundaryRangeValues; import cytoscape.visual.mappings.ContinuousMapping; import cytoscape.visual.mappings.continuous.AddPointListener; import cytoscape.visual.mappings.continuous.ContinuousMappingPoint; /** * Gradient editor. * * @version 0.7 * @since Cytoscpae 2.5 * @author kono */ public class GradientEditorPanel extends ContinuousMappingEditorPanel implements PropertyChangeListener { /** * Creates a new GradientEditorPanel object. * * @param type * DOCUMENT ME! */ public GradientEditorPanel(VisualPropertyType type) { super(type); iconPanel.setVisible(false); setSlider(); belowPanel.addPropertyChangeListener(this); abovePanel.addPropertyChangeListener(this); } /** * DOCUMENT ME! * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param title DOCUMENT ME! * @param type DOCUMENT ME! */ public static Object showDialog(final int width, final int height, final String title, VisualPropertyType type) { editor = new GradientEditorPanel(type); editor.setSize(new Dimension(width, height)); editor.setTitle(title); editor.setAlwaysOnTop(true); editor.setLocationRelativeTo(Cytoscape.getDesktop()); editor.setVisible(true); editor.repaint(); return editor; } public static ImageIcon getLegend(final int width, final int height, final VisualPropertyType type) { editor = new GradientEditorPanel(type); CyGradientTrackRenderer rend = (CyGradientTrackRenderer)editor.slider.getTrackRenderer(); rend.getRendererComponent(editor.slider); return rend.getLegend(width, height); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static ImageIcon getIcon(final int iconWidth, final int iconHeight, VisualPropertyType type) { editor = new GradientEditorPanel(type); CyGradientTrackRenderer rend = (CyGradientTrackRenderer)editor.slider.getTrackRenderer(); rend.getRendererComponent(editor.slider); return rend.getTrackGraphicIcon(iconWidth, iconHeight); } @Override protected void addButtonActionPerformed(ActionEvent evt) { BoundaryRangeValues newRange; if (mapping.getPointCount() == 0) { slider.getModel().addThumb(50f, Color.white); newRange = new BoundaryRangeValues(below, Color.white, above); mapping.addPoint(maxValue / 2, newRange); Cytoscape.getVisualMappingManager().getNetworkView().redrawGraph(false, true); slider.repaint(); repaint(); return; } // Add a new white thumb in the min. slider.getModel().addThumb(100f, Color.white); // Update continuous mapping final Double newVal = maxValue; // Pick Up first point. final ContinuousMappingPoint previousPoint = mapping.getPoint(mapping.getPointCount() - 1); final BoundaryRangeValues previousRange = previousPoint.getRange(); newRange = new BoundaryRangeValues(previousRange); newRange.lesserValue = slider.getModel().getSortedThumbs() .get(slider.getModel().getThumbCount() - 1); System.out.println("EQ color = " + newRange.lesserValue); newRange.equalValue = Color.white; newRange.greaterValue = previousRange.greaterValue; mapping.addPoint(maxValue, newRange); updateMap(); Cytoscape.getVisualMappingManager().getNetworkView().redrawGraph(false, true); slider.repaint(); repaint(); } @Override protected void deleteButtonActionPerformed(ActionEvent evt) { final int selectedIndex = slider.getSelectedIndex(); if (0 <= selectedIndex) { slider.getModel().removeThumb(selectedIndex); mapping.removePoint(selectedIndex); updateMap(); mapping.fireStateChanged(); Cytoscape.getVisualMappingManager().getNetworkView().redrawGraph(false, true); repaint(); } } private void initButtons() { addButton.addActionListener(new AddPointListener(mapping, Color.white)); } /** * DOCUMENT ME! */ public void setSlider() { Dimension dim = new Dimension(600, 100); setPreferredSize(dim); setSize(dim); setMinimumSize(new Dimension(300, 80)); slider.updateUI(); // slider.setComponentPopupMenu(menu); slider.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { } else { final JComponent selectedThumb = slider.getSelectedThumb(); if (selectedThumb != null) { final Point location = selectedThumb.getLocation(); double diff = Math.abs(location.getX() - e.getX()); if (e.getClickCount() == 2) { final Color newColor = CyColorChooser.showDialog(slider, "Choose new color...", Color.white); if (newColor != null) { slider.getModel().getThumbAt(slider.getSelectedIndex()) .setObject(newColor); final ContinuousMapping cMapping = mapping; int selected = getSelectedPoint(slider.getSelectedIndex()); cMapping.getPoint(selected).getRange().equalValue = newColor; final BoundaryRangeValues brv = new BoundaryRangeValues(cMapping.getPoint(selected) .getRange().lesserValue, newColor, cMapping.getPoint(selected) .getRange().greaterValue); cMapping.getPoint(selected).setRange(brv); int numPoints = cMapping.getAllPoints().size(); // Update Values which are not accessible from // UI if (numPoints > 1) { if (selected == 0) brv.greaterValue = newColor; else if (selected == (numPoints - 1)) brv.lesserValue = newColor; else { brv.lesserValue = newColor; brv.greaterValue = newColor; } cMapping.fireStateChanged(); Cytoscape.getVisualMappingManager().getNetworkView() .redrawGraph(false, true); slider.repaint(); } } } } } } }); double actualRange = Math.abs(minValue - maxValue); if (allPoints != null) { for (ContinuousMappingPoint point : allPoints) { BoundaryRangeValues bound = point.getRange(); slider.getModel() .addThumb(((Double) ((point.getValue() - minValue) / actualRange)).floatValue() * 100, (Color) bound.equalValue); } if (allPoints.size() != 0) { below = (Color) allPoints.get(0).getRange().lesserValue; above = (Color) allPoints.get(allPoints.size() - 1).getRange().greaterValue; } else { below = Color.black; above = Color.white; } setSidePanelIconColor((Color) below, (Color) above); } TriangleThumbRenderer thumbRend = new TriangleThumbRenderer(slider); // System.out.println("--------- VS = " // + Cytoscape.getVisualMappingManager().getVisualStyle() // .getNodeAppearanceCalculator() // .getCalculator(VisualPropertyType.NODE_SHAPE) + " ----"); CyGradientTrackRenderer gRend = new CyGradientTrackRenderer(minValue, maxValue, (Color) below, (Color) above, mapping .getControllingAttributeName()); //updateBelowAndAbove(); slider.setThumbRenderer(thumbRend); slider.setTrackRenderer(gRend); slider.addMouseListener(new ThumbMouseListener()); /* * Set tooltip for the slider. */ slider.setToolTipText("Double-click handles to edit boundary colors."); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ public void propertyChange(PropertyChangeEvent e) { // TODO Auto-generated method stub if (e.getPropertyName().equals(BelowAndAbovePanel.COLOR_CHANGED)) { String sourceName = ((BelowAndAbovePanel) e.getSource()).getName(); if (sourceName.equals("abovePanel")) this.above = e.getNewValue(); else this.below = e.getNewValue(); final CyGradientTrackRenderer gRend = new CyGradientTrackRenderer(minValue, maxValue, (Color) below, (Color) above, mapping .getControllingAttributeName()); slider.setTrackRenderer(gRend); repaint(); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
c95c32e4c8ec6b3f5e328133bba73f49e7afdd39
d54ce3d39f3c93b0ad78a476ae7f71730bcbc658
/backup/client/emotes/EmoteManager.java
cc971b208268fda943cbd6b56ad6630c23f89000
[ "MIT" ]
permissive
TheShinyBunny/HandiClient
8d5b68ab425cc0d0ce00dcddde7b2ecd0173efc4
95b657e46d9730b83ae5fa15ed5e34cb8a7ff873
refs/heads/master
2023-05-14T11:54:38.490027
2020-11-03T16:00:26
2020-11-03T16:00:26
307,407,822
0
0
null
null
null
null
UTF-8
Java
false
false
2,667
java
/* * Copyright (c) 2020. Yaniv - TheShinyBunny */ package com.handicraft.client.emotes; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.network.ServerSidePacketRegistry; import net.minecraft.client.network.AbstractClientPlayerEntity; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.Identifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class EmoteManager { public static final List<Identifier> EMOTES = new ArrayList<>(); public static final Identifier BARVAZY; public static final Identifier DARKVAZY; static { BARVAZY = add("hcclient:barvazy"); DARKVAZY = add("hcclient:darkvazy"); } private static Identifier add(String id) { Identifier i = new Identifier(id); EMOTES.add(i); return i; } private static Map<AbstractClientPlayerEntity, EmoteInstance> currentEmotes = new HashMap<>(); public static void displayEmote(AbstractClientPlayerEntity player, Identifier id, int time) { currentEmotes.put(player,new EmoteInstance(new Identifier(id.getNamespace(),"emotes/" + id.getPath() + ".png"),time)); } public static EmoteInstance getEmoteFor(AbstractClientPlayerEntity player) { EmoteInstance e = currentEmotes.get(player); if (e == null) return null; e.time++; if (e.time > e.lifespan) { currentEmotes.put(player,null); } return e; } public static final Identifier SEND_EMOTE_PACKET = new Identifier("hcclient:show_emote"); public static void sendEmote(ServerPlayerEntity player, Identifier emote, int time) { for (ServerPlayerEntity e : player.server.getPlayerManager().getPlayerList()) { PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer()); buf.writeUuid(player.getUuid()); buf.writeIdentifier(emote); buf.writeVarInt(time); ServerSidePacketRegistry.INSTANCE.sendToPlayer(e,SEND_EMOTE_PACKET,buf); } } public static class EmoteInstance { private Identifier texture; private int time; private int lifespan; public EmoteInstance(Identifier texture, int lifespan) { this.texture = texture; this.lifespan = lifespan; this.time = 0; } public Identifier getTexture() { return texture; } public int getTime() { return time; } public int getLifespan() { return lifespan; } } }
[ "shinybunny123@gmail.com" ]
shinybunny123@gmail.com
3f197fb52c78c96f034721441767c24a8be8e3b2
00bebafa5b68bfaa1da296347d3895b104b8c590
/src/test/java/com/microservicio/app/familia/MicroservicioFamiliaApplicationTests.java
722a673dce9705435fb9a6cf7fc88fcc55228143
[]
no_license
carloscruzcasas/Nexos-MicroservicioFamilia
cdabb34848249782c32b5c2aeefd59dca4cd8ee7
94c797d859a12eb4ebd44cce2a176ae554f44f21
refs/heads/master
2023-02-12T14:55:21.387500
2021-01-10T22:57:24
2021-01-10T22:57:24
328,275,038
0
0
null
null
null
null
UTF-8
Java
false
false
235
java
package com.microservicio.app.familia; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class MicroservicioFamiliaApplicationTests { @Test void contextLoads() { } }
[ "2705.cacc@gmail.com" ]
2705.cacc@gmail.com
76c960ad8cc3a34663185c296f07fc027b943314
d73573b9ff8ee1ec4abb20ef16f81fc46092f7e6
/Builder/src/main/java/com/builder/ServletInitializer.java
97d144e42157cf0cdcb0f959368de67cf2741b86
[]
no_license
kennedylima/Design-Patterns
f40146120bef3f4cb0faa429bffd118063c3b041
8b29d67e8f65e9519bee250544898001d6c65cd7
refs/heads/master
2021-01-19T21:24:37.090189
2017-04-18T18:14:43
2017-04-18T18:14:43
88,655,923
0
0
null
null
null
null
UTF-8
Java
false
false
394
java
package com.builder; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(BuilderApplication.class); } }
[ "kennedy@hightechcursos.com.br" ]
kennedy@hightechcursos.com.br
8db5cc727e86f81bf4497d122e916d66f0f280a9
7838ffd4293d3ece34b570842fc3fff80278a469
/src/main/java/twitter4j/TwitterFactory.java
a79b36026a8503f7c8e8cbf47f1035a910f7bb68
[ "BSD-3-Clause", "JSON" ]
permissive
huxi/twitter4j
9c1c234c9fccfad4805be05ccf598dc7f9a24cbf
7cc033a0e9b1f27aefa4a95a5213003a74d242c3
refs/heads/master
2021-01-16T21:11:36.003997
2009-12-31T07:56:57
2009-12-31T07:56:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,644
java
/* Copyright (c) 2007-2009, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package twitter4j; import twitter4j.conf.Configuration; import twitter4j.http.AccessToken; import twitter4j.http.Authorization; import twitter4j.http.BasicAuthorization; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.0 */ public class TwitterFactory { private static final Twitter DEFAULT_INSTANCE; private transient static final Configuration conf = Configuration.getInstance(); static { DEFAULT_INSTANCE = new Twitter(); } private TwitterFactory() { throw new AssertionError(); } /** * Returns a Twitter instance. * * @return default singleton instance */ public static Twitter getInstance() { return DEFAULT_INSTANCE; } public static Twitter getInstance(Authorization auth) { return new Twitter(auth); } /** * @param screenName screen name * @param password password * @return basic authenticated instance * @noinspection deprecation */ public static Twitter getBasicAuthenticatedInstance(String screenName , String password) { return getInstance(new BasicAuthorization(screenName, password)); } public static Twitter getOAuthAuthenticatedInstance(String consumerKey , String consumerSecret, AccessToken accessToken) { Twitter twitter = new Twitter(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); return twitter; } public static Twitter getOAuthAuthenticatedInstance(AccessToken accessToken) { String consumerKey = conf.getOAuthConsumerKey(); String consumerSecret = conf.getOAuthConsumerSecret(); if (null == consumerKey && null == consumerSecret) { throw new IllegalStateException("Consumer key and Consumer secret not supplied."); } Twitter twitter = new Twitter(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); return twitter; } // public static Twitter getInstance(Authentication authentication) { // // } }
[ "yusuke@117b7e0d-5933-0410-9d29-ab41bb01d86b" ]
yusuke@117b7e0d-5933-0410-9d29-ab41bb01d86b
268bf4bb842ca509cd3cd9beb29bfdf30a2fef16
3c7b34b30f1cd5464fecca6dbb52afe77d04a635
/app/src/main/java/edu/uit/dictplus/TraTu/Tab_AnhViet.java
f16672caa478fae0aea66f255198a41e4423ab68
[]
no_license
NguyenMinhTri/DictPlus
8ebc4003a24cd38102576ddbbc0f9ffc507b495b
03bf5ae3dcefbb88a45c4f3542c54cfb67bcffa6
refs/heads/master
2020-06-11T05:19:46.404918
2016-12-09T03:26:38
2016-12-09T03:26:38
75,997,677
0
0
null
null
null
null
UTF-8
Java
false
false
11,064
java
package edu.uit.dictplus.TraTu; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.parse.ParseCloud; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SaveCallback; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import edu.uit.dictplus.ActivityTabStudy.DauNhan; import edu.uit.dictplus.DataOffline.DataAdapter; import edu.uit.dictplus.DataOffline.DataOffline; import edu.uit.dictplus.DataOffline.Popup_TraTu; import edu.uit.dictplus.ParseHistory.FragmentHistory; import edu.uit.dictplus.ParseHistory.History; import edu.uit.dictplus.R; import android.support.v4.app.Fragment; /** * Created by nmtri_000 on 12/31/2015. */ public class Tab_AnhViet extends Fragment { public static String dataFullAV; public static String dataVocabulary; StringBuilder _dataFullAV; StringBuilder _dataVocabulary; public List<DataOffline> mDataVA=new ArrayList<>(); public DataAdapter mAdapterAV; public List<DataOffline> mDataAV; public static ListView mListView; private EditText editText; public Tab_AnhViet() {} OnHeadlineSelectedListener mCallback; // Container Activity must implement this interface public interface OnHeadlineSelectedListener { public void onArticleSelected(int position); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (OnHeadlineSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab_anhviet, container, false); mListView=(ListView)view.findViewById(R.id.listView); mDataAV=new ArrayList<>(); editText=(EditText)view.findViewById(R.id.editText); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence cs, int start, int before, int count) { mAdapterAV.getFilter().filter(cs); mAdapterAV.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ((TextView) view.findViewById(R.id.tvVoca)).getText().toString(); Intent acPop = new Intent(getActivity(), Popup_TraTu.class); acPop.putExtra("Value", ((TextView) view.findViewById(R.id.tvVoca)).getText().toString().replace(" /", " ☺/") + "\n" + ((TextView) view.findViewById(R.id.tvMean)).getText().toString()); startActivity(acPop); createHistory(((TextView) view.findViewById(R.id.tvVoca)).getText().toString().split(" /")[0], getShortMean(((TextView) view.findViewById(R.id.tvMean)).getText().toString())); //Toast.makeText(getActivity(), ((TextView) view.findViewById(R.id.tvVoca)).getText().toString(), Toast.LENGTH_SHORT).show(); } }); new Thread(new Runnable() { @Override public void run() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { readData(); } }); } }).start(); return view; } public String getShortMean(String mean) { String []chuoiMean=mean.split("\n"); if(chuoiMean.length>=2) { return mean.split("\n")[1]; } else return mean; } public static void createHistory(final String voca,String mean) { ParseUser currentUser = ParseUser.getCurrentUser(); if(currentUser != null) { int STT=0; try { STT = FragmentHistory.mAdapter.getItem(0).getSTT() + 1; } catch (Exception e){ } //khoi tao hash map HashMap<String,Object> dataVoca=new HashMap<>(); dataVoca.put("Stt", STT); dataVoca.put("Mean", mean); dataVoca.put("Voca", voca); dataVoca.put("DauNhan", DauNhan.getDauNhan(voca)); dataVoca.put("User", ParseUser.getCurrentUser().getUsername()); // final History history = new History(); history.setCheck(false); history.setSTT(STT); history.setMean(mean); history.setVoca(voca); final HashMap<String, String> data = new HashMap<>(); history.setDauNhan(DauNhan.getDauNhan(voca)); //history.pinInBackground("History"); history.put("User", ParseUser.getCurrentUser().getUsername()); //new offline history.pinInBackground("History"); FragmentHistory.mAdapter.insert(history, 0); history.saveEventually(new SaveCallback() { @Override public void done(ParseException e) { data.put("data", history.getVocabulay() + "#" + history.getObjectId()); Object kq = null; try { kq = ParseCloud.callFunction("setMp3", data); } catch (ParseException e1) { e1.printStackTrace(); } History historyLocal = (History) kq; if (historyLocal != null) { FragmentHistory.mAdapter.remove(history); FragmentHistory.mAdapter.insert(historyLocal, 0); historyLocal.pinInBackground("History"); } } }); // ParseCloud.callFunctionInBackground("new", dataVoca); } } public void readData() { _dataFullAV=new StringBuilder(); _dataVocabulary=new StringBuilder(); //Doc Anh Viet Log.v("Doc Lai Du Lieu", ".............................................."); String data; InputStream in= getResources().openRawResource(R.raw.anhviet); InputStreamReader inreader=new InputStreamReader(in); BufferedReader bufreader=new BufferedReader(inreader); StringBuilder readAll=new StringBuilder(); int dem=0; StringBuilder builder=new StringBuilder(); //Doc Viet Anh String data2=" "; InputStream in2= getResources().openRawResource(R.raw.vietanh); InputStreamReader inreader2=new InputStreamReader(in2); BufferedReader bufreader2=new BufferedReader(inreader2); boolean checkVA=true; StringBuilder readAll2=new StringBuilder(); int dem2=0; StringBuilder builder2=new StringBuilder(); // if(in!=null) { try { while(((data=bufreader.readLine())!=null) ) { _dataFullAV.append(data+"\n"); try { if (data.indexOf("@") != -1) { if (dem == 1) { _dataVocabulary.append(data + "\n"); String TuVung = String.valueOf(builder); String Nghia = String.valueOf(readAll); mDataAV.add(new DataOffline(TuVung.substring(1), Nghia)); readAll = new StringBuilder(); builder = new StringBuilder(); dem = 0; } builder.append(data); dem = 1; } else { readAll.append(data); readAll.append("\n"); } } catch (Exception e){} try { if(checkVA) if((data2=bufreader2.readLine())!=null) { if (data2.indexOf("@") != -1) { if (dem2 == 1) { String TuVung = String.valueOf(builder2); String Nghia = String.valueOf(readAll2); mDataVA.add(new DataOffline(TuVung.substring(1), Nghia)); readAll2 = new StringBuilder(); builder2 = new StringBuilder(); dem2 = 0; } builder2.append(data2); dem2 = 1; } else { readAll2.append(data2); readAll2.append("\n"); } } else { checkVA=false; } } catch (Exception e){} } dataFullAV=_dataFullAV.toString(); dataVocabulary=_dataVocabulary.toString(); in.close(); in2.close(); // mAdapterAV.addAll(mDataAV); mAdapterAV = new DataAdapter(getActivity(), mDataAV,false); mListView.setAdapter(mAdapterAV); Tab_VietAnh.mAdapterVA = new DataAdapter(getActivity(), mDataVA,true); Tab_VietAnh.mListViewVA.setAdapter(Tab_VietAnh.mAdapterVA); mCallback.onArticleSelected(5); } catch(IOException ex){ Log.e("ERROR", ex.getMessage()); } } } }
[ "nmtri.uit@gmail.com" ]
nmtri.uit@gmail.com
4ede0f823a33454648c6576b9136a53a9b72f1a6
2d141f336de01a5e728d9618cd2b3d344222769b
/Vijay_JavaPractice/src/com/qspiders/BlackBelt/Set6/Bubble.java
1b8cacbe1cf669a902fe41317f4d04d79ebe9e5f
[]
no_license
VijayVasi/UploadTool
63c503e502d7a93fb62d20068d80feda3e511bc7
230824dd865b6f59659561f5b4061276ffd28e63
refs/heads/master
2021-01-23T03:59:00.369022
2017-08-24T06:43:10
2017-08-24T06:43:10
86,139,091
0
0
null
null
null
null
UTF-8
Java
false
false
896
java
package com.qspiders.BlackBelt.Set6; public class Bubble { public static void main(String[] args) { int arr[] = {89,23,45,12,67,78}; System.out.println("--------Bubble Sorting---------"); System.out.println("Before Sorting"); for(int i=0; i <arr.length; i++) { System.out.print(arr[i] + " "); } //System.out.println(Arrays.toString(arr)); System.out.println(); bubbleSort(arr); System.out.println("After Sorting"); for(int i=0; i <arr.length; i++) { System.out.print(arr[i] + " "); } } static void bubbleSort(int[] arr) { int temp=0; //holding variable boolean flag = true; while(flag) { flag = false; for(int j=0; j<arr.length - 1; j++) { if(arr[j]>arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1]= temp; flag = true; } } } } }
[ "Dell@192.168.2.7" ]
Dell@192.168.2.7
0887d1bec52dc2f5e7592dd5e0b5de15433df8e5
de897e577c2bd95abbf98b143a2ec3d8cc5b9f80
/app/src/main/java/com/lwc/shanxiu/module/bean/PartsTypeBean.java
0b51615b62dd0784e70f25eba1fa638d1e9b37b6
[]
no_license
popularcloud/SHANXIU06042120
6b4e02c1e4c1df2cf5ac9145992125f0cf930d80
60cb0a4512f36fb2933009f97b6ab332d7b370bb
refs/heads/master
2021-06-29T01:30:10.062909
2021-01-04T01:51:36
2021-01-04T01:51:36
199,803,391
0
0
null
null
null
null
UTF-8
Java
false
false
1,416
java
package com.lwc.shanxiu.module.bean; import java.io.Serializable; /** * @author younge * @date 2018/12/20 0020 * @email 2276559259@qq.com * @Des 配件 */ public class PartsTypeBean implements Serializable{ private String typeName; private String createTime; private int sn; private String typeIcon; private int isValid; private String typeId; public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public int getSn() { return sn; } public void setSn(int sn) { this.sn = sn; } public String getTypeIcon() { return typeIcon; } public void setTypeIcon(String typeIcon) { this.typeIcon = typeIcon; } public int getIsValid() { return isValid; } public void setIsValid(int isValid) { this.isValid = isValid; } public String getTypeId() { return typeId; } public void setTypeId(String typeId) { this.typeId = typeId; } }
[ "liushuzhiyt@163.com" ]
liushuzhiyt@163.com
213edd29b8c06e8091e01ff03e9e981a1407443c
45ec4a8d3b6e175647207734d1aa8bf533968181
/java-checks/src/test/java/org/sonar/java/checks/DataStoredInSessionCheckTest.java
62d071b82a1af2e19a78e1ec88074e4144c84b47
[]
no_license
MarkZ3/sonar-java
00aa78e50ff79e7b5b11e7776c0f5bcd96285c11
c7558f46cdec47f097634a0f69c1d39c25e999ca
refs/heads/master
2021-01-18T18:05:29.135062
2015-12-15T04:16:07
2015-12-15T04:25:56
48,019,139
0
0
null
2015-12-15T04:14:01
2015-12-15T04:14:01
null
UTF-8
Java
false
false
1,131
java
/* * SonarQube Java * Copyright (C) 2012 SonarSource * sonarqube@googlegroups.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.java.checks; import org.junit.Test; import org.sonar.java.checks.verifier.JavaCheckVerifier; public class DataStoredInSessionCheckTest { @Test public void test() { JavaCheckVerifier.verify("src/test/files/checks/DataStoredInSessionCheck.java", new DataStoredInSessionCheck()); } }
[ "michael.gumowski@sonarsource.com" ]
michael.gumowski@sonarsource.com
3dd42c7c6b84cad725e609e710178d3dde91c555
d7032bc925ba92b30c446146e8b19f574917939e
/gen/com/example/login/R.java
4c5fe3d2e2b383ab6de5243e96b2df555335bff8
[]
no_license
saidfuad/AAC2014
f16bcf08a963edb5e02152c08b6f01657a450d77
8019b9b6b3c475bce49a0921c72cbf3df001351c
refs/heads/master
2021-01-02T22:57:37.745133
2014-05-23T21:12:30
2014-05-23T21:12:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,077
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.login; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080009; public static final int buttonCreateAccount=0x7f080008; public static final int buttonSignIN=0x7f080003; public static final int buttonSignIn=0x7f080002; public static final int buttonSignUP=0x7f080004; public static final int editTextConfirmPassword=0x7f080007; public static final int editTextPassword=0x7f080006; public static final int editTextPasswordToLogin=0x7f080001; public static final int editTextUserName=0x7f080005; public static final int editTextUserNameToLogin=0x7f080000; } public static final class layout { public static final int login=0x7f030000; public static final int main=0x7f030001; public static final int signup=0x7f030002; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
[ "saidfuad91@gmail.com" ]
saidfuad91@gmail.com
6947c48800abbb1d63c4e32616047b44c7ba3993
816b5e665d315aee920fca44b32c60ec8bfad7db
/domain/net/xidlims/dao/SchoolWeekdayDAOImpl.java
14965153b922d04f0d79843c2ed54b7b46902962
[]
no_license
iqiangzi/ssdutZhangCC
d9c34bde6197f4ccb060cbb1c130713a5663989a
f5f7acd9ef45b5022accbdd7f6f730963fe3dddd
refs/heads/master
2020-08-02T22:07:50.428824
2018-05-13T03:03:04
2018-05-13T03:03:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,174
java
package net.xidlims.dao; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import net.xidlims.domain.SchoolWeekday; import org.skyway.spring.util.dao.AbstractJpaDao; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * DAO to manage SchoolWeekday entities. * */ @Repository("SchoolWeekdayDAO") @Transactional public class SchoolWeekdayDAOImpl extends AbstractJpaDao<SchoolWeekday> implements SchoolWeekdayDAO { /** * Set of entity classes managed by this DAO. Typically a DAO manages a single entity. * */ private final static Set<Class<?>> dataTypes = new HashSet<Class<?>>(Arrays.asList(new Class<?>[] { SchoolWeekday.class })); /** * EntityManager injected by Spring for persistence unit xidlimsConn * */ @PersistenceContext(unitName = "xidlimsConn") private EntityManager entityManager; /** * Instantiates a new SchoolWeekdayDAOImpl * */ public SchoolWeekdayDAOImpl() { super(); } /** * Get the entity manager that manages persistence unit * */ public EntityManager getEntityManager() { return entityManager; } /** * Returns the set of entity classes managed by this DAO. * */ public Set<Class<?>> getTypes() { return dataTypes; } /** * JPQL Query - findSchoolWeekdayByWeekdayName * */ @Transactional public Set<SchoolWeekday> findSchoolWeekdayByWeekdayName(String weekdayName) throws DataAccessException { return findSchoolWeekdayByWeekdayName(weekdayName, -1, -1); } /** * JPQL Query - findSchoolWeekdayByWeekdayName * */ @SuppressWarnings("unchecked") @Transactional public Set<SchoolWeekday> findSchoolWeekdayByWeekdayName(String weekdayName, int startResult, int maxRows) throws DataAccessException { Query query = createNamedQuery("findSchoolWeekdayByWeekdayName", startResult, maxRows, weekdayName); return new LinkedHashSet<SchoolWeekday>(query.getResultList()); } /** * JPQL Query - findSchoolWeekdayById * */ @Transactional public SchoolWeekday findSchoolWeekdayById(Integer id) throws DataAccessException { return findSchoolWeekdayById(id, -1, -1); } /** * JPQL Query - findSchoolWeekdayById * */ @Transactional public SchoolWeekday findSchoolWeekdayById(Integer id, int startResult, int maxRows) throws DataAccessException { try { Query query = createNamedQuery("findSchoolWeekdayById", startResult, maxRows, id); return (net.xidlims.domain.SchoolWeekday) query.getSingleResult(); } catch (NoResultException nre) { return null; } } /** * JPQL Query - findAllSchoolWeekdays * */ @Transactional public Set<SchoolWeekday> findAllSchoolWeekdays() throws DataAccessException { return findAllSchoolWeekdays(-1, -1); } /** * JPQL Query - findAllSchoolWeekdays * */ @SuppressWarnings("unchecked") @Transactional public Set<SchoolWeekday> findAllSchoolWeekdays(int startResult, int maxRows) throws DataAccessException { Query query = createNamedQuery("findAllSchoolWeekdays", startResult, maxRows); return new LinkedHashSet<SchoolWeekday>(query.getResultList()); } /** * JPQL Query - findSchoolWeekdayByPrimaryKey * */ @Transactional public SchoolWeekday findSchoolWeekdayByPrimaryKey(Integer id) throws DataAccessException { return findSchoolWeekdayByPrimaryKey(id, -1, -1); } /** * JPQL Query - findSchoolWeekdayByPrimaryKey * */ @Transactional public SchoolWeekday findSchoolWeekdayByPrimaryKey(Integer id, int startResult, int maxRows) throws DataAccessException { try { Query query = createNamedQuery("findSchoolWeekdayByPrimaryKey", startResult, maxRows, id); return (net.xidlims.domain.SchoolWeekday) query.getSingleResult(); } catch (NoResultException nre) { return null; } } /** * JPQL Query - findSchoolWeekdayByWeekdayNameContaining * */ @Transactional public Set<SchoolWeekday> findSchoolWeekdayByWeekdayNameContaining(String weekdayName) throws DataAccessException { return findSchoolWeekdayByWeekdayNameContaining(weekdayName, -1, -1); } /** * JPQL Query - findSchoolWeekdayByWeekdayNameContaining * */ @SuppressWarnings("unchecked") @Transactional public Set<SchoolWeekday> findSchoolWeekdayByWeekdayNameContaining(String weekdayName, int startResult, int maxRows) throws DataAccessException { Query query = createNamedQuery("findSchoolWeekdayByWeekdayNameContaining", startResult, maxRows, weekdayName); return new LinkedHashSet<SchoolWeekday>(query.getResultList()); } /** * Used to determine whether or not to merge the entity or persist the entity when calling Store * @see store * * */ public boolean canBeMerged(SchoolWeekday entity) { return true; } }
[ "1501331454@qq.com" ]
1501331454@qq.com
90709e70ac82f08e99f3ed6a1a316a5518527363
746572ba552f7d52e8b5a0e752a1d6eb899842b9
/JDK8Source/src/main/java/org/w3c/dom/events/UIEvent.java
8e680598a6542603ef2a58a06aa0573673b78b98
[]
no_license
lobinary/Lobinary
fde035d3ce6780a20a5a808b5d4357604ed70054
8de466228bf893b72c7771e153607674b6024709
refs/heads/master
2022-02-27T05:02:04.208763
2022-01-20T07:01:28
2022-01-20T07:01:28
26,812,634
7
5
null
null
null
null
UTF-8
Java
false
false
3,842
java
/***** Lobxxx Translate Finished ******/ /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. * <p> *  版权所有(c)2000万维网联盟,(马萨诸塞理工学院,庆应义藩大学信息自动化研究所)。版权所有。该程序根据W3C的软件知识产权许可证分发。 * 这个程序是分发的,希望它将是有用的,但没有任何保证;甚至没有对适销性或适用于特定用途的隐含保证。有关详细信息,请参阅W3C许可证http://www.w3.org/Consortium/Legal/。 * */ package org.w3c.dom.events; import org.w3c.dom.views.AbstractView; /** * The <code>UIEvent</code> interface provides specific contextual information * associated with User Interface events. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * <p> *  <code> UIEvent </code>界面提供与用户界面事件相关联的特定上下文信息。 * <p>另请参阅<a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>文档对象模型(DOM)2级事件规范< a>。 * * * @since DOM Level 2 */ public interface UIEvent extends Event { /** * The <code>view</code> attribute identifies the <code>AbstractView</code> * from which the event was generated. * <p> *  <code> view </code>属性标识生成事件的<code> AbstractView </code>。 * */ public AbstractView getView(); /** * Specifies some detail information about the <code>Event</code>, * depending on the type of event. * <p> *  指定有关<code> Event </code>的一些详细信息,具体取决于事件的类型。 * */ public int getDetail(); /** * The <code>initUIEvent</code> method is used to initialize the value of * a <code>UIEvent</code> created through the <code>DocumentEvent</code> * interface. This method may only be called before the * <code>UIEvent</code> has been dispatched via the * <code>dispatchEvent</code> method, though it may be called multiple * times during that phase if necessary. If called multiple times, the * final invocation takes precedence. * <p> *  <code> initUIEvent </code>方法用于初始化通过<code> DocumentEvent </code>接口创建的<code> UIEvent </code>的值。 * 此方法只能在通过<code> dispatchEvent </code>方法分派<code> UIEvent </code>之前调用,但如果需要,可以在该阶段多次调用。如果多次调用,则最终调用优先。 * * @param typeArg Specifies the event type. * @param canBubbleArg Specifies whether or not the event can bubble. * @param cancelableArg Specifies whether or not the event's default * action can be prevented. * @param viewArg Specifies the <code>Event</code>'s * <code>AbstractView</code>. * @param detailArg Specifies the <code>Event</code>'s detail. */ public void initUIEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, int detailArg); }
[ "919515134@qq.com" ]
919515134@qq.com
4a2969fdaa08eb2e4523df6fb569d914c0b31864
7559bead0c8a6ad16f016094ea821a62df31348a
/src/com/vmware/vim25/VirtualMachineBootOptionsBootableDevice.java
4d08605e9d3827fccd15fac05fa17664c6a93ca8
[]
no_license
ZhaoxuepengS/VsphereTest
09ba2af6f0a02d673feb9579daf14e82b7317c36
59ddb972ce666534bf58d84322d8547ad3493b6e
refs/heads/master
2021-07-21T13:03:32.346381
2017-11-01T12:30:18
2017-11-01T12:30:18
109,128,993
1
1
null
null
null
null
UTF-8
Java
false
false
1,113
java
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for VirtualMachineBootOptionsBootableDevice complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="VirtualMachineBootOptionsBootableDevice"> * &lt;complexContent> * &lt;extension base="{urn:vim25}DynamicData"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "VirtualMachineBootOptionsBootableDevice") @XmlSeeAlso({ VirtualMachineBootOptionsBootableFloppyDevice.class, VirtualMachineBootOptionsBootableCdromDevice.class, VirtualMachineBootOptionsBootableDiskDevice.class, VirtualMachineBootOptionsBootableEthernetDevice.class }) public class VirtualMachineBootOptionsBootableDevice extends DynamicData { }
[ "495149700@qq.com" ]
495149700@qq.com
4a2370c113fb24bbea2fd5908a8d9eed9ae3b934
c64fcaac5b27d2beb5e048946e33cb0709babc23
/src/main/java/Leetcode/二分查找/m_540.java
e533b0cd946e641f5386e5f5906bd348f9c9f711
[]
no_license
hqf1996/Algorithm
be367493841c7488b78cc6b55c8fb38a6f1549f3
fc602eea443d64917a9fba722a8275aa9a3e3cc8
refs/heads/master
2022-11-18T04:03:02.577322
2020-07-21T09:52:22
2020-07-21T09:52:22
202,994,504
0
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
package Leetcode.二分查找; /** * @Author: hqf * @description: * @Data: Create in 13:01 2020/2/20 * @Modified By: */ public class m_540 { public int singleNonDuplicate(int[] nums) { // 思路:可用位运算,但是时间复杂度会在O(n)。又由于其是有序数组,考虑二分。 int low = 0, high = nums.length-1; while (low < high) { int mid = low+(high-low)/2; // 一奇一偶可以看成一对数对,如果当前m是奇数,则应该m-1与它相等。如果当前m是偶数,则应该m+1与它相等。相等则说明m之前的这段数字中还没有破坏这个规律,单独的这个数在后半段。否则,则已经破坏了规律,单独的这个数在前半段。 if (mid % 2 == 1) { if (nums[mid] == nums[mid-1]) { low = mid+1; } else { high = mid; } } else { if (nums[mid] == nums[mid+1]) { low = mid+1; } else { high = mid; } } } return nums[low]; } }
[ "378938941@qq.com" ]
378938941@qq.com
70d7bdb664d93a1e56fc34cfd62a76fd06197000
0278475a7aeb6de0ff3ee26fd0d47d87d69d722a
/src/LogikaGry/Plansza.java
de3236f6ac49d341f2a16b313b623dec02ac8b38
[]
no_license
cecyliaborek/warcaby
371795b7f049606b1867bdba52d72b611980c2b7
3bd82670a9e1f068f54e62a16d751bd6075a7b94
refs/heads/master
2020-04-17T12:39:06.663001
2019-01-22T12:37:27
2019-01-22T12:37:27
166,587,199
0
0
null
null
null
null
UTF-8
Java
false
false
3,837
java
package LogikaGry; import Wyjatki.ZabronionyRuchException; import java.util.HashMap; public class Plansza { private final int szerokosc = 8; private final int wysokosc = 8; private HashMap<PozycjaNaPlanszy, Pole> pola = new HashMap<>(); public Plansza() { for (int r = 0; r < wysokosc; r++) { for (int c = 0; c < szerokosc; c++) { PozycjaNaPlanszy pozycja = new PozycjaNaPlanszy(r, c); pola.put(pozycja, new Pole(pozycja)); } } for (int c = 0; c < 4; c++) { new Pionek(this, pola.get(new PozycjaNaPlanszy(0, 2 * c)), RodzajFigury.BIALY_PIONEK); new Pionek(this, pola.get(new PozycjaNaPlanszy(1, 2 * c + 1)), RodzajFigury.BIALY_PIONEK); new Pionek(this, pola.get(new PozycjaNaPlanszy(2, 2 * c)), RodzajFigury.BIALY_PIONEK); } for (int c = 0; c < 4; c++) { new Pionek(this, pola.get(new PozycjaNaPlanszy(5, 2 * c + 1)), RodzajFigury.CZARNY_PIONEK); new Pionek(this, pola.get(new PozycjaNaPlanszy(6, 2 * c)), RodzajFigury.CZARNY_PIONEK); new Pionek(this, pola.get(new PozycjaNaPlanszy(7, 2 * c + 1)), RodzajFigury.CZARNY_PIONEK); } } public void zamienPionkaWKrolowaJesliJestNaOdpowiednimPolu(PozycjaNaPlanszy pozycjaPionka){ Pole polePionka = this.pola.get(pozycjaPionka); if(pozycjaPionka.getRzad() == 0 && this.pola.get(pozycjaPionka).getFigura().getRodzajFigury() == RodzajFigury.CZARNY_PIONEK){ polePionka.ustawPuste(); new Krolowa(this, polePionka, RodzajFigury.CZARNA_KROLOWA); } else if(pozycjaPionka.getRzad() == wysokosc - 1 && this.pola.get(pozycjaPionka).getFigura().getRodzajFigury() == RodzajFigury.BIALY_PIONEK){ polePionka.ustawPuste(); new Krolowa(this, polePionka, RodzajFigury.BIALA_KROLOWA); } } public boolean zrobRuchOrazCzyByloBicie(Pole polePoczatkowe, Pole poleKoncowe) throws ZabronionyRuchException{ if(poleKoncowe == null) throw new ZabronionyRuchException(); boolean czyByloBicie = false; if(polePoczatkowe.getFigura().czyMozliweZbicie(poleKoncowe)){ Pole poleDoZbicia = polePoczatkowe.getFigura().poleZbijane(poleKoncowe); polePoczatkowe.getFigura().przesunNa(poleKoncowe); poleDoZbicia.ustawPuste(); czyByloBicie = true; }else{ polePoczatkowe.getFigura().przesunNa(poleKoncowe); } zamienPionkaWKrolowaJesliJestNaOdpowiednimPolu(poleKoncowe.getPozycja()); return czyByloBicie; } public boolean czyGraczMozeSieRuszyc(Kolor kolorGracza){ for(int r = 0; r < wysokosc; r++){ for(int k = 0; k < szerokosc; k++){ if(this.getPole(new PozycjaNaPlanszy(r, k)).getFigura() != null && this.getPole(new PozycjaNaPlanszy(r, k)).getFigura().getKolor() == kolorGracza){ boolean czyMozeRuszyc = false; for(int i = -1; i <=1; i+=2){ for(int j = -1; j <=1; j +=2){ if(this.getPole(new PozycjaNaPlanszy(r,k)).getFigura().czyMozliwyRuch(this.getPole(new PozycjaNaPlanszy(r+i,j+k))))czyMozeRuszyc=true; } } if(czyMozeRuszyc)return true; } } } return false; } public Pole getPole(PozycjaNaPlanszy pozycja){ return this.pola.get(pozycja); } @Override public String toString(){ String ret = ""; for(int r=0;r<8;r++){ ret+="|"; for(int c=0;c<8;c++){ ret+=getPole(new PozycjaNaPlanszy(r,c)).toString()+"|"; } ret+="\n"; } return ret; } }
[ "cecylia.borek@gmail.com" ]
cecylia.borek@gmail.com
a0d3f86f6234d5a2294de9391d220d2bb0a862d4
a1917d83c9bb6f507f810c55df36bdfdc1dc481d
/app/src/main/java/com/example/domenico/myapp/DettagliSegnalazioneDCCittadino.java
50f206b34709cd3ab3709ee7bb3501cfa1d95b1e
[]
no_license
domenico97/RecyclAppCode
40c1199daa09efbcd2499f20bc71c420be4669f2
7d174ef6ceadf9240fce0bb971334c6bb04fab09
refs/heads/master
2020-04-18T04:05:19.233555
2019-02-07T17:06:12
2019-02-07T17:06:12
167,225,373
0
0
null
null
null
null
UTF-8
Java
false
false
2,355
java
package com.example.domenico.myapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class DettagliSegnalazioneDCCittadino extends Activity { TextView cfSegnalatore,dataSegnalazione,cfSegnalato,descrizioneInfrazione; String infrazioni; private BottomNavigationView bottomNavigationView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dettagli_segnalazione_dc_cittadino); cfSegnalatore = findViewById(R.id.cfSegnalatore); dataSegnalazione = findViewById(R.id.dataSegnalazione); descrizioneInfrazione = findViewById(R.id.descrizioneInfrazione); bottomNavigationView = findViewById(R.id.navigationView); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent i = new Intent(); switch (item.getItemId()) { case R.id.home_dipendente_comunale: i.setClass(getApplicationContext(), HomepageDipendenteComunale.class); startActivity(i); break; case R.id.avvisi_dipendente_comunale: /*i.setClass(getApplicationContext(), Avvisi.class); startActivity(i);*/ break; case R.id.area_personale_dipendente_comunale: i.setClass(getApplicationContext(), AreaPersonaleDipendenteComunale.class); startActivity(i); break; } return false; } }); Intent i = getIntent(); cfSegnalatore.setText(i.getStringExtra("mittente")); dataSegnalazione.setText(i.getStringExtra("data")); infrazioni = i.getStringExtra("messaggio"); descrizioneInfrazione.setText(infrazioni); } public void back(View view) { finish(); } }
[ "43062263+mcastellaneta@users.noreply.github.com" ]
43062263+mcastellaneta@users.noreply.github.com
603be287ced622cccc2a539ae85661c90143d93d
cda1a29b5a66975b04a7438bacd41fbb4212a08c
/src/main/java/com/meliora/dao/OperationLogDAO.java
a3501cae916655606064a1935c16e3d2ee970295
[]
no_license
zwj5582/120ManageHUZHOU
d28f9812920ccd09f4f43d78784de71d6414705a
18df9d2c07cf0eede9894bbebd1bb7b473fe248c
refs/heads/master
2021-07-12T21:32:29.674160
2017-10-15T04:14:39
2017-10-15T04:14:39
106,977,001
0
0
null
null
null
null
UTF-8
Java
false
false
315
java
/* * Created by ZhongWenjie on 2017-10-07 22:11 */ package com.meliora.dao; import com.meliora.dao.repository.BaseRepository; import com.meliora.model.OperationLog; import org.springframework.stereotype.Repository; @Repository public interface OperationLogDAO extends BaseRepository<OperationLog,Integer> { }
[ "zwj5582@gmail.com" ]
zwj5582@gmail.com
cdafa930001f52ac2792b986894967bbd74fb994
b2077049ef06f0e095a46c5f9013b6c4e6e08dcd
/utils/src/main/java/chaos/utils/ComparatorUtils.java
c5517b15795e1237fbad5d9eb97f6f1276554af4
[]
no_license
wsad137/chaos
ba8d156406a3d6d88dc2012bcaf387ef333c8cb1
956b02ad8424aa93b523e89cc4ff3b036a330e65
refs/heads/master
2018-11-11T11:40:54.500699
2018-08-28T12:43:32
2018-08-28T12:43:32
114,718,273
0
1
null
null
null
null
UTF-8
Java
false
false
1,804
java
package chaos.utils; import org.apache.commons.beanutils.BeanComparator; import org.apache.commons.collections.comparators.ComparableComparator; import java.util.*; public class ComparatorUtils { public static void main(String[] args) throws Exception { test1(); test2(); } private static void test1() { List<Map<String, Object>> users = new ArrayList<Map<String, Object>>(); for (int i = 0; i < 5; i++) { Map<String, Object> user = new LinkedHashMap<String, Object>(); user.put("username", "user_" + i); user.put("password", "passwd_" + i); user.put("email", "user_" + i + "@localhost"); users.add(user); } System.out.println(users); sort(users, "username", false); System.out.println(users); sort(users, "username", true); System.out.println(users); } private static void test2() { // List<UserModel> users = new ArrayList<UserModel>(); // for (int i = 0; i < 5; i++) { // users.add(new UserModel().setUsername("adfasf"+i)); // } // System.out.println(users); // // sort(users, "username", false); // System.out.println(users); // // sort(users, "username", true); // System.out.println(users); } public static <T> void sort(List<T> list, String property, boolean asc) { Comparator<?> comparator = ComparableComparator.getInstance(); comparator = org.apache.commons.collections.ComparatorUtils.nullLowComparator(comparator); if (!asc) { comparator = org.apache.commons.collections.ComparatorUtils.reversedComparator(comparator); } Collections.sort(list, new BeanComparator(property, comparator)); } }
[ "wsad136@sina.com" ]
wsad136@sina.com
9f9ce099b093333de3ca48043f8873961cdc4789
9ca5ececd2e435778609fe35ffad1f48133b14ae
/src/main/java/com/example/sweater/service/service/FindCurrentPageService.java
ed93e0b7ce40009ecdbd6a43732db0dae5d569c9
[]
no_license
Aretomko/SklankaMriy-quest-rooms-game-quest-project
6227b228a3fd787b1e10960fd5c75d398a0ad9d4
c5f55605c2ba6d794db6b724e7ea9f3ee228f61f
refs/heads/master
2023-03-29T08:51:22.180875
2021-03-20T21:33:24
2021-03-20T21:33:24
349,839,003
0
0
null
null
null
null
UTF-8
Java
false
false
425
java
package com.example.sweater.service.service; import com.example.sweater.entities.PageGame; import org.springframework.stereotype.Service; import java.util.List; @Service public class FindCurrentPageService { public PageGame findCurrentPage(List<PageGame> pagesGame){ for (PageGame p: pagesGame) { if (!p.isAnswered()){ return p; } } return null; } }
[ "aroma7752424@gmail.com" ]
aroma7752424@gmail.com
1f87a6ee07c45f989e6e274aabe3422a69731862
f13383497ba5c43cf39e8981a89e9793a936f1d1
/src/test/java/javaPractice/BubbleBee.java
d59a4534ce75e6f129d89732c642e2bc36340d81
[]
no_license
devesha/javaPractice
d6f22c7f3d6fb4e8d5e484e57a12aa7ffcf5b28a
99c77afdfe1f4d8f4debc1f3e95ce62373aacbff
refs/heads/master
2020-03-15T20:13:41.399779
2018-05-06T17:00:23
2018-05-06T17:00:23
132,327,708
0
0
null
null
null
null
UTF-8
Java
false
false
567
java
package javaPractice; import java.util.HashMap; import java.util.Map; public class BubbleBee { public static void main(String[] args) { String s= "bubble bee"; char a[]=s.toCharArray(); Map<String,Integer> m = new HashMap(); for(int i=0;i<a.length-1;i++) { if(m.containsValue(Character.toString(a[i]))) { m.put(Character.toString(a[i]), m.get(Character.toString(a[i]))+1); } else { m.put(Character.toString(a[i]),1); } } for(String key:m.keySet()) { System.out.println(key + +m.get(key)); } } }
[ "darora.4u@gmail.com" ]
darora.4u@gmail.com
2a9749fbadb837452f6deff1657bd2b8f71dc7a5
ca1bfbe23826b0d7f912218acd1705903f214ba0
/src/main/java/com/example/beans/SamplePojo.java
f0b624e494a65413cf2940ed0f997ee8053744f4
[]
no_license
ajain90/SprintBoot_Sample
aefb637b9db5ba2e8a7f46c5c03c91def64bacc7
a364f3d80dee2740c18a6fe7a9e77b1cdc02c96e
refs/heads/master
2021-08-26T09:47:26.977410
2017-11-23T07:39:36
2017-11-23T07:39:36
111,778,454
0
0
null
null
null
null
UTF-8
Java
false
false
344
java
package com.example.beans; public class SamplePojo { public String getName() { return name; } public String getLastname() { return lastname; } private String name ; private String lastname; public void setName(String name) { this.name = name; } public void setLastname(String lastname) { this.lastname = lastname; } }
[ "ayush.jain@prowareness.com" ]
ayush.jain@prowareness.com
7d27334df2867930a22b8d1323c6d2cf9c595ee2
ffaf7aadee50ad03494e9d4ecaa1dbc295699c8b
/lib_com/src/main/java/com/zyj/plugin/common/data/bean/ComIntentBean.java
78bf507c14c28b780cd31b9afd41dc7e891f1a30
[]
no_license
yueyue10/PluginProject
23c2fd4624bb55ef14b7d0b79fd931b78079c0b5
28e5ccd950491d4ff11ab9b530897590b8e25303
refs/heads/master
2021-07-12T20:56:23.813950
2020-08-26T10:40:58
2020-08-26T10:40:58
201,000,515
0
0
null
null
null
null
UTF-8
Java
false
false
746
java
package com.zyj.plugin.common.data.bean; import com.zyj.plugin.common.mvp.BaseActivity; public class ComIntentBean { private String name; private Class<? extends BaseActivity> activityClass; public ComIntentBean(String name,Class<? extends BaseActivity> activityClass) { this.name = name; this.activityClass = activityClass; } public String getName() { return name == null ? "" : name; } public void setName(String name) { this.name = name; } public Class<? extends BaseActivity> getActivityClass() { return activityClass; } public void setActivityClass(Class<? extends BaseActivity> activityClass) { this.activityClass = activityClass; } }
[ "1650432983@qq.com" ]
1650432983@qq.com
5691b51085262e413def9d2167a979d435360684
fb9a96e48a4880b82ca6bb9c60673bd7a571dc1a
/com/vbera/util/LRU.java
81d1d07698761bc845050f540ed51f4e0c29fd08
[]
no_license
vimalbera92/java-data-structure
a7153207647a27d3fc8f0a888bdfa22346d1e4ff
af3dba56855c5f0e6985c677f98c85b085f8cf03
refs/heads/master
2021-06-10T10:34:56.141228
2016-12-23T17:01:07
2016-12-23T17:01:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,133
java
package com.vbera.util; import java.util.HashMap; import java.util.Map; public class LRU<E> { private int size; private int occupiedBlocks = 0; private Node<E> leastRecentlyUsedElement; private Node<E> mostRecentlyUsedElement; private Map<E, Node<E>> cache = new HashMap<E, Node<E>>(); public LRU(int size) { this.size = size; } public void add(E element) { if (leastRecentlyUsedElement == null) { Node<E> node = createNode(element); leastRecentlyUsedElement = node; mostRecentlyUsedElement = node; cache.put(element, node); occupiedBlocks++; } else { if (cache.containsKey(element)) { Node<E> elementNode = cache.get(element); addElementToFront(elementNode); } else { Node<E> node = createNode(element, mostRecentlyUsedElement, null); if (occupiedBlocks >= size) { cache.remove(leastRecentlyUsedElement.value); leastRecentlyUsedElement = leastRecentlyUsedElement.next; leastRecentlyUsedElement.prev = null; occupiedBlocks--; } mostRecentlyUsedElement.next = node; mostRecentlyUsedElement = node; cache.put(element, node); occupiedBlocks++; } } } private void addElementToFront(Node<E> elementNode) { if (elementNode.next != null) { if (elementNode.prev == null) { mostRecentlyUsedElement.next = leastRecentlyUsedElement; leastRecentlyUsedElement = leastRecentlyUsedElement.next; mostRecentlyUsedElement.next = null; } else { elementNode.prev.next = elementNode.next; elementNode.next.prev = elementNode.prev; mostRecentlyUsedElement.next = elementNode; elementNode.prev = mostRecentlyUsedElement; mostRecentlyUsedElement = mostRecentlyUsedElement.next; } } } private LRU<E>.Node<E> createNode(E element, Node<E> prev, Node<E> next) { Node<E> node = new Node<E>(element, prev, next); return node; } private Node<E> createNode(E element) { return createNode(element, null, null); } public void printCache() { Node<E> temp = mostRecentlyUsedElement; System.out.println("=============="); do { System.out.println(temp.value); temp = temp.prev; } while (temp != null); System.out.println("=============="); } public class Node<E> { private Node<E> next; private Node<E> prev; private E value; public Node(E element, Node<E> prev, Node<E> next) { this.value = element; this.prev = prev; this.next = next; } public Node<E> getNext() { return next; } public void setNext(Node<E> next) { this.next = next; } public Node<E> getPrev() { return prev; } public void setPrev(Node<E> prev) { this.prev = prev; } public E getValue() { return value; } public void setValue(E value) { this.value = value; } @Override public String toString() { return "Node [next=" + next + ", prev=" + prev + ", value=" + value + "]"; } } @Override public String toString() { return "LRU [size=" + size + ", occupiedBlocks=" + occupiedBlocks + ", leastRecentlyUsedElement=" + leastRecentlyUsedElement + ", mostRecentlyUsedElement=" + mostRecentlyUsedElement + ", cache=" + cache + "]"; } }
[ "vimalbera92@gmail.com" ]
vimalbera92@gmail.com
76fbf4ebfca40539907ba39ca38dcfe92c86cf60
efbd1c706182526e53ceae75d155c42179b49748
/app/src/main/java/com/codegemz/elfi/coreapp/api/ExternalCommandReceiver.java
eeb7903a13e32f16712fa180737b46cc37a65ceb
[]
no_license
adrobnych/yoda_robohead
a8d3449f70c2d3f413945e36b4534f70a17db362
2deb78e054608642410e93bf51e514c49649c0ad
refs/heads/master
2021-08-30T20:06:01.184929
2017-12-19T08:13:09
2017-12-19T08:13:09
106,193,322
0
0
null
null
null
null
UTF-8
Java
false
false
719
java
package com.codegemz.elfi.coreapp.api; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class ExternalCommandReceiver extends BroadcastReceiver { public ExternalCommandReceiver() { } @Override public void onReceive(Context context, Intent intent) { String externalCommand = intent.getStringExtra("EXTERNAL_COMMAND"); Log.e("ExtCommandReceiver:", externalCommand); // start service to do heavy work Intent iService = new Intent(context, ExtCommandIntentService.class); iService.putExtra("EXTERNAL_COMMAND",externalCommand); context.startService(iService); } }
[ "adrobnych@gmail.com" ]
adrobnych@gmail.com
dafdb03496763d507f630158ee75ba65039d6644
6b088cf73cf815778661192585fb20c7303daac2
/library/src/main/java/com/hjq/gson/factory/GsonFactory.java
2a455444bebc2e7083d54ae70fcf5640cb81c6e2
[ "Apache-2.0" ]
permissive
longzekai/GsonFactory
e9c667c23ae7cd8e0ab964cf489c53b16c2ae2a2
1524ba3f9c061d6f77bd5071a30770345181fbea
refs/heads/master
2023-01-23T04:54:27.861073
2020-12-05T03:44:29
2020-12-05T03:44:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,741
java
package com.hjq.gson.factory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.internal.bind.TypeAdapters; import java.util.List; /** * author : Android 轮子哥 * github : https://github.com/getActivity/GsonFactory * time : 2020/11/10 * desc : Gson 解析容错适配器 */ public final class GsonFactory { private static volatile Gson sGson; private GsonFactory() {} /** * 获取单例的 Gson 对象 */ public static Gson getSingletonGson() { // 加入双重校验锁 if(sGson == null) { synchronized (GsonFactory.class) { if(sGson == null){ sGson = createGsonBuilder().create(); } } } return sGson; } /** * 创建 Gson 构建器 */ public static GsonBuilder createGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(TypeAdapters.newFactory(String.class, new StringTypeAdapter())) .registerTypeAdapterFactory(TypeAdapters.newFactory(boolean.class, Boolean.class, new BooleanTypeAdapter())) .registerTypeAdapterFactory(TypeAdapters.newFactory(int.class, Integer.class, new IntegerTypeAdapter())) .registerTypeAdapterFactory(TypeAdapters.newFactory(long.class, Long.class, new LongTypeAdapter())) .registerTypeAdapterFactory(TypeAdapters.newFactory(float.class, Float.class, new FloatTypeAdapter())) .registerTypeAdapterFactory(TypeAdapters.newFactory(double.class, Double.class, new DoubleTypeAdapter())) .registerTypeHierarchyAdapter(List.class, new ListTypeAdapter()); } }
[ "880634@qq.com" ]
880634@qq.com
5fc0a6b833f70b293e9ebb31304cde73722f4584
aae7b53ab23b535936569cfa660c524c705bcdd9
/src/main/java/net/thumbtack/school/elections/dao/VoterDao.java
13441d4cf9e8352af9929bcfe5ebca71fa8497a2
[]
no_license
PetukhovDN/ThumbTackCorrespondenceSchool
0c83bdc5bfc1101939b6077883df5eb351257254
219f283cc0d0b21c961c82f6f52da6059c36ea52
refs/heads/master
2022-12-06T23:31:29.885306
2020-06-18T12:43:15
2020-06-18T12:43:15
291,932,811
1
0
null
null
null
null
UTF-8
Java
false
false
619
java
package net.thumbtack.school.elections.dao; import net.thumbtack.school.elections.enums.ResultsOfRequests; import net.thumbtack.school.elections.exceptions.ElectionsException; import net.thumbtack.school.elections.model.Voter; import java.util.List; import java.util.UUID; public interface VoterDao { UUID insertToDataBase(Voter voter) throws ElectionsException; UUID loginToDatabase(String login, String password) throws ElectionsException; ResultsOfRequests logoutFromDatabase(UUID token) throws ElectionsException; List<Voter> getAllVotersFromDatabase(UUID token) throws ElectionsException; }
[ "petuhov77112@mail.ru" ]
petuhov77112@mail.ru
b9f275f4d1c7ecb118982bf5cb1f35a945d141a7
48e48c14e1d6781c96386eefff73149c6feac01f
/codelib/java/src/main/java/c04_crawler/myproxy/SocketThread.java
4f607986e599a74fcbfaa9b25827ae04fca2804e
[]
no_license
zj-github/ws01
518edd3a0ad700e2bc1769816d681c61e56210f6
8406305070a479bbd2a280dee1275e632e116e91
refs/heads/master
2021-01-10T01:50:48.464944
2016-01-27T15:12:13
2016-01-27T15:12:13
48,802,986
0
0
null
null
null
null
GB18030
Java
false
false
3,518
java
package c04_crawler.myproxy; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class SocketThread extends Thread { private Socket socketIn; private InputStream isIn; private OutputStream osIn; // private Socket socketOut; private InputStream isOut; private OutputStream osOut; public SocketThread(Socket socket) { this.socketIn = socket; } private byte[] buffer = new byte[4096]; private static final byte[] VER = { 0x5, 0x0 }; private static final byte[] CONNECT_OK = { 0x5, 0x0, 0x0, 0x1, 0, 0, 0, 0, 0, 0 }; public void run() { try { System.out.println("\n\na client connect " + socketIn.getInetAddress() + ":" + socketIn.getPort()); isIn = socketIn.getInputStream(); osIn = socketIn.getOutputStream(); int len = isIn.read(buffer); System.out.println("< " + bytesToHexString(buffer, 0, len)); osIn.write(VER); osIn.flush(); System.out.println("> " + bytesToHexString(VER, 0, VER.length)); len = isIn.read(buffer); System.out.println("< " + bytesToHexString(buffer, 0, len)); // 查找主机和端口 String host = findHost(buffer, 4, 7); int port = findPort(buffer, 8, 9); System.out.println("host=" + host + ",port=" + port); socketOut = new Socket(host, port); isOut = socketOut.getInputStream(); osOut = socketOut.getOutputStream(); // for (int i = 4; i <= 9; i++) { CONNECT_OK[i] = buffer[i]; } osIn.write(CONNECT_OK); osIn.flush(); System.out.println("> " + bytesToHexString(CONNECT_OK, 0, CONNECT_OK.length)); SocketThreadOutput out = new SocketThreadOutput(isIn, osOut); out.start(); SocketThreadInput in = new SocketThreadInput(isOut, osIn); in.start(); out.join(); in.join(); } catch (Exception e) { System.out.println("a client leave"); } finally { try { if (socketIn != null) { socketIn.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("socket close"); } public static String findHost(byte[] bArray, int begin, int end) { StringBuffer sb = new StringBuffer(); for (int i = begin; i <= end; i++) { sb.append(Integer.toString(0xFF & bArray[i])); sb.append("."); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static int findPort(byte[] bArray, int begin, int end) { int port = 0; for (int i = begin; i <= end; i++) { port <<= 16; port += bArray[i]; } return port; } // 4A 7D EB 69 // 74 125 235 105 public static final String bytesToHexString(byte[] bArray, int begin, int end) { StringBuffer sb = new StringBuffer(bArray.length); String sTemp; for (int i = begin; i < end; i++) { sTemp = Integer.toHexString(0xFF & bArray[i]); if (sTemp.length() < 2) sb.append(0); sb.append(sTemp.toUpperCase()); sb.append(" "); } return sb.toString(); } }
[ "zj_github@163.com" ]
zj_github@163.com
939dc9a0913090cee367a7b67f92803115e5b562
0ee3a75fd1f42f286e8fbfd95c4b2b8b8e364956
/src/main/java/algorithms/simples/MaxPalinromeFromFivesTheBest.java
73f499c835011a5fbd32ef6cd0eb830a4c1f57ef
[]
no_license
anauk/fs6Lesson
41634d549fc05b00ab5f8f2785ba4357e6180169
916ce341c8214094ea2d5fe84c9b671e2216caa6
refs/heads/master
2020-04-06T16:22:33.354216
2018-09-19T18:11:35
2018-09-19T18:11:35
157,617,303
0
0
null
null
null
null
UTF-8
Java
false
false
1,245
java
package algorithms.simples; public class MaxPalinromeFromFivesTheBest { final int MIN=10000; final int MAX=99999; boolean findValue(int[]a, int v) { for (int i = 0; i < a.length; i++) { if (a[i]==v) return true; } return false; } public long doFind() { int[] simples = new SimpleV4(MIN, MAX).array(); long max=0; PalindromeWoString p = new PalindromeWoString(); for (int i = 0; i < simples.length; i++) { for (int j = simples.length-1; j > i ; j--) { long mult=(long)simples[i]*simples[j]; if ((mult > max) && p.is(mult)) { max = mult; break; } } } return max; } public static void main(String[] args) { final int ITER_COUNT=10; MaxPalinromeFromFivesTheBest p = new MaxPalinromeFromFivesTheBest(); long l=System.currentTimeMillis(); long max=0; for (int i = 0; i < ITER_COUNT; i++) { max=p.doFind(); } l=System.currentTimeMillis()-l; System.out.printf("Maximum:%d\n",max); System.out.printf("Time spent:%d\n", l/ITER_COUNT); } }
[ "alexey.rykhalskiy@gmail.com" ]
alexey.rykhalskiy@gmail.com
5adb367a460f311a6a1858f0ae8de846c1f8ef27
51c9cbeac78d93763118d1f08bfd1dc43770827c
/src/test/java/team830/SuperCanvasser/VariableTest.java
ff0c6d7d92693516bcd4be0b39255eeb3b8bc0a5
[]
no_license
Suprr/SuperCanvasser
fb6b97ddcee426f05d6196da594050a8f8127b75
d0f132259382863f799f460e5cb6e73b034d9dd1
refs/heads/master
2020-04-18T05:13:18.809345
2018-11-29T03:53:39
2018-11-29T03:53:39
167,270,589
1
0
null
null
null
null
UTF-8
Java
false
false
2,579
java
//package team830.SuperCanvasser; // //import org.junit.Assert; //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.test.annotation.Rollback; //import org.springframework.test.context.junit4.SpringRunner; //import team830.SuperCanvasser.Variable.Variable; //import team830.SuperCanvasser.Variable.VariableRepo; //import team830.SuperCanvasser.Variable.VariableService; // //import java.util.List; // //@Rollback //@RunWith(SpringRunner.class) //@SpringBootTest //public class VariableTest { // @Autowired // private VariableRepo variableRepo; // // @Autowired // VariableService variableService; // // @Test // public void testAddVar() { // Variable var0 = new Variable("avgSpeed", "5"); // Variable var1 = new Variable("dayDuration", "10"); // Variable res0 = variableRepo.save(var0); // Variable res1 = variableRepo.save(var1); // // Assert.assertEquals(var0, res0); // Assert.assertEquals(var1, res1); // } // // @Test // public void testEditVar() { // variableRepo.deleteAll(); // Variable var0 = new Variable("avgSpeed", "5"); // Variable res0 = variableRepo.save(var0); // Assert.assertEquals(var0, res0); // // this is not working setValue Errorrrrrrrrrr compiling // res0.setValue("99"); // Variable res2 = variableService.editVariable(res0); // Assert.assertEquals(res0, res2); // // // Variable var1 = new Variable("dayDuration", "10"); // Variable res1 = variableRepo.save(var1); // Assert.assertEquals(var1, res1); // // res1.setValue("83"); // Variable res3 = variableService.editVariable(res1); // Assert.assertEquals(res1, res3); // } // // @Test // public void testGetVars() { // variableRepo.deleteAll(); // Variable var0 = new Variable("avgSpeed", "5"); // Variable var1 = new Variable("dayDuration", "10"); // Variable res0 = variableRepo.save(var0); // Variable res1 = variableRepo.save(var1); // // Assert.assertEquals(var0, res0); // Assert.assertEquals(var1, res1); // // List<Variable> res2 = variableService.findAll(); // Assert.assertEquals(res0, res2.get(0)); // Assert.assertEquals(res1, res2.get(1)); // } // //}
[ "kat.ah.choi@gmail.com" ]
kat.ah.choi@gmail.com
c8c800d4bbb651e9ef5eb7cf42aeaf0765c0ae55
4a55b31930700171377209e10035fe0dea36d675
/f1app/src/main/java/uniWork/f1app/Exceptions/DriverNotFoundException.java
33401d9d2a3eed24b893893d95c4296d20a51484
[]
no_license
Tudiman/F1MVCApp
d31af6150be11223cea377ca339a759856ce6c4b
bcb6e24bc5ae3824f17c3e2f9937a86d378d2547
refs/heads/main
2023-02-12T05:32:05.530887
2021-01-15T14:05:24
2021-01-15T14:05:24
329,896,180
0
0
null
null
null
null
UTF-8
Java
false
false
202
java
package uniWork.f1app.Exceptions; public class DriverNotFoundException extends RuntimeException { public DriverNotFoundException(String id) { super("Cound not find driver " + id); } }
[ "vladtudose496@gmail.com" ]
vladtudose496@gmail.com
882299c56608b38cb98770172905e81078cdd222
fea99e4d534ce3a5019618459d785637a0266ce9
/src/main/java/PlayerManager.java
8ffbfd9da783569eee7e47b4e356d7fd7479dbed
[ "MIT" ]
permissive
JeffreyRiggle/playerlib-example
0ef142d4ed53c4409341711b963cce1f93b71ae0
70d4d14d9057cc0d46466dbe8391cea39032ba12
refs/heads/master
2021-07-14T01:31:00.487003
2021-06-26T01:09:28
2021-06-26T01:09:28
99,224,696
0
0
MIT
2021-06-26T01:09:10
2017-08-03T11:17:11
Java
UTF-8
Java
false
false
9,497
java
package consoleplayerlibapplication; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import playerlib.attributes.IAttribute; import playerlib.characteristics.ICharacteristic; import playerlib.equipment.IBodyPart; import playerlib.equipment.IEquipment; import playerlib.inventory.IInventory; import playerlib.items.*; import playerlib.player.IPlayer; public class PlayerManager { private Scanner _input; public PlayerManager(Scanner input) { _input = input; } public boolean execute(String option, IPlayer player, List<IAttribute> attributes, List<IBodyPart> bodyParts, List<ICharacteristic> characteristics) { boolean retVal = true; switch(option) { case "1": createPlayer(player, attributes, bodyParts, characteristics); break; case "2": addAttribute(player, attributes); break; case "3": removeAttribute(player); break; case "4": addBodyPart(player, bodyParts); break; case "5": removeBodyPart(player); break; case "6": addCharacteristic(player, characteristics); break; case "7": removeCharacteristic(player); break; case "8": listPlayer(player); break; case "9": retVal = false; break; default: System.out.printf("%s, is an unknown command. \n", option); break; } return retVal; } private void listPlayer(IPlayer player) { System.out.println("*****Player*****"); System.out.printf("Name: %s", player.name()); System.out.println("\n**BodyParts**"); printBodyPartsFull(player.bodyParts()); System.out.println("\n**Characteristics**"); printCharacteristicsFull(player.characteristics()); System.out.println("\n**Attributes**"); printAttributesFull(player.attributes()); System.out.println("\n**Inventory**"); printInventoryFull(player.inventory()); System.out.println("\n**Equipment**"); printEquipment(player.equipment(), player.bodyParts()); } private void printEquipment(IEquipment equipment, List<IBodyPart> parts) { for (IItem item : equipment.equipted()) { System.out.printf("Name: %s, Description: %s, BodyPart: %s", item.name(), item.description(), findBodyPart(item, equipment, parts)); System.out.println(" **Properties** "); printProperties(item.properties()); } } private void printInventoryFull(IInventory inventory) { for(IItem item : inventory.items()) { System.out.printf("Name: %s, Description: %s, Amount: %s", item.name(), item.description(), inventory.getAmount(item)); System.out.println(" **Properties** "); printProperties(item.properties()); } } private void printBodyPartsFull(List<IBodyPart> bodyParts) { for (IBodyPart part : bodyParts) { System.out.printf("Name: %s, Description: %s\n", part.name(), part.description()); System.out.println(" **Characteristics** "); printCharacteristicsFull(part.getCharacteristics()); } } private void printCharacteristicsFull(List<ICharacteristic> characteristics) { for (ICharacteristic characteristic : characteristics) { System.out.printf("Name: %s, Description: %s, Value: %s", characteristic.name(), characteristic.description(), characteristic.value()); } } private void printAttributesFull(List<IAttribute> attributes) { for (IAttribute attribute : attributes) { System.out.printf("Name: %s, Description: %s, Value: %s", attribute.name(), attribute.description(), attribute.value()); } } private void printProperties(List<IProperty> properties) { for (IProperty property : properties) { System.out.printf("Name: %s, Description: %s, Value: %s", property.name(), property.description(), property.value()); } } private String findBodyPart(IItem item, IEquipment equip, List<IBodyPart> parts) { IBodyPart part = null; for(IBodyPart bp : parts) { if (equip.equipted(bp) != item) continue; part = bp; break; } if (part == null) { return ""; } return part.name(); } private void removeCharacteristic(IPlayer player) { listCharacteristicNames(player.characteristics()); System.out.print("Characteristic to remove: "); String removeChar = _input.nextLine(); ICharacteristic characteristic = getCharacteristic(removeChar, player.characteristics()); if (characteristic != null) { player.removeCharacteristic(characteristic); } } private ICharacteristic getCharacteristic(String removeChar, List<ICharacteristic> characteristics) { ICharacteristic character = null; for (ICharacteristic characteristic : characteristics) { if (!characteristic.name().equalsIgnoreCase(removeChar)) continue; character = characteristic; } return character; } private void listCharacteristicNames(List<ICharacteristic> characteristics) { System.out.print("Characteristics: "); for (ICharacteristic characteristic : characteristics) { System.out.printf("%s, ", characteristic.name()); } System.out.println(); } private void addCharacteristic(IPlayer player, List<ICharacteristic> characteristics) { listCharacteristicNames(characteristics); System.out.print("Characteristic to add: "); String addChar = _input.nextLine(); ICharacteristic characteristic = getCharacteristic(addChar, characteristics); if (characteristic != null) { player.addCharacteristic(characteristic); } } private void removeBodyPart(IPlayer player) { listBodyPartNames(player.bodyParts()); System.out.print("Body Part to remove: "); String removePart = _input.nextLine(); IBodyPart bodyPart = getBodyPart(removePart, player.bodyParts()); if (bodyPart != null) { player.addBodyPart(bodyPart); } } private IBodyPart getBodyPart(String removePart, List<IBodyPart> bodyParts) { IBodyPart bPart = null; for(IBodyPart part : bodyParts) { if (!part.name().equalsIgnoreCase(removePart)) continue; bPart = part; break; } return bPart; } private void listBodyPartNames(List<IBodyPart> bodyParts) { System.out.print("Body Parts: "); for (IBodyPart bodyPart : bodyParts) { System.out.printf("%s, ", bodyPart.name()); } System.out.println(); } private void addBodyPart(IPlayer player, List<IBodyPart> bodyParts) { listBodyPartNames(bodyParts); System.out.print("Body Part to add: "); String addPart = _input.nextLine(); IBodyPart part = getBodyPart(addPart, bodyParts); if (part != null) { player.addBodyPart(part); } } private void removeAttribute(IPlayer player) { listAttributeNames(player.attributes()); System.out.print("Attribute to remove: "); String removeAtt = _input.nextLine(); IAttribute attribute = getAttribute(removeAtt, player.attributes()); if (attribute != null) { player.addAttribute(attribute); } } private IAttribute getAttribute(String removeAtt, List<IAttribute> attributes) { IAttribute atrib = null; for (IAttribute att : attributes) { if (!att.name().equalsIgnoreCase(removeAtt)) continue; atrib = att; break; } return atrib; } private void listAttributeNames(List<IAttribute> attributes) { System.out.print("Attributes: "); for (IAttribute att : attributes) { System.out.printf("%s, ", att.name()); } System.out.println(); } private void addAttribute(IPlayer player, List<IAttribute> attributes) { listAttributeNames(attributes); System.out.print("Attribute to add: "); String addAtt = _input.nextLine(); IAttribute attribute = getAttribute(addAtt, player.attributes()); if (attribute != null) { player.removeAttribute(attribute); } } private void createPlayer(IPlayer player, List<IAttribute> attributes, List<IBodyPart> bodyParts, List<ICharacteristic> characteristics) { System.out.println("Name: "); String name = _input.nextLine(); player.name(name); List<IAttribute> att = getAttributes(attributes); player.clearAttributes(); player.addAttributes(att); List<ICharacteristic> characters = getCharacteristics(characteristics); player.clearCharacteristics(); player.addCharacteristics(characters); List<IBodyPart> parts = getBodyParts(bodyParts); player.clearBodyParts(); player.addBodyParts(parts); } private List<IAttribute> getAttributes(List<IAttribute> attributes) { List<IAttribute> attribs = new ArrayList<IAttribute>(); listAttributeNames(attributes); while(true) { System.out.print("Attribute to add(~ to end): "); String addAtt = _input.nextLine(); if (addAtt.equals("~")) break; IAttribute att = getAttribute(addAtt, attributes); if (att != null) { attribs.add(att); } } return attribs; } private List<IBodyPart> getBodyParts(List<IBodyPart> bodyPartList) { List<IBodyPart> bodyParts = new ArrayList<IBodyPart>(); listBodyPartNames(bodyPartList); while(true) { System.out.print("Body Part to add(~ to end): "); String addPart = _input.nextLine(); if (addPart.equals("~")) break; IBodyPart part = getBodyPart(addPart, bodyPartList); if (part != null) { bodyParts.add(part); } } return bodyParts; } private List<ICharacteristic> getCharacteristics(List<ICharacteristic> chars) { List<ICharacteristic> characteristics = new ArrayList<ICharacteristic>(); listCharacteristicNames(chars); while(true) { System.out.print("Characteristic to add(~ to end): "); String addChar = _input.nextLine(); if (addChar.equals("~")) break; ICharacteristic character = getCharacteristic(addChar, chars); if (character != null) { characteristics.add(character); } } return characteristics; } }
[ "JeffreyRiggle@gmail.com" ]
JeffreyRiggle@gmail.com
1c2e00b9ddb2603fbcf71bcbccb0a0c9c3dd60d0
a561011fc563a85fc0390644adf7c5dc0fff4773
/src/main/java/exerciseOne/formyproject/Test_KeyAndMousePress.java
4896db9cce809408c84e9e873abebeccf4d0a1fd
[]
no_license
SwathiLiz/SeleniumEssentialTraining
c94230c2f82f5f6be10a3b51c84a985a20809d6d
e0374f92738955d3e55c1eb36650c36e2dd9b506
refs/heads/master
2022-10-06T10:31:22.094138
2020-06-10T02:19:37
2020-06-10T02:19:37
265,639,613
0
0
null
null
null
null
UTF-8
Java
false
false
863
java
package exerciseOne.formyproject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Test_KeyAndMousePress { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "E:/LinkedIn/Selenium Essential Training/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://formy-project.herokuapp.com/keypress"); //driver.findElement(By.linkText("Key and Mouse Press")).click(); WebElement nameField = driver.findElement(By.cssSelector(".form-control[id='name']")); nameField.click(); nameField.sendKeys("Swathi Liz"); driver.findElement(By.id("button")).click(); driver.quit(); } }
[ "swathilizthomas@gmail.com" ]
swathilizthomas@gmail.com