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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8afb2972ed090254397f16bcd4684af063401c20 | 662429775d1be51c7df07a0dbb7d9d7cc1aae877 | /src/main/java/wind/yang/security/service/RoleService.java | 9c4a3e137ef14c2f1b77057ba5395109449b31ae | [] | no_license | swampwar/springsecurity-inflearnlecture-project | a13f3225e3b2b5679110f3a8caf21a99ecfb5800 | d0be2a44113faa0e92111cc93776799b8f15188b | refs/heads/master | 2022-12-02T10:56:31.054686 | 2020-08-03T12:45:01 | 2020-08-03T12:45:01 | 277,491,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 260 | java | package wind.yang.security.service;
import wind.yang.security.domain.entity.Role;
import java.util.List;
public interface RoleService {
Role getRole(long id);
List<Role> getRoles();
void createRole(Role role);
void deleteRole(long id);
}
| [
"dkdfl88@gmail.com"
] | dkdfl88@gmail.com |
2b88b18d5bf33be16fe0eef7770c4e4f0c5f4cdb | 2f0436c72eb19d6c069b9b78288536aae09c6c25 | /app/src/main/java/com/example/gamerapp/Modal/GameList.java | 59792e753438fe971510364a140af3ddb63ac713 | [] | no_license | samirthaker2020/GamerApp1.0 | be608d1a4ea45db76c3e88c2a4d2eff3ff0414f1 | 1a89159800072aad0c06bf38f9b054d104b22b37 | refs/heads/master | 2022-12-06T14:43:53.071350 | 2020-08-25T01:41:34 | 2020-08-25T01:41:34 | 268,860,502 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,390 | java | package com.example.gamerapp.Modal;
import java.io.Serializable;
public class GameList implements Serializable {
public String gamename,gameimage,gametrailer;
public int gameid;
public float lstgame_rating;
public float getLstgame_rating() {
return lstgame_rating;
}
@Override
public String toString() {
return "GameList{" +
"gamename='" + gamename + '\'' +
", gameimage='" + gameimage + '\'' +
", gametrailer='" + gametrailer + '\'' +
", gameid=" + gameid +
", lstgame_rating=" + lstgame_rating +
'}';
}
public void setLstgame_rating(float lstgame_rating) {
this.lstgame_rating = lstgame_rating;
}
public String getGametrailer() {
return gametrailer;
}
public void setGametrailer(String gametrailer) {
this.gametrailer = gametrailer;
}
public String getGamename() {
return gamename;
}
public void setGamename(String gamename) {
this.gamename = gamename;
}
public String getGameimage() {
return gameimage;
}
public void setGameimage(String gameimage) {
this.gameimage = gameimage;
}
public int getGameid() {
return gameid;
}
public void setGameid(int gameid) {
this.gameid = gameid;
}
}
| [
"samir2009thaker@gmail.com"
] | samir2009thaker@gmail.com |
70d88ccc5a6eb2c4a772fcf75c18d8a40232b8cb | ce2a7cb5e2891de0667368f5c6f1dfffe3d91b2e | /org.neclipse.xtext.validator.example.funcdsl/src-gen/org/neclipse/xtext/validator/example/funcdsl/funcDsl/Func.java | 42e715f07d1d033470682a62f3e3cffff5a8d1f6 | [] | no_license | nbhusare/Xtext-sandbox | cde65ac55e8762bb6d2776912bfb16b5154638da | df34250dfbf325d642892646ce9726b6ed0912c9 | refs/heads/master | 2020-04-15T16:12:25.006621 | 2020-02-10T12:23:25 | 2020-02-10T12:23:25 | 21,731,634 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,695 | java | /**
* ******************************************************************************
* Copyright (C) 2018 Neeraj Bhusare (https://nbhusare.github.io/)
* 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
* ******************************************************************************
*/
package org.neclipse.xtext.validator.example.funcdsl.funcDsl;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Func</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.neclipse.xtext.validator.example.funcdsl.funcDsl.Func#getName <em>Name</em>}</li>
* <li>{@link org.neclipse.xtext.validator.example.funcdsl.funcDsl.Func#getParams <em>Params</em>}</li>
* </ul>
*
* @see org.neclipse.xtext.validator.example.funcdsl.funcDsl.FuncDslPackage#getFunc()
* @model
* @generated
*/
public interface Func extends EObject
{
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.neclipse.xtext.validator.example.funcdsl.funcDsl.FuncDslPackage#getFunc_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.neclipse.xtext.validator.example.funcdsl.funcDsl.Func#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Params</b></em>' containment reference list.
* The list contents are of type {@link org.neclipse.xtext.validator.example.funcdsl.funcDsl.Param}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Params</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Params</em>' containment reference list.
* @see org.neclipse.xtext.validator.example.funcdsl.funcDsl.FuncDslPackage#getFunc_Params()
* @model containment="true"
* @generated
*/
EList<Param> getParams();
} // Func
| [
"neerajbhusare@gmail.com"
] | neerajbhusare@gmail.com |
225513af2065759f0c32b38807123e97d46f0a9c | b800e70528ec0d906ea3d1abd1b364b6ef4ff0ee | /app/src/main/java/smsproject/app/mastergame/com/smsproject/G.java | bba726c236ce3ade4bb22bc2ab48dbcf158ba972 | [] | no_license | mohsendeadspace/SmsProjectApp | 8bc662e40d30542ba2ed0aea04d5d91190f5cef8 | 73bc8b971118527b8e34c9a70f10d07a459e51c5 | refs/heads/master | 2023-03-21T08:28:21.644497 | 2021-03-08T09:30:05 | 2021-03-08T09:30:05 | 345,600,132 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 669 | java | package smsproject.app.mastergame.com.smsproject;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import java.io.File;
public class G extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context=this.getApplicationContext();
/*
database.execSQL("CREATE TABLE IF NOT EXISTS person (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE ," +
" phone_num VARCHAR ," +
" password VARCHAR " +
")");
*/
}
} | [
"mohsen.deadspace.mf@gmail.com"
] | mohsen.deadspace.mf@gmail.com |
2e27a5430c51c346761e898a575c5e6eda5ff838 | 1401bd17b2db67b371823ca54cfb5a26d4dbb5de | /src/main/java/com/google/devtools/build/lib/syntax/Starlark.java | 4abb74e3a521c5e6fe32c69ea700111420148047 | [
"Apache-2.0"
] | permissive | yazici/bazel | 1078a8ba0a347419bcfdbd0c0854d5c00b4f283b | 4e2b4958d508ef2ed65db7b681c3be5939e7f147 | refs/heads/master | 2020-09-30T07:39:44.049771 | 2019-12-10T20:19:20 | 2019-12-10T20:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,009 | java | // Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.syntax;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkInterfaceUtils;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.util.Pair;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* The Starlark class defines the most important entry points, constants, and functions needed by
* all clients of the Starlark interpreter.
*/
// TODO(adonovan): move these here:
// len, str, iterate, equal, compare, getattr, index, slice, parse, exec, eval, and so on.
public final class Starlark {
private Starlark() {} // uninstantiable
/** The Starlark None value. */
public static final NoneType NONE = NoneType.NONE;
/**
* A sentinel value passed to optional parameters of SkylarkCallable-annotated methods to indicate
* that no argument value was supplied.
*/
public static final Object UNBOUND = new UnboundMarker();
@Immutable
private static final class UnboundMarker implements StarlarkValue {
private UnboundMarker() {}
@Override
public String toString() {
return "<unbound>";
}
@Override
public boolean isImmutable() {
return true;
}
@Override
public void repr(Printer printer) {
printer.append("<unbound>");
}
}
/**
* The universal bindings predeclared in every Starlark file, such as None, True, len, and range.
*/
public static final ImmutableMap<String, Object> UNIVERSE = makeUniverse();
private static ImmutableMap<String, Object> makeUniverse() {
ImmutableMap.Builder<String, Object> env = ImmutableMap.builder();
env //
.put("False", false)
.put("True", true)
.put("None", Starlark.NONE);
addMethods(env, new MethodLibrary());
return env.build();
}
/**
* Reports whether the argument is a legal Starlark value: a string, boolean, integer, or
* StarlarkValue.
*/
public static boolean valid(Object x) {
return x instanceof StarlarkValue
|| x instanceof String
|| x instanceof Boolean
|| x instanceof Integer;
}
/**
* Returns {@code x} if it is a {@link #valid} Starlark value, otherwise throws
* IllegalArgumentException.
*/
public static <T> T checkValid(T x) {
if (!valid(x)) {
throw new IllegalArgumentException("invalid Starlark value: " + x.getClass());
}
return x;
}
/**
* Converts a Java value {@code x} to a Starlark one, if x is not already a valid Starlark value.
* A Java List or Map is converted to a Starlark list or dict, respectively, and null becomes
* {@link #NONE}. Any other non-Starlark value causes the function to throw
* IllegalArgumentException.
*
* <p>This function is applied to the results of @SkylarkCallable-annotated Java methods.
*/
public static Object fromJava(Object x, @Nullable Mutability mutability) {
if (x == null) {
return NONE;
} else if (Starlark.valid(x)) {
return x;
} else if (x instanceof List) {
return StarlarkList.copyOf(mutability, (List<?>) x);
} else if (x instanceof Map) {
return Dict.copyOf(mutability, (Map<?, ?>) x);
} else {
throw new IllegalArgumentException(
"cannot expose internal type to Starlark: " + x.getClass());
}
}
/**
* Returns the truth value of a valid Starlark value, as if by the Starlark expression {@code
* bool(x)}.
*/
public static boolean truth(Object x) {
if (x instanceof Boolean) {
return (Boolean) x;
} else if (x instanceof StarlarkValue) {
return ((StarlarkValue) x).truth();
} else if (x instanceof String) {
return !((String) x).isEmpty();
} else if (x instanceof Integer) {
return (Integer) x != 0;
} else {
throw new IllegalArgumentException("invalid Starlark value: " + x.getClass());
}
}
/**
* Returns an iterable view of {@code x} if it is an iterable Starlark value; throws EvalException
* otherwise.
*
* <p>Whereas the interpreter temporarily freezes the iterable value using {@link EvalUtils#lock}
* and {@link EvalUtils#unlock} while iterating in {@code for} loops and comprehensions, iteration
* using this method does not freeze the value. Callers should exercise care not to mutate the
* underlying object during iteration.
*/
public static Iterable<?> toIterable(Object x) throws EvalException {
if (x instanceof StarlarkIterable) {
return (Iterable<?>) x;
}
throw new EvalException(null, "type '" + EvalUtils.getDataTypeName(x) + "' is not iterable");
}
/**
* Returns a new array containing the elements of Starlark iterable value {@code x}. A Starlark
* value is iterable if it implements {@link StarlarkIterable}.
*/
public static Object[] toArray(Object x) throws EvalException {
// Specialize Sequence and Dict to avoid allocation and/or indirection.
if (x instanceof Sequence) {
return ((Sequence<?>) x).toArray();
} else if (x instanceof Dict) {
return ((Dict<?, ?>) x).keySet().toArray();
} else {
return Iterables.toArray(toIterable(x), Object.class);
}
}
/**
* Returns the length of a Starlark string, sequence (such as a list or tuple), dict, or other
* iterable, as if by the Starlark expression {@code len(x)}, or -1 if the value is valid but has
* no length.
*/
public static int len(Object x) {
if (x instanceof String) {
return ((String) x).length();
} else if (x instanceof Sequence) {
return ((Sequence) x).size();
} else if (x instanceof Dict) {
return ((Dict) x).size();
} else if (x instanceof StarlarkIterable) {
// Iterables.size runs in constant time if x implements Collection.
return Iterables.size((Iterable<?>) x);
} else {
checkValid(x);
return -1; // valid but not a sequence
}
}
/** Returns the string form of a value as if by the Starlark expression {@code str(x)}. */
public static String str(Object x) {
return Printer.getPrinter().str(x).toString();
}
/** Returns the string form of a value as if by the Starlark expression {@code repr(x)}. */
public static String repr(Object x) {
return Printer.getPrinter().repr(x).toString();
}
/** Returns a string formatted as if by the Starlark expression {@code pattern % arguments}. */
public static String format(String pattern, Object... arguments) {
return Printer.getPrinter().format(pattern, arguments).toString();
}
/** Returns a string formatted as if by the Starlark expression {@code pattern % arguments}. */
public static String formatWithList(String pattern, List<?> arguments) {
return Printer.getPrinter().formatWithList(pattern, arguments).toString();
}
/**
* Adds to the environment {@code env} all {@code StarlarkCallable}-annotated fields and methods
* of value {@code v}. The class of {@code v} must have or inherit a {@code SkylarkModule} or
* {@code SkylarkGlobalLibrary} annotation.
*/
public static void addMethods(ImmutableMap.Builder<String, Object> env, Object v) {
Class<?> cls = v.getClass();
if (!SkylarkInterfaceUtils.hasSkylarkGlobalLibrary(cls)
&& SkylarkInterfaceUtils.getSkylarkModule(cls) == null) {
throw new IllegalArgumentException(
cls.getName() + " is annotated with neither @SkylarkGlobalLibrary nor @SkylarkModule");
}
// TODO(adonovan): logically this should be a parameter.
StarlarkSemantics semantics = StarlarkSemantics.DEFAULT_SEMANTICS;
for (String name : CallUtils.getMethodNames(semantics, v.getClass())) {
// We pass desc=null instead of the descriptor that CallUtils.getMethod would
// return because DEFAULT_SEMANTICS is probably incorrect for the call.
// The effect is that the default semantics determine which methods appear in
// env, but the thread's semantics determine which method calls succeed.
env.put(name, new BuiltinCallable(v, name, /*desc=*/ null));
}
}
/**
* Adds to the environment {@code env} the value {@code v}, under its annotated name. The class of
* {@code v} must have or inherit a {@code SkylarkModule} annotation.
*/
public static void addModule(ImmutableMap.Builder<String, Object> env, Object v) {
Class<?> cls = v.getClass();
SkylarkModule annot = SkylarkInterfaceUtils.getSkylarkModule(cls);
if (annot == null) {
throw new IllegalArgumentException(cls.getName() + " is not annotated with @SkylarkModule");
}
env.put(annot.name(), v);
}
// TODO(adonovan):
//
// The code below shows the API that is the destination toward which all of the recent
// tiny steps are headed. It doesn't work yet, but it helps to remember our direction.
//
// The API assumes that the "universe" portion (None, len, str) of the "predeclared" lexical block
// is always available, so clients needn't mention it in the API. Starlark.UNIVERSE will expose it
// as a public constant.
//
// Q. is there any value to returning the Module as opposed to just its global bindings as a Map?
// The Go implementation does the latter and it works well.
// This would allow the the Module class to be private.
// The Bazel "Label" function, and various Bazel caller whitelists, depend on
// being able to dig the label metadata out of a function's module,
// but this could be addressed with a StarlarkFunction.getModuleLabel accessor.
// A. The Module has an associated mutability (that of the thread),
// and it might benefit from a 'freeze' method.
// (But longer term, we might be able to eliminate Thread.mutability,
// and the concept of a shared Mutability entirely, as in go.starlark.net.)
//
// Any FlagRestrictedValues among 'predeclared' and 'env' maps are implicitly filtered by the
// semantics or thread.semantics.
//
// For exec(file), 'predeclared' corresponds exactly to the predeclared environment (sans
// UNIVERSE) as described in the language spec. For eval(expr), 'env' is the complete environment
// in which the expression is evaluated, which might include a mixture of predeclared, global,
// file-local, and function-local variables, as when (for example) the debugger evaluates an
// expression as if at a particular point in the source. As far as 'eval' is concerned, there is
// no difference in kind between these bindings.
//
// The API does not rely on StarlarkThread acting as an environment, or on thread.globals.
//
// These functions could be implemented today with minimal effort.
// The challenge is to migrate all the callers from the old API,
// and in particular to reduce their assumptions about thread.globals,
// which is going away.
// ---- One shot execution API: parse, compile, and execute ----
/**
* Parse the input as a file, validate it in the specified predeclared environment, compile it,
* and execute it. On success, the module is returned; on failure, it throws an exception.
*/
public static Module exec(
StarlarkThread thread, ParserInput input, Map<String, Object> predeclared)
throws SyntaxError, EvalException, InterruptedException {
// Pseudocode:
// file = StarlarkFile.parse(input)
// validateFile(file, predeclared.keys, thread.semantics)
// prog = compile(file.statements)
// module = new module(predeclared)
// toplevel = new StarlarkFunction(prog.toplevel, module)
// call(thread, toplevel)
// return module # or module.globals?
throw new UnsupportedOperationException();
}
/**
* Parse the input as an expression, validate it in the specified environment, compile it, and
* evaluate it. On success, the expression's value is returned; on failure, it throws an
* exception.
*/
public static Object eval(StarlarkThread thread, ParserInput input, Map<String, Object> env)
throws SyntaxError, EvalException, InterruptedException {
// Pseudocode:
// StarlarkFunction fn = exprFunc(input, env, thread.semantics)
// return call(thread, fn)
throw new UnsupportedOperationException();
}
/**
* Parse the input as a file, validate it in the specified environment, compile it, and execute
* it. If the final statement is an expression, return its value.
*
* <p>This complicated function, which combines exec and eval, is intended for use in a REPL or
* debugger. In case of parse of validation error, it throws SyntaxError. In case of execution
* error, the function returns partial results: the incomplete module plus the exception.
*
* <p>Assignments in the input act as updates to a new module created by this function, which is
* returned.
*
* <p>In a typical REPL, the module bindings may be provided as predeclared bindings to the next
* call.
*
* <p>In a typical debugger, predeclared might contain the complete environment at a particular
* point in a running program, including its predeclared, global, and local variables. Assignments
* in the debugger affect only the ephemeral module created by this call, not the values of
* bindings observable by the debugged Starlark program. Thus execAndEval("x = 1; x + x") will
* return a value of 2, and a module containing x=1, but it will not affect the value of any
* variable named x in the debugged program.
*
* <p>A REPL will typically set the legacy "load binds globally" semantics flag, otherwise the
* names bound by a load statement will not be visible in the next REPL chunk.
*/
public static ModuleAndValue execAndEval(
StarlarkThread thread, ParserInput input, Map<String, Object> predeclared)
throws SyntaxError {
// Pseudocode:
// file = StarlarkFile.parse(input)
// validateFile(file, predeclared.keys, thread.semantics)
// prog = compile(file.statements + [return lastexpr])
// module = new module(predeclared)
// toplevel = new StarlarkFunction(prog.toplevel, module)
// value = call(thread, toplevel)
// return (module, value, error) # or module.globals?
throw new UnsupportedOperationException();
}
/**
* The triple returned by {@link #execAndEval}. At most one of {@code value} and {@code error} is
* set.
*/
public static class ModuleAndValue {
/** The module, containing global values from top-level assignments. */
public Module module;
/** The value of the final expression, if any, on success. */
@Nullable public Object value;
/** An EvalException or InterruptedException, if execution failed. */
@Nullable public Exception error;
}
// ---- Two-stage API: compilation and execution are separate ---
/**
* Parse the input as a file, validates it in the specified predeclared environment (a set of
* names, optionally filtered by the semantics), and compiles it to a Program. It throws
* SyntaxError in case of scan/parse/validation error.
*
* <p>In addition to the program, it returns the validated syntax tree. This permits clients such
* as Bazel to inspect the syntax (for BUILD dialect checks, glob prefetching, etc.)
*/
public static Pair<Program, StarlarkFile> compileFile(
ParserInput input, //
Set<String> predeclared,
StarlarkSemantics semantics)
throws SyntaxError {
// Pseudocode:
// file = StarlarkFile.parse(input)
// validateFile(file, predeclared.keys, thread.semantics)
// prog = compile(file.statements)
// return (prog, file)
throw new UnsupportedOperationException();
}
/**
* An opaque executable representation of a StarlarkFile. Programs may be efficiently serialized
* and deserialized without parsing and recompiling.
*/
public static class Program {
/**
* Execute the toplevel function of a compiled program and returns the module populated by its
* top-level assignments.
*
* <p>The keys of predeclared must match the set used when creating the Program.
*/
public Module init(
StarlarkThread thread, //
Map<String, Object> predeclared,
@Nullable Object label) // a regrettable Bazelism we needn't widely expose in the API
throws EvalException, InterruptedException {
// Pseudocode:
// module = new module(predeclared, label=label)
// toplevel = new StarlarkFunction(prog.toplevel, module)
// call(thread, toplevel)
// return module # or module.globals?
throw new UnsupportedOperationException();
}
}
/**
* Parse the input as an expression, validates it in the specified environment, and returns a
* callable Starlark no-argument function value that computes and returns the value of the
* expression.
*/
private static StarlarkFunction exprFunc(
ParserInput input, //
Map<String, Object> env,
StarlarkSemantics semantics)
throws SyntaxError {
// Pseudocode:
// expr = Expression.parse(input)
// validateExpr(expr, env.keys, semantics)
// prog = compile([return expr])
// module = new module(env)
// return new StarlarkFunction(prog.toplevel, module)
throw new UnsupportedOperationException();
}
}
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
06e38f388d541d29a1d1d6af875ccbf42371c6a0 | 82fd989f92810b1d33d87fecb73f719acdfcf36c | /src/main/java/translate/commerce/CommerceRules.java | a9409e3b4c21d7ce8952c424893f50fe9d35bbdc | [] | no_license | anilkothari10/translate | 45e934ff94354aee199e06c933c29a1aad9ee573 | 2c8e2d2954e2fe54f943050e2cf58d312d807666 | refs/heads/master | 2022-07-07T02:34:08.327794 | 2019-09-12T17:10:59 | 2019-09-12T17:10:59 | 146,479,825 | 0 | 1 | null | 2022-06-29T16:57:00 | 2018-08-28T17:03:19 | Java | UTF-8 | Java | false | false | 886 | java | package translate.commerce;
public class CommerceRules {
private String name;
private String variableName;
private String description;
private String ruleType;
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "CommerceRules [name=" + name + ", variableName=" + variableName + ", description=" + description
+ ", ruleType=" + ruleType + "]";
}
}
| [
"sshirore@USMUMSSHIRORE2.us.deloitte.com"
] | sshirore@USMUMSSHIRORE2.us.deloitte.com |
35941cf5170c636effe927832a128757e7132072 | ff28a0226ae36bed47de587bca583dc9c1d3086d | /other projects/airlines/payment.java | 96323c472f5bb3ff5b5ef3f869c92e34113795d0 | [] | no_license | varunkvn/courseProjects | 22d43bb07a43c8b2757333fd43e2a92fe66fa833 | 623e6b77e212cf15f498fc12a13f0acc8787eb44 | refs/heads/master | 2021-01-10T02:09:11.218892 | 2017-06-02T20:18:51 | 2017-06-02T20:18:51 | 55,561,322 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,433 | java | import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class payment extends HttpServlet
{
Connection con;
Statement st;
ResultSet rst;
String str,rno,amt,total,date;
String month[]={"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
int dt,mo,ye;
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
rno=req.getParameter("rno");
total=req.getParameter("total");
Calendar c=Calendar.getInstance();
dt=c.get(Calendar.DAY_OF_MONTH);
mo=c.get(Calendar.MONTH);
ye=c.get(Calendar.YEAR);
date=(dt+"-"+month[mo]+"-"+ye);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:DSN","scott","tiger");
st=con.createStatement();
rst=st.executeQuery("select nvl(max(invoice_no),0)+1 from payment_details");
while(rst.next())
str=rst.getString(1);
out.println("<html><body>");
out.println("<center><table>");
out.println("<caption><font size=5><b><u>Payment Details</u></b></font></caption>");
out.println("<form method=post action=\"http://localhost:8080/servlet/pinsert\">");
out.println("<tr><td><label>Invoice No:</label></td><td><input size=20 name=ino value="+str+" readonly></td>");
out.println("<td><label>Res No:</label></td><td><input size=20 name=rno value="+rno+" readonly></td></tr>");
out.println("<tr><td><label>Amount:</label></td><td><input size=20 name=amt value="+total+" readonly></td>");
out.println("<td><label>Date:</label></td><td><input size=20 name=date value="+date+" readonly></td></tr>");
out.println("<tr><td><label>Mode:</label></td><td><input type=radio name=mode value=credit>:Credit Card</td>");
out.println("<td><input type=radio name=mode value=cheque>:Cheque</td>");
out.println("<table><tr><td align=center><input type=submit value=\" Insert \"></td></tr></table>");
out.println("</form>");
out.println("</tabel>");
out.println("</body></html>");
}
catch(Exception e)
{
out.println("Exception in connection:"+e);
}
}
}
| [
"Varun.Kavalipurapu@cerner.com"
] | Varun.Kavalipurapu@cerner.com |
9e2236876c35e9d52f3306c27c23125efd66077e | f7b5030f2e6c50c2ef743b32884e0fe0bdeffc52 | /CORE JAVA LABS/javajlc/Lab346.java | 9075f79f3416b7ca320b3e72e48b20c435a7a635 | [] | no_license | nareshdas/springMvc1 | c18bb2e209bafd2cd3519a568b0fe72438d1b0de | 3c3981f8e894125a8be986c851eced396df9423b | refs/heads/master | 2020-03-27T19:10:34.818818 | 2018-09-01T06:16:46 | 2018-09-01T06:16:46 | 146,970,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 189 | java | class Lab346{
public static void main(String args[]){
new B();
}
}
class A{
A(int a){
System.out.println("A int");
}
}
class B extends A{
B(){
System.out.println("B> DC");
super(10);
}
}
| [
"nareshchandra886@gmail.com"
] | nareshchandra886@gmail.com |
6704cadc6d82960d1e7a59244f70d9120dac4d6f | 4fef26abdb26a1eec419253ccd28c7f668ee6a2c | /FlightBooking/src/main/java/com/FlightBookingSystem/FlightBooking/service/ScheduledFlightServiceImpl.java | a71d2ca37b6dbe14501b4acd947a645132e5df88 | [] | no_license | Gaurav007omnitrix/Flight_Booking_System | a322a5460abb21b76856aff7cacf11e9d7a7ea60 | 376fe2853cfafe7c6797262f5a840a3cf112582a | refs/heads/main | 2023-08-13T17:27:09.294488 | 2021-10-19T10:24:59 | 2021-10-19T10:24:59 | 412,734,818 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,758 | java | package com.FlightBookingSystem.FlightBooking.service;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import com.FlightBookingSystem.FlightBooking.exception.RecordNotFoundException;
import com.FlightBookingSystem.FlightBooking.exception.ScheduledFlightNotFoundException;
import com.FlightBookingSystem.FlightBooking.model.Schedule;
import com.FlightBookingSystem.FlightBooking.model.ScheduledFlight;
import com.FlightBookingSystem.FlightBooking.repository.ScheduleRepository;
import com.FlightBookingSystem.FlightBooking.repository.ScheduledFlightRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Service
public class ScheduledFlightServiceImpl implements ScheduledFlightService {
@Autowired
ScheduledFlightRepository dao;
@Autowired
ScheduleRepository scheduleDao;
@Autowired
BookingService bookingService;
@Override
public ScheduledFlight addScheduledFlight(ScheduledFlight scheduledFlight) {
return dao.save(scheduledFlight);
}
@Override
public ScheduledFlight modifyScheduledFlight(ScheduledFlight scheduleFlight) {
ScheduledFlight updateScheduleFlight = dao.findById(scheduleFlight.getScheduleFlightId()).get();
Schedule updateSchedule = scheduleDao.findById(scheduleFlight.getSchedule().getScheduleId()).get();
updateScheduleFlight.setAvailableSeats(scheduleFlight.getAvailableSeats());
updateSchedule.setSrcAirport(scheduleFlight.getSchedule().getSrcAirport());
updateSchedule.setDstnAirport(scheduleFlight.getSchedule().getDstnAirport());
updateSchedule.setArrDateTime(scheduleFlight.getSchedule().getArrDateTime());
updateSchedule.setDeptDateTime(scheduleFlight.getSchedule().getDeptDateTime());
dao.save(updateScheduleFlight);
return scheduleFlight;
}
@Override
public String removeScheduledFlight(BigInteger flightId) throws RecordNotFoundException {
if (flightId == null)
throw new RecordNotFoundException("Enter flight Id");
Optional<ScheduledFlight> scheduleFlight = dao.findById(flightId);
if (!scheduleFlight.isPresent())
throw new RecordNotFoundException("Enter a valid Flight Id");
else {
// try {
// cancelBookings(flightId);
// } catch (RecordNotFoundException e) {
// System.out.println("No Bookings Found");
// }
dao.deleteById(flightId);
}
return "Scheduled flight with ID " + flightId + " is not found";
}
// @Override
// public boolean cancelBookings(BigInteger flightId) throws
// RecordNotFoundException {
// Iterable<Booking> bookingList = bookingService.displayAllBooking();
// for (Booking booking : bookingList) {
// if (booking.getScheduleFlight().getScheduleFlightId().equals(flightId)) {
// bookingService.deleteBooking(booking.getBookingId());
// }
// }
// return true;
// }
@Override
public Iterable<ScheduledFlight> viewAllScheduledFlights() {
return dao.findAll();
}
@Override
public ScheduledFlight viewScheduledFlight(BigInteger flightId) throws ScheduledFlightNotFoundException {
if (flightId == null)
throw new ScheduledFlightNotFoundException("Enter flight Id");
Optional<ScheduledFlight> scheduleFlight = dao.findById(flightId);
if (!scheduleFlight.isPresent())
throw new ScheduledFlightNotFoundException("Enter a valid Flight Id");
else
return scheduleFlight.get();
}
}
| [
"gauravmahato178.gkm@gmail.com"
] | gauravmahato178.gkm@gmail.com |
3c588744e4b83d6e3f4afff797883869511cce9e | a308a7c6409e22cf8ce27bdc85acaaf29b08315e | /app/build/generated/not_namespaced_r_class_sources/debug/r/androidx/viewpager2/R.java | 7582a9f9423cfdfb1cedb4932195549375768bec | [] | no_license | timife007/ApplePlayApplications | 56dfd7be6c0cdb37bbbef733710185905f55707f | b7d3b1f9492c61c5b40bb02e63010732ca6abdca | refs/heads/master | 2022-11-10T21:29:21.710883 | 2020-06-21T18:40:19 | 2020-06-21T18:40:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,917 | 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 androidx.viewpager2;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f030028;
public static final int fastScrollEnabled = 0x7f030119;
public static final int fastScrollHorizontalThumbDrawable = 0x7f03011a;
public static final int fastScrollHorizontalTrackDrawable = 0x7f03011b;
public static final int fastScrollVerticalThumbDrawable = 0x7f03011c;
public static final int fastScrollVerticalTrackDrawable = 0x7f03011d;
public static final int font = 0x7f030120;
public static final int fontProviderAuthority = 0x7f030122;
public static final int fontProviderCerts = 0x7f030123;
public static final int fontProviderFetchStrategy = 0x7f030124;
public static final int fontProviderFetchTimeout = 0x7f030125;
public static final int fontProviderPackage = 0x7f030126;
public static final int fontProviderQuery = 0x7f030127;
public static final int fontStyle = 0x7f030128;
public static final int fontVariationSettings = 0x7f030129;
public static final int fontWeight = 0x7f03012a;
public static final int layoutManager = 0x7f030169;
public static final int recyclerViewStyle = 0x7f0301f9;
public static final int reverseLayout = 0x7f0301fa;
public static final int spanCount = 0x7f030215;
public static final int stackFromEnd = 0x7f03021b;
public static final int ttcIndex = 0x7f03028d;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f0500a7;
public static final int notification_icon_bg_color = 0x7f0500a8;
public static final int ripple_material_light = 0x7f0500b2;
public static final int secondary_text_default_material_light = 0x7f0500b4;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f060053;
public static final int compat_button_inset_vertical_material = 0x7f060054;
public static final int compat_button_padding_horizontal_material = 0x7f060055;
public static final int compat_button_padding_vertical_material = 0x7f060056;
public static final int compat_control_corner_material = 0x7f060057;
public static final int compat_notification_large_icon_max_height = 0x7f060058;
public static final int compat_notification_large_icon_max_width = 0x7f060059;
public static final int fastscroll_default_thickness = 0x7f06008b;
public static final int fastscroll_margin = 0x7f06008c;
public static final int fastscroll_minimum_range = 0x7f06008d;
public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f060095;
public static final int item_touch_helper_swipe_escape_max_velocity = 0x7f060096;
public static final int item_touch_helper_swipe_escape_velocity = 0x7f060097;
public static final int notification_action_icon_size = 0x7f06012e;
public static final int notification_action_text_size = 0x7f06012f;
public static final int notification_big_circle_margin = 0x7f060130;
public static final int notification_content_margin_start = 0x7f060131;
public static final int notification_large_icon_height = 0x7f060132;
public static final int notification_large_icon_width = 0x7f060133;
public static final int notification_main_column_padding_top = 0x7f060134;
public static final int notification_media_narrow_margin = 0x7f060135;
public static final int notification_right_icon_size = 0x7f060136;
public static final int notification_right_side_padding_top = 0x7f060137;
public static final int notification_small_icon_background_padding = 0x7f060138;
public static final int notification_small_icon_size_as_large = 0x7f060139;
public static final int notification_subtext_size = 0x7f06013a;
public static final int notification_top_pad = 0x7f06013b;
public static final int notification_top_pad_large_text = 0x7f06013c;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f070084;
public static final int notification_bg = 0x7f070085;
public static final int notification_bg_low = 0x7f070086;
public static final int notification_bg_low_normal = 0x7f070087;
public static final int notification_bg_low_pressed = 0x7f070088;
public static final int notification_bg_normal = 0x7f070089;
public static final int notification_bg_normal_pressed = 0x7f07008a;
public static final int notification_icon_background = 0x7f07008b;
public static final int notification_template_icon_bg = 0x7f07008c;
public static final int notification_template_icon_low_bg = 0x7f07008d;
public static final int notification_tile_bg = 0x7f07008e;
public static final int notify_panel_notification_icon_bg = 0x7f07008f;
}
public static final class id {
private id() {}
public static final int accessibility_action_clickable_span = 0x7f08000a;
public static final int accessibility_custom_action_0 = 0x7f08000b;
public static final int accessibility_custom_action_1 = 0x7f08000c;
public static final int accessibility_custom_action_10 = 0x7f08000d;
public static final int accessibility_custom_action_11 = 0x7f08000e;
public static final int accessibility_custom_action_12 = 0x7f08000f;
public static final int accessibility_custom_action_13 = 0x7f080010;
public static final int accessibility_custom_action_14 = 0x7f080011;
public static final int accessibility_custom_action_15 = 0x7f080012;
public static final int accessibility_custom_action_16 = 0x7f080013;
public static final int accessibility_custom_action_17 = 0x7f080014;
public static final int accessibility_custom_action_18 = 0x7f080015;
public static final int accessibility_custom_action_19 = 0x7f080016;
public static final int accessibility_custom_action_2 = 0x7f080017;
public static final int accessibility_custom_action_20 = 0x7f080018;
public static final int accessibility_custom_action_21 = 0x7f080019;
public static final int accessibility_custom_action_22 = 0x7f08001a;
public static final int accessibility_custom_action_23 = 0x7f08001b;
public static final int accessibility_custom_action_24 = 0x7f08001c;
public static final int accessibility_custom_action_25 = 0x7f08001d;
public static final int accessibility_custom_action_26 = 0x7f08001e;
public static final int accessibility_custom_action_27 = 0x7f08001f;
public static final int accessibility_custom_action_28 = 0x7f080020;
public static final int accessibility_custom_action_29 = 0x7f080021;
public static final int accessibility_custom_action_3 = 0x7f080022;
public static final int accessibility_custom_action_30 = 0x7f080023;
public static final int accessibility_custom_action_31 = 0x7f080024;
public static final int accessibility_custom_action_4 = 0x7f080025;
public static final int accessibility_custom_action_5 = 0x7f080026;
public static final int accessibility_custom_action_6 = 0x7f080027;
public static final int accessibility_custom_action_7 = 0x7f080028;
public static final int accessibility_custom_action_8 = 0x7f080029;
public static final int accessibility_custom_action_9 = 0x7f08002a;
public static final int action_container = 0x7f080032;
public static final int action_divider = 0x7f080034;
public static final int action_image = 0x7f080035;
public static final int action_text = 0x7f08003b;
public static final int actions = 0x7f08003c;
public static final int async = 0x7f080043;
public static final int blocking = 0x7f080047;
public static final int chronometer = 0x7f080053;
public static final int dialog_button = 0x7f080068;
public static final int forever = 0x7f08007c;
public static final int icon = 0x7f080085;
public static final int icon_group = 0x7f080086;
public static final int info = 0x7f080089;
public static final int italic = 0x7f08008b;
public static final int item_touch_helper_previous_elevation = 0x7f08008c;
public static final int line1 = 0x7f080090;
public static final int line3 = 0x7f080091;
public static final int normal = 0x7f0800bf;
public static final int notification_background = 0x7f0800c0;
public static final int notification_main_column = 0x7f0800c1;
public static final int notification_main_column_container = 0x7f0800c2;
public static final int right_icon = 0x7f0800d3;
public static final int right_side = 0x7f0800d4;
public static final int tag_accessibility_actions = 0x7f080103;
public static final int tag_accessibility_clickable_spans = 0x7f080104;
public static final int tag_accessibility_heading = 0x7f080105;
public static final int tag_accessibility_pane_title = 0x7f080106;
public static final int tag_screen_reader_focusable = 0x7f080107;
public static final int tag_transition_group = 0x7f080108;
public static final int tag_unhandled_key_event_manager = 0x7f080109;
public static final int tag_unhandled_key_listeners = 0x7f08010a;
public static final int text = 0x7f08010d;
public static final int text2 = 0x7f08010e;
public static final int time = 0x7f080118;
public static final int title = 0x7f080119;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f090014;
}
public static final class layout {
private layout() {}
public static final int custom_dialog = 0x7f0b001d;
public static final int notification_action = 0x7f0b004b;
public static final int notification_action_tombstone = 0x7f0b004c;
public static final int notification_template_custom_big = 0x7f0b004d;
public static final int notification_template_icon_group = 0x7f0b004e;
public static final int notification_template_part_chronometer = 0x7f0b004f;
public static final int notification_template_part_time = 0x7f0b0050;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f0f0051;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f100155;
public static final int TextAppearance_Compat_Notification_Info = 0x7f100156;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f100157;
public static final int TextAppearance_Compat_Notification_Time = 0x7f100158;
public static final int TextAppearance_Compat_Notification_Title = 0x7f100159;
public static final int Widget_Compat_NotificationActionContainer = 0x7f100236;
public static final int Widget_Compat_NotificationActionText = 0x7f100237;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030028 };
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[] FontFamily = { 0x7f030122, 0x7f030123, 0x7f030124, 0x7f030125, 0x7f030126, 0x7f030127 };
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 = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f030120, 0x7f030128, 0x7f030129, 0x7f03012a, 0x7f03028d };
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 = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
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 = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
public static final int[] RecyclerView = { 0x10100c4, 0x10100eb, 0x10100f1, 0x7f030119, 0x7f03011a, 0x7f03011b, 0x7f03011c, 0x7f03011d, 0x7f030169, 0x7f0301fa, 0x7f030215, 0x7f03021b };
public static final int RecyclerView_android_orientation = 0;
public static final int RecyclerView_android_clipToPadding = 1;
public static final int RecyclerView_android_descendantFocusability = 2;
public static final int RecyclerView_fastScrollEnabled = 3;
public static final int RecyclerView_fastScrollHorizontalThumbDrawable = 4;
public static final int RecyclerView_fastScrollHorizontalTrackDrawable = 5;
public static final int RecyclerView_fastScrollVerticalThumbDrawable = 6;
public static final int RecyclerView_fastScrollVerticalTrackDrawable = 7;
public static final int RecyclerView_layoutManager = 8;
public static final int RecyclerView_reverseLayout = 9;
public static final int RecyclerView_spanCount = 10;
public static final int RecyclerView_stackFromEnd = 11;
public static final int[] ViewPager2 = { 0x10100c4 };
public static final int ViewPager2_android_orientation = 0;
}
}
| [
"timife007@gmail.com"
] | timife007@gmail.com |
67315bd7ea84a21d47330eb613215002507d3838 | bd94a511f5c5a997d8672a196d08bed01fd2c943 | /Programming/src/com/danielchan/Dec2012UTMQuestion6/Counter.java | 0b1b67f375b427a4d7f3020df4431d9d11fcf517 | [] | no_license | DanielChanJA/CSC207Final | 06fcb6511db131b3df926a406445dac2768b2180 | 2368dc0e5d4a42b85d7ab6823ddd01c55ec6ae03 | refs/heads/master | 2021-05-01T04:57:17.864185 | 2016-04-25T21:23:38 | 2016-04-25T21:23:38 | 56,996,461 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 658 | java | package com.danielchan.Dec2012UTMQuestion6;
/**
* Created by chanj on 4/25/2016.
*/
public class Counter {
private int count;
public Counter() {
this.count = 0;
}
public int increment() throws OverLimitException {
if (count > 2) {
throw new OverLimitException("Greater than 2 limit");
}
return ++count;
}
public int decrement() throws UnderLimitException {
if (count < -2) {
throw new UnderLimitException("Less than 2 limit");
}
return --count;
}
public int getCount() {
return count;
}
}
| [
"iam@danielchan.me"
] | iam@danielchan.me |
830638a085961925fae1f81debf67d3f158d7cef | 0727272150ada4ed54f1f7eb5b6e6b0c65909183 | /products/stratos/modules/integration/src/test/java/org/apache/stratos/integration/tests/rest/IntegrationMockClient.java | 2b094a456f5b4b6335549d7f01e522b49e76a5c5 | [
"MIT",
"Apache-2.0"
] | permissive | gayangunarathne/stratos | 6f48080ad51102bb85741a558634443ce213bfce | 2c34f816cfbd5a93c62ecc4dffe1d87026e7c329 | refs/heads/master | 2020-04-08T19:54:35.719109 | 2015-09-01T05:48:43 | 2015-09-01T05:48:43 | 21,611,620 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,258 | 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.stratos.integration.tests.rest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.stratos.mock.iaas.client.MockIaasApiClient;
import org.apache.stratos.mock.iaas.client.rest.*;
import org.apache.stratos.mock.iaas.client.rest.HttpResponse;
import org.apache.stratos.mock.iaas.client.rest.HttpResponseHandler;
import org.apache.stratos.mock.iaas.client.rest.RestClient;
import org.apache.stratos.mock.iaas.domain.*;
import java.net.URI;
/**
* Mock client
*/
public class IntegrationMockClient extends MockIaasApiClient {
private static final Log log = LogFactory.getLog(IntegrationMockClient.class);
private static final String INSTANCES_CONTEXT = "/instances/";
private DefaultHttpClient httpClient;
private String endpoint;
public IntegrationMockClient(String endpoint) {
super(endpoint);
this.endpoint = endpoint;
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 50
cm.setDefaultMaxPerRoute(50);
httpClient = new DefaultHttpClient(cm);
httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient);
}
public void terminateInstance(String instanceId) {
try {
if (log.isDebugEnabled()) {
log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
}
URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
if (response != null) {
if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
return;
} else {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ErrorResponse errorResponse = gson.fromJson(response.getContent(), ErrorResponse.class);
if (errorResponse != null) {
throw new RuntimeException(errorResponse.getErrorMessage());
}
}
}
throw new RuntimeException("An unknown error occurred");
} catch (Exception e) {
String message = "Could not start mock instance";
throw new RuntimeException(message, e);
}
}
public HttpResponse doDelete(URI resourcePath) throws Exception {
HttpDelete httpDelete = null;
try {
httpDelete = new HttpDelete(resourcePath);
httpDelete.addHeader("Content-Type", "application/json");
return httpClient.execute(httpDelete, new HttpResponseHandler());
} finally {
releaseConnection(httpDelete);
}
}
private void releaseConnection(HttpRequestBase request) {
if (request != null) {
request.releaseConnection();
}
}
}
| [
"gayang@wso2.com"
] | gayang@wso2.com |
58c8b36ab9f9e0a1802796be1288d2f0dd500e93 | 411de30f7fa69808ad726f976694cd4dd7a40bef | /src/com/xiuman/xingduoduo/ui/activity/LimitBuyActivity.java | 6ee7af5e130537575b32545d30fac100a723d875 | [] | no_license | Lucaziki/XingDuoduo | a629655df3968164c66bca2827f38add0e1548cd | bf78e7b27e6efc262b80e99e57275a4c5cce1892 | refs/heads/master | 2021-01-14T12:34:43.492953 | 2014-12-10T05:08:09 | 2014-12-10T05:08:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,838 | java | package com.xiuman.xingduoduo.ui.activity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xiuman.xingduoduo.R;
import com.xiuman.xingduoduo.adapter.LimitBuyListViewAdapter;
import com.xiuman.xingduoduo.app.AppConfig;
import com.xiuman.xingduoduo.app.AppManager;
import com.xiuman.xingduoduo.app.URLConfig;
import com.xiuman.xingduoduo.callback.TaskCenterClassifyGoodsBack;
import com.xiuman.xingduoduo.model.ActionValue;
import com.xiuman.xingduoduo.model.GoodsOne;
import com.xiuman.xingduoduo.net.HttpUrlProvider;
import com.xiuman.xingduoduo.ui.base.Base2Activity;
import com.xiuman.xingduoduo.util.TimeUtil;
import com.xiuman.xingduoduo.util.ToastUtil;
import com.xiuman.xingduoduo.util.options.CustomOptions;
import com.xiuman.xingduoduo.view.pulltorefresh.PullToRefreshBase;
import com.xiuman.xingduoduo.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xiuman.xingduoduo.view.pulltorefresh.PullToRefreshListView;
/**
* @名称:LimitBuyActivity.java
* @描述:限时抢购
* @author danding 2014-9-17
*/
public class LimitBuyActivity extends Base2Activity implements OnClickListener {
/*----------------------------------组件------------------------------------*/
// 用来判断是否是推送商品的标记,如果是则为true,finish的时候打开商城首页,如果不是则,不做任何动作
private boolean start_tag = false;
// 返回
private Button btn_back;
// 标题栏
private TextView tv_title;
// 右侧
private Button btn_right;
// 下拉刷新sv
private PullToRefreshListView pulllv_limitbuy;
// ListView
private ListView lv_limitbuy_container;
// 网络连接失败显示的布局
private LinearLayout llyt_network_error;
// 商品为空为空时显示的布局
private LinearLayout llyt_null_goods;
// 倒计时
private TextView tv_center_daojishi;
/*-------------------------------------ImageLoader-------------------------*/
// ImageLoader
public ImageLoader imageLoader = ImageLoader.getInstance();
// 配置图片加载及显示选项
public DisplayImageOptions options;
/*----------------------------------标记----------------------------------*/
// 是上拉还是下拉
private boolean isUp = true;
/*----------------------------------数据---------------------------------*/
// 接收到的分类名,测试数据
private String classify_name = "";
// 接收到的分类地址后缀
private String classify_url = "";
// 请求接口得到的商品数据
private ActionValue<GoodsOne> value = new ActionValue<GoodsOne>();
// (商品列表)
private ArrayList<GoodsOne> goods_get = new ArrayList<GoodsOne>();
// 当前现实的商品列表
private ArrayList<GoodsOne> goods_current = new ArrayList<GoodsOne>();
// 当前页
private int currentPage = 1;
private LimitBuyListViewAdapter adapter;
// 消息处理Handler
@SuppressLint("HandlerLeak")
@SuppressWarnings("unchecked")
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case AppConfig.NET_SUCCED:// 获取数据成功
value = (ActionValue<GoodsOne>) msg.obj;
if (value==null||!value.isSuccess()) {
llyt_null_goods.setVisibility(View.VISIBLE);
} else {
goods_get = (ArrayList<GoodsOne>) value.getDatasource();
if (isUp) {// 下拉
goods_current = goods_get;
adapter = new LimitBuyListViewAdapter(
LimitBuyActivity.this, goods_current, options,
imageLoader);
// 下拉加载完成
pulllv_limitbuy.onPullDownRefreshComplete();
lv_limitbuy_container.setAdapter(adapter);
} else {// 上拉
goods_current.addAll(goods_get);
adapter.notifyDataSetChanged();
// 上拉刷新完成
pulllv_limitbuy.onPullUpRefreshComplete();
// 设置是否有更多的数据
if (currentPage < value.getTotalpage()) {
// pullsv_limitbuy
// .setHasMoreData(true);
} else {
// pullsv_limitbuy
// .setHasMoreData(false);
}
}
TimeUtil.setLastUpdateTime(pulllv_limitbuy);
llyt_null_goods.setVisibility(View.INVISIBLE);
}
llyt_network_error.setVisibility(View.INVISIBLE);
break;
case AppConfig.NET_ERROR_NOTNET:// 无网络
llyt_network_error.setVisibility(View.VISIBLE);
llyt_null_goods.setVisibility(View.INVISIBLE);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_limitby);
initData();
findViewById();
initUI();
setListener();
}
@Override
protected void initData() {
options = CustomOptions.getOptions2();
// 获取Intent传递的数据
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
classify_name = bundle.getString("classify_name");
classify_url = bundle.getString("classify_url");
currentPage = 1;
// 商品标记(短信链接)
start_tag = getIntent().getExtras().getBoolean("start_tag");
}
@Override
protected void findViewById() {
btn_back = (Button) findViewById(R.id.btn_common_back);
btn_right = (Button) findViewById(R.id.btn_common_right);
tv_title = (TextView) findViewById(R.id.tv_common_title);
llyt_network_error = (LinearLayout) findViewById(R.id.llyt_network_error);
llyt_null_goods = (LinearLayout) findViewById(R.id.llyt_goods_null);
pulllv_limitbuy = (PullToRefreshListView) findViewById(R.id.pulllv_limtbuy);
pulllv_limitbuy.setScrollLoadEnabled(true);
pulllv_limitbuy.setPullLoadEnabled(true);
lv_limitbuy_container = pulllv_limitbuy.getRefreshableView();
lv_limitbuy_container.setDividerHeight(1);
lv_limitbuy_container.setDivider(getResources().getDrawable(R.drawable.line_solid));
View view = View.inflate(this, R.layout.include_limitbuy_container,
null);
tv_center_daojishi = (TextView) view
.findViewById(R.id.tv_center_daojishi);
lv_limitbuy_container.addHeaderView(view);
}
@Override
protected void initUI() {
btn_right.setVisibility(View.INVISIBLE);
tv_title.setText(classify_name);
// 加载数据,测试数据,添加操作
// initFirstData(currentPage);
pulllv_limitbuy.doPullRefreshing(true, 500);
// 设置刷新时间
TimeUtil.setLastUpdateTime(pulllv_limitbuy);
// 设置倒计时
startDaojishi();
}
@Override
protected void setListener() {
btn_back.setOnClickListener(this);
llyt_network_error.setOnClickListener(this);
// 下拉刷新,上拉加载
pulllv_limitbuy.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
isUp = true;
currentPage = 1;
initFirstData(currentPage);
}
@Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
isUp = false;
if (value.getPage() < value.getTotalpage()) {
currentPage += 1;
initFirstData(currentPage);
} else {
ToastUtil.ToastView(LimitBuyActivity.this, getResources()
.getString(R.string.no_more));
// 下拉加载完成
pulllv_limitbuy.onPullDownRefreshComplete();
// 上拉刷新完成
pulllv_limitbuy.onPullUpRefreshComplete();
// 设置是否有更多的数据
pulllv_limitbuy
.setHasMoreData(false);
}
}
});
lv_limitbuy_container.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Object obj = lv_limitbuy_container.getItemAtPosition(position);
// 将商品数据传递给
if (obj instanceof GoodsOne) {
GoodsOne goods_one = (GoodsOne) obj;
Intent intent = new Intent(LimitBuyActivity.this,
GoodsActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("goods_one", goods_one);
bundle.putSerializable("goods_id", goods_one.getId());
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(
R.anim.translate_horizontal_start_in,
R.anim.translate_horizontal_start_out);
}
}
});
}
/**
* 点击事件
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_common_back:// 返回
finish();
overridePendingTransition(R.anim.translate_horizontal_finish_in,
R.anim.translate_horizontal_finish_out);
break;
case R.id.llyt_network_error:// 重新加载
//
// currentPage = 1;
// initFirstData(currentPage);
pulllv_limitbuy.doPullRefreshing(true, 500);
break;
}
}
/**
* @描述:加载数据(首次加载)--测试数据,添加操作
* @date:2014-6-25
*/
private void initFirstData(int currentPage) {
HttpUrlProvider.getIntance().getCenterClassifyGoods(
LimitBuyActivity.this,
new TaskCenterClassifyGoodsBack(handler),
URLConfig.CENTER_HOME_PLATE, currentPage, classify_url);
}
/*------------------------------------倒计时-------------------------------*/
private Calendar mDate2;
private int mYear, mMonth, mDay;
private String date;
private Handler mHandler = new Handler();// 全局handler
int time = 0;// 时间差
private void updateDateTime() {
mDate2 = Calendar.getInstance();
mYear = mDate2.get(Calendar.YEAR);
mMonth = mDate2.get(Calendar.MONTH);
mDay = mDate2.get(Calendar.DAY_OF_MONTH);
date = mYear + "-" + (getDateFormat(mMonth + 1)) + "-"
+ getDateFormat(mDay) + " " + 24 + ":" + "00" + ":00";
// if(mHour>=17){
// date = mYear + "-" + (getDateFormat(mMonth + 1)) + "-"
// + getDateFormat(mDay+1) + " " + 17 + ":"
// + "00" + ":00";
// }
}
public String getDateFormat(int time) {
String date = time + "";
if (time < 10) {
date = "0" + date;
}
return date;
}
class TimeCount implements Runnable {
@Override
public void run() {
while (time >= 0)// 整个倒计时执行的循环
{
time--;
mHandler.post(new Runnable() // 通过它在UI主线程中修改显示的剩余时间
{
public void run() {
tv_center_daojishi.setText(getInterval(time));// 显示剩余时间
}
});
try {
Thread.sleep(1000);// 线程休眠一秒钟 这个就是倒计时的间隔时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 下面是倒计时结束逻辑
mHandler.post(new Runnable() {
@Override
public void run() {
tv_center_daojishi.setText("设定的时间到。");
}
});
}
}
/**
* 设定显示文字
*/
public static String getInterval(int time) {
String txt = null;
if (time >= 0) {
long hour = time % (24 * 3600) / 3600;// 小时
long minute = time % 3600 / 60;// 分钟
long second = time % 60;// 秒
txt = hour + "小时" + minute + "分" + second + "秒";
} else {
txt = "已过期";
}
return txt;
}
private void startDaojishi() {
updateDateTime();
time = getTimeInterval(date);
new Thread(new TimeCount()).start();// 开启线程
}
/**
* 获取两个日期的时间差
*/
public static int getTimeInterval(String data) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
int interval = 0;
try {
Date currentTime = new Date();// 获取现在的时间
Date beginTime = dateFormat.parse(data);
interval = (int) ((beginTime.getTime() - currentTime.getTime()) / (1000));// 时间差
// 单位秒
} catch (ParseException e) {
e.printStackTrace();
}
return interval;
}
@Override
protected void onDestroy() {
super.onDestroy();
imageLoader.stop();
imageLoader.clearMemoryCache();
if (start_tag
&& getIntent().getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK
&& AppManager.getAppManager().count <= 1) {
startActivity(new Intent(LimitBuyActivity.this, MainActivity.class));
}
}
}
| [
"598281865@qq.com"
] | 598281865@qq.com |
6c87d94140f61d78ff02006f802ef9e5085f03b5 | 4f2403f0c545a9ea500ad61cd01df313f865889c | /src/main/java/com/rainbow/tony/guice/robotproblem/Car.java | e70bb0a5ef6b0973612c1240c64c9bd4e89d33d8 | [] | no_license | softPrisoner/tony-guice-netty | 54ad978113de48af1ff3b9057c09819f3f9d683e | 05bef03660a5c1c19643b9a01eeebdb43cf1d01a | refs/heads/master | 2022-06-30T00:43:32.354483 | 2020-05-12T03:02:21 | 2020-05-12T03:02:21 | 261,941,406 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 751 | java | package com.rainbow.tony.guice.robotproblem;
import com.google.inject.Inject;
/**
* @author wabslygzj@163.com (Tony Li)
* @copyright rainbow
* @description Car
* @date 2020-05-11
*/
class Car {
private final Engine engine;
private final Transmission transmission;
private final Driveline driveline;
@Inject
public Car(Engine engine, Transmission transmission, Driveline driveline) {
this.engine = engine;
this.transmission = transmission;
this.driveline = driveline;
;
}
public Driveline getDriveline() {
return driveline;
}
public Engine getEngine() {
return engine;
}
public Transmission getTransmission() {
return transmission;
}
}
| [
"wabslygzj@163.com"
] | wabslygzj@163.com |
00eeadc834b8bbfbc144b6dc547991fa43f9c50b | 2e9c2b7a5fedb2fc59fc2c9c6ed032065ef784c9 | /src/main/java/ArmstrongNumbers.java | 6e91d8c44ce6f2724f844131b77684e4af4abaad | [] | no_license | Sahana-Nagaraja/Exercism | e9acc73fd9c948583c18fae646ca9cd843ff0096 | b123db1b6ed23a3b99bcebdb39af543d2058f718 | refs/heads/master | 2020-03-10T02:06:16.587155 | 2018-04-15T07:37:46 | 2018-04-15T07:37:46 | 129,128,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 487 | java | public class ArmstrongNumbers {
public boolean isArmstrongNumber(int input) {
int output = input,digit=0,i,remainder,result=0;
while(output>0)
{
output /= 10;
digit++;
}
output = input;
i = digit;
while(digit>0)
{
remainder = output%10;
output /= 10;
result += Math.pow(remainder,i);
digit--;
}
return result == input;
}
}
| [
"nsahana@IN-nsahana.local"
] | nsahana@IN-nsahana.local |
d632ac125da41d3f61b8ead22751352abe2dc57c | 7fd3eb10282dce42308c67d59bafa1d8b3fc720d | /src/PCT5/MatRot.java | 262373d69c62c136ebab672cee19a23e91ba3a5e | [] | no_license | karthikbeepi/PCT | c651780092915ba3a6cebf9e5bb118af32b91503 | 0a2060d82e80633ea427244d920f6fa659f1c9fd | refs/heads/master | 2020-04-15T00:04:36.455560 | 2019-04-09T15:38:34 | 2019-04-09T15:38:34 | 164,227,609 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,123 | java | package PCT5;
import java.util.ArrayList;
import java.util.Scanner;
public class MatRot {
int rows, cols, noOfRotations;
int mat[][];
public static void main(String args[])
{
MatRot ob = new MatRot();
ob.getInput();
}
private void getInput() {
Scanner scan = new Scanner(System.in);
String[] sp = scan.nextLine().split(" ");
rows = Integer.parseInt(sp[0]);
cols = Integer.parseInt(sp[1]);
mat = new int[rows][cols];
noOfRotations = Integer.parseInt(sp[2]);
for(int i=0; i<rows; i++)
{
sp = scan.nextLine().split(" ");
for(int j=0; j<cols; j++)
{
mat[i][j] = Integer.parseInt(sp[j]);
}
}
rotateMat(noOfRotations);
printMat();
}
private void rotateMat(int r) {
ArrayList<Integer> loop[] = new ArrayList[rows/2];
for(int i=0; i<rows/2; i++)
loop[i] = new ArrayList<Integer>();
for(int k=0; k<rows/2; k++)
{
loop[k] = getLoop(k);
for(int j=0; j<r; j++)
{
int temp = loop[k].get(0);
loop[k].remove(0);
loop[k].add(temp);
}
putLoop(loop[k], k);
// for(int var: loop[k])
// System.out.print(var+" ");
// System.out.println();
}
}
private void putLoop(ArrayList<Integer> arrayList, int k) {
for(int i=k+1; i<cols-k; i++)
{
mat[k][i]= arrayList.get(0);
arrayList.remove(0);
}
for(int i=k+1; i<rows-k; i++)
{
mat[i][cols-1-k]= arrayList.get(0);
arrayList.remove(0);
}
for(int i=cols-2-k; i>=k; i--)
{
mat[rows-1-k][i]= arrayList.get(0);
arrayList.remove(0);
}
for(int i=rows-2-k; i>=k; i--)
{
mat[i][k]= arrayList.get(0);
arrayList.remove(0);
}
}
private ArrayList<Integer> getLoop(int k) {
ArrayList<Integer> l = new ArrayList<>();
//l.add(mat[k][0]);
for(int i=k+1; i<cols-k; i++)
l.add(mat[k][i]);
for(int i=k+1; i<rows-k; i++)
l.add(mat[i][cols-1-k]);
for(int i=cols-2-k; i>=k; i--)
l.add(mat[rows-1-k][i]);
for(int i=rows-2-k; i>=k; i--)
l.add(mat[i][k]);
return l;
}
private void printMat() {
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
System.out.print(mat[i][j]+" ");
System.out.println();
}
}
}
| [
"karthikbeepi@gmail.com"
] | karthikbeepi@gmail.com |
6e17155244629804eb45b4e97d7ab8e0f93846c8 | 69f5e79c25fff5dc3414058c1780cb751ce3f2ec | /app/src/main/java/com/shudongedu/energy/manager/LoginSession.java | e5c39baa66506b65c3dd3d0b3ed07ef4fcb28b43 | [] | no_license | zhaozeyx/Energy | a9f9a83a9594a1aa26046d2e4d69e252f2578f1d | 27217f2c9635845a4b0f33d769282f495855b31b | refs/heads/master | 2021-01-22T17:52:50.229362 | 2017-05-16T07:49:14 | 2017-05-16T07:49:14 | 85,042,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,570 | java | /*
* 文件名: LogInSession
* 版 权: Copyright Hengrtech Tech. Co. Ltd. All Rights Reserved.
* 描 述: [该类的简要描述]
* 创建人: zhaozeyang
* 创建时间:16/4/27
*
* 修改人:
* 修改时间:
* 修改内容:[修改内容]
*/
package com.shudongedu.energy.manager;
import android.text.TextUtils;
import com.shudongedu.energy.CustomApp;
import com.shudongedu.energy.injection.GlobalModule;
import com.shudongedu.energy.login.LoginEvent;
import com.shudongedu.energy.net.rpc.model.UserInfo;
import com.shudongedu.energy.net.rpc.service.AuthService;
import com.shudongedu.energy.net.rpc.service.UserService;
import com.shudongedu.energy.ui.serviceinjection.DaggerServiceComponent;
import com.shudongedu.energy.ui.serviceinjection.ServiceModule;
import com.shudongedu.energy.utils.JsonConverter;
import com.shudongedu.energy.utils.preferences.CustomAppPreferences;
import javax.inject.Inject;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
/**
* Session<BR>
* 处理登录登出相关
*
* @author zhaozeyang
* @version [Taobei Client V20160411, 16/4/27]
*/
public class LoginSession {
private CustomApp mContext;
private UserInfo mUserInfo;
@Inject
AuthService mAuthService;
@Inject
UserService mUserService;
private CompositeSubscription mSubscriptions = new CompositeSubscription();
public LoginSession(CustomApp app) {
mContext = app;
DaggerServiceComponent.builder().globalModule(new GlobalModule(mContext)).serviceModule(new
ServiceModule()).build().inject(this);
switchUserInfo();
}
public int getUserId() {
return 0;
}
private void switchUserInfo() {
String userJson = mContext.getGlobalComponent().appPreferences().getString
(CustomAppPreferences.KEY_USER_INFO, "");
if (!TextUtils.isEmpty(userJson)) {
mUserInfo = JsonConverter.jsonToObject(UserInfo.class, userJson);
return;
}
mUserInfo = new UserInfo();
}
public UserInfo getUserInfo() {
return mUserInfo;
}
public void login(UserInfo userInfo) {
saveUserInfo(userInfo);
onLoginStatusChanged();
mContext.getGlobalComponent().getGlobalBus().post(new LoginEvent());
}
public Subscription loadUserInfo() {
//Subscription getUserInfoSubscription = mAuthService.getUserInfo(new GetUserInfoParams
// (mUserInfo.getUserId
// ())).subscribeOn(Schedulers.newThread())
// .observeOn(AndroidSchedulers.mainThread()).subscribe(new UiRpcSubscriber<UserInfo>
// (mContext) {
// @Override
// protected void onSuccess(UserInfo info) {
// saveUserInfo(info);
// switchUserInfo();
// mContext.getGlobalComponent().getGlobalBus().post(new UserInfoChangedEvent());
// }
//
// @Override
// protected void onEnd() {
//
// }
// });
//mSubscriptions.add(getUserInfoSubscription);
//return getUserInfoSubscription;
return null;
}
private Subscription updateUserInfo() {
//Subscription updateUserInfoSubscription = mUserService.updateUser(mUserInfo).subscribeOn
// (Schedulers
// .newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new UiRpcSubscriber<UserInfo>(mContext) {
//
// @Override
// protected void onSuccess(UserInfo userInfo) {
// saveUserInfo(userInfo);
// switchUserInfo();
// mContext.getGlobalComponent().getGlobalBus().post(new UserInfoChangedEvent());
// }
//
// @Override
// public void onApiError(RpcApiError apiError) {
// super.onApiError(apiError);
// mContext.getGlobalComponent().getGlobalBus().post(new UserInfoChangedEvent(false));
// }
//
// @Override
// protected void onEnd() {
//
// }
//
//});
//mSubscriptions.add(updateUserInfoSubscription);
//return updateUserInfoSubscription;
return null;
}
private void saveUserInfo(UserInfo userInfo) {
//mContext.getGlobalComponent().appPreferences().put(CustomAppPreferences.KEY_USER_INFO,
// JsonConverter
// .objectToJson(userInfo));
//mContext.getGlobalComponent().appPreferences().put(CustomAppPreferences.KEY_USER_ID, userInfo
// .getUserId());
//mContext.getGlobalComponent().appPreferences().put(CustomAppPreferences.KEY_USER_TYPE,
// userInfo.getType());
}
public void logout() {
//mContext.getGlobalComponent().appPreferences().remove(CustomAppPreferences.KEY_USER_INFO);
//mContext.getGlobalComponent().appPreferences().remove(CustomAppPreferences.KEY_USER_ID);
//mContext.getGlobalComponent().appPreferences().remove(CustomAppPreferences.KEY_USER_TYPE);
//mContext.getGlobalComponent().appPreferences().remove(CustomAppPreferences.KEY_COOKIE_SESSION_ID);
//mContext.getGlobalComponent().getGlobalBus().post(new LogoutEvent());
onLoginStatusChanged();
}
public void onLoginStatusChanged() {
switchUserInfo();
}
public void onDestroy() {
//mSubscriptions.unsubscribe();
}
//public UserInfoChangeBuilder userInfoChangeBuilder() {
// return new UserInfoChangeBuilder();
//}
//public class UserInfoChangeBuilder {
//
// public Subscription update() {
// return updateUserInfo();
// }
//
// public UserInfoChangeBuilder setAvart(String avart) {
// mUserInfo.setAvart(avart);
// return this;
// }
//
// public UserInfoChangeBuilder setBirthPlace(String birthPlace) {
// mUserInfo.setBirthPlace(birthPlace);
// return this;
// }
//
// public UserInfoChangeBuilder setBirthday(String birthday) {
// mUserInfo.setBirthday(birthday);
// return this;
// }
//
// public UserInfoChangeBuilder setCertified(String certified) {
// mUserInfo.setCertified(certified);
// return this;
// }
//
// public UserInfoChangeBuilder setDevId(String devId) {
// mUserInfo.setDevId(devId);
// return this;
// }
//
// public UserInfoChangeBuilder setEducation(String education) {
// mUserInfo.setEducation(education);
// return this;
// }
//
// public UserInfoChangeBuilder setGender(String gender) {
// mUserInfo.setGender(gender);
// return this;
// }
//
// public UserInfoChangeBuilder setIdCardImg(String idCardImg) {
// mUserInfo.setIdCardImg(idCardImg);
// return this;
// }
//
// public UserInfoChangeBuilder setIntroduce(String introduce) {
// mUserInfo.setIntroduce(introduce);
// return this;
// }
//
// public UserInfoChangeBuilder setInviteCode(String inviteCode) {
// mUserInfo.setInviteCode(inviteCode);
// return this;
// }
//
// public UserInfoChangeBuilder setLoginNum(int loginNum) {
// mUserInfo.setLoginNum(loginNum);
// return this;
// }
//
// public UserInfoChangeBuilder setLoginTime(Object loginTime) {
// mUserInfo.setLoginTime(loginTime);
// return this;
// }
//
// public UserInfoChangeBuilder setMobileNo(String mobileNo) {
// mUserInfo.setMobileNo(mobileNo);
// return this;
// }
//
// public UserInfoChangeBuilder setMoney(int money) {
// mUserInfo.setMoney(money);
// return this;
// }
//
// public UserInfoChangeBuilder setMsgCounts(int msgCounts) {
// mUserInfo.setMsgCounts(msgCounts);
// return this;
// }
//
// public UserInfoChangeBuilder setMyCity(String myCity) {
// mUserInfo.setMyCity(myCity);
// return this;
// }
//
// public UserInfoChangeBuilder setOccupation(String occupation) {
// mUserInfo.setOccupation(occupation);
// return this;
// }
//
// public UserInfoChangeBuilder setPassword(String password) {
// mUserInfo.setPassword(password);
// return this;
// }
//
// public UserInfoChangeBuilder setPayPwd(String payPwd) {
// mUserInfo.setPayPwd(payPwd);
// return this;
// }
//
// public UserInfoChangeBuilder setRegisterDate(Object registerDate) {
// mUserInfo.setRegisterDate(registerDate);
// return this;
// }
//
// public UserInfoChangeBuilder setResult(String result) {
// mUserInfo.setResult(result);
// return this;
// }
//
// public UserInfoChangeBuilder setSecurityLevel(String securityLevel) {
// mUserInfo.setSecurityLevel(securityLevel);
// return this;
// }
//
// public UserInfoChangeBuilder setState(String state) {
// mUserInfo.setState(state);
// return this;
// }
//
// public UserInfoChangeBuilder setThirdAccount(String thirdAccount) {
// mUserInfo.setThirdAccount(thirdAccount);
// return this;
// }
//
// public UserInfoChangeBuilder setTodayBenefit(int todayBenefit) {
// mUserInfo.setTodayBenefit(todayBenefit);
// return this;
// }
//
// public UserInfoChangeBuilder setType(String type) {
// mUserInfo.setType(type);
// return this;
// }
//
// public UserInfoChangeBuilder setUserId(int userId) {
// mUserInfo.setUserId(userId);
// return this;
// }
//
// public UserInfoChangeBuilder setUserLabel(String userLabel) {
// mUserInfo.setUserLabel(userLabel);
// return this;
// }
//
// public UserInfoChangeBuilder setUserName(String userName) {
// mUserInfo.setUserName(userName);
// return this;
// }
//
// public UserInfoChangeBuilder setVirtualMoney(int virtualMoney) {
// mUserInfo.setVirtualMoney(virtualMoney);
// return this;
// }
//}
}
| [
"yangzhaoze@gmail.com"
] | yangzhaoze@gmail.com |
a4744ae68d8467fe5af98cf63fa209016f7d48e1 | 56bf047fa003902cdcb02fab6fea2e00647892f8 | /src/main/java/com/ulyseo/model/Stats.java | 76fcf9fd853235dd3861a5a2db36d240fd6813e4 | [
"Apache-2.0"
] | permissive | UlyseoCorp/Ulyseo | 6e3854ea9b6a118df66add0fba5e9a2f3b94dcf9 | 50b6844c340e18fd826258de4cf977ae5dfa308b | refs/heads/dev | 2021-01-10T15:20:33.887539 | 2016-01-14T15:06:57 | 2016-01-14T15:06:57 | 47,476,486 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,374 | java | package com.ulyseo.model;
import java.util.Date;
import java.util.Map;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MapKeyColumn;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "stats")
public class Stats {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(unique = true)
@DateTimeFormat(pattern = "MM/yyyy")
private Date monthAndYear;
@ElementCollection
@CollectionTable(name = "listenCount")
@MapKeyColumn(name = "audioElement")
private Map<AudioElement, Integer> listenCountByAudioElements;
public Map<AudioElement, Integer> getListenCountByAudioElements() {
return listenCountByAudioElements;
}
public void setListenCountByAudioElements(Map<AudioElement, Integer> listenCountByAudioElements) {
this.listenCountByAudioElements = listenCountByAudioElements;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getMonthAndYear() {
return monthAndYear;
}
public void setMonthAndYear(Date monthAndYear) {
this.monthAndYear = monthAndYear;
}
}
| [
"steve.magras@gmail.com"
] | steve.magras@gmail.com |
223ab45c46dadf342691b3a518fd29cd282590f2 | 9c71f5994d0336603ad9ee156867a5427b9fb6a9 | /src/main/java/javastudy/jungsuk/ch_07/inter/InterfaceTest2.java | 020e7c1509aa0b9bf19834d7b4b0f007219b2041 | [] | no_license | oinochoe/jungsuk | 339daad5fa4be2f8a518ec12825a9e1ffe97f555 | 4440e0a98ba8f98e752b08ec71a143634a33123b | refs/heads/master | 2020-04-03T01:12:12.151658 | 2018-11-10T12:18:29 | 2018-11-10T12:18:29 | 154,923,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 608 | java | package javastudy.jungsuk.ch_07.inter;
/**
* InterfaceTest2
*/
class C {
void autoPlay(I i) {
i.play();
}
}
interface I {
public abstract void play();
}
class D implements I {
public void play() {
System.out.println("play in D class");
}
}
class E implements I {
public void play() {
System.out.println("play in E class");
}
}
public class InterfaceTest2 {
public static void main(String[] args) {
C c = new C();
c.autoPlay(new D()); // void autoPlay(I i) 호출
c.autoPlay(new E()); // void autoPlay(I i) 호출
}
} | [
"oinochoe@naver.com"
] | oinochoe@naver.com |
24b66f7bc3d09b428feb1c81c92d4dfa25a88b4d | cc693a2aa8e73eaff00245775110bba337301f42 | /simplewebapp/src/main/java/me/impressione/fpu/simplewebapp/FirstServlet.java | afe84b2968caa9184f79299ef8f88e235386edfc | [] | no_license | marcelosfreitas/SimpleWebProject | 0121369648d66e69659f596d1023ef57a47b4ad4 | b8f287e8285988ddf700c2305f7f204ed3717380 | refs/heads/master | 2020-12-25T03:10:40.055483 | 2015-08-17T22:52:30 | 2015-08-17T22:52:30 | 40,508,955 | 0 | 0 | null | 2015-08-10T23:33:31 | 2015-08-10T22:20:05 | HTML | UTF-8 | Java | false | false | 660 | java | package me.impressione.fpu.simplewebapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.write("Primeiro Servlet ;)");
}
}
| [
"guilherme.oliveira@sankhya.com.br"
] | guilherme.oliveira@sankhya.com.br |
bc282cdd66baa0eb8ed35d782ff656678cb25912 | 09f11b601b03a9b07c4a99d86555f70f25933bde | /src/main/java/guru/springframework/api/domain/Name.java | 5ca04248c54115367fb84faaeb265574b7116263 | [] | no_license | ditri28/spring-rest-client-examples | 263b078ab7d46202a131aaacdfde03ae47d03640 | 6f8b96d02e2e773ab7933c5d8ca466615a57f6b6 | refs/heads/master | 2022-10-19T05:46:59.405756 | 2020-06-08T13:44:39 | 2020-06-08T13:44:39 | 270,612,608 | 0 | 0 | null | 2020-06-08T09:44:17 | 2020-06-08T09:44:16 | null | UTF-8 | Java | false | false | 1,036 | java | package guru.springframework.api.domain;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class Name implements Serializable
{
private String title;
private String first;
private String last;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = 420620315591775395L;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
} | [
"diksha.tripathi@cerner.com"
] | diksha.tripathi@cerner.com |
a61992de7cb588a5ccb9f58a3c80c67318ce1710 | 58558513bbd69fe99463b4895bc5078dbe09596a | /src/us/jaba/titaniumblocks/core/frames/effects/rectangular/NoEffect.java | e52c6c1807e5633c84ad92e6b918ecedd373c6b4 | [] | no_license | tonybeckett/TitaniumBlocks | 16fdd135b46cb2e4b534a7b5ea36c3ee7e2c7139 | 32354597255b007a67fed500a707538509c5bfb5 | refs/heads/master | 2020-05-21T13:43:54.732539 | 2016-12-08T23:21:09 | 2016-12-08T23:21:09 | 48,827,953 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,998 | java | /*
* Copyright (c) 2015, Tony Beckett
* 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.
* The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package us.jaba.titaniumblocks.core.frames.effects.rectangular;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import us.jaba.titaniumblocks.core.frames.RectangularFrameEffect;
/**
*
* @author tbeckett
*/
public class NoEffect implements RectangularFrameEffect
{
@Override
public void paint(Graphics2D graphics, Dimension dimensions, Area outerFrame)
{
//do nothing
}
}
| [
"tonybeckett@yahoo.com"
] | tonybeckett@yahoo.com |
38d80b6402c207b3a304a45be02a3e4a3d19928e | 552a5d265040f6b74836a9a6618a25d4f79f925e | /Lecture-14/src/main/java/ru/otus/ArraySort.java | 728d2697c34405bbd8c0190b6b890fe2d55f74e3 | [] | no_license | AlexJPo/otus-java-2017-11-alexjpo | 69304186c0c724d1c1b3bbdd0d9e3038ca4d452b | fe6c570e1a7b3927e0382c11d4928b76115606e4 | refs/heads/master | 2021-09-29T01:17:35.069459 | 2018-11-22T07:57:39 | 2018-11-22T07:57:39 | 111,140,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,405 | java | package ru.otus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraySort {
private int[] array;
private List<Thread> threadList = new ArrayList<>();
private static final int MAX_THREADS = 4;
private static final int SHORT_ARRAY_SIZE = 8;
public void setArray(int[] array) {
this.array = array;
}
private boolean isShortArray() {
return array.length <= SHORT_ARRAY_SIZE;
}
public int[] sort() {
if (isShortArray()) {
Arrays.sort(array);
return this.array;
}
int[][] arrParts = splitArray();
for (int i = 0; i < arrParts.length; i++) {
int finalI = i;
Thread thread = new Thread(() -> Arrays.sort(arrParts[finalI]));
thread.setName("Part of array: " + i);
threadList.add(thread);
}
iniTreads();
return mergeParts(arrParts);
}
private void iniTreads() {
threadList.forEach(Thread::start);
for (Thread thread : threadList) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int[][] splitArray() {
int step = array.length / MAX_THREADS;
int[][] arrParts = new int[MAX_THREADS][];
for (int i = 0; i < MAX_THREADS; i++) {
int from = i * step;
int to = (i + 1) * step;
if (i == MAX_THREADS - 1) {
to = array.length;
}
arrParts[i] = Arrays.copyOfRange(array, from, to);
}
return arrParts;
}
private int[] mergeParts(int[][] arrParts) {
int[] result = arrParts[0];
for (int i = 0; i < arrParts.length-1; i++) {
result = merge(result, arrParts[i+1]);
}
return result;
}
public int[] merge(int[] part1, int[] part2) {
int i1 = 0;
int i2 = 0;
int[] result = new int[part1.length + part2.length];
for (int i = 0; i < result.length; i++) {
if (i2 >= part1.length || (i1 < part2.length && part2[i1] <= part1[i2])) {
result[i] = part2[i1];
i1++;
} else {
result[i] = part1[i2];
i2++;
}
}
return result;
}
}
| [
"swtorigra@gmail.com"
] | swtorigra@gmail.com |
4218b09e6a403416baf5e87532638c864adc9229 | d8168756a8cbab57531b6d19d5f92c384257f5b5 | /src/persistency/MySQLConnection.java | 991e51d53d4c985f516b0b6e140e156d2c8d56ad | [] | no_license | kutayzorlu/invoicing | baf941e50d8379ff8ecb0c9c5d72629265e7ec48 | 8a1ff5ffdd31a824e556435192bf9083375b43e2 | refs/heads/master | 2020-06-27T23:50:32.193911 | 2019-03-04T09:24:33 | 2019-03-04T09:24:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package persistency;
import utilities.Constants;
import utilities.LoadProperties;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
public class MySQLConnection extends DBConnection {
private LoadProperties props;
public MySQLConnection() {
super();
try {
props = new LoadProperties(new File(Constants.SETTINGS_PATH
+ Constants.SETTINGS_FILE));
} catch (IOException e) {
e.printStackTrace();
}
setUrl(props.getProperty(Constants.URL));
Properties info = new Properties();
info.setProperty(Constants.USER, props.getProperty(Constants.USER));
info.setProperty(Constants.PASSWORD,
props.getProperty(Constants.PASSWORD));
setInfo(info);
}
}
| [
"mpaesen@gmail.com"
] | mpaesen@gmail.com |
b6f0fc4255a81b1144cfeba5e4d95cc5b168ce50 | de3435fcda83e92232cc42e144fe1d9f14aa53ce | /src/main/java/com/frw/dangdang/DangDangMain.java | e9c695cb2a542c90f3c9aa4cb934688225e97689 | [] | no_license | frubby/study | 5a5582d7c769f71fd7a1b4bdaa321e5242f64e79 | e33bef051a17307dc7a4ca901478ea7a87c80353 | refs/heads/master | 2020-12-10T19:54:58.400356 | 2016-12-11T13:21:59 | 2016-12-11T13:21:59 | 50,180,632 | 0 | 0 | null | 2016-03-08T06:24:17 | 2016-01-22T12:42:55 | Java | UTF-8 | Java | false | false | 3,777 | java | package com.frw.dangdang;
import java.io.IOException;
import java.net.URI;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.frw.util.FileOperate;
public class DangDangMain {
ConcurrentHashMap<String,String> map=new ConcurrentHashMap<String,String> ();
public static String DD_UTL="http://promo.dangdang.com/subject.php?pm_id=3238481&tag_id=&sort=priority_asc&province_id=132&p=";
public static final int THREAD_NUM=10;
HttpClient ht;
ThreadPoolExecutor exes;
ThreadLocal<HttpClient> localClient;
public DangDangMain(){
init();
}
public void init(){
exes=(ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_NUM);
localClient=new ThreadLocal<HttpClient>(){
@Override
protected HttpClient initialValue() {
return HttpClients.createDefault();
}
};
}
public void get(int page){
HttpClient ht=localClient.get();
HttpGet get=new HttpGet();
get.setURI(URI.create(DD_UTL+page));
try {
HttpResponse rep= ht.execute(get);
String html = EntityUtils.toString(rep.getEntity());
Document doc = Jsoup.parse(html);
Element ele= doc.getElementsByClass("pro_table").get(0);
Elements links=ele.getElementsByClass("name");
StringBuilder sb=new StringBuilder();
for (Element link : links) {
Element ea= link.getElementsByTag("a").get(0);
String linkHref = ea.attr("href");
String linkText = ea.attr("title");
// System.out.print(linkHref+" ");
// System.out.println(linkText);
map.put(linkHref, linkText);
// sb.append(linkText+" \t\t\t"+linkHref+"\r\n");
}
// FileOperate fop=new FileOperate();
// fop.createFile("E:/page/"+page, sb.toString(), "UTF-8");
//System.out.println(ele.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class MyTask implements Runnable{
int page;
public MyTask(int i){
page=i;
}
public void run() {
get(page);
}
}
public void start(){
for(int i=1;i<=501;i++){
exes.submit(new MyTask(i));
}
}
public void end(){
while(exes.getActiveCount()!=0&&exes.getTaskCount()!=exes.getCompletedTaskCount()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
exes.shutdown();
try {
exes.awaitTermination(100,TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
Enumeration<String> iter=map.keys();
StringBuilder sb=new StringBuilder();
while(iter.hasMoreElements()){
String url=iter.nextElement();
String name=map.get(url);
// System.out.println(name+" "+url);
sb.append(name+"\t\t\t"+url+"\r\n");
}
FileOperate fop=new FileOperate();
fop.createFile("E:/page/all.txt", sb.toString(), "UTF-8");
}
public static void main(String args[]){
DangDangMain dd=new DangDangMain();
dd.start();
dd.end();
}
}
| [
"Administrator@shr-PC"
] | Administrator@shr-PC |
71ecf9583bdb0237676bd769272f55a8bc231862 | 25f47ddb872e8793847f793c6cd6ce86700de857 | /FOODING/Fooding/app/src/main/java/com/technology/greenenjoyshoppingstreet/newui/util/Api.java | d02a32c0bc21b87a1def6e4378e484061a444e41 | [] | no_license | didigosl/foodinn-android | caf7236dba7bc159c46d3409f79e7fe7af1b392a | 30d11f8fdfc45842fd4680bf75c25ce664b12b0c | refs/heads/master | 2020-09-11T05:15:17.242548 | 2019-11-15T15:40:14 | 2019-11-15T15:40:14 | 221,950,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 241 | java | package com.technology.greenenjoyshoppingstreet.newui.util;
import static com.technology.greenenjoyshoppingstreet.utils.constant.URLConstant.BASE_URL;
public class Api {
public static final String list = BASE_URL + "goods_spu/list";
}
| [
"alexandervr92@gmail.com"
] | alexandervr92@gmail.com |
025d921944acbdfc3ca2382f297c9d8d6f8d1301 | a61ea4334aeb96d4fcb47a0249d2e7734b80d515 | /src/main/java/br/edu/ifpb/domain/Autor.java | 5bfd3bb69c5689d84d9071b4124c06a3f3b88158 | [] | no_license | ifpb-disciplinas-2017-2/pos-rest-server | 137bf691017cde39cd8553f025a9ff9c12cc647c | c10f0cb0f240eb10f276cb8ba9b5a05aa755e40a | refs/heads/master | 2021-08-31T07:52:42.388432 | 2017-12-20T17:45:04 | 2017-12-20T17:45:04 | 114,914,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,625 | java | package br.edu.ifpb.domain;
import java.io.Serializable;
import java.util.Objects;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Ricardo Job
* @mail ricardo.job@ifpb.edu.br
* @since 20/12/2017, 13:48:15
*/
@XmlRootElement
public class Autor implements Serializable {
private String nome;
private String cpf;
private Endereco endereco;
public Autor() {
}
public Autor(String nome, String cpf) {
this.nome = nome;
this.cpf = cpf;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + Objects.hashCode(this.nome);
hash = 83 * hash + Objects.hashCode(this.cpf);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Autor other = (Autor) obj;
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.cpf, other.cpf)) {
return false;
}
return true;
}
}
| [
"sousajob@gmail.com"
] | sousajob@gmail.com |
a4e54f9cc554a40039243cb97bb5127078e6713e | 5e6474d50fc5ccc2126904a640461456974f778f | /homelink_util/src/main/java/com/smart/util/TransformationUtil.java | 81e556e22d43fab4a9894f2737f6c2538a6a8245 | [] | no_license | liuhan/homelink | 1c189adb5872b4c6dc41c8b603a0035d08a857bd | 505a852bcd333da96b4b626e6103759cb0a55953 | refs/heads/master | 2020-04-06T14:09:14.216100 | 2019-02-14T09:13:29 | 2019-02-14T09:13:29 | 157,530,005 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,280 | java | package com.smart.util;
import java.text.NumberFormat;
import java.util.HashMap;
/**
* Created by admin on 2016/1/23.
* wha -- 数字转换成中文大写
*/
public class TransformationUtil {
public static final String EMPTY = "";
public static final String ZERO = "零";
public static final String ONE = "壹";
public static final String TWO = "贰";
public static final String THREE = "叁";
public static final String FOUR = "肆";
public static final String FIVE = "伍";
public static final String SIX = "陆";
public static final String SEVEN = "柒";
public static final String EIGHT = "捌";
public static final String NINE = "玖";
public static final String TEN = "拾";
public static final String HUNDRED = "佰";
public static final String THOUSAND = "仟";
public static final String TEN_THOUSAND = "万";
public static final String HUNDRED_MILLION = "亿";
public static final String YUAN = "元";
public static final String JIAO = "角";
public static final String FEN = "分";
public static final String DOT = ".";
private static TransformationUtil formatter = null;
private HashMap chineseNumberMap = new HashMap();
private HashMap chineseMoneyPattern = new HashMap();
private NumberFormat numberFormat = NumberFormat.getInstance();
private TransformationUtil() {
numberFormat.setMaximumFractionDigits(4);
numberFormat.setMinimumFractionDigits(2);
numberFormat.setGroupingUsed(false);
chineseNumberMap.put("0", ZERO);
chineseNumberMap.put("1", ONE);
chineseNumberMap.put("2", TWO);
chineseNumberMap.put("3", THREE);
chineseNumberMap.put("4", FOUR);
chineseNumberMap.put("5", FIVE);
chineseNumberMap.put("6", SIX);
chineseNumberMap.put("7", SEVEN);
chineseNumberMap.put("8", EIGHT);
chineseNumberMap.put("9", NINE);
chineseNumberMap.put(DOT, DOT);
chineseMoneyPattern.put("1", TEN);
chineseMoneyPattern.put("2", HUNDRED);
chineseMoneyPattern.put("3", THOUSAND);
chineseMoneyPattern.put("4", TEN_THOUSAND);
chineseMoneyPattern.put("5", TEN);
chineseMoneyPattern.put("6", HUNDRED);
chineseMoneyPattern.put("7", THOUSAND);
chineseMoneyPattern.put("8", HUNDRED_MILLION);
}
public static TransformationUtil getInstance() {
if (formatter == null)
formatter = new TransformationUtil();
return formatter;
}
public String format(String moneyStr) {
checkPrecision(moneyStr);
String result;
result = convertToChineseNumber(moneyStr);
result = addUnitsToChineseMoneyString(result);
return result;
}
public String format(double moneyDouble) {
return format(numberFormat.format(moneyDouble));
}
public String format(int moneyInt) {
return format(numberFormat.format(moneyInt));
}
public String format(long moneyLong) {
return format(numberFormat.format(moneyLong));
}
public String format(Number moneyNum) {
return format(numberFormat.format(moneyNum));
}
public String convertToChineseNumber(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer();
for (int i = 0; i < moneyStr.length(); i++) {
cMoneyStringBuffer.append(chineseNumberMap.get(moneyStr.substring(i, i + 1)));
} // 拾佰仟万亿等都是汉字里面才有的单位,加上它们
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
int moneyPatternCursor = 1;
for (int i = indexOfDot - 1; i > 0; i--) {
cMoneyStringBuffer.insert(i, chineseMoneyPattern.get(EMPTY + moneyPatternCursor));
moneyPatternCursor = moneyPatternCursor == 8 ? 1 : moneyPatternCursor + 1;
}
String fractionPart = cMoneyStringBuffer.substring(cMoneyStringBuffer.indexOf("."));
cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("."), cMoneyStringBuffer.length());
while (cMoneyStringBuffer.indexOf("零拾") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零拾"),
cMoneyStringBuffer.indexOf("零拾") + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零佰") != -1) cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零佰"),
cMoneyStringBuffer.indexOf("零佰") + 2, ZERO);
while (cMoneyStringBuffer.indexOf("零仟") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零仟"), cMoneyStringBuffer.indexOf("零仟") + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零万") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零万"), cMoneyStringBuffer.indexOf("零万") + 2, TEN_THOUSAND);
}
while (cMoneyStringBuffer.indexOf("零亿") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零亿"), cMoneyStringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);
}
while (cMoneyStringBuffer.indexOf("零零") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零零"), cMoneyStringBuffer.indexOf("零零") + 2, ZERO);
}
if (cMoneyStringBuffer.lastIndexOf(ZERO) == cMoneyStringBuffer.length() - 1)
cMoneyStringBuffer.delete(cMoneyStringBuffer.length() - 1, cMoneyStringBuffer.length());
cMoneyStringBuffer.append(fractionPart);
result = cMoneyStringBuffer.toString();
return result;
}
private String addUnitsToChineseMoneyString(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer(moneyStr);
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
if(indexOfDot!=0){
cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, YUAN);
}else{
cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, "");
}
cMoneyStringBuffer.insert(cMoneyStringBuffer.length() - 1, JIAO);
cMoneyStringBuffer.insert(cMoneyStringBuffer.length(), FEN);
if (cMoneyStringBuffer.indexOf("零角零分") != -1)// 没有零头,加整
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零角零分"), cMoneyStringBuffer.length(), "整");
else if (cMoneyStringBuffer.indexOf("零分") != -1)// 没有零分,加整
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零分"), cMoneyStringBuffer.length(), "整");
else {
if (cMoneyStringBuffer.indexOf("零角") != -1)
cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("零角"), cMoneyStringBuffer.indexOf("零角") + 2);
}
result = cMoneyStringBuffer.toString();
return result;
}
private void checkPrecision(String moneyStr) {
int fractionDigits = moneyStr.length() - moneyStr.indexOf(DOT) - 1;
if (fractionDigits > 2)
throw new RuntimeException("金额" + moneyStr + "的小数位多于两位。"); //精度不能比分低
}
public static void main(String args[]) {
System.out.println(getInstance().format(new Double(0.25)));
}
}
| [
"86_liuhan@163.com"
] | 86_liuhan@163.com |
3b76b6a553b382da65ffb819d5ac4dc99d8d1ccd | 9c726e47b90906f301e5e40ef4ee7379a57fe745 | /app/src/main/java/pl/karol202/paintplus/options/OptionSave.java | b0a47e258fd436ae451a05ec8b070297af0bd248 | [
"Apache-2.0"
] | permissive | veritas44/PaintPlusPlus | e4b1abf2db28edf5ca3eeaa2c94563311661d847 | 4d0029d6d355317f45f0d359ec4bf436e0ad992f | refs/heads/master | 2021-04-27T09:46:05.099756 | 2017-12-03T22:17:57 | 2017-12-03T22:17:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,079 | java | /*
* Copyright 2017 karol-202
*
* 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 pl.karol202.paintplus.options;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import pl.karol202.paintplus.AsyncBlocker;
import pl.karol202.paintplus.AsyncManager;
import pl.karol202.paintplus.R;
import pl.karol202.paintplus.activity.ActivityPaint;
import pl.karol202.paintplus.activity.ActivityResultListener;
import pl.karol202.paintplus.file.*;
import pl.karol202.paintplus.file.BitmapSaveAsyncTask.OnBitmapSaveListener;
import pl.karol202.paintplus.file.explorer.FileExplorer;
import pl.karol202.paintplus.file.explorer.FileExplorerFactory;
import pl.karol202.paintplus.image.Image;
import pl.karol202.paintplus.recent.OnFileEditListener;
import static android.app.Activity.RESULT_OK;
abstract class OptionSave extends Option implements ActivityResultListener, AsyncBlocker, OnBitmapSaveListener
{
private ActivityPaint activity;
private OnFileEditListener listener;
private AsyncManager asyncManager;
BitmapSaveAsyncTask asyncTask;
Uri uri;
BitmapSaveFormat format;
ParcelFileDescriptor parcelFileDescriptor;
OptionSave(ActivityPaint activity, Image image, AsyncManager asyncManager, OnFileEditListener listener)
{
super(activity, image);
this.activity = activity;
this.asyncManager = asyncManager;
this.listener = listener;
}
abstract int getRequestId();
abstract Bitmap getBitmapToSave();
@Override
public void execute()
{
activity.registerActivityResultListener(getRequestId(), this);
FileExplorer explorer = FileExplorerFactory.createFileExplorer(activity);
explorer.saveFile(getRequestId());
}
public void execute(Uri uri, BitmapSaveFormat format)
{
this.uri = uri;
this.format = format;
if(format != null) saveBitmapAsynchronously();
else if(checkFileFormat() && !showSettingsDialog()) saveBitmapAsynchronously();
}
@Override
public void onActivityResult(int resultCode, Intent intent)
{
activity.unregisterActivityResultListener(getRequestId());
if(resultCode != RESULT_OK) return;
uri = intent.getData();
if(checkFileFormat() && !showSettingsDialog()) saveBitmapAsynchronously();
}
private boolean checkFileFormat()
{
UriMetadata metadata = new UriMetadata(getContext(), uri);
format = ImageLoader.getFormat(metadata.getDisplayName());
if(format == null) unsupportedFormat();
return format != null;
}
private void unsupportedFormat()
{
UriUtils.deleteDocument(getContext(), uri);
getAppContext().createSnackbar(R.string.message_unsupported_format, Toast.LENGTH_SHORT).show();
}
private boolean showSettingsDialog()
{
if(!format.providesSettingsDialog()) return false;
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(format.getSettingsDialogLayout(), null);
format.customizeSettingsDialog(view);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(format.getSettingsDialogTitle());
builder.setView(view);
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
saveBitmapAsynchronously();
}
});
builder.setNegativeButton(R.string.cancel, null);
builder.show();
return true;
}
void saveBitmapAsynchronously()
{
asyncManager.block(this);
parcelFileDescriptor = UriUtils.createFileSaveDescriptor(getContext(), uri);
BitmapSaveParams params = new BitmapSaveParams(this, getBitmapToSave(),
parcelFileDescriptor.getFileDescriptor(), format);
asyncTask = new BitmapSaveAsyncTask();
asyncTask.execute(params);
}
@Override
public void cancel()
{
asyncTask.cancel(true);
asyncManager.unblock(this);
}
@Override
public int getMessage()
{
return R.string.dialog_save_message;
}
@Override
public void onBitmapSaved(BitmapSaveResult result)
{
asyncManager.unblock(this);
UriUtils.closeFileDescriptor(parcelFileDescriptor);
switch(result.getResult())
{
case SUCCESSFUL:
if(listener != null) listener.onFileEdited(uri, result.getBitmap());
break;
case ERROR:
UriUtils.deleteDocument(getContext(), uri);
getAppContext().createSnackbar(R.string.message_cannot_save_file, Toast.LENGTH_SHORT).show();
break;
}
}
} | [
"karoljurski1@gmail.com"
] | karoljurski1@gmail.com |
96a528e8b76e0e1acb9cf03f830f542f96467e78 | 95a6b30e845f83e5d802d7f6c441e9d74555a8d6 | /it.unibo.iss.group15.model.abstracts/src/model/interfaces/operativeUnit/dashboard/IGaugeElement.java | 943094434c9e1996b708a1cc30d524d295976ce7 | [] | no_license | antoniomagnani/ISS_Gruppo15 | 3aa516313ed772a2bbd915c100123aa44349ded2 | ab0428eec305bfa20bcf50a4724e42106adfe208 | refs/heads/master | 2021-01-22T22:24:01.652389 | 2015-02-06T10:58:03 | 2015-02-06T10:58:03 | 30,405,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 214 | java | package model.interfaces.operativeUnit.dashboard;
import javax.swing.JPanel;
public interface IGaugeElement<ValueType> {
public JPanel getPanel();
public abstract void setValue(final ValueType value);
} | [
"antonio.magnani2@gmail.com"
] | antonio.magnani2@gmail.com |
7c04df611a4a704da19e8486edaeae1c0c08128a | be6ec0fc1acc094fc9764d51c3470d4e82100b9d | /Model/src/model/LogLibDB.java | cc558d58a1cba6192b3b078db267bf137ed09b5c | [] | no_license | m4gi/java_fpt | a7d6782d53ea10b8490efce45b2d481f88f01e80 | ae0b3e62dab1899bcf077918364f2638ad691458 | refs/heads/main | 2023-01-06T09:47:00.158075 | 2020-11-07T15:15:11 | 2020-11-07T15:15:11 | 310,869,228 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 936 | java |
package model;
import java.util.ArrayList;
import java.util.Vector;
public class LogLibDB {
//---------------------------------------------------------------------------------------
public static LogLib getLog(int logID){
return null;
}
//---------------------------------------------------------------------------------------
public static void updateLog(LogLib log){
}
//---------------------------------------------------------------------------------------
public static int writeLog(LogLib log){
return -1;
}
//---------------------------------------------------------------------------------------
public static Vector<Vector> viewLogByUser(String uid){
return null;
}
//---------------------------------------------------------------------------------------
public static ArrayList<LogLib> getLogsByUser(String uid){
return null;
}
}
| [
"letuan79200@gmail.com"
] | letuan79200@gmail.com |
95c243294885d0aeac614b4649225f49d7c74525 | 6c28eca2c33a275fb0008a51b8e5776a82f5904d | /Code/Hierarchy/src/net/unconventionalthinking/hierarchy/grammar/node/PDescriptorHeadSet.java | de8634bfb717b78c571c1265482718fa0a568999 | [] | no_license | UnconventionalThinking/hierarchy | 17dc9e224595f13702b9763829e12fbce2c48cfe | de8590a29c19202c01d1a6e62ca92e91aa9fc6ab | refs/heads/master | 2021-01-19T21:28:29.793371 | 2014-12-19T03:16:24 | 2014-12-19T03:16:24 | 13,262,291 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 927 | java | /* Copyright 2012, 2013 Unconventional Thinking
*
* This file is part of Hierarchy.
*
* Hierarchy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* Hierarchy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Hierarchy.
* If not, see <http://www.gnu.org/licenses/>.
*/
/* This file was generated by SableCC (http://www.sablecc.org/). */
package net.unconventionalthinking.hierarchy.grammar.node;
public abstract class PDescriptorHeadSet extends Node
{
// Empty body
}
| [
"github@unconventionalthinking.com"
] | github@unconventionalthinking.com |
a43d725966aecebd3df97acd6775f7ba7afb3ad6 | 99c7920038f551b8c16e472840c78afc3d567021 | /aliyun-java-sdk-openanalytics-open-v5/src/main/java/com/aliyuncs/v5/openanalytics_open/model/v20180619/GetAllowIPResponse.java | 4f59ffb882f102f688cf1670d754fa20a3e27f8e | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-java-sdk-v5 | 9fa211e248b16c36d29b1a04662153a61a51ec88 | 0ece7a0ba3730796e7a7ce4970a23865cd11b57c | refs/heads/master | 2023-03-13T01:32:07.260745 | 2021-10-18T08:07:02 | 2021-10-18T08:07:02 | 263,800,324 | 4 | 2 | NOASSERTION | 2022-05-20T22:01:22 | 2020-05-14T02:58:50 | Java | UTF-8 | Java | false | false | 1,657 | java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.v5.openanalytics_open.model.v20180619;
import com.aliyuncs.v5.AcsResponse;
import com.aliyuncs.v5.openanalytics_open.transform.v20180619.GetAllowIPResponseUnmarshaller;
import com.aliyuncs.v5.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class GetAllowIPResponse extends AcsResponse {
private String requestId;
private String regionId;
private String allowIP;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getRegionId() {
return this.regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getAllowIP() {
return this.allowIP;
}
public void setAllowIP(String allowIP) {
this.allowIP = allowIP;
}
@Override
public GetAllowIPResponse getInstance(UnmarshallerContext context) {
return GetAllowIPResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
654e3c2c92118b0242fb3f0afeb243a011b03bca | 238b18f835679319049d70cee616a452a864d06b | /src/test/java/com/cts/jhipster/web/rest/ProfileInfoResourceIntTest.java | 2a95454cf06a3e4359f91030cdaa58b5b36057df | [] | no_license | PrasanthMohanCognizant/JHipsterSampleApp | 66e4d190b6d037ae6101849a638af3059fda55ea | 75c9065194e01aebec99c847728f4911edf374b7 | refs/heads/master | 2021-01-24T11:35:17.253024 | 2018-02-27T07:30:35 | 2018-02-27T07:30:35 | 123,086,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,236 | java | package com.cts.jhipster.web.rest;
import io.github.jhipster.config.JHipsterProperties;
import com.cts.jhipster.JhipstersampleappApp;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the ProfileInfoResource REST controller.
*
* @see ProfileInfoResource
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JhipstersampleappApp.class)
public class ProfileInfoResourceIntTest {
@Mock
private Environment environment;
@Mock
private JHipsterProperties jHipsterProperties;
private MockMvc restProfileMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
String mockProfile[] = { "test" };
JHipsterProperties.Ribbon ribbon = new JHipsterProperties.Ribbon();
ribbon.setDisplayOnActiveProfiles(mockProfile);
when(jHipsterProperties.getRibbon()).thenReturn(ribbon);
String activeProfiles[] = {"test"};
when(environment.getDefaultProfiles()).thenReturn(activeProfiles);
when(environment.getActiveProfiles()).thenReturn(activeProfiles);
ProfileInfoResource profileInfoResource = new ProfileInfoResource(environment, jHipsterProperties);
this.restProfileMockMvc = MockMvcBuilders
.standaloneSetup(profileInfoResource)
.build();
}
@Test
public void getProfileInfoWithRibbon() throws Exception {
restProfileMockMvc.perform(get("/api/profile-info"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
public void getProfileInfoWithoutRibbon() throws Exception {
JHipsterProperties.Ribbon ribbon = new JHipsterProperties.Ribbon();
ribbon.setDisplayOnActiveProfiles(null);
when(jHipsterProperties.getRibbon()).thenReturn(ribbon);
restProfileMockMvc.perform(get("/api/profile-info"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
public void getProfileInfoWithoutActiveProfiles() throws Exception {
String emptyProfile[] = {};
when(environment.getDefaultProfiles()).thenReturn(emptyProfile);
when(environment.getActiveProfiles()).thenReturn(emptyProfile);
restProfileMockMvc.perform(get("/api/profile-info"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
}
| [
"prasanth.mohan@cognizant.com"
] | prasanth.mohan@cognizant.com |
b86d1a81d40e536d8436eea80d2d7cc5ad1b7e4e | ec55b1500817b454e67cf3842e2d29ca92e26e89 | /Beanstalk Android Client/src/com/applicake/beanstalkclient/activities/CreateNewServerEnvironmentActivity.java | 5e7f9c34a9cd382e2efb64a030f75136e30ab15c | [] | no_license | applicake/Beandroid | 69035d6dce0e00759568396749aff31e9a4c4c75 | fa943c03c5b881c451e0b5e2522c303acfd9c8a8 | refs/heads/master | 2021-01-21T12:46:46.876500 | 2012-02-29T13:06:25 | 2012-02-29T13:06:25 | 1,737,348 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,845 | java | package com.applicake.beanstalkclient.activities;
import java.io.IOException;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import com.applicake.beanstalkclient.Constants;
import com.applicake.beanstalkclient.R;
import com.applicake.beanstalkclient.ServerEnvironment;
import com.applicake.beanstalkclient.Strings;
import com.applicake.beanstalkclient.utils.GUI;
import com.applicake.beanstalkclient.utils.HttpSender;
import com.applicake.beanstalkclient.utils.HttpSender.HttpSenderException;
import com.applicake.beanstalkclient.utils.HttpSender.HttpSenderServerErrorException;
import com.applicake.beanstalkclient.utils.SimpleRetryDialogBuilder;
import com.applicake.beanstalkclient.utils.XmlCreator;
import com.applicake.beanstalkclient.utils.XmlParser.XMLParserException;
public class CreateNewServerEnvironmentActivity extends BeanstalkActivity {
private EditText nameEditText;
private CheckBox automaticCheckBox;
private EditText branchName;
private int repoId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_server_environment_layout);
repoId = getIntent().getIntExtra(Constants.REPOSITORY_ID, 0);
nameEditText = (EditText) findViewById(R.id.nameEditText);
automaticCheckBox = (CheckBox) findViewById(R.id.is_automatic_checkbox);
branchName = (EditText) findViewById(R.id.branch_name_edittext);
findViewById(R.id.createButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new SendNewServerEnvironment(CreateNewServerEnvironmentActivity.this).execute();
}
});
}
class SendNewServerEnvironment extends AsyncTask<Void, Void, Integer> {
ProgressDialog progressDialog;
String errorMessage;
private AsyncTask<Void, Void, Integer> thisTask;
private Context mContext;
private String failMessage;
private boolean failed;
public SendNewServerEnvironment(Context context) {
mContext = context;
thisTask = this;
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(mContext, "Please wait...",
"creating repository");
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
thisTask.cancel(true);
GUI.displayMonit(mContext, "Repository creating task was cancelled");
}
});
}
protected Integer doInBackground(Void... params) {
XmlCreator xmlCreator = new XmlCreator();
try {
ServerEnvironment serverEnvironment = new ServerEnvironment();
serverEnvironment.setName(nameEditText.getText().toString());
serverEnvironment.setAutomatic(automaticCheckBox.isChecked());
serverEnvironment.setBranchName(branchName.getText().toString());
String newServerEnvironmentXml = xmlCreator
.createNewServerEnvironmentXML(serverEnvironment);
return HttpSender.sendCreateNewServerEnvironmentXML(prefs,
newServerEnvironmentXml, repoId);
} catch (XMLParserException e) {
failMessage = Strings.internalErrorMessage;
} catch (IllegalArgumentException e) {
failMessage = Strings.internalErrorMessage;
} catch (IllegalStateException e) {
failMessage = Strings.internalErrorMessage;
} catch (IOException e) {
failMessage = Strings.internalErrorMessage;
} catch (HttpSenderException e) {
failMessage = Strings.networkConnectionErrorMessage;
} catch (HttpSenderServerErrorException e) {
errorMessage = e.getMessage();
return 0;
}
failed = true;
return 0;
}
@Override
protected void onPostExecute(Integer result) {
progressDialog.dismiss();
if (failed) {
SimpleRetryDialogBuilder builder = new SimpleRetryDialogBuilder(mContext,
failMessage) {
@Override
public void retryAction() {
new SendNewServerEnvironment(mContext).execute();
}
};
builder.displayDialog();
} else {
if (result == 201) {
GUI.displayMonit(mContext, "Reposiotry was created successfully!");
setResult(Constants.REFRESH_ACTIVITY);
finish();
}
if ((result == 0) && (errorMessage != null))
GUI.displayMonit(mContext, errorMessage);
}
}
}
}
| [
"bartek.f@applicake.com"
] | bartek.f@applicake.com |
f6e388d87f66efd4c1382e186ef668002ffad363 | 013b3febb1233983da0f9424037683cd011990bb | /Opdrachten AP/src/Opd8/Main.java | 98b3acb3f661da9534458789c9338396e0a8f552 | [] | no_license | vlreinier/AP | c7df54b6937b8d4b406a14a3c7d63f033a4bc83f | faab2eaed9ed10f541a922f3590e610a49b67305 | refs/heads/master | 2022-02-01T16:24:02.484699 | 2019-07-03T18:23:22 | 2019-07-03T18:23:22 | 195,106,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 640 | java | package Opd8;
public class Main {
public static void main(String[] arg) {
int n = 5;
int i,j;
for (i = 0; i < n; i++) {
for(j= n-i ; j > 0; j--) {
System.out.print(" ");
}
for(j=0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
for (i = 0; i < n; i++) {
for(j=0; j < i; j++) {
System.out.print(" ");
}
for(j= n-i ; j > 0; j--) {
System.out.print("*");
}
System.out.println();
}
}
}
| [
"43336873+vlreinier@users.noreply.github.com"
] | 43336873+vlreinier@users.noreply.github.com |
a4391a28ecde7ae60b639f899e3e60cb2efc5e72 | 0db7256b1eefab91209f0168bd4224d6df10ab54 | /src/bookapp/books/impl/entities/BookEntity.java | 5b8205aad3d6cddd2991105107e7a68c4ce16718 | [] | no_license | lojzatran/bookapp-migration | a02a7546d0032e12db39ae8c13f3b64cf57570b7 | d7fe68a99727509e2f5eaff0a18dc93859c71bb9 | refs/heads/master | 2021-08-29T12:05:27.912513 | 2017-12-13T22:51:17 | 2017-12-13T22:51:17 | 114,177,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 639 | java | package books.impl.entities;
import books.api.entities.Book;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class BookEntity implements Book {
@Id
@GeneratedValue
private int id;
private String title;
private double price;
public BookEntity() {
}
public BookEntity(String title, double price) {
this.title = title;
this.price = price;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
}
| [
"lojza.tran@tradesports.com"
] | lojza.tran@tradesports.com |
222a5e25369b4dd3d41ac5d3adf0c00ffb298fe1 | 79628762d6d1070804cd53cc5429c23e5f432c6f | /backend/src/main/java/com/devsuperior/dsdeliver/services/OrderService.java | 0b2ba83c0bffbb61e2f8c13ac498c11f047984c7 | [] | no_license | leandroabreu02/dsdeliver-sds2 | 76c62aa5ed3e16596275a067b3be8cf9189ac586 | 7efec157500729ebba7c6dab0bfd0d517b550a12 | refs/heads/main | 2023-03-31T19:33:28.393722 | 2021-01-09T11:36:28 | 2021-01-09T11:36:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,650 | java | package com.devsuperior.dsdeliver.services;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.devsuperior.dsdeliver.dto.OrderDTO;
import com.devsuperior.dsdeliver.dto.ProductDTO;
import com.devsuperior.dsdeliver.entities.Order;
import com.devsuperior.dsdeliver.entities.OrderStatus;
import com.devsuperior.dsdeliver.entities.Product;
import com.devsuperior.dsdeliver.repositories.OrderRepository;
import com.devsuperior.dsdeliver.repositories.ProductRepository;
@Service
public class OrderService {
@Autowired
private OrderRepository repository;
@Autowired
private ProductRepository productRepository;
@Transactional(readOnly = true)
public List<OrderDTO> findAll() {
List<Order> list = repository.findOrdersWithProducts();
return list.stream().map(x -> new OrderDTO(x)).collect(Collectors.toList());
}
@Transactional
public OrderDTO insert(OrderDTO dto) {
Order order = new Order(null, dto.getAddress(), dto.getLatitude(), dto.getLongitude(),
Instant.now(), OrderStatus.PENDING);
for(ProductDTO p : dto.getProducts()) {
Product product = productRepository.getOne(p.getId());
order.getProducts().add(product);
}
order = repository.save(order);
return new OrderDTO(order);
}
@Transactional
public OrderDTO setDelivered(Long id) {
Order order = repository.getOne(id);
order.setStatus(OrderStatus.DELIVERED);
order = repository.save(order);
return new OrderDTO(order);
}
}
| [
"djleandro.cardoso@gmail.com"
] | djleandro.cardoso@gmail.com |
cca96bf56a5ffb50cfef9d46b0f85a26f67320e5 | e56384c8334d4ad2efb0475684e5f58e1eb30efc | /SegmentTreeQuery.java | 720229262a89dd40c244eedac6b33cb159098f85 | [] | no_license | fang19911030/LeetCode2 | 0cd2d41c0342092235cb69bbb1f72c5db2fb1664 | 2d3cea26159331a996a378fca6d80fa548de376d | refs/heads/master | 2021-01-01T18:03:48.189490 | 2018-06-15T04:54:15 | 2018-06-15T04:54:15 | 98,231,242 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,156 | java | /**
* Definition of SegmentTreeNode:
* public class SegmentTreeNode {
* public int start, end, max;
* public SegmentTreeNode left, right;
* public SegmentTreeNode(int start, int end, int max) {
* this.start = start;
* this.end = end;
* this.max = max
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of segment tree.
* @param start: start value.
* @param end: end value.
* @return: The maximum number in the interval [start, end]
*/
public int query(SegmentTreeNode root, int start, int end) {
// write your code here
if(root.start == start && root.end == end){
return root.max;
}
int mid = (root.start+root.end)/2;
if(end<=mid){
return query(root.left,start,end);
}else if(start>mid){
return query(root.right,start,end);
}else{
int leftMax = query(root.left,start,mid);
int rightMax = query(root.right,mid+1,end);
return Math.max(leftMax,rightMax);
}
}
}; | [
"fang291831388@gmail.com"
] | fang291831388@gmail.com |
6207ba4cd8f9a26dca30016a8a6c7f1cb6a1fc05 | 0a5d546ae5825e9da4ecda0b0144bd4002d51e11 | /pegasusec2/pegasus/planner/parser/dax/DAX2Metadata.java | bab0a42fa0320f60fc0bca1fcb89d6476d5160cb | [] | no_license | amelieczhou/deco-declarative-workflow-optimization | dd6704486de5d4ed25f4c945800fa17493fe788e | 323549722f6f8d4cd812e55ecb168fbe856ea485 | refs/heads/master | 2016-09-06T10:34:27.813533 | 2014-08-07T13:33:14 | 2014-08-07T13:33:14 | 32,119,530 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,963 | java | /**
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.planner.parser.dax;
import edu.isi.pegasus.planner.catalog.transformation.TransformationCatalogEntry;
import edu.isi.pegasus.planner.classes.CompoundTransformation;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.ReplicaLocation;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.dax.Invoke;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A callback that causes the parser to exit after the metadata about the DAX
* has been parsed. This is achieved by stopping the parsing after the
* cbDocument method.
*
* @author Karan Vahi
* @version $Revision: 314 $
*/
public class DAX2Metadata implements Callback {
/**
* The parsing completed message.
*/
public static final String PARSING_DONE_ERROR_MESSAGE = "Parsing done";
/**
* Default attribute value for the count attribute
*/
public static final String DEFAULT_ADAG_COUNT_ATTRIBUTE = "1";
/**
* Default index value for the count attribute
*/
public static final String DEFAULT_ADAG_INDEX_ATTRIBUTE = "0";
/**
* The handle to the properties object.
*/
private PegasusProperties mProps;
/**
* A flag to specify whether the graph has been generated for the partition
* or not.
*/
private boolean mDone;
/**
* The metadata of the workflow.
*/
private Map mMetadata;
/**
* The overloaded constructor.
*
* @param properties the properties passed to the planner.
* @param dax the path to the DAX file.
*/
public DAX2Metadata( PegasusProperties properties, String dax ) {
mProps = properties;
mDone = false;
}
/**
* Callback when the opening tag was parsed. This contains all
* attributes and their raw values within a map. It ends up storing
* the attributes with the adag element in the internal memory structure.
*
* @param attributes is a map of attribute key to attribute value
*/
public void cbDocument(Map attributes) {
mMetadata = new HashMap();
mMetadata.put( "count", attributes.containsKey( "count" ) ?
(String)attributes.get( "count" ) :
DEFAULT_ADAG_COUNT_ATTRIBUTE ) ;
mMetadata.put( "index", attributes.containsKey( "index" ) ?
(String)attributes.get( "index" ) :
DEFAULT_ADAG_INDEX_ATTRIBUTE ) ;
mMetadata.put( "name", (String)attributes.get( "name" ) );
mMetadata.put( "version", (String)attributes.get( "version" ) );
//call the cbDone()
cbDone();
}
/**
* Callback when a invoke entry is encountered in the top level inside the adag element in the DAX.
*
* @param invoke the invoke object
*/
public void cbWfInvoke(Invoke invoke){
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback for the job from section 2 jobs. These jobs are completely
* assembled, but each is passed separately.
*
* @param job the <code>Job</code> object storing the job information
* gotten from parser.
*/
public void cbJob( Job job ) {
}
/**
* Callback for child and parent relationships from section 3.
*
* @param child is the IDREF of the child element.
* @param parents is a list of IDREFs of the included parents.
*/
public void cbParents(String child, List parents) {
}
/**
* Callback when the parsing of the document is done. It sets the flag
* that the parsing has been done, that is used to determine whether the
* ADag object has been fully generated or not.
*/
public void cbDone() {
mDone = true;
throw new RuntimeException( PARSING_DONE_ERROR_MESSAGE );
}
/**
* Returns an ADag object corresponding to the abstract plan it has generated.
* It throws a runtime exception if the method is called before the object
* has been created fully.
*
* @return ADag object containing the abstract plan referred in the dax.
*/
public Object getConstructedObject(){
if(!mDone)
throw new RuntimeException( "Method called before the metadata was parsed" );
return mMetadata;
}
/**
* Callback when a compound transformation is encountered in the DAX
*
* @param compoundTransformation the compound transforamtion
*/
public void cbCompoundTransformation( CompoundTransformation compoundTransformation ){
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback when a replica catalog entry is encountered in the DAX
*
* @param rl the ReplicaLocation object
*/
public void cbFile( ReplicaLocation rl ){
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Callback when a transformation catalog entry is encountered in the DAX
*
* @param tce the transformationc catalog entry object.
*/
public void cbExecutable( TransformationCatalogEntry tce ){
throw new UnsupportedOperationException("Not supported yet.");
}
}
| [
"amelie.czhou@gmail.com@cfe2f41d-cc59-d38a-9a6a-4683ffef75d1"
] | amelie.czhou@gmail.com@cfe2f41d-cc59-d38a-9a6a-4683ffef75d1 |
6f671f32a08b283ae90c4b54cf7c67595a031730 | 6290b8c353da8061aa9a3d798bdd0e96fdfdbd6b | /app/src/main/java/edu/cpp/awh/easyabc/AddStudentActivity.java | 050287edf32a3d2ab25a7fcd0a91fb9852d5dfe0 | [] | no_license | Sarcross/EasyABC | 373b4c9c5522ca2e6d26f9b90eee2f9ac4dbeeff | e4db576a620c57e59876b4b1b75978ae6c3d2286 | refs/heads/master | 2021-01-19T11:43:53.641015 | 2017-05-30T19:35:24 | 2017-05-30T19:35:37 | 87,991,382 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 967 | java | package edu.cpp.awh.easyabc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import edu.cpp.awh.easyabc.util.Logging;
public class AddStudentActivity extends AppCompatActivity implements UI{
private Button addStudentButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_student);
Log.d(Logging.TAG_ADD_STUDENT_ACTIVITY, Logging.DEBUG_LAUNCH_ACTIVITY);
setUpUI();
}
@Override
public void setUpUI() {
addStudentButton = (Button) findViewById(R.id.addStudentActivity_add_button);
addStudentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddStudentActivity.this.finish();
}
});
}
}
| [
"antzyee@yahoo.com"
] | antzyee@yahoo.com |
07223aae065fcce8e21fc3160f98058a6dda2936 | 621733f26cae2b2c18f155fb719018cfb122cc27 | /spectrumsdk/src/main/java/com/spectrochips/spectrumsdk/FRAMEWORK/SampleGattAttributes.java | 91c83cae84a610d5aa8ca299081aace973254d78 | [] | no_license | Vedas-Labs/GtsrSdk | 163c6cf8502f5918e29e414c92ed14357b6ef080 | 1c343df538b9511d5ac6f3ab527e4cb37d4a4c5a | refs/heads/master | 2023-03-25T13:05:29.917596 | 2021-03-19T04:14:19 | 2021-03-19T04:14:19 | 349,297,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 988 | java | package com.spectrochips.spectrumsdk.FRAMEWORK;
import java.util.HashMap;
public class SampleGattAttributes {
private static HashMap<String, String> attributes = new HashMap();
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static String HM_10_CONF = "0000ffe0-0000-1000-8000-00805f9b34fb";
public static String HM_RX_TX = "0000ffe1-0000-1000-8000-00805f9b34fb";
static {
attributes.put("0000ffe0-0000-1000-8000-00805f9b34fb", "HM 10 Serial");
attributes.put("00001800-0000-1000-8000-00805f9b34fb", "Device Information Service");
attributes.put(HM_RX_TX, "RX/TX data");
attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
}
public SampleGattAttributes() {
}
public static String lookup(String uuid, String defaultName) {
String name = (String)attributes.get(uuid);
return name == null ? defaultName : name;
}
}
| [
"50829215+chandrikaReddyBunga@users.noreply.github.com"
] | 50829215+chandrikaReddyBunga@users.noreply.github.com |
52f9804e2f5e23b6736549b5de60dc789e347867 | 59bb402f4aeea8793cb655e73b2dc4554486558d | /src/com/company/Main.java | f7e03236d8979d81ba6c462dab5606976e99da65 | [] | no_license | zerrox200429/H.W_2.6 | eb9e6d17918b281192e0a1eb6ce9771e5f19ff2c | 8da0356e9c7a3300e906d1a9892c954c2c63f1d3 | refs/heads/master | 2020-07-05T19:01:49.801732 | 2019-08-16T14:15:37 | 2019-08-16T14:15:37 | 202,739,857 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,445 | java | package com.company;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList <Car> cars = new ArrayList<>(10);
cars.add(new Car("Acura", 2018, 4.0));
cars.add(new Car("Bugatti", 2010, 5.8));
cars.add(new Car("Buick", 2011, 4.4));
cars.add(new Car("Cadilac", 2006, 5.5));
cars.add(new Car("Audi", 1991, 2.3));
cars.add(new Car("Cherry", 2008, 3.0));
cars.add(new Car("Porshe", 2002, 5.3));
cars.add(new Car("Bentley", 2013, 4.5));
cars.add(new Car("BMW", 1993, 2.5));
cars.add(new Car("Ford", 2019, 5.3));
System.out.println("До сортировки");
for (Car car : cars) {
System.out.println(" Модель машины- (" + car.getModel() + ")" +
" Год выпуска машины -(" + car.getYear() + ")" +
" Обьем двигателя :" + car.getVolume() + ")");
}
Collections.sort(cars);
System.out.println("После сортировки");
for (Car car : cars) {
System.out.println(" Модель машины- (" + car.getModel() + ")" +
" Год выпуска машины -(" + car.getYear() + ")" +
" Обьем двигателя :" + car.getVolume() + ")");
}
}
}
| [
"mr.jumobekov@mail.ru"
] | mr.jumobekov@mail.ru |
a7e2d6b2e91a5bcab09ae686874d62924e005cab | 1b39effcea22bdf36cce27ec52b5253d6f2aa60b | /app/src/main/java/in/college/safety247/MainActivity.java | ab1a07ac84fe4d374edc5c8debcb848c931c4340 | [] | no_license | charmygarg/Safety-24-7 | 7a05c5afdd454c3baf116400ac5248ebfab975d3 | 1724d2117a31bcf64da625e2e6b1931de5f9b880 | refs/heads/master | 2021-01-13T08:16:21.498278 | 2016-12-04T14:01:24 | 2016-12-04T14:01:24 | 71,805,664 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,672 | java | package in.college.safety247;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.andexert.library.RippleView;
public class MainActivity extends AppCompatActivity{
LoginDataBaseAdapter loginDataBaseAdapter;
EditText userEdit, passEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
}
public void buttonClicked(View v)
{
if(v.getId() == R.id.loginButton)
{
final RippleView rippleView = (RippleView) findViewById(R.id.rippleView);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
@Override
public void onComplete(RippleView rippleView) {
userEdit = (EditText) findViewById(R.id.user_editText);
String user = userEdit.getText().toString();
passEdit = (EditText) findViewById(R.id.pass_editText);
String pass = passEdit.getText().toString();
String storedPassword=loginDataBaseAdapter.getSingleEntry(user);
if(pass.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Successfully Login", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,Showpager.class);
startActivity(intent);
}
else
{
Toast.makeText(MainActivity.this, "Incorrect Username or Password", Toast.LENGTH_SHORT).show();
}
}
});
}
if(v.getId() == R.id.signupTextView)
{
final RippleView rippleView = (RippleView) findViewById(R.id.ripple);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
@Override
public void onComplete(RippleView rippleView) {
Intent intent = new Intent(MainActivity.this, SignUp.class);
startActivityForResult(intent, 1);
}
});
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
| [
"charmiigarg@gmail.com"
] | charmiigarg@gmail.com |
6b917ce11b05c6f1ec72cad14198f086553b7064 | 20b406fda2f2be9ab81aac7f58b77d3e9cbee701 | /src/main/java/lu/tessyglodt/site/spring/ConfigWebSecurity.java | f31a1ec05404eccc45b33437b949727360c46ebc | [] | no_license | yglodt/tessyglodt.lu | 770f99b9fcd0731c1318efb72e8d14eb991c02eb | 3398eaec12f5db1e077dbb712d5e98f5c42285df | refs/heads/master | 2023-06-09T18:01:04.592814 | 2023-05-31T20:47:41 | 2023-05-31T20:47:41 | 33,419,590 | 3 | 1 | null | 2022-09-01T22:20:02 | 2015-04-04T20:38:55 | HTML | UTF-8 | Java | false | false | 2,525 | java | package lu.tessyglodt.site.spring;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
@Configuration
@EnableWebSecurity
public class ConfigWebSecurity extends WebSecurityConfigurerAdapter {
@Override
public void configure(final WebSecurity web) {
web.ignoring().antMatchers("/b/**", "/ckeditor/**", "/css/**", "/fonts/**", "/img/**", "/js/**");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// http.authorizeRequests().and().requiresChannel().antMatchers("/login",
// "/authcheck", "/admin/**").requiresSecure();
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").permitAll();
http
.formLogin()
.defaultSuccessUrl("/", true)
.failureUrl("/login?error")
.loginPage("/login")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication auth) throws IOException, ServletException {
if (request.getServerName().contains("tessyglodt.lu")) {
response.sendRedirect("https://www.tessyglodt.lu/");
} else {
response.sendRedirect("/");
}
}
})
.loginProcessingUrl("/authcheck").usernameParameter("username").passwordParameter("password")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.permitAll();
http
.authorizeRequests().anyRequest().authenticated();
http.csrf();
}
}
| [
"yves.glodt@ypzeelon.com"
] | yves.glodt@ypzeelon.com |
f4a9406102f04f101223b47972fbc9cbbeec7a25 | f1b8dc2abd2f6806b40c8b75e7db0d306f328ef3 | /B.java | 1735f0a7b3ccb5908de9f83381f174a269f89822 | [] | no_license | YiyangZhu/Dynamic_Programming_Java_Practice | 7f34b4a0046e1530bdc8d65f2ea332560d12d00b | eb5c4433419e8d61d93ec9db6304b0a9f317d126 | refs/heads/master | 2021-09-06T13:04:56.705327 | 2018-02-06T21:15:34 | 2018-02-06T21:15:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 82 | java | class B extends A{
B(){
System.out.println("Constructing B.");
}
} | [
"ererandkeke@gmail.com"
] | ererandkeke@gmail.com |
23cbcc7748764336447c0f668c33af29441ca8be | c909bbaa1a9edc30fce29385478839bd880b3f33 | /src/main/java/upce/nnpda/semb/Entity/User.java | b6ec46cc03649e5a2a32395f6457831f5438bb84 | [] | no_license | st52542/nnpdaSemB | 7aebb29121ce4f46c9cb9abee59e9a926fabafe3 | b17040ee8f1c54736cd8b45c7027f5e56d151075 | refs/heads/master | 2023-08-30T04:40:51.856433 | 2021-10-25T19:23:22 | 2021-10-25T19:23:22 | 413,577,880 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,165 | java | package upce.nnpda.semb.Entity;
import javax.persistence.*;
import java.util.Set;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 45, nullable = false)
private String username;
@Column(length = 100, nullable = false, unique = true)
private String email;
@Column(length = 100, nullable = false)
private String password;
@Column(length = 45, nullable = false)
private String name;
@Column(length = 45, nullable = false)
private String surname;
@Column(length = 200)
private String uuid;
@OneToMany(mappedBy = "id")
private Set<ListOfDevices> listOfDevices;
public User(String firstname, String lastname, String username, String email, String encode) {
this.name = firstname;
this.surname = lastname;
this.email = email;
this.password = encode;
this.username = username;
}
public User() {
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Set<ListOfDevices> getListOfDevices() {
return listOfDevices;
}
public void setListOfDevices(Set<ListOfDevices> listOfDevices) {
this.listOfDevices = listOfDevices;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
| [
"43936282+st52542@users.noreply.github.com"
] | 43936282+st52542@users.noreply.github.com |
6bd7cecd48fde59d7e4b2b3dfc7940f4d2612940 | 13b88f9c0084b44edc448431ded83326ba173408 | /src/serv/Initializer.java | 2d8024c861b982060fe5372c2399fdf96dff3f11 | [] | no_license | srisai-n/multi-threaded-web-server | 2daa95ac59454537bd81c4db89327589ecfbbcc2 | 9d4901ce21d85ad1aa0a10326c6c5590128ee849 | refs/heads/main | 2023-02-22T14:07:49.315655 | 2021-01-21T08:16:22 | 2021-01-21T08:16:22 | 331,560,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 428 | java | package serv;
public class Initializer {
public static void main(String[] args) {
int port = 8080;
if(args.length == 1) {
try {
port = Integer.parseInt(args[0]);
}
catch (NumberFormatException nfe) {
System.err.println("SERVER >> Integer Port is not provided. Server will start at default port.");
}
}
System.out.println("SERVER >> Using Port "+port);
new Thread(new Server(port)).start();
}
}
| [
"66721043+srisaikarthikn@users.noreply.github.com"
] | 66721043+srisaikarthikn@users.noreply.github.com |
cd20c76575390776a24cc3a2d63a608ab44a095e | a0b308e11a9eead83c93ef84f6bf5956c57f7cc0 | /src/main/java/org/unitec/AplicacionServicios.java | 38d758d01ac39c6c760817c255f8832fee318b66 | [
"MIT"
] | permissive | KarenEsteban/Proyecto-Elementos-EstebanGavira | 36983957ed9165f5f35a0b5b2523174424028248 | e302b351e934f31fe2b2c24c7e55de27ea99867c | refs/heads/master | 2020-06-27T07:02:15.150989 | 2016-11-23T03:42:34 | 2016-11-23T03:42:34 | 74,533,271 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 461 | 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 org.unitec;
import org.springframework.context.annotation.Configuration;
/**
*
* @author T-107
*/
@Configuration
public class AplicacionServicios {
public TipoBebida obtenerBebida(){
return new BebidasNoAlcoholicas();
}
}
| [
"T-107@PC250"
] | T-107@PC250 |
3379604fb87e48ecf9651dd53edf748149ea932e | 5cddc374cd2f62d22574c89a58df3897e5c4476c | /src/main/java/com/gft/pets/PetsApplication.java | d4fc488fa92b714e7da4dc565296253cb3ea037c | [] | no_license | haroldoalcobacas/crud_pets | 751d1ae5176b552abe789c7fcb1146e0f5a2c72a | b699376045acd53d1835ed61a0175e8aaa4f06ba | refs/heads/master | 2023-08-11T14:52:27.113822 | 2021-10-05T14:25:08 | 2021-10-05T14:25:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 301 | java | package com.gft.pets;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PetsApplication {
public static void main(String[] args) {
SpringApplication.run(PetsApplication.class, args);
}
}
| [
"pamela.dpaulas@gmail.com"
] | pamela.dpaulas@gmail.com |
845b300151dec49d8ec0896968202e275fe37678 | c341992d77439d1aff4dd33055ee1862a8f8a2aa | /zuul/src/main/java/com/ambity/zuul/filter/MyFilter.java | c65aaa7d54685ce114258f2940bb424965ad4bd0 | [] | no_license | yuanfeilv/base | 6a4d53eb1aedcc708e0c8f2127880ff3c74dd09d | 3eb1ada04f35a6427077df8b654b535f9425f76a | refs/heads/main | 2023-03-07T20:35:13.268799 | 2021-02-16T13:42:32 | 2021-02-16T13:42:32 | 339,400,721 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 911 | java | package com.ambity.zuul.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class MyFilter extends ZuulFilter {
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext rc = RequestContext.getCurrentContext();
HttpServletRequest request = rc.getRequest();
log.info("filter.....method={},url={}",
request.getMethod(),request.getRequestURL().toString());
return null;
}
}
| [
"yuanfei.lv"
] | yuanfei.lv |
465cd59ebee9418a006039b1ba84f6aaa912c02b | b28f8d61b7604600ff255bca4af99d4957e26cd4 | /Aula01/src/CorrecaoExercicios/Exericio9.java | 450066101e26fd1cdb783ff8a9b626c5d4d3a94b | [] | no_license | sarahneuburger/java_apex | eebb284074522310d53acbc0405fdd0efb606221 | fb97c6a06bbef231e14e6076f029e24f9440fe31 | refs/heads/main | 2023-03-12T14:15:50.865876 | 2021-02-13T20:24:12 | 2021-02-13T20:24:12 | 332,909,454 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 738 | java | package CorrecaoExercicios;
import javax.swing.JOptionPane;
public class Exericio9 {
public static void main(String[] args) {
// Identificar palíndromo
String fraseOriginal = JOptionPane.showInputDialog("Informe uma palavra para verificação:");
fraseOriginal = fraseOriginal.replaceAll(" ", "");
String[] palindromo = fraseOriginal.split("");
String contrario = "";
for (int j = (palindromo.length - 1); j >= 0; j--) {
contrario = contrario + palindromo[j];
}
if(contrario.equalsIgnoreCase(fraseOriginal)) {
JOptionPane.showMessageDialog(null, "A palavra é um palíndromo.");
} else {JOptionPane.showMessageDialog(null, "A palavra não é um palíndromo.");}
}
}
| [
"sarahneuburger94@gmail.com"
] | sarahneuburger94@gmail.com |
d424efa24b053913b6a05b879c160f7c2098c10b | e7db683262ad1ed6bc420076db5f5d446678229a | /ProjetoFinalOnGradle/temp_dump/repository/TipoInfracoes.java | 9138e4a92e83e4152200327ef11c5a42a8660a61 | [] | no_license | otavio99/frames | 9e738edc048df88a159144862a2a71a9db428b9e | 85e27a40e9bf1f51ada15df2f5e481156e015732 | refs/heads/master | 2020-09-16T18:56:12.368298 | 2019-12-16T09:34:27 | 2019-12-16T09:34:27 | 223,859,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 245 | java | package br.edu.ifms.dbf2.ProjetoN1.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import br.edu.ifms.dbf2.ProjetoN1.model.TipoInfracao;
public interface TipoInfracoes extends JpaRepository<TipoInfracao, Long> {
}
| [
"otavio.nathanael@gmail.com"
] | otavio.nathanael@gmail.com |
6b1276805ca61cb78e389a6768cbcf775f910f10 | 1b37978e11cbc6df07656cef142d676700b50da3 | /src/main/java/com/kursova/travel/service/CompetitionService.java | cff93043ce18f6e37dc5fd74bbb9cd84e147e0ee | [] | no_license | YourGregory/travel_agency_back | 2e0107945d5a2999c7502aba0f69c441d75263bb | e496be7a7eb6430ccac6785b0d2e25263ad46611 | refs/heads/master | 2022-02-03T18:41:54.354109 | 2019-06-01T17:43:47 | 2019-06-01T17:43:47 | 180,625,069 | 0 | 0 | null | 2022-01-21T23:24:23 | 2019-04-10T16:51:49 | Java | UTF-8 | Java | false | false | 687 | java | package com.kursova.travel.service;
import com.kursova.travel.entity.model.Competition;
import com.kursova.travel.repository.CompetitionRepository;
import com.kursova.travel.service.base.DefaultCrudSupport;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Service;
@Service
@FieldDefaults(level = AccessLevel.PRIVATE)
public class CompetitionService extends DefaultCrudSupport<Competition> {
CompetitionRepository competitionRepository;
public CompetitionService(CompetitionRepository competitionRepository) {
super(competitionRepository);
this.competitionRepository = competitionRepository;
}
}
| [
"vadim.symotiuk@inventorsoft.co"
] | vadim.symotiuk@inventorsoft.co |
550293b601233eb57f9ea02bd76640b385eed5b1 | b067d5061e4ae5e3e7f010175694bf2802706485 | /American/ravv-service/src/main/java/cn/farwalker/ravv/service/goods/image/model/GoodsImageVo.java | 853d8c9c5145141820113517c181b26aa3ee9b6f | [] | no_license | lizhenghong20/web | 7cf5a610ec19a0b8f7ba662131e56171fffabf9b | 8941e68a2cf426b831e8219aeea8555568f95256 | refs/heads/master | 2022-11-05T18:02:47.842268 | 2019-06-10T02:22:32 | 2019-06-10T02:22:32 | 190,309,917 | 0 | 0 | null | 2022-10-12T20:27:42 | 2019-06-05T02:09:30 | Java | UTF-8 | Java | false | false | 107 | java | package cn.farwalker.ravv.service.goods.image.model;
public class GoodsImageVo extends GoodsImageBo {
}
| [
"simple.ding816@gmail.com"
] | simple.ding816@gmail.com |
aedae60ae2d3eca082b8da05ba544edd15e4588c | 6601a636bd62e7c42091c1b239785fbc0abac922 | /app/src/main/java/com/nostra13/universalimageloader/core/ProcessAndDisplayImageTask.java | 38fc0ec274649d11af1e4d099d834cab1d15298b | [] | no_license | quantum-y/Android_Funnylive | e1134da578ada8a370f8b4b4da028b624cb0a3ab | 14e63c3945d548b00b066eeee604e8c735ff599c | refs/heads/master | 2020-04-01T23:04:40.608427 | 2018-12-13T08:50:01 | 2018-12-13T08:50:01 | 153,740,564 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,371 | java | /*******************************************************************************
* Copyright 2011-2014 Sergey Tarasevich
*
* 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 test2 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.nostra13.universalimageloader.core;
import android.graphics.Bitmap;
import android.os.Handler;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.assist.LoadedFrom;
import com.nostra13.universalimageloader.core.process.BitmapProcessor;
import com.nostra13.universalimageloader.utils.L;
/**
* Presents process'n'display image task. Processes image {@linkplain Bitmap} and display it in {@link ImageView} using
* {@link DisplayBitmapTask}.
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @since 1.8.0
*/
final class ProcessAndDisplayImageTask implements Runnable {
private static final String LOG_POSTPROCESS_IMAGE = "PostProcess image before displaying [%s]";
private final ImageLoaderEngine engine;
private final Bitmap bitmap;
private final ImageLoadingInfo imageLoadingInfo;
private final Handler handler;
public ProcessAndDisplayImageTask(ImageLoaderEngine engine, Bitmap bitmap, ImageLoadingInfo imageLoadingInfo,
Handler handler) {
this.engine = engine;
this.bitmap = bitmap;
this.imageLoadingInfo = imageLoadingInfo;
this.handler = handler;
}
@Override
public void run() {
L.d(LOG_POSTPROCESS_IMAGE, imageLoadingInfo.memoryCacheKey);
BitmapProcessor processor = imageLoadingInfo.options.getPostProcessor();
Bitmap processedBitmap = processor.process(bitmap);
DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(processedBitmap, imageLoadingInfo, engine,
LoadedFrom.MEMORY_CACHE);
LoadAndDisplayImageTask.runTask(displayBitmapTask, imageLoadingInfo.options.isSyncLoading(), handler, engine);
}
}
| [
"nyhilacmlong@gmail.com"
] | nyhilacmlong@gmail.com |
acf908c9fd945c09d5ee8283a5019773d8bb5c3e | ff1c94519f9672fb26b31a97853774ba8c9016a8 | /src/SplitAStringInBalancedStrings/Solution.java | c82dd9a4798fa4eeb40c1d919833e0a18cf4c934 | [] | no_license | wangyao2221/LeetCode | 0a796af620e9e6dfefb8c49f755b4f2b6ee8d6ba | 9ec81a60dcda022cf17cda14c1d373ffd28d8a72 | refs/heads/master | 2021-01-20T02:53:08.629877 | 2020-07-29T05:53:39 | 2020-07-29T05:53:39 | 89,457,428 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 981 | java | package SplitAStringInBalancedStrings;
import java.util.ArrayList;
import java.util.List;
/**
* 算法不符合提议,但也可以出一道题,就是找最大数量的RRLL对称数量
*/
class Solution {
public int balancedStringSplit(String s) {
int result = 0;
int flag = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == 'R') {
flag++;
} else {
flag--;
}
if (flag == 0) {
result++;
}
}
return result;
}
public static void main(String[] args) {
// System.out.println(new Solution().balancedStringSplit("RLRRLLRLRL"));
// System.out.println(new Solution().balancedStringSplit("RLLLLRRRLR"));
// System.out.println(new Solution().balancedStringSplit("LLLLRRRR"));
System.out.println(new Solution().balancedStringSplit("RRLRRLRLLLRL"));
}
} | [
"wangyao2221@163.com"
] | wangyao2221@163.com |
4254fc25bd2b66ffd0f06c00feaebf95e64bdee3 | 73e7702fde67dd837918ba1af4fc7e1e90730134 | /app/src/main/java/com/example/hoangtruc/shopapp/presenter/search/SearchMvpPresenter.java | 26f513633708557e6dff1b79595c8ba63767f03e | [] | no_license | boytubi/ShopApp | afcf0338b11d7790e16b701a41677d46a8af6b7c | 68384dede54a6064c435aac63b440d5fda5a8f94 | refs/heads/master | 2020-05-26T14:41:54.440661 | 2019-05-23T16:14:38 | 2019-05-23T16:34:41 | 188,269,165 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 233 | java | package com.example.hoangtruc.shopapp.presenter.search;
import com.example.hoangtruc.shopapp.data.db.model.Product;
import java.util.List;
public interface SearchMvpPresenter {
void getListResult(String nameProduct);
}
| [
"hoangtruc14@gmail.com"
] | hoangtruc14@gmail.com |
0d03cca44df89a10f55d994b2ad6c0517463ee0f | 03c0cf79380e16a1229ee66169e98229c68ed84e | /src/main/java/com/mwy/starter/config/FlowRuleConfig.java | 98d377b0c703d24bf2afa29d670c456b79e07798 | [] | no_license | jeanswing/exception-monitor-starter | 42510f1c8b6c2d2165414c85ddb1f920f6eee2e4 | 5376bc350b60718c5752417438c7cc7a07fc8849 | refs/heads/master | 2023-04-12T00:25:48.336231 | 2021-04-14T07:28:34 | 2021-04-14T07:28:34 | 347,004,958 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,962 | java | package com.mwy.starter.config;
import com.mwy.starter.core.FlowRulePostHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static com.mwy.starter.utils.Constants.Default_Flow_Map_Size;
/**
* @author Jack Ma
* @description 限流规则初始化配置
* @date 2021-01-21
**/
@Configuration
@ConditionalOnBean(BaseConfig.class)
@EnableConfigurationProperties(FlowRuleConfigProperties.class)
@Slf4j
@ConditionalOnProperty(
prefix = "monitor.flow",
name = "enable",
havingValue = "true"
)
public class FlowRuleConfig {
@Autowired
FlowRuleConfigProperties flowRuleConfigProperties;
@Bean("flowRulePostHandler")
public FlowRulePostHandler flowRuleHandler(){
FlowRulePostHandler flowRule = new FlowRulePostHandler();
if(flowRuleConfigProperties.isEnable()){
flowRule.setRuleMap(new ConcurrentHashMap<>(Default_Flow_Map_Size));
}
Integer num = flowRuleConfigProperties.getNum();
if(num==null || num<=0){
log.warn("(exception-monitor)config [monitor.flow.num] is unavailable,set it 300 default");
flowRuleConfigProperties.setNum(300);
}
Executors.newSingleThreadScheduledExecutor().schedule(()->{
if(flowRule!=null){
flowRule.setRuleMap(new ConcurrentHashMap<>(Default_Flow_Map_Size));
}
}, 24, TimeUnit.HOURS);
return flowRule;
}
}
| [
"738876820@qq.com"
] | 738876820@qq.com |
629f113c16740c7e0316c1a044526288c8f94299 | 0d8f8eed6446b3c52e5444c146a542f70de01c3d | /src/JavaSessions/Customer.java | 1824a868079f36e8ef5b0d0a861b8ec16f9e3b5d | [] | no_license | viveksheat01/CoreJava2021 | c1d75fe1d88fac5cadc087259a438df282b105f7 | 965c8f5f85ded96e845963dee8a016fbc1986ce4 | refs/heads/master | 2023-08-31T03:45:09.837925 | 2021-10-18T07:13:27 | 2021-10-18T07:13:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 168 | java | package JavaSessions;
public class Customer {
String name;
String emailId;
long phone;
boolean isPrime;
static final String category = "Online Shopping";
}
| [
"viveksheat01@gmail.com"
] | viveksheat01@gmail.com |
95c171f6773a7171281d9919a083ec4225d9ce43 | 726767f9086d12adda738363e969d5eeacec3f8a | /app/src/main/java/com/wangcong/dzl/create.java | 7be536486958772f544289753ae69c6ad9490dc2 | [] | no_license | CleverWang/DZL | 5d1b0c55300fa47edec1d4fbb802618371c3b307 | 58471792cee6034a9dab1a5a81e203bf8384bf40 | refs/heads/master | 2021-01-12T11:10:58.255104 | 2016-11-04T15:24:19 | 2016-11-04T15:24:19 | 72,859,954 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,059 | java | package com.wangcong.dzl;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
/**
* Created by HASEE on 2016/10/1.
*/
public class create extends AppCompatActivity {
Button create;
EditText content;
String a;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
ActivityCollector.activities.add(this);
Bmob.initialize(this, "2f221c1babaeca6d42723047fba1289e");
create = (Button) findViewById(R.id.create);
content = (EditText) findViewById(R.id.content);
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a = content.getText().toString().trim();
if (a.length() != 0)
write(a, login.user);
else
Toast.makeText(create.this, "段子内容不能为空!", Toast.LENGTH_SHORT).show();
}
});
}
protected void write(String a, String b) {
alldata p2 = new alldata();
p2.setRoot(a + ":.:" + b + ":.:0");
p2.setSecondData("");
p2.setThirdData("");
p2.save(new SaveListener<String>() {
@Override
public void done(String objectId, BmobException e) {
if (e == null) {
Toast.makeText(create.this, "段子发布成功!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(create.this, main.class);
startActivity(intent);
} else {
Toast.makeText(create.this, "段子发布失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
| [
"1330792337@qq.com"
] | 1330792337@qq.com |
dea12cba621a85cf9ba7f4c6f79a168d252ebe29 | 2fa04f21cbb7203b468f7598df6696a88b05a286 | /bus-gitlab/src/main/java/org/aoju/bus/gitlab/models/NotificationSettings.java | c095d0a70a950960f6b92188ff7ff4fc0f9df934 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | jingshuai5213/bus | 17bb475fd76592682123488608a559abec788f81 | f3ec545617acffaf2668ea78e974a05be268cfd1 | refs/heads/master | 2022-11-16T00:35:46.037858 | 2020-07-02T09:35:10 | 2020-07-02T09:35:10 | 254,873,385 | 0 | 0 | MIT | 2020-07-02T09:35:11 | 2020-04-11T13:26:50 | null | UTF-8 | Java | false | false | 6,737 | java | /*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org Greg Messner and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
********************************************************************************/
package org.aoju.bus.gitlab.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import org.aoju.bus.gitlab.JacksonJson;
import org.aoju.bus.gitlab.JacksonJsonEnumHelper;
/**
* @author Kimi Liu
* @version 6.0.1
* @since JDK 1.8+
*/
public class NotificationSettings {
private Level level;
private String email;
private Events events;
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Events getEvents() {
return events;
}
public void setEvents(Events events) {
this.events = events;
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
/**
* Notification level
*/
public static enum Level {
DISABLED, PARTICIPATING, WATCH, GLOBAL, MENTION, CUSTOM;
private static JacksonJsonEnumHelper<Level> enumHelper = new JacksonJsonEnumHelper<>(Level.class);
@JsonCreator
public static Level forValue(String value) {
return enumHelper.forValue(value);
}
@JsonValue
public String toValue() {
return (enumHelper.toString(this));
}
@Override
public String toString() {
return (enumHelper.toString(this));
}
}
public static class Events {
private Boolean newNote;
private Boolean newIssue;
private Boolean reopenIssue;
private Boolean closeIssue;
private Boolean reassignIssue;
private Boolean newMergeRequest;
private Boolean reopenMergeRequest;
private Boolean closeMergeRequest;
private Boolean reassignMergeRequest;
private Boolean mergeMergeRequest;
private Boolean failedPipeline;
private Boolean successPipeline;
public Boolean getNewNote() {
return newNote;
}
public void setNewNote(Boolean newNote) {
this.newNote = newNote;
}
public Boolean getNewIssue() {
return newIssue;
}
public void setNewIssue(Boolean newIssue) {
this.newIssue = newIssue;
}
public Boolean getReopenIssue() {
return reopenIssue;
}
public void setReopenIssue(Boolean reopenIssue) {
this.reopenIssue = reopenIssue;
}
public Boolean getCloseIssue() {
return closeIssue;
}
public void setCloseIssue(Boolean closeIssue) {
this.closeIssue = closeIssue;
}
public Boolean getReassignIssue() {
return reassignIssue;
}
public void setReassignIssue(Boolean reassignIssue) {
this.reassignIssue = reassignIssue;
}
public Boolean getNewMergeRequest() {
return newMergeRequest;
}
public void setNewMergeRequest(Boolean newMergeRequest) {
this.newMergeRequest = newMergeRequest;
}
public Boolean getReopenMergeRequest() {
return reopenMergeRequest;
}
public void setReopenMergeRequest(Boolean reopenMergeRequest) {
this.reopenMergeRequest = reopenMergeRequest;
}
public Boolean getCloseMergeRequest() {
return closeMergeRequest;
}
public void setCloseMergeRequest(Boolean closeMergeRequest) {
this.closeMergeRequest = closeMergeRequest;
}
public Boolean getReassignMergeRequest() {
return reassignMergeRequest;
}
public void setReassignMergeRequest(Boolean reassignMergeRequest) {
this.reassignMergeRequest = reassignMergeRequest;
}
public Boolean getMergeMergeRequest() {
return mergeMergeRequest;
}
public void setMergeMergeRequest(Boolean mergeMergeRequest) {
this.mergeMergeRequest = mergeMergeRequest;
}
public Boolean getFailedPipeline() {
return failedPipeline;
}
public void setFailedPipeline(Boolean failedPipeline) {
this.failedPipeline = failedPipeline;
}
public Boolean getSuccessPipeline() {
return successPipeline;
}
public void setSuccessPipeline(Boolean successPipeline) {
this.successPipeline = successPipeline;
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
}
} | [
"839536@qq.com"
] | 839536@qq.com |
30ebdc64daecc82bebc2978d6c388303f899d28e | 0339336ef2c065df42bd496c0499a77427beba37 | /src/main/java/msa/lang/autocompute/semantics/exceptions/AlreadyDefinedException.java | f108b379b034f94b7424813a94c5b5413bfca7c5 | [
"MIT"
] | permissive | shamilatesoglu/AutoCompute | 797d8d35e803761ed64439cb1b910a80d13cef94 | d428b61bbc6c3a934800c08c10a824458fd5f094 | refs/heads/master | 2023-03-30T16:37:01.944289 | 2021-03-29T21:07:06 | 2021-03-29T21:07:06 | 340,981,538 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,389 | java | // Copyright (c) 2021 M. Samil Atesoglu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package msa.lang.autocompute.semantics.exceptions;
public class AlreadyDefinedException extends RuntimeException {
public AlreadyDefinedException(String reference, String scopeId) {
super(String.format("%s is already defined in %s", reference, scopeId));
}
}
| [
"m.samilatesoglu@gmail.com"
] | m.samilatesoglu@gmail.com |
66d101c4b65b10d0461f83e012545d246c4bf3bd | 25e9ac73dce49e4c89beec9281cb4196a8598fa9 | /src/main/java/com/avs/portal/service/LoginService.java | 66e2a7c30247ec7d03aee9b42c77b40b5e873345 | [] | no_license | pmarimuthu/Application | 2e7094d67bef42db50cb48ebe99ed79307d3dc31 | bca69967e0caf6bb7fef8148946ec18621789697 | refs/heads/master | 2023-06-02T19:25:04.763686 | 2021-06-15T19:04:17 | 2021-06-15T19:04:17 | 376,702,303 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,652 | java | package com.avs.portal.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.avs.portal.bean.LoginBean;
import com.avs.portal.bean.UserAccountBean;
import com.avs.portal.entity.User;
import com.avs.portal.entity.UserAccount;
import com.avs.portal.exception.ApplicationException;
import com.avs.portal.repository.UserAccountRepository;
import com.avs.portal.repository.UserRepository;
@Service
public class LoginService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserAccountRepository accountRepository;
public LoginBean authenticate(LoginBean loginBean) throws ApplicationException {
if (loginBean == null) {
return loginBean;
}
String code = "XXXX"; // PALV
List<User> users = userRepository.findByEmailOrPhone(loginBean.getEmail(), loginBean.getPhone());
User user = users.stream().findFirst().orElse(null);
if(user != null) {
UserAccount account = accountRepository.findByIdAndPassword(user.getId(), loginBean.getPassword());
if(account != null)
code = getCode(account.toBean());
else
code = "1XXX";
loginBean.setId(user.getId());
loginBean.setEmail(user.getEmail());
loginBean.setPhone(user.getPhone());
}
loginBean.setResultCode(code);
return loginBean;
}
private String getCode(UserAccountBean accountBean) {
return String.format("%s%s%s%s;", "0", // Password
accountBean.getIsActive() ? "0" : "1", // Active
accountBean.getIsLocked() ? "0" : "1", // Locked
accountBean.getIsVerified() ? "0" : "1" // Verified
);
}
}
| [
"pmarimuthu@gmail.com"
] | pmarimuthu@gmail.com |
4d6a25fccd71ccadfacb9d617001982949be5cb6 | 1c53d5257ea7be9450919e6b9e0491944a93ba80 | /merge-scenarios/elasticsearch/fb24469fe75-server-src-test-java-org-elasticsearch-snapshots-DedicatedClusterSnapshotRestoreIT/expected.java | c2eb38b5220fe200e4f4efa72edd035dcd235415 | [] | no_license | anonyFVer/mastery-material | 89062928807a1f859e9e8b9a113b2d2d123dc3f1 | db76ee571b84be5db2d245f3b593b29ebfaaf458 | refs/heads/master | 2023-03-16T13:13:49.798374 | 2021-02-26T04:19:19 | 2021-02-26T04:19:19 | 342,556,129 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 66,129 | java | package org.elasticsearch.snapshots;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntSet;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStats;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.NamedDiff;
import org.elasticsearch.cluster.SnapshotsInProgress;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataIndexStateService;
import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsFilter;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.discovery.zen.ElectMasterService;
import org.elasticsearch.env.Environment;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.node.Node;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.repositories.RepositoryMissingException;
import org.elasticsearch.rest.AbstractRestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.admin.cluster.RestClusterStateAction;
import org.elasticsearch.rest.action.admin.cluster.RestGetRepositoriesAction;
import org.elasticsearch.snapshots.mockstore.MockRepository;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.TestCustomMetaData;
import org.elasticsearch.test.discovery.TestZenDiscovery;
import org.elasticsearch.test.disruption.BusyMasterServiceDisruption;
import org.elasticsearch.test.disruption.ServiceDisruptionScheme;
import org.elasticsearch.test.rest.FakeRestRequest;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0, transportClientRatio = 0)
public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCase {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder().put(super.nodeSettings(nodeOrdinal)).put(TestZenDiscovery.USE_ZEN2.getKey(), false).build();
}
public static class TestCustomMetaDataPlugin extends Plugin {
private final List<NamedWriteableRegistry.Entry> namedWritables = new ArrayList<>();
private final List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>();
public TestCustomMetaDataPlugin() {
registerBuiltinWritables();
}
private <T extends MetaData.Custom> void registerMetaDataCustom(String name, Writeable.Reader<T> reader, Writeable.Reader<NamedDiff> diffReader, CheckedFunction<XContentParser, T, IOException> parser) {
namedWritables.add(new NamedWriteableRegistry.Entry(MetaData.Custom.class, name, reader));
namedWritables.add(new NamedWriteableRegistry.Entry(NamedDiff.class, name, diffReader));
namedXContents.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(name), parser));
}
private void registerBuiltinWritables() {
registerMetaDataCustom(SnapshottableMetadata.TYPE, SnapshottableMetadata::readFrom, SnapshottableMetadata::readDiffFrom, SnapshottableMetadata::fromXContent);
registerMetaDataCustom(NonSnapshottableMetadata.TYPE, NonSnapshottableMetadata::readFrom, NonSnapshottableMetadata::readDiffFrom, NonSnapshottableMetadata::fromXContent);
registerMetaDataCustom(SnapshottableGatewayMetadata.TYPE, SnapshottableGatewayMetadata::readFrom, SnapshottableGatewayMetadata::readDiffFrom, SnapshottableGatewayMetadata::fromXContent);
registerMetaDataCustom(NonSnapshottableGatewayMetadata.TYPE, NonSnapshottableGatewayMetadata::readFrom, NonSnapshottableGatewayMetadata::readDiffFrom, NonSnapshottableGatewayMetadata::fromXContent);
registerMetaDataCustom(SnapshotableGatewayNoApiMetadata.TYPE, SnapshotableGatewayNoApiMetadata::readFrom, NonSnapshottableGatewayMetadata::readDiffFrom, SnapshotableGatewayNoApiMetadata::fromXContent);
}
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
return namedWritables;
}
@Override
public List<NamedXContentRegistry.Entry> getNamedXContent() {
return namedXContents;
}
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(MockRepository.Plugin.class, TestCustomMetaDataPlugin.class);
}
public void testRestorePersistentSettings() throws Exception {
logger.info("--> start 2 nodes");
internalCluster().startNode();
Client client = client();
String secondNode = internalCluster().startNode();
logger.info("--> wait for the second node to join the cluster");
assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("2").get().isTimedOut(), equalTo(false));
logger.info("--> set test persistent setting");
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(Settings.builder().put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), 2)).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState().getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), -1), equalTo(2));
logger.info("--> create repository");
AcknowledgedResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0));
assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> clean the test persistent setting");
client.admin().cluster().prepareUpdateSettings().setPersistentSettings(Settings.builder().put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), 1)).execute().actionGet();
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState().getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), -1), equalTo(1));
stopNode(secondNode);
assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("1").get().isTimedOut(), equalTo(false));
logger.info("--> restore snapshot");
try {
client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet();
fail("can't restore minimum master nodes");
} catch (IllegalArgumentException ex) {
assertEquals("illegal value can't update [discovery.zen.minimum_master_nodes] from [1] to [2]", ex.getMessage());
assertEquals("cannot set discovery.zen.minimum_master_nodes to more than the current master nodes count [1]", ex.getCause().getMessage());
}
logger.info("--> ensure that zen discovery minimum master nodes wasn't restored");
assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState().getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING.getKey(), -1), not(equalTo(2)));
}
public void testRestoreCustomMetadata() throws Exception {
Path tempDir = randomRepoPath();
logger.info("--> start node");
internalCluster().startNode();
Client client = client();
createIndex("test-idx");
logger.info("--> add custom persistent metadata");
updateClusterState(currentState -> {
ClusterState.Builder builder = ClusterState.builder(currentState);
MetaData.Builder metadataBuilder = MetaData.builder(currentState.metaData());
metadataBuilder.putCustom(SnapshottableMetadata.TYPE, new SnapshottableMetadata("before_snapshot_s"));
metadataBuilder.putCustom(NonSnapshottableMetadata.TYPE, new NonSnapshottableMetadata("before_snapshot_ns"));
metadataBuilder.putCustom(SnapshottableGatewayMetadata.TYPE, new SnapshottableGatewayMetadata("before_snapshot_s_gw"));
metadataBuilder.putCustom(NonSnapshottableGatewayMetadata.TYPE, new NonSnapshottableGatewayMetadata("before_snapshot_ns_gw"));
metadataBuilder.putCustom(SnapshotableGatewayNoApiMetadata.TYPE, new SnapshotableGatewayNoApiMetadata("before_snapshot_s_gw_noapi"));
builder.metaData(metadataBuilder);
return builder.build();
});
logger.info("--> create repository");
AcknowledgedResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", tempDir)).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot");
CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().successfulShards()));
assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> change custom persistent metadata");
updateClusterState(currentState -> {
ClusterState.Builder builder = ClusterState.builder(currentState);
MetaData.Builder metadataBuilder = MetaData.builder(currentState.metaData());
if (randomBoolean()) {
metadataBuilder.putCustom(SnapshottableMetadata.TYPE, new SnapshottableMetadata("after_snapshot_s"));
} else {
metadataBuilder.removeCustom(SnapshottableMetadata.TYPE);
}
metadataBuilder.putCustom(NonSnapshottableMetadata.TYPE, new NonSnapshottableMetadata("after_snapshot_ns"));
if (randomBoolean()) {
metadataBuilder.putCustom(SnapshottableGatewayMetadata.TYPE, new SnapshottableGatewayMetadata("after_snapshot_s_gw"));
} else {
metadataBuilder.removeCustom(SnapshottableGatewayMetadata.TYPE);
}
metadataBuilder.putCustom(NonSnapshottableGatewayMetadata.TYPE, new NonSnapshottableGatewayMetadata("after_snapshot_ns_gw"));
metadataBuilder.removeCustom(SnapshotableGatewayNoApiMetadata.TYPE);
builder.metaData(metadataBuilder);
return builder.build();
});
logger.info("--> delete repository");
assertAcked(client.admin().cluster().prepareDeleteRepository("test-repo"));
logger.info("--> create repository");
putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo-2").setType("fs").setSettings(Settings.builder().put("location", tempDir)).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> restore snapshot");
client.admin().cluster().prepareRestoreSnapshot("test-repo-2", "test-snap").setRestoreGlobalState(true).setIndices("-*").setWaitForCompletion(true).execute().actionGet();
logger.info("--> make sure old repository wasn't restored");
assertThrows(client.admin().cluster().prepareGetRepositories("test-repo"), RepositoryMissingException.class);
assertThat(client.admin().cluster().prepareGetRepositories("test-repo-2").get().repositories().size(), equalTo(1));
logger.info("--> check that custom persistent metadata was restored");
ClusterState clusterState = client.admin().cluster().prepareState().get().getState();
logger.info("Cluster state: {}", clusterState);
MetaData metaData = clusterState.getMetaData();
assertThat(((SnapshottableMetadata) metaData.custom(SnapshottableMetadata.TYPE)).getData(), equalTo("before_snapshot_s"));
assertThat(((NonSnapshottableMetadata) metaData.custom(NonSnapshottableMetadata.TYPE)).getData(), equalTo("after_snapshot_ns"));
assertThat(((SnapshottableGatewayMetadata) metaData.custom(SnapshottableGatewayMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw"));
assertThat(((NonSnapshottableGatewayMetadata) metaData.custom(NonSnapshottableGatewayMetadata.TYPE)).getData(), equalTo("after_snapshot_ns_gw"));
logger.info("--> restart all nodes");
internalCluster().fullRestart();
ensureYellow();
logger.info("--> check that gateway-persistent custom metadata survived full cluster restart");
clusterState = client().admin().cluster().prepareState().get().getState();
logger.info("Cluster state: {}", clusterState);
metaData = clusterState.getMetaData();
assertThat(metaData.custom(SnapshottableMetadata.TYPE), nullValue());
assertThat(metaData.custom(NonSnapshottableMetadata.TYPE), nullValue());
assertThat(((SnapshottableGatewayMetadata) metaData.custom(SnapshottableGatewayMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw"));
assertThat(((NonSnapshottableGatewayMetadata) metaData.custom(NonSnapshottableGatewayMetadata.TYPE)).getData(), equalTo("after_snapshot_ns_gw"));
assertThat(metaData.custom(SnapshotableGatewayNoApiMetadata.TYPE), nullValue());
metaData = internalCluster().getInstance(ClusterService.class).state().metaData();
assertThat(((SnapshotableGatewayNoApiMetadata) metaData.custom(SnapshotableGatewayNoApiMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw_noapi"));
}
private void updateClusterState(final ClusterStateUpdater updater) throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final ClusterService clusterService = internalCluster().getInstance(ClusterService.class);
clusterService.submitStateUpdateTask("test", new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
return updater.execute(currentState);
}
@Override
public void onFailure(String source, @Nullable Exception e) {
countDownLatch.countDown();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
countDownLatch.countDown();
}
});
countDownLatch.await();
}
private interface ClusterStateUpdater {
ClusterState execute(ClusterState currentState) throws Exception;
}
public void testSnapshotDuringNodeShutdown() throws Exception {
logger.info("--> start 2 nodes");
Client client = client();
assertAcked(prepareCreate("test-idx", 2, Settings.builder().put("number_of_shards", 2).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
for (int i = 0; i < 100; i++) {
index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
logger.info("--> create repository");
logger.info("--> creating repository");
AcknowledgedResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put("random", randomAlphaOfLength(10)).put("wait_after_unblock", 200)).get();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
String blockedNode = blockNodeWithIndex("test-repo", "test-idx");
logger.info("--> snapshot");
client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> waiting for block to kick in");
waitForBlock(blockedNode, "test-repo", TimeValue.timeValueSeconds(60));
logger.info("--> execution was blocked on node [{}], shutting it down", blockedNode);
unblockNode("test-repo", blockedNode);
logger.info("--> stopping node [{}]", blockedNode);
stopNode(blockedNode);
logger.info("--> waiting for completion");
SnapshotInfo snapshotInfo = waitForCompletion("test-repo", "test-snap", TimeValue.timeValueSeconds(60));
logger.info("Number of failed shards [{}]", snapshotInfo.shardFailures().size());
logger.info("--> done");
}
public void testSnapshotWithStuckNode() throws Exception {
logger.info("--> start 2 nodes");
ArrayList<String> nodes = new ArrayList<>();
nodes.add(internalCluster().startNode());
nodes.add(internalCluster().startNode());
Client client = client();
assertAcked(prepareCreate("test-idx", 2, Settings.builder().put("number_of_shards", 2).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
for (int i = 0; i < 100; i++) {
index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
logger.info("--> creating repository");
Path repo = randomRepoPath();
AcknowledgedResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", repo).put("random", randomAlphaOfLength(10)).put("wait_after_unblock", 200)).get();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
String blockedNode = blockNodeWithIndex("test-repo", "test-idx");
nodes.remove(blockedNode);
int numberOfFilesBeforeSnapshot = numberOfFiles(repo);
logger.info("--> snapshot");
client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> waiting for block to kick in");
waitForBlock(blockedNode, "test-repo", TimeValue.timeValueSeconds(60));
logger.info("--> execution was blocked on node [{}], aborting snapshot", blockedNode);
ActionFuture<AcknowledgedResponse> deleteSnapshotResponseFuture = internalCluster().client(nodes.get(0)).admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap").execute();
Thread.sleep(100);
unblockNode("test-repo", blockedNode);
logger.info("--> stopping node [{}]", blockedNode);
stopNode(blockedNode);
try {
AcknowledgedResponse deleteSnapshotResponse = deleteSnapshotResponseFuture.actionGet();
assertThat(deleteSnapshotResponse.isAcknowledged(), equalTo(true));
} catch (SnapshotMissingException ex) {
}
logger.info("--> making sure that snapshot no longer exists");
assertThrows(client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute(), SnapshotMissingException.class);
assertThat("not all files were deleted during snapshot cancellation", numberOfFilesBeforeSnapshot, equalTo(numberOfFiles(repo) - 4));
logger.info("--> done");
}
public void testRestoreIndexWithMissingShards() throws Exception {
logger.info("--> start 2 nodes");
internalCluster().startNode();
internalCluster().startNode();
cluster().wipeIndices("_all");
logger.info("--> create an index that will have some unallocated shards");
assertAcked(prepareCreate("test-idx-some", 2, Settings.builder().put("number_of_shards", 6).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data into test-idx-some");
for (int i = 0; i < 100; i++) {
index("test-idx-some", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client().prepareSearch("test-idx-some").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
logger.info("--> shutdown one of the nodes");
internalCluster().stopRandomDataNode();
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForNodes("<2").execute().actionGet().isTimedOut(), equalTo(false));
logger.info("--> create an index that will have all allocated shards");
assertAcked(prepareCreate("test-idx-all", 1, Settings.builder().put("number_of_shards", 6).put("number_of_replicas", 0)));
ensureGreen("test-idx-all");
logger.info("--> create an index that will be closed");
assertAcked(prepareCreate("test-idx-closed", 1, Settings.builder().put("number_of_shards", 4).put("number_of_replicas", 0)));
ensureGreen("test-idx-closed");
logger.info("--> indexing some data into test-idx-all");
for (int i = 0; i < 100; i++) {
index("test-idx-all", "doc", Integer.toString(i), "foo", "bar" + i);
index("test-idx-closed", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh("test-idx-closed", "test-idx-all");
assertThat(client().prepareSearch("test-idx-all").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
assertAcked(client().admin().indices().prepareClose("test-idx-closed"));
logger.info("--> create an index that will have no allocated shards");
assertAcked(prepareCreate("test-idx-none", 1, Settings.builder().put("number_of_shards", 6).put("index.routing.allocation.include.tag", "nowhere").put("number_of_replicas", 0)).setWaitForActiveShards(ActiveShardCount.NONE).get());
assertTrue(client().admin().indices().prepareExists("test-idx-none").get().isExists());
logger.info("--> creating repository");
AcknowledgedResponse putRepositoryResponse = client().admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
logger.info("--> start snapshot with default settings and closed index - should be blocked");
assertBlocked(client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setIndices("test-idx-all", "test-idx-none", "test-idx-some", "test-idx-closed").setWaitForCompletion(true), MetaDataIndexStateService.INDEX_CLOSED_BLOCK);
logger.info("--> start snapshot with default settings without a closed index - should fail");
CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setIndices("test-idx-all", "test-idx-none", "test-idx-some").setWaitForCompletion(true).execute().actionGet();
assertThat(createSnapshotResponse.getSnapshotInfo().state(), equalTo(SnapshotState.FAILED));
assertThat(createSnapshotResponse.getSnapshotInfo().reason(), containsString("Indices don't have primary shards"));
if (randomBoolean()) {
logger.info("checking snapshot completion using status");
client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-2").setIndices("test-idx-all", "test-idx-none", "test-idx-some").setWaitForCompletion(false).setPartial(true).execute().actionGet();
assertBusy(() -> {
SnapshotsStatusResponse snapshotsStatusResponse = client().admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-snap-2").get();
List<SnapshotStatus> snapshotStatuses = snapshotsStatusResponse.getSnapshots();
assertEquals(snapshotStatuses.size(), 1);
logger.trace("current snapshot status [{}]", snapshotStatuses.get(0));
assertTrue(snapshotStatuses.get(0).getState().completed());
}, 1, TimeUnit.MINUTES);
SnapshotsStatusResponse snapshotsStatusResponse = client().admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-snap-2").get();
List<SnapshotStatus> snapshotStatuses = snapshotsStatusResponse.getSnapshots();
assertThat(snapshotStatuses.size(), equalTo(1));
SnapshotStatus snapshotStatus = snapshotStatuses.get(0);
logger.info("State: [{}], Reason: [{}]", createSnapshotResponse.getSnapshotInfo().state(), createSnapshotResponse.getSnapshotInfo().reason());
assertThat(snapshotStatus.getShardsStats().getTotalShards(), equalTo(18));
assertThat(snapshotStatus.getShardsStats().getDoneShards(), lessThan(12));
assertThat(snapshotStatus.getShardsStats().getDoneShards(), greaterThan(6));
assertBusy(() -> {
GetSnapshotsResponse response = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap-2").get();
assertThat(response.getSnapshots().size(), equalTo(1));
SnapshotInfo snapshotInfo = response.getSnapshots().get(0);
assertTrue(snapshotInfo.state().completed());
assertEquals(SnapshotState.PARTIAL, snapshotInfo.state());
}, 1, TimeUnit.MINUTES);
} else {
logger.info("checking snapshot completion using wait_for_completion flag");
createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-2").setIndices("test-idx-all", "test-idx-none", "test-idx-some").setWaitForCompletion(true).setPartial(true).execute().actionGet();
logger.info("State: [{}], Reason: [{}]", createSnapshotResponse.getSnapshotInfo().state(), createSnapshotResponse.getSnapshotInfo().reason());
assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(18));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), lessThan(12));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(6));
assertThat(client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap-2").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.PARTIAL));
}
assertAcked(client().admin().indices().prepareClose("test-idx-some", "test-idx-all"));
logger.info("--> restore incomplete snapshot - should fail");
assertThrows(client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setWaitForCompletion(true).execute(), SnapshotRestoreException.class);
logger.info("--> restore snapshot for the index that was snapshotted completely");
RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setIndices("test-idx-all").setWaitForCompletion(true).execute().actionGet();
assertThat(restoreSnapshotResponse.getRestoreInfo(), notNullValue());
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().successfulShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().failedShards(), equalTo(0));
assertThat(client().prepareSearch("test-idx-all").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
logger.info("--> restore snapshot for the partial index");
cluster().wipeIndices("test-idx-some");
restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setIndices("test-idx-some").setPartial(true).setWaitForCompletion(true).get();
assertThat(restoreSnapshotResponse.getRestoreInfo(), notNullValue());
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().successfulShards(), allOf(greaterThan(0), lessThan(6)));
assertThat(restoreSnapshotResponse.getRestoreInfo().failedShards(), greaterThan(0));
assertThat(client().prepareSearch("test-idx-some").setSize(0).get().getHits().getTotalHits().value, allOf(greaterThan(0L), lessThan(100L)));
logger.info("--> restore snapshot for the index that didn't have any shards snapshotted successfully");
cluster().wipeIndices("test-idx-none");
restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false).setIndices("test-idx-none").setPartial(true).setWaitForCompletion(true).get();
assertThat(restoreSnapshotResponse.getRestoreInfo(), notNullValue());
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), equalTo(6));
assertThat(restoreSnapshotResponse.getRestoreInfo().successfulShards(), equalTo(0));
assertThat(restoreSnapshotResponse.getRestoreInfo().failedShards(), equalTo(6));
assertThat(client().prepareSearch("test-idx-some").setSize(0).get().getHits().getTotalHits().value, allOf(greaterThan(0L), lessThan(100L)));
}
public void testRestoreIndexWithShardsMissingInLocalGateway() throws Exception {
logger.info("--> start 2 nodes");
Settings nodeSettings = Settings.builder().put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), EnableAllocationDecider.Rebalance.NONE).build();
internalCluster().startNode(nodeSettings);
internalCluster().startNode(nodeSettings);
cluster().wipeIndices("_all");
logger.info("--> create repository");
AcknowledgedResponse putRepositoryResponse = client().admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath())).execute().actionGet();
assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
int numberOfShards = 6;
logger.info("--> create an index that will have some unallocated shards");
assertAcked(prepareCreate("test-idx", 2, Settings.builder().put("number_of_shards", numberOfShards).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data into test-idx");
for (int i = 0; i < 100; i++) {
index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
}
refresh();
assertThat(client().prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
logger.info("--> start snapshot");
assertThat(client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setIndices("test-idx").setWaitForCompletion(true).get().getSnapshotInfo().state(), equalTo(SnapshotState.SUCCESS));
logger.info("--> close the index");
assertAcked(client().admin().indices().prepareClose("test-idx"));
logger.info("--> shutdown one of the nodes that should make half of the shards unavailable");
internalCluster().restartRandomDataNode(new InternalTestCluster.RestartCallback() {
@Override
public boolean clearData(String nodeName) {
return true;
}
});
assertThat(client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setTimeout("1m").setWaitForNodes("2").execute().actionGet().isTimedOut(), equalTo(false));
logger.info("--> restore index snapshot");
assertThat(client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-1").setRestoreGlobalState(false).setWaitForCompletion(true).get().getRestoreInfo().successfulShards(), equalTo(6));
ensureGreen("test-idx");
assertThat(client().prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits().value, equalTo(100L));
IntSet reusedShards = new IntHashSet();
List<RecoveryState> recoveryStates = client().admin().indices().prepareRecoveries("test-idx").get().shardRecoveryStates().get("test-idx");
for (RecoveryState recoveryState : recoveryStates) {
if (recoveryState.getIndex().reusedBytes() > 0) {
reusedShards.add(recoveryState.getShardId().getId());
}
}
logger.info("--> check that at least half of the shards had some reuse: [{}]", reusedShards);
assertThat(reusedShards.size(), greaterThanOrEqualTo(numberOfShards / 2));
}
public void testRegistrationFailure() {
logger.info("--> start first node");
internalCluster().startNode();
logger.info("--> start second node");
internalCluster().startNode(Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false));
for (int i = 0; i < 5; i++) {
client().admin().cluster().preparePutRepository("test-repo" + i).setType("mock").setSettings(Settings.builder().put("location", randomRepoPath())).setVerify(false).get();
}
logger.info("--> make sure that properly setup repository can be registered on all nodes");
client().admin().cluster().preparePutRepository("test-repo-0").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath())).get();
}
public void testThatSensitiveRepositorySettingsAreNotExposed() throws Exception {
Settings nodeSettings = Settings.EMPTY;
logger.info("--> start two nodes");
internalCluster().startNodes(2, nodeSettings);
client().admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put(MockRepository.Plugin.USERNAME_SETTING.getKey(), "notsecretusername").put(MockRepository.Plugin.PASSWORD_SETTING.getKey(), "verysecretpassword")).get();
NodeClient nodeClient = internalCluster().getInstance(NodeClient.class);
RestGetRepositoriesAction getRepoAction = new RestGetRepositoriesAction(nodeSettings, mock(RestController.class), internalCluster().getInstance(SettingsFilter.class));
RestRequest getRepoRequest = new FakeRestRequest();
getRepoRequest.params().put("repository", "test-repo");
final CountDownLatch getRepoLatch = new CountDownLatch(1);
final AtomicReference<AssertionError> getRepoError = new AtomicReference<>();
getRepoAction.handleRequest(getRepoRequest, new AbstractRestChannel(getRepoRequest, true) {
@Override
public void sendResponse(RestResponse response) {
try {
assertThat(response.content().utf8ToString(), containsString("notsecretusername"));
assertThat(response.content().utf8ToString(), not(containsString("verysecretpassword")));
} catch (AssertionError ex) {
getRepoError.set(ex);
}
getRepoLatch.countDown();
}
}, nodeClient);
assertTrue(getRepoLatch.await(1, TimeUnit.SECONDS));
if (getRepoError.get() != null) {
throw getRepoError.get();
}
RestClusterStateAction clusterStateAction = new RestClusterStateAction(nodeSettings, mock(RestController.class), internalCluster().getInstance(SettingsFilter.class));
RestRequest clusterStateRequest = new FakeRestRequest();
final CountDownLatch clusterStateLatch = new CountDownLatch(1);
final AtomicReference<AssertionError> clusterStateError = new AtomicReference<>();
clusterStateAction.handleRequest(clusterStateRequest, new AbstractRestChannel(clusterStateRequest, true) {
@Override
public void sendResponse(RestResponse response) {
try {
assertThat(response.content().utf8ToString(), containsString("notsecretusername"));
assertThat(response.content().utf8ToString(), not(containsString("verysecretpassword")));
} catch (AssertionError ex) {
clusterStateError.set(ex);
}
clusterStateLatch.countDown();
}
}, nodeClient);
assertTrue(clusterStateLatch.await(1, TimeUnit.SECONDS));
if (clusterStateError.get() != null) {
throw clusterStateError.get();
}
}
public void testMasterShutdownDuringSnapshot() throws Exception {
logger.info("--> starting two master nodes and two data nodes");
internalCluster().startMasterOnlyNodes(2);
internalCluster().startDataOnlyNodes(2);
final Client client = client();
logger.info("--> creating repository");
assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
assertAcked(prepareCreate("test-idx", 0, Settings.builder().put("number_of_shards", between(1, 20)).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
final int numdocs = randomIntBetween(10, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
for (int i = 0; i < builders.length; i++) {
builders[i] = client().prepareIndex("test-idx", "type1", Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
flushAndRefresh();
final int numberOfShards = getNumShards("test-idx").numPrimaries;
logger.info("number of shards: {}", numberOfShards);
dataNodeClient().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> stopping master node");
internalCluster().stopCurrentMasterNode();
logger.info("--> wait until the snapshot is done");
assertBusy(() -> {
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertTrue(snapshotInfo.state().completed());
}, 1, TimeUnit.MINUTES);
logger.info("--> verify that snapshot was succesful");
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertEquals(SnapshotState.SUCCESS, snapshotInfo.state());
assertEquals(snapshotInfo.totalShards(), snapshotInfo.successfulShards());
assertEquals(0, snapshotInfo.failedShards());
}
public void testMasterAndDataShutdownDuringSnapshot() throws Exception {
logger.info("--> starting three master nodes and two data nodes");
internalCluster().startMasterOnlyNodes(3);
internalCluster().startDataOnlyNodes(2);
final Client client = client();
logger.info("--> creating repository");
assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
assertAcked(prepareCreate("test-idx", 0, Settings.builder().put("number_of_shards", between(1, 20)).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
final int numdocs = randomIntBetween(10, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
for (int i = 0; i < builders.length; i++) {
builders[i] = client().prepareIndex("test-idx", "type1", Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
flushAndRefresh();
final int numberOfShards = getNumShards("test-idx").numPrimaries;
logger.info("number of shards: {}", numberOfShards);
final String masterNode = blockMasterFromFinalizingSnapshotOnSnapFile("test-repo");
final String dataNode = blockNodeWithIndex("test-repo", "test-idx");
dataNodeClient().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> stopping data node {}", dataNode);
stopNode(dataNode);
logger.info("--> stopping master node {} ", masterNode);
internalCluster().stopCurrentMasterNode();
logger.info("--> wait until the snapshot is done");
assertBusy(() -> {
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertTrue(snapshotInfo.state().completed());
}, 1, TimeUnit.MINUTES);
logger.info("--> verify that snapshot was partial");
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertEquals(SnapshotState.PARTIAL, snapshotInfo.state());
assertNotEquals(snapshotInfo.totalShards(), snapshotInfo.successfulShards());
assertThat(snapshotInfo.failedShards(), greaterThan(0));
for (SnapshotShardFailure failure : snapshotInfo.shardFailures()) {
assertNotNull(failure.reason());
}
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/25281")
public void testMasterShutdownDuringFailedSnapshot() throws Exception {
logger.info("--> starting two master nodes and two data nodes");
internalCluster().startMasterOnlyNodes(2);
internalCluster().startDataOnlyNodes(2);
logger.info("--> creating repository");
assertAcked(client().admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
assertAcked(prepareCreate("test-idx", 0, Settings.builder().put("number_of_shards", 6).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
final int numdocs = randomIntBetween(50, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
for (int i = 0; i < builders.length; i++) {
builders[i] = client().prepareIndex("test-idx", "type1", Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
flushAndRefresh();
logger.info("--> stopping random data node, which should cause shards to go missing");
internalCluster().stopRandomDataNode();
assertBusy(() -> assertEquals(ClusterHealthStatus.RED, client().admin().cluster().prepareHealth().get().getStatus()), 30, TimeUnit.SECONDS);
final String masterNode = blockMasterFromFinalizingSnapshotOnIndexFile("test-repo");
logger.info("--> snapshot");
client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
logger.info("--> waiting for block to kick in on " + masterNode);
waitForBlock(masterNode, "test-repo", TimeValue.timeValueSeconds(60));
logger.info("--> stopping master node");
internalCluster().stopCurrentMasterNode();
logger.info("--> wait until the snapshot is done");
assertBusy(() -> {
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").setIgnoreUnavailable(true).get();
assertEquals(1, snapshotsStatusResponse.getSnapshots().size());
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertTrue(snapshotInfo.state().completed());
ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
SnapshotsInProgress snapshotsInProgress = clusterState.custom(SnapshotsInProgress.TYPE);
assertEquals(0, snapshotsInProgress.entries().size());
}, 30, TimeUnit.SECONDS);
logger.info("--> verify that snapshot failed");
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertEquals(SnapshotState.FAILED, snapshotInfo.state());
}
public void testRestoreShrinkIndex() throws Exception {
logger.info("--> starting a master node and a data node");
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNode();
final Client client = client();
final String repo = "test-repo";
final String snapshot = "test-snap";
final String sourceIdx = "test-idx";
final String shrunkIdx = "test-idx-shrunk";
logger.info("--> creating repository");
assertAcked(client.admin().cluster().preparePutRepository(repo).setType("fs").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean())));
assertAcked(prepareCreate(sourceIdx, 0, Settings.builder().put("number_of_shards", between(2, 10)).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
IndexRequestBuilder[] builders = new IndexRequestBuilder[randomIntBetween(10, 100)];
for (int i = 0; i < builders.length; i++) {
builders[i] = client().prepareIndex(sourceIdx, "type1", Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
flushAndRefresh();
logger.info("--> shrink the index");
assertAcked(client.admin().indices().prepareUpdateSettings(sourceIdx).setSettings(Settings.builder().put("index.blocks.write", true)).get());
assertAcked(client.admin().indices().prepareResizeIndex(sourceIdx, shrunkIdx).get());
logger.info("--> snapshot the shrunk index");
CreateSnapshotResponse createResponse = client.admin().cluster().prepareCreateSnapshot(repo, snapshot).setWaitForCompletion(true).setIndices(shrunkIdx).get();
assertEquals(SnapshotState.SUCCESS, createResponse.getSnapshotInfo().state());
logger.info("--> delete index and stop the data node");
assertAcked(client.admin().indices().prepareDelete(sourceIdx).get());
assertAcked(client.admin().indices().prepareDelete(shrunkIdx).get());
internalCluster().stopRandomDataNode();
client().admin().cluster().prepareHealth().setTimeout("30s").setWaitForNodes("1");
logger.info("--> start a new data node");
final Settings dataSettings = Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), randomAlphaOfLength(5)).put(Environment.PATH_HOME_SETTING.getKey(), createTempDir()).build();
internalCluster().startDataOnlyNode(dataSettings);
client().admin().cluster().prepareHealth().setTimeout("30s").setWaitForNodes("2");
logger.info("--> restore the shrunk index and ensure all shards are allocated");
RestoreSnapshotResponse restoreResponse = client().admin().cluster().prepareRestoreSnapshot(repo, snapshot).setWaitForCompletion(true).setIndices(shrunkIdx).get();
assertEquals(restoreResponse.getRestoreInfo().totalShards(), restoreResponse.getRestoreInfo().successfulShards());
ensureYellow();
}
public void testSnapshotWithDateMath() {
final String repo = "repo";
final AdminClient admin = client().admin();
final IndexNameExpressionResolver nameExpressionResolver = new IndexNameExpressionResolver();
final String snapshotName = "<snapshot-{now/d}>";
logger.info("--> creating repository");
assertAcked(admin.cluster().preparePutRepository(repo).setType("fs").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean())));
final String expression1 = nameExpressionResolver.resolveDateMathExpression(snapshotName);
logger.info("--> creating date math snapshot");
CreateSnapshotResponse snapshotResponse = admin.cluster().prepareCreateSnapshot(repo, snapshotName).setIncludeGlobalState(true).setWaitForCompletion(true).get();
assertThat(snapshotResponse.status(), equalTo(RestStatus.OK));
final String expression2 = nameExpressionResolver.resolveDateMathExpression(snapshotName);
SnapshotsStatusResponse response = admin.cluster().prepareSnapshotStatus(repo).setSnapshots(Sets.newHashSet(expression1, expression2).toArray(Strings.EMPTY_ARRAY)).setIgnoreUnavailable(true).get();
List<SnapshotStatus> snapshots = response.getSnapshots();
assertThat(snapshots, hasSize(1));
assertThat(snapshots.get(0).getState().completed(), equalTo(true));
}
public void testSnapshotTotalAndIncrementalSizes() throws IOException {
Client client = client();
final String indexName = "test-blocks-1";
final String repositoryName = "repo-" + indexName;
final String snapshot0 = "snapshot-0";
final String snapshot1 = "snapshot-1";
createIndex(indexName);
int docs = between(10, 100);
for (int i = 0; i < docs; i++) {
client.prepareIndex(indexName, "type").setSource("test", "init").execute().actionGet();
}
logger.info("--> register a repository");
final Path repoPath = randomRepoPath();
assertAcked(client.admin().cluster().preparePutRepository(repositoryName).setType("fs").setSettings(Settings.builder().put("location", repoPath)));
logger.info("--> create a snapshot");
client.admin().cluster().prepareCreateSnapshot(repositoryName, snapshot0).setIncludeGlobalState(true).setWaitForCompletion(true).get();
SnapshotsStatusResponse response = client.admin().cluster().prepareSnapshotStatus(repositoryName).setSnapshots(snapshot0).get();
List<SnapshotStatus> snapshots = response.getSnapshots();
List<Path> snapshot0Files = scanSnapshotFolder(repoPath);
assertThat(snapshots, hasSize(1));
final int snapshot0FileCount = snapshot0Files.size();
final long snapshot0FileSize = calculateTotalFilesSize(snapshot0Files);
SnapshotStats stats = snapshots.get(0).getStats();
assertThat(stats.getTotalFileCount(), is(snapshot0FileCount));
assertThat(stats.getTotalSize(), is(snapshot0FileSize));
assertThat(stats.getIncrementalFileCount(), equalTo(snapshot0FileCount));
assertThat(stats.getIncrementalSize(), equalTo(snapshot0FileSize));
assertThat(stats.getIncrementalFileCount(), equalTo(stats.getProcessedFileCount()));
assertThat(stats.getIncrementalSize(), equalTo(stats.getProcessedSize()));
docs = between(1, 5);
for (int i = 0; i < docs; i++) {
client.prepareIndex(indexName, "type").setSource("test", "test" + i).execute().actionGet();
}
assertThat(client.admin().cluster().prepareCreateSnapshot(repositoryName, snapshot1).setWaitForCompletion(true).get().status(), equalTo(RestStatus.OK));
assertTrue(client.admin().cluster().prepareDeleteSnapshot(repositoryName, snapshot0).get().isAcknowledged());
response = client.admin().cluster().prepareSnapshotStatus(repositoryName).setSnapshots(snapshot1).get();
final List<Path> snapshot1Files = scanSnapshotFolder(repoPath);
final int snapshot1FileCount = snapshot1Files.size();
final long snapshot1FileSize = calculateTotalFilesSize(snapshot1Files);
snapshots = response.getSnapshots();
SnapshotStats anotherStats = snapshots.get(0).getStats();
ArrayList<Path> snapshotFilesDiff = new ArrayList<>(snapshot1Files);
snapshotFilesDiff.removeAll(snapshot0Files);
assertThat(anotherStats.getIncrementalFileCount(), equalTo(snapshotFilesDiff.size()));
assertThat(anotherStats.getIncrementalSize(), equalTo(calculateTotalFilesSize(snapshotFilesDiff)));
assertThat(anotherStats.getIncrementalFileCount(), equalTo(anotherStats.getProcessedFileCount()));
assertThat(anotherStats.getIncrementalSize(), equalTo(anotherStats.getProcessedSize()));
assertThat(stats.getTotalSize(), lessThan(anotherStats.getTotalSize()));
assertThat(stats.getTotalFileCount(), lessThan(anotherStats.getTotalFileCount()));
assertThat(anotherStats.getTotalFileCount(), is(snapshot1FileCount));
assertThat(anotherStats.getTotalSize(), is(snapshot1FileSize));
}
public void testDataNodeRestartWithBusyMasterDuringSnapshot() throws Exception {
logger.info("--> starting a master node and two data nodes");
internalCluster().startMasterOnlyNode();
internalCluster().startDataOnlyNodes(2);
logger.info("--> creating repository");
assertAcked(client().admin().cluster().preparePutRepository("test-repo").setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("max_snapshot_bytes_per_sec", "1000b").put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
assertAcked(prepareCreate("test-idx", 0, Settings.builder().put("number_of_shards", 5).put("number_of_replicas", 0)));
ensureGreen();
logger.info("--> indexing some data");
final int numdocs = randomIntBetween(50, 100);
IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
for (int i = 0; i < builders.length; i++) {
builders[i] = client().prepareIndex("test-idx", "type1", Integer.toString(i)).setSource("field1", "bar " + i);
}
indexRandom(true, builders);
flushAndRefresh();
final String dataNode = blockNodeWithIndex("test-repo", "test-idx");
logger.info("--> snapshot");
client(internalCluster().getMasterName()).admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
ServiceDisruptionScheme disruption = new BusyMasterServiceDisruption(random(), Priority.HIGH);
setDisruptionScheme(disruption);
disruption.startDisrupting();
logger.info("--> restarting data node, which should cause primary shards to be failed");
internalCluster().restartNode(dataNode, InternalTestCluster.EMPTY_CALLBACK);
unblockNode("test-repo", dataNode);
disruption.stopDisrupting();
assertBusy(() -> {
GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").setIgnoreUnavailable(true).get();
assertEquals(1, snapshotsStatusResponse.getSnapshots().size());
SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
assertTrue(snapshotInfo.state().toString(), snapshotInfo.state().completed());
}, 60L, TimeUnit.SECONDS);
}
private long calculateTotalFilesSize(List<Path> files) {
return files.stream().mapToLong(f -> {
try {
return Files.size(f);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).sum();
}
private List<Path> scanSnapshotFolder(Path repoPath) throws IOException {
List<Path> files = new ArrayList<>();
Files.walkFileTree(repoPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().startsWith("__")) {
files.add(file);
}
return super.visitFile(file, attrs);
}
});
return files;
}
public static class SnapshottableMetadata extends TestCustomMetaData {
public static final String TYPE = "test_snapshottable";
public SnapshottableMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.CURRENT;
}
public static SnapshottableMetadata readFrom(StreamInput in) throws IOException {
return readFrom(SnapshottableMetadata::new, in);
}
public static NamedDiff<MetaData.Custom> readDiffFrom(StreamInput in) throws IOException {
return readDiffFrom(TYPE, in);
}
public static SnapshottableMetadata fromXContent(XContentParser parser) throws IOException {
return fromXContent(SnapshottableMetadata::new, parser);
}
@Override
public EnumSet<MetaData.XContentContext> context() {
return MetaData.API_AND_SNAPSHOT;
}
}
public static class NonSnapshottableMetadata extends TestCustomMetaData {
public static final String TYPE = "test_non_snapshottable";
public NonSnapshottableMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.CURRENT;
}
public static NonSnapshottableMetadata readFrom(StreamInput in) throws IOException {
return readFrom(NonSnapshottableMetadata::new, in);
}
public static NamedDiff<MetaData.Custom> readDiffFrom(StreamInput in) throws IOException {
return readDiffFrom(TYPE, in);
}
public static NonSnapshottableMetadata fromXContent(XContentParser parser) throws IOException {
return fromXContent(NonSnapshottableMetadata::new, parser);
}
@Override
public EnumSet<MetaData.XContentContext> context() {
return MetaData.API_ONLY;
}
}
public static class SnapshottableGatewayMetadata extends TestCustomMetaData {
public static final String TYPE = "test_snapshottable_gateway";
public SnapshottableGatewayMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.CURRENT;
}
public static SnapshottableGatewayMetadata readFrom(StreamInput in) throws IOException {
return readFrom(SnapshottableGatewayMetadata::new, in);
}
public static NamedDiff<MetaData.Custom> readDiffFrom(StreamInput in) throws IOException {
return readDiffFrom(TYPE, in);
}
public static SnapshottableGatewayMetadata fromXContent(XContentParser parser) throws IOException {
return fromXContent(SnapshottableGatewayMetadata::new, parser);
}
@Override
public EnumSet<MetaData.XContentContext> context() {
return EnumSet.of(MetaData.XContentContext.API, MetaData.XContentContext.SNAPSHOT, MetaData.XContentContext.GATEWAY);
}
}
public static class NonSnapshottableGatewayMetadata extends TestCustomMetaData {
public static final String TYPE = "test_non_snapshottable_gateway";
public NonSnapshottableGatewayMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.CURRENT;
}
public static NonSnapshottableGatewayMetadata readFrom(StreamInput in) throws IOException {
return readFrom(NonSnapshottableGatewayMetadata::new, in);
}
public static NamedDiff<MetaData.Custom> readDiffFrom(StreamInput in) throws IOException {
return readDiffFrom(TYPE, in);
}
public static NonSnapshottableGatewayMetadata fromXContent(XContentParser parser) throws IOException {
return fromXContent(NonSnapshottableGatewayMetadata::new, parser);
}
@Override
public EnumSet<MetaData.XContentContext> context() {
return MetaData.API_AND_GATEWAY;
}
}
public static class SnapshotableGatewayNoApiMetadata extends TestCustomMetaData {
public static final String TYPE = "test_snapshottable_gateway_no_api";
public SnapshotableGatewayNoApiMetadata(String data) {
super(data);
}
@Override
public String getWriteableName() {
return TYPE;
}
@Override
public Version getMinimalSupportedVersion() {
return Version.CURRENT;
}
public static SnapshotableGatewayNoApiMetadata readFrom(StreamInput in) throws IOException {
return readFrom(SnapshotableGatewayNoApiMetadata::new, in);
}
public static SnapshotableGatewayNoApiMetadata fromXContent(XContentParser parser) throws IOException {
return fromXContent(SnapshotableGatewayNoApiMetadata::new, parser);
}
@Override
public EnumSet<MetaData.XContentContext> context() {
return EnumSet.of(MetaData.XContentContext.GATEWAY, MetaData.XContentContext.SNAPSHOT);
}
}
} | [
"namasikanam@gmail.com"
] | namasikanam@gmail.com |
018a291bb69388e1a68375af70ee6025c4d5e233 | 03e438bde732278750c0bf18da3e39389cea3e70 | /app/src/main/java/com/namit/scantastic/MainActivity.java | d27e7c2d605c82e038aaba22a10f122142e17319 | [] | no_license | NitsanAmit/Scantastic | 282f3a442f25141e05affba520cec90c7330eacc | 56db2bb0133c097bf8a63b8b4660403770f3b346 | refs/heads/master | 2020-09-12T11:33:01.140955 | 2019-11-18T10:03:28 | 2019-11-18T10:03:28 | 222,408,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 899 | java | package com.namit.scantastic;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@BindView(R.id.fab_main) FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fab.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.fab_main){
Intent intent = new Intent(this, CaptureActivity.class);
startActivity(intent);
}
}
}
| [
"Nitsan135@gmail.com"
] | Nitsan135@gmail.com |
e392e2e67efc5adc2a4a87991d997cb0121dab28 | 1cdeeb4b0471da9c0dcf7351adbb77d43ea9dc26 | /de.larsschuetze.storyboard.runtime/src/de/larsschuetze/storyboard/runtime/execution/execution/TokenManager.java | fe3aa5ac176f980bd14009f34705ba508d46728a | [] | no_license | lschuetze/context-storyboard | 4b04fa4fcfeb93b6a90fc59b16e957d5a87d1175 | b17132a1256bc66d20dc3593dcf0d6899263de64 | refs/heads/master | 2021-01-21T13:48:31.108100 | 2016-05-24T14:05:39 | 2016-05-24T14:05:39 | 54,029,975 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,112 | java | package de.larsschuetze.storyboard.runtime.execution.execution;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
import de.larsschuetze.storyboard.runtime.library.Token;
public class TokenManager {
private Set<Token> tokens;
private BigInteger nextId;
private EventManager eventManager;
public TokenManager(EventManager eventManager) {
tokens = new HashSet<>();
nextId = BigInteger.ZERO;
// TODO implement manager registry for lookup to reduce coupling
this.eventManager = eventManager;
}
public Token createToken() {
nextId = nextId.add(BigInteger.ONE);
Token token = new Token(this, nextId);
tokens.add(token);
return token;
}
public Token copyToken(Token token) {
Token copy = createToken();
// TODO copy token values
return copy;
}
public void destroy(Token token) {
// Add internal VM events about token destruction
// so runtime can remove it (implementing listeners)
tokens.remove(token);
}
public void setStalled(Token token, String eventType) {
token.setStalled(true);
eventManager.addWaitingToken(eventType, token);
}
}
| [
"dev@larsschuetze.de"
] | dev@larsschuetze.de |
5374d79f143c888ea1dea0d2260dd2cc0d9619de | 47f15e2a3b8de90b0322fbc9579141299cc386b0 | /Services/src/org/almuallim/service/browser/Browser.java | 240e419f00c20f8aca25db01c637721a8ad6246e | [] | no_license | naveedmurtuza/Al-muallim | 0dc2a978f138a52917c5c313edb19ff51bd9359b | 4f0da379e60203d6cb4ccfc33a8ec0f742a9b77f | refs/heads/master | 2016-09-05T11:30:52.260743 | 2014-04-12T16:16:02 | 2014-04-12T16:16:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,137 | java | package org.almuallim.service.browser;
import java.beans.PropertyChangeListener;
import org.almuallim.service.url.AlmuallimURL;
/**
* This interface is for opening
* <code>AlmuallimURL</code> in a browser window. The browser window can also be
* opened by just exposing the
* <code>AlmuallimURL</code> in the lookup. But i was unable to do it from the
* an action class.. In those scenarios where exposing AlmuallimURL is not an
* option, using this interface to get a new instance of browser. apart from the
* string property
*
* @author Naveed
*/
public interface Browser {
public static String PROP_TITLE_CHANGED = "TITLE_CHANGED";
public static String PAGE_LOADED = "PAGE_LOADED";
public void addPropertyChangeListener(PropertyChangeListener listener);
public void removePropertyChangeListener(PropertyChangeListener listener);
public void navigate(AlmuallimURL url);
/**
* Hook up to the propertychangelistener and wait for PAGE_LOADED property to
* fire to make sure the DOM is ready before using the js
*
* @return JSEngine
*/
public JSEngine getJSEngine();
}
| [
"naveedmurtuza@gmail.com"
] | naveedmurtuza@gmail.com |
cb922466779982ff5c4bbf690c4ad235ef2f26ed | 327053e1007538aa4418abc3baf32c3ece901dee | /src/main/java/com/hanains/mysite/interceptor/AuthLoginInterceptor.java | 54c84f75d785ad602b4e77d245505f11942d4a50 | [] | no_license | 801sanae/mysite3 | 8e9ea1ac07346e4ff63a8983054c34ec45232430 | 68c6f5a94388b8c2604aacf400831c5a0e42e182 | refs/heads/master | 2021-01-13T00:40:42.062654 | 2015-12-23T00:58:22 | 2015-12-23T00:58:22 | 47,959,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,743 | java | package com.hanains.mysite.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.hanains.mysite.service.UserService;
import com.hanains.mysite.vo.UserVo;
public class AuthLoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String email = request.getParameter("email");
String password = request.getParameter("password");
UserVo vo = new UserVo();
vo.setEmail(email); vo.setPassword(password);
//web application context에 이미 생성되있다..
//listener가 만드는 컨테이너(root web application Context) controller, service,등등 다들어잇다.
WebApplicationContext applicationContext
= WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
UserService userService = applicationContext.getBean(UserService.class);
UserVo authUser = userService.login(vo);
if(authUser==null){
response.sendRedirect(request.getContextPath()+"/user/loginform");
return false;
}
//login 처리
HttpSession session = request.getSession(true);
session.setAttribute("authUser", authUser);
response.sendRedirect(request.getContextPath());
return false;
}
}
| [
"bit-user@bit"
] | bit-user@bit |
69fd5c0aef3852b856487ae2a68853b3f441c812 | 8ffd45f78c37f6bee6e1444939200eca52e88b6c | /04-14Login/app/src/androidTest/java/com/example/a04_14login/ExampleInstrumentedTest.java | 0526be33447ab172876d9b49087c22f9a319d922 | [] | no_license | WNGary/Android | be95a44969034200fba5b18f7d101d96ce148084 | ee80f8858cd1ee4ef3cd958273b89f228158eb0c | refs/heads/master | 2022-04-17T01:32:48.752038 | 2020-04-17T08:53:05 | 2020-04-17T08:53:05 | 256,445,610 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 789 | java | package com.example.a04_14login;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.a04_14login", appContext.getPackageName());
}
}
| [
"2225671356@qq.com"
] | 2225671356@qq.com |
0419fd8a2b93ea3975d1c5c9ee8f6eb385692beb | a6358860de8dc5cd0e755b967a840d10b7799a4a | /app/src/main/java/global/imas/bintouch/PercentFrameLayout.java | a6265b58a4d2e5bd0d24eb626366ab62f7bcdae2 | [] | no_license | hash-14/SafeChatRefactor | 7cb15cb97a88b5e13cdab9f95e39bb93c704afd4 | f7522e90800dd17a4c8468cdfd618594e218d486 | refs/heads/master | 2020-08-09T06:06:22.058370 | 2019-10-13T14:22:54 | 2019-10-13T14:22:54 | 214,005,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,691 | java | /*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package global.imas.bintouch;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Simple container that confines the children to a subrectangle specified as percentage values of
* the container size. The children are centered horizontally and vertically inside the confined
* space.
*/
public class PercentFrameLayout extends ViewGroup {
private int xPercent = 0;
private int yPercent = 0;
private int widthPercent = 100;
private int heightPercent = 100;
public PercentFrameLayout(Context context) {
super(context);
}
public PercentFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PercentFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setPosition(int xPercent, int yPercent, int widthPercent, int heightPercent) {
this.xPercent = xPercent;
this.yPercent = yPercent;
this.widthPercent = widthPercent;
this.heightPercent = heightPercent;
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = getDefaultSize(Integer.MAX_VALUE, widthMeasureSpec);
final int height = getDefaultSize(Integer.MAX_VALUE, heightMeasureSpec);
setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
final int childWidthMeasureSpec =
MeasureSpec.makeMeasureSpec(width * widthPercent / 100, MeasureSpec.AT_MOST);
final int childHeightMeasureSpec =
MeasureSpec.makeMeasureSpec(height * heightPercent / 100, MeasureSpec.AT_MOST);
for (int i = 0; i < getChildCount(); ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = right - left;
final int height = bottom - top;
// Sub-rectangle specified by percentage values.
final int subWidth = width * widthPercent / 100;
final int subHeight = height * heightPercent / 100;
final int subLeft = left + width * xPercent / 100;
final int subTop = top + height * yPercent / 100;
for (int i = 0; i < getChildCount(); ++i) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
// Center child both vertically and horizontally.
final int childLeft = subLeft + (subWidth - childWidth) / 2;
final int childTop = subTop + (subHeight - childHeight) / 2;
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
}
}
}
}
| [
"shaitou.hassan14@gmail.com"
] | shaitou.hassan14@gmail.com |
41711a8dae754c97b6ef61e7a7ca3d735fb26bb2 | 14d9d6ed035bb8ce753f55cc58419d4374801089 | /app/src/main/java/com/android/loanassistant/model/Login.java | fff6ef4315cf2dad6ed62167602e20542d703613 | [] | no_license | niteshlekhi/LoanAssistant | 4ba20f17f487d86930bd051482854dea193ea069 | 589234cc674fb47664af1952bc091312e3945d7a | refs/heads/master | 2020-05-02T08:52:57.343026 | 2019-05-23T11:48:36 | 2019-05-23T11:48:36 | 177,854,522 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 853 | java | package com.android.loanassistant.model;
public class Login {
private String email;
private String password;
private int type;
public Login() {
}
public Login(String email, String password, int type) {
this.email = email;
this.password = password;
this.type = type;
}
public Login(String password, int type) {
this.password = password;
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| [
"niteshlekhi@gmail.com"
] | niteshlekhi@gmail.com |
c0f081bec361f56484ad7964b3ba462b3e10acd7 | 440fb2e16e9d024e95e9f646b3bd8b1fc61b0eec | /src/main/java/project/demo/JDKDynamicProxy.java | 76ef47ad93413ae298417f8b51768936247965ad | [] | no_license | xiaolonggezte/Practice | 256b88a5ad7be0733659c7dddcd5fe23fa394ae1 | 3dcaeb7060cfa62ae26ced5582bb745f7298da67 | refs/heads/master | 2020-03-27T03:42:39.941872 | 2018-09-20T16:20:32 | 2018-09-20T16:20:32 | 145,883,123 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,045 | java | package project.demo;
import project.service.TestService;
import project.service.impl.TestServiceImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author: xiaolong
* @Date: 下午9:51 2018/8/31
* @Description: JDK 动态代理
*/
public class JDKDynamicProxy implements InvocationHandler {
private Object proxyObj;
public Object newProxy(Object proxyObj) {
this.proxyObj = proxyObj;
/**
* Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
* loader :类加载器 一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载
* interfaces:一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了
* h :一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上
*/
//返回代理对象
return Proxy.newProxyInstance(proxyObj.getClass().getClassLoader(),proxyObj.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforce();
Object object = method.invoke(this.proxyObj,args);
after();
return object;
}
public void beforce() {
System.out.println("before");
}
public void after() {
System.out.println("after");
}
public static void main(String[] args) {
TestService testService = new TestServiceImpl();
// testService.add();//不是用代理
JDKDynamicProxy jdkDynamicProxy = new JDKDynamicProxy();
TestService testServiceProxy = (TestService) jdkDynamicProxy.newProxy(testService);
testServiceProxy.add();
}
}
| [
"xiaolong05@meituan.com"
] | xiaolong05@meituan.com |
ff1ee693e629161b9d6bfe0b71011048590f19dd | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/14/14_acf882df6811d0653cb6c6bf4a5b640d34aa0885/ConsoleServlet/14_acf882df6811d0653cb6c6bf4a5b640d34aa0885_ConsoleServlet_t.java | 5f1cd96e332df47e7ece6137c5fc236f9352c6ef | [] | 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 | 3,258 | 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.tomee.webapp.servlet;
import org.apache.openejb.util.OpenEJBScripter;
import org.apache.tomee.webapp.JsonExecutor;
import org.apache.tomee.webapp.listener.UserSessionListener;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
public class ConsoleServlet extends HttpServlet {
public static final OpenEJBScripter SCRIPTER = new OpenEJBScripter();
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
JsonExecutor.execute(resp, new JsonExecutor.Executor() {
@Override
public void call(Map<String, Object> json) throws Exception {
final String scriptCode = req.getParameter("scriptCode");
if (scriptCode == null || "".equals(scriptCode.trim())) {
return; //nothing to do
}
final HttpSession session = req.getSession();
String engineName = req.getParameter("engineName");
if (engineName == null || "".equals(engineName.trim())) {
engineName = "js";
}
final Bindings bindings = new SimpleBindings();
bindings.put("req", req);
bindings.put("resp", resp);
bindings.put("util", new Utility() {
@Override
public void write(Object obj) throws Exception {
resp.getWriter().write(String.valueOf(obj));
}
@Override
public void save(String key, Object obj) {
UserSessionListener.getServiceContext(req.getSession()).getSaved().put(key, obj);
}
});
SCRIPTER.evaluate(engineName, scriptCode, bindings);
}
});
}
private interface Utility {
void write(Object obj) throws Exception;
void save(String key, Object obj);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
ef3b85a5e413b4d61d275a688975750cbf80bf87 | 2481d8c57b43b95d70c6d1a28ee90dd4d6ae1372 | /temp/src/minecraft/net/minecraft/src/Packet42RemoveEntityEffect.java | 1b16a4e91139e11d2c0190a9d6f952f4219b44d4 | [] | no_license | UserCake/Gallifrey | c20bc8c6e75dc3a6b61301458ba5704d2db5872a | 2a55cb6106224b274f3326d7f5802540063bfa66 | refs/heads/master | 2021-01-20T21:53:10.901777 | 2012-03-28T05:58:35 | 2012-03-28T05:58:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,049 | java | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.io.*;
// Referenced classes of package net.minecraft.src:
// Packet, NetHandler
public class Packet42RemoveEntityEffect extends Packet
{
public int field_35253_a;
public byte field_35252_b;
public Packet42RemoveEntityEffect()
{
}
public void func_327_a(DataInputStream p_327_1_)
throws IOException
{
field_35253_a = p_327_1_.readInt();
field_35252_b = p_327_1_.readByte();
}
public void func_322_a(DataOutputStream p_322_1_)
throws IOException
{
p_322_1_.writeInt(field_35253_a);
p_322_1_.writeByte(field_35252_b);
}
public void func_323_a(NetHandler p_323_1_)
{
p_323_1_.func_35783_a(this);
}
public int func_329_a()
{
return 5;
}
}
| [
"eightbitme@me.com"
] | eightbitme@me.com |
18725b2044ec0efc5fbb28ea1266b924438e0c37 | cc5b6639da8cb790ed00b681dc31a436b5cba981 | /Patterns/src/Patterns/Numerialstar.java | 6c0ef6ace86ac1f9b528d7c1e8cc41cfd628bd71 | [] | no_license | g1rjeevan/Programming-eclipse | 9c86bf025bfa5cb93d06b570277e7cdf26b00c34 | ad6176439f8d15ff9e792476cbda6c818bf68b79 | refs/heads/master | 2021-01-21T14:01:34.485678 | 2019-09-24T03:10:33 | 2019-09-24T03:10:33 | 53,764,553 | 0 | 0 | null | 2020-10-13T04:38:02 | 2016-03-13T02:54:23 | HTML | UTF-8 | Java | false | false | 479 | java | package Patterns;
public class Numerialstar {
public static void main(String[] args) {
int count=0,n=25,i=0,l=5,r=0;
while(i<n){
i++;
System.out.print(i+"*");
count++;
if(count==(n/l)){
i=i+l;
count=0;
r++;
System.out.println();
}
}
i=i-(l*r-1);
for(int k=0;k<l*2;k++){
System.out.print(i+"*");
i++;
count++;
if(count==l){
i=i-(l*r);
count=0;
System.out.println();
}
}
}
}
| [
"G1willdie"
] | G1willdie |
9cff06054395130a8e04df96fb3d5a49f197fbe6 | 5d64fa845a9c2c0b62ff2accdaf713baca5f4cf9 | /app/src/main/java/com/anova/indiaadmin/SampleDetailsFragment.java | 7f16ad4fd4b173ba48018ac533ffc624be416e3f | [] | no_license | Anki10/coal-app-admin_new | 90984f594f18ae7b2c57824d9c7e52549e02891c | bb04d680d80b172420cd233981b76a8705a220b3 | refs/heads/master | 2022-04-01T20:18:21.340824 | 2020-02-08T06:24:40 | 2020-02-08T06:24:40 | 208,259,331 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 46,682 | java | package com.anova.indiaadmin;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.anova.indiaadmin.database.AppDatabase;
import com.anova.indiaadmin.database.AppDatabaseResponse;
import com.anova.indiaadmin.database.area.Area;
import com.anova.indiaadmin.database.area.SubsidiaryAreaHelper;
import com.anova.indiaadmin.database.location.AreaLocationHelper;
import com.anova.indiaadmin.database.location.Location;
import com.anova.indiaadmin.database.samples.SampleDBHelper;
import com.anova.indiaadmin.database.samples.SampleEntity;
import com.anova.indiaadmin.database.subsidiary.Subsidiary;
import com.anova.indiaadmin.database.subsidiary.SubsidiaryHelper;
import com.anova.indiaadmin.network.AppNetworkResponse;
import com.anova.indiaadmin.network.Volley;
import com.anova.indiaadmin.utils.Constants;
import com.anova.indiaadmin.utils.DecimalFilter;
import com.anova.indiaadmin.utils.FormatConversionHelper;
import com.anova.indiaadmin.utils.PreferenceHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* A simple {@link Fragment} subclass.
*/
public class SampleDetailsFragment extends Fragment implements AdapterView.OnItemSelectedListener, AppNetworkResponse, AppDatabaseResponse {
@BindView(R.id.subsidiaryName)
Spinner subsidiaryName;
Unbinder unbinder;
@BindView(R.id.areaName)
Spinner areaName;
@BindView(R.id.locationName)
Spinner locationName;
@BindView(R.id.dateCollection)
TextView dateCollection;
@BindView(R.id.liftingType)
Spinner liftingType;
@BindView(R.id.auctionType_spinner)
Spinner auctionType_spinner;
@BindView(R.id.totalQuantityLifted)
EditText totalQuantityLifted;
@BindView(R.id.totalQuantitySampled)
EditText totalQuantitySampled;
String getDate, selectedDate, sampleID = "";
String editMode = "false";
Calendar calendar;
int day = 0, month = 0, year = 0;
Calendar myCalendar = Calendar.getInstance();
HomeActivity mCallback;
@BindView(R.id.typeSampling)
Spinner typeSampling;
private String subsidery;
Double lifted_value;
JSONObject response;
JSONArray responseData;
private String location_name;
Bundle bundle;
String returnJson, areaReturn, locationReturn;
ArrayAdapter<String> liftingTypeAdapter, auctionTypeAdapter, typeSamplingAdapter, subsidiaryAdapter, areaNameAdapter, locationNameAdapter;
List<String> subsidiaryNameList = new ArrayList<String>();
List<String> areaNameList = new ArrayList<String>();
List<String> locationNameList = new ArrayList<String>();
List<String> locationCodeList = new ArrayList<>();
List<String> typeSamplingList = new ArrayList<String>();
List<String> liftingTypeList = new ArrayList<String>();
List<Subsidiary> subsidiaryList;
List<Area> areaList;
List<Location> locationsList;
List<Location> selectlocationlist;
private String location_code;
private String declared_grade;
private String submit_status = "no";
private DecimalFilter filter_decimal;
boolean firstTime = false;
boolean subsidiaryCheck = false, areaCheck = false;
String quantityLiftedPattern = "[0-9]{1,5}(\\.[0-9]{1,3})?";
boolean editModeBoolean;
private String savedTypeSampling;
private boolean overRideSamplingTypeIssue = false;
public interface OpenCustomerInterface {
public void openCustomerFrag(String i, boolean firstTimeCheck, String liftType, boolean deleteExistingCustomers);
}
@TargetApi(23)
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.e(TAG, "onAttach context");
try {
mCallback = (HomeActivity) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement IFragmentToActivity");
}
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.e(TAG, "onAttach activity");
try {
mCallback = (HomeActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement IFragmentToActivity");
}
}
@Override
public void onDetach() {
mCallback = null;
super.onDetach();
}
public SampleDetailsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sample_details, container, false);
unbinder = ButterKnife.bind(this, view);
totalQuantitySampled.addTextChangedListener(new DecimalInputTextWatcher(totalQuantitySampled, 3));
bundle = getArguments();
Log.e(TAG, "onCreate");
/*if(bundle!=null)
{
editMode=bundle.getString("editMode");
if(editMode.equals("true")) {
returnJson = bundle.getString("returnJson");
}
Log.e("data",editMode+" : "+returnJson);
}*/
//
//totalQuantityLifted.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
return view;
}
private void getData(JSONObject responseJSON) {
Logger.json(responseJSON.toString());
/* "sample_id": "4",
"sample_user_id": "1",
"subsidiary_name": "Business Services",
"area": "Business Services",
"location": "Business Services",
"date_of_collection": "2018-02-24",
"lifting_type": "Business Services",
"auction_type": "Business Services",
"quantity_lifted": "5.00",
"quantity_sampled": "5.00",
"sampling_type": "base",*/
try {
SampleEntity sampleEntity = new Gson().fromJson(responseJSON.toString(), new TypeToken<SampleEntity>() {
}.getType());
sampleID = String.valueOf(PreferenceHelper.getInteger(Constants.SP_KEY_CURRENT_COLLECTION_ID));
getDate = getFromPrefs(Constants.date);
areaReturn = responseJSON.getString("area");
locationReturn = responseJSON.getString("location");
selectedDate = getDate;
if (!selectedDate.isEmpty()){
dateCollection.setText(getDate);
dateCollection.setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
totalQuantitySampled.setText(responseJSON.getString("quantitySampled"));
totalQuantityLifted.setText(responseJSON.getString("quantityLifted"));
mCallback.challanNumber = sampleEntity.getChallanNumber();
mCallback.qciNumber = sampleEntity.getQciNumber();
subsidery = responseJSON.getString("subsidiaryName");
if (responseJSON.getString("subsidiaryName") != null) {
int spinnerPosition = subsidiaryAdapter.getPosition(responseJSON.getString("subsidiaryName"));
subsidiaryName.setSelection(spinnerPosition);
if (subsidiaryList != null && spinnerPosition > 0) {
getAreaList(subsidiaryList.get(spinnerPosition - 1).getId());
}
}
if (responseJSON.getString("location") != null){
location_name = responseJSON.getString("location");
}
if (responseJSON.getString("liftingType") != null) {
int spinnerPosition = liftingTypeAdapter.getPosition(responseJSON.getString("liftingType"));
liftingType.setSelection(spinnerPosition);
}
String lifting_type = responseJSON.getString("liftingType");
typeSamplingList.clear();
typeSamplingList.add("Type of Sampling");
/* typeSamplingList.add("Gross");
typeSamplingList.add("Individual");*/
System.out.println("xxx" + liftingType.getSelectedItemId());
if (lifting_type.equalsIgnoreCase("Rail")) {
// typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
typeSamplingList.add("Multigrade sampling");
} else {
typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
}
typeSamplingAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, typeSamplingList);
typeSamplingAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
if (responseJSON.getString("samplingType") != null) {
final int spinnerPosition = typeSamplingAdapter.getPosition(responseJSON.getString("samplingType"));
typeSampling.setSelection(spinnerPosition);
View v = typeSampling.getSelectedView();
((TextView)v).setTextColor(getResources().getColor(R.color.colorDarkGrey));
// savedTypeSampling = responseJSON.getString("samplingType");
}
Log.e("sample_data_2", sampleID);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onResume() {
super.onResume();
subsidiaryCheck = false;
areaCheck = false;
try {
mCallback = (HomeActivity) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement IFragmentToActivity");
}
Log.e(TAG, "onResume");
setAdapters();
checkSession();
if (editMode.equals("true")) {
firstTime = true;
subsidiaryCheck = true;
areaCheck = true;
//getData();
}
}
public void setAdapters() {
Log.e(TAG, "setAdapter");
subsidiaryNameList.clear();
subsidiaryNameList.add("Name of Subsidiary");
SubsidiaryHelper.ManageSubsidiaries selectAllSubsidiaries = new SubsidiaryHelper.ManageSubsidiaries(AppDatabase.getAppDatabase(getActivity()), this, Constants.SELECT_ALL_SUBSIDIARIES, null, AppDatabase.SELECT_ACTION);
selectAllSubsidiaries.execute();
subsidiaryAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, subsidiaryNameList);
subsidiaryAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
subsidiaryName.setAdapter(subsidiaryAdapter);
subsidiaryName.setOnItemSelectedListener(this);
areaNameList.clear();
areaNameList.add("Name of Area");
areaNameAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, areaNameList);
areaNameAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
areaName.setAdapter(areaNameAdapter);
areaName.setOnItemSelectedListener(this);
locationNameList.clear();
locationNameList.add("Name of Location");
locationNameAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, locationNameList);
locationNameAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
locationName.setAdapter(locationNameAdapter);
locationName.setOnItemSelectedListener(this);
liftingTypeList.clear();
liftingTypeList.add("Mode");
liftingTypeList.add("Road");
liftingTypeList.add("Rail");
liftingTypeAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, liftingTypeList);
liftingTypeAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
liftingType.setAdapter(liftingTypeAdapter);
liftingType.setOnItemSelectedListener(this);
/* auctionTypeList.clear();
auctionTypeList.add("Auction Type");
auctionTypeList.add("Linkage");
auctionTypeList.add("Special Forwad E-auction");
auctionTypeList.add("Spot");
auctionTypeList.add("Exclusive auction");
auctionTypeList.add("Shakti");
auctionTypeAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, auctionTypeList);
auctionTypeAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
auctionType_spinner.setAdapter(auctionTypeAdapter);
auctionType_spinner.setOnItemSelectedListener(this);*/
typeSamplingList.clear();
typeSamplingList.add("Type of Sampling");
/* typeSamplingList.add("Gross");
typeSamplingList.add("Individual");*/
System.out.println("xxx" + liftingType.getSelectedItemId());
if (liftingType.getSelectedItemId() == 1) {
// typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
typeSamplingList.add("Multigrade sampling");
} else {
typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
}
typeSamplingAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simple_spinner_item, typeSamplingList);
typeSamplingAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
typeSampling.setAdapter(typeSamplingAdapter);
typeSampling.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
try {
String item = parent.getItemAtPosition(position).toString();
switch (parent.getId()) {
case R.id.subsidiaryName:
if (!item.equals("Name of Subsidiary")) {
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
if (subsidiaryList == null || position <= 0) {
break;
}
int selectedSubsidiaryId = subsidiaryList.get(position - 1).getId();
String name = subsidiaryList.get(position - 1).getName();
if (subsidery != null){
if (subsidery.equalsIgnoreCase(name)){
subsidiaryCheck = false;
}else {
subsidiaryCheck = true;
}
}else {
subsidiaryCheck = true;
}
Log.e(TAG, "spinner clicked : " + item + " : (sub_check = " + Boolean.toString(subsidiaryCheck) + ") : (volleyCheck = " + "( : (areaCheck = " + Boolean.toString(areaCheck));
if (mCallback.isNew || subsidiaryCheck) {
if (!item.equals("Name of Subsidiary")) {
getAreaList(selectedSubsidiaryId);
areaCheck = true;
}
} else {
subsidiaryCheck = true;
}
break;
case R.id.areaName:
if (!item.equals("Name of Area")) {
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
if (areaList == null || position <= 0) {
break;
}
int selectedAreaId = areaList.get(position - 1).getId();
Log.e(TAG, "spinner clicked : " + item + " : (sub_check = " + Boolean.toString(subsidiaryCheck) + ") : (volleyCheck = " + "( : (areaCheck = " + Boolean.toString(areaCheck));
if (mCallback.isNew || areaCheck) {
if (!item.equals("Name of Area")) {
getLocationList(selectedAreaId);
}
} else {
areaCheck = true;
}
break;
case R.id.locationName:
if (!item.equals("Name of Location")){
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
break;
case R.id.liftingType:
if (!item.equals("Mode")){
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
typeSamplingList.clear();
System.out.println("xxx" + liftingType.getSelectedItemId());
if (liftingType.getSelectedItemId() == 2) {
// typeSamplingList.add("Gross");
typeSamplingList.add("Type of Sampling");
typeSamplingList.add("Individual");
typeSamplingList.add("Multigrade sampling");
totalQuantityLifted.setEnabled(true);
// totalQuantityLifted.setCursorVisible(false);
} else if (liftingType.getSelectedItemId() == 0) {
typeSamplingList.add("Type of Sampling");
typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
totalQuantityLifted.setFocusable(true);
} else if (liftingType.getSelectedItemId() == 1) {
typeSamplingList.add("Type of Sampling");
typeSamplingList.add("Gross");
typeSamplingList.add("Individual");
totalQuantityLifted.setEnabled(false);
}
typeSamplingAdapter.notifyDataSetChanged();
break;
case R.id.typeSampling:
if (!item.equals("Type of Sampling")){
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
break;
case R.id.auctionType_spinner:
if (!item.equals("Auction Type")){
((TextView) parent.getChildAt(0)).setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
System.out.println("xxx auction");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getAreaList(int subsidiaryId) {
areaNameList.clear();
areaNameList.add("Name of Area");
areaName.setSelection(0);
locationNameList.clear();
locationNameList.add("Name of Location");
// locationName.setSelection(0);
SubsidiaryAreaHelper.ManageSubsidiaryArea getSubsidiaryAreas = new SubsidiaryAreaHelper.ManageSubsidiaryArea(AppDatabase.getAppDatabase(getActivity()), this, Constants.SELECT_AREA_BY_SUBSIDIARY, null, subsidiaryId, SubsidiaryAreaHelper.SELECT_BY_SUBSIDIARY_ACTION);
getSubsidiaryAreas.execute();
}
private void getLocationList(int areaId) {
locationNameList.clear();
locationNameList.add("Name of Location");
// locationName.setSelection(0);
AreaLocationHelper.ManageAreaLocation getAreaLocations = new AreaLocationHelper.ManageAreaLocation(AppDatabase.getAppDatabase(getActivity()), this, Constants.SELECT_LOCATIONS_BY_AREA, null, areaId, AreaLocationHelper.SELECT_BY_AREA_ACTION);
getAreaLocations.execute();
locationCodeList.add("Name of code");
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onStop() {
super.onStop();
try {
String sub_name = ((String) subsidiaryName.getSelectedItem());
String area_name = ((String) areaName.getSelectedItem());
String location = ((String) locationName.getSelectedItem());
if (submit_status.equalsIgnoreCase("No")){
if (!sub_name.equalsIgnoreCase("Name of Subsidiary") && !area_name.equalsIgnoreCase("Name of Area") && !location.equalsIgnoreCase("Name of Location")){
sendSampling();
}
mCallback.isNew = false;
}
}catch (Exception e){
e.printStackTrace();
}
}
@OnClick({R.id.dateCollection, R.id.submit})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.dateCollection:
DatePickerDialog datePickerDialog =
new DatePickerDialog(getActivity(), R.style.DateDialogTheme, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
Calendar c = Calendar.getInstance();
c.setTime(new Date());
datePickerDialog.getDatePicker().setMaxDate(c.getTime().getTime());
c.add(Calendar.MONTH, -3);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
datePickerDialog.show();
break;
case R.id.submit:
if (validationCheck()) {
submit_status = "yes";
sendSampling();
mCallback.isNew = false;
}
break;
}
}
/* public void saveSample(){
saveIntoPrefs(Constants.SubsidiaryName, (String) subsidiaryName.getSelectedItem());
saveIntoPrefs(Constants.Area_Location, (String) areaName.getSelectedItem());
saveIntoPrefs(Constants.Location_code,location_code);
saveIntoPrefs(Constants.date, selectedDate);
saveIntoPrefs(Constants.LOCAlSAVE,"No");
}*/
public void sendSampling() {
//TODO save this in local db along with updatedAt and stop fetching data from session
try {
if (savedTypeSampling != null && savedTypeSampling.equalsIgnoreCase("gross") && !((String) typeSampling.getSelectedItem()).equalsIgnoreCase("gross")) {
if (overRideSamplingTypeIssue) {
//do nothing and let it delete all customers
} else {
new AlertDialog.Builder(getActivity())
.setTitle("Warning")
.setMessage("You have changed sampling type from Gross to Individual, This will delete existing saved customers")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
overRideSamplingTypeIssue = true;
}
})
.setNegativeButton(android.R.string.no, null).show();
return;
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("sample_id", sampleID);
jsonObject.put("subsidiary", subsidiaryName.getSelectedItem());
jsonObject.put("area", areaName.getSelectedItem());
jsonObject.put("location", locationName.getSelectedItem());
jsonObject.put("collection_date", selectedDate);
jsonObject.put("lifting_type", liftingType.getSelectedItem());
jsonObject.put("auction_type", auctionType_spinner.getSelectedItem());
jsonObject.put("lifted_quantity", totalQuantityLifted.getText().toString());
jsonObject.put("sampled_quantity", totalQuantitySampled.getText().toString());
jsonObject.put("sampling_type", typeSampling.getSelectedItem());
jsonObject.put("editMode", Boolean.valueOf(editMode));
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setSubsidiaryName((String) subsidiaryName.getSelectedItem());
sampleEntity.setArea((String) areaName.getSelectedItem());
sampleEntity.setLocation((String) locationName.getSelectedItem());
sampleEntity.setIsPrimary("false");
sampleEntity.setCollectionDate(selectedDate);
sampleEntity.setLiftingType((String) liftingType.getSelectedItem());
sampleEntity.setAuctionType((String) auctionType_spinner.getSelectedItem());
sampleEntity.setQuantityLifted(totalQuantityLifted.getText().toString());
sampleEntity.setQuantitySampled(totalQuantitySampled.getText().toString());
sampleEntity.setSamplingType((String) typeSampling.getSelectedItem());
mCallback.samplingType = (String) typeSampling.getSelectedItem();
mCallback.subsidiary = sampleEntity.getSubsidiaryName();
mCallback.area = sampleEntity.getArea();
mCallback.location = sampleEntity.getLocation();
/* if (sampleEntity.getAuctionType().equalsIgnoreCase("Special Forwad E-auction")) {
mCallback.auction_type = sampleEntity.getAuctionType();
} else {
mCallback.auction_type = sampleEntity.getAuctionType() + " Auction";
}*/
for (int i=0;i<locationsList.size();i++){
if (((String) locationName.getSelectedItem()).equalsIgnoreCase(locationsList.get(i).getName())){
location_code = locationsList.get(i).getLocation_code();
declared_grade = locationsList.get(i).getDeclared_grade();
}
}
sampleEntity.setLocation_code(location_code);
saveIntoPrefs(Constants.SubsidiaryName, sampleEntity.getSubsidiaryName());
saveIntoPrefs(Constants.Area_Location, sampleEntity.getLocation());
saveIntoPrefs(Constants.Location_code,location_code);
saveIntoPrefs(Constants.declared_grade,declared_grade);
saveIntoPrefs(Constants.date, sampleEntity.getCollectionDate());
if (sampleID != null && sampleID.length() > 0) {
sampleEntity.setLocalSampleId(Integer.parseInt(sampleID));
SampleDBHelper sampleDBHelper = new SampleDBHelper(AppDatabase.getAppDatabase(getActivity()), this);
sampleDBHelper.updateSample(sampleEntity, Constants.UPDATE_SAMPLE);
} else {
SampleDBHelper sampleDBHelper = new SampleDBHelper(AppDatabase.getAppDatabase(getActivity()), this);
sampleDBHelper.insertSample(sampleEntity, Constants.INSERT_SAMPLE);
}
Log.e("json", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean validationCheck() {
if (liftingType.getSelectedItemId() == 1) {
try {
if (subsidiaryName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Subsidiary Name", Toast.LENGTH_SHORT).show();
} else if (areaName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Area Name", Toast.LENGTH_SHORT).show();
} else if (locationName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Location Name", Toast.LENGTH_SHORT).show();
} else if (selectedDate == null) {
Toast.makeText(getActivity(), "Select Date of Collection", Toast.LENGTH_SHORT).show();
} else if (liftingType.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Mode", Toast.LENGTH_SHORT).show();
} /*else if (auctionType_spinner.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Auction Type", Toast.LENGTH_SHORT).show();
}*/ else if (totalQuantitySampled.getText().length() == 0) {
Toast.makeText(getActivity(), "Enter Total Quantity Sampled", Toast.LENGTH_SHORT).show();
} else if (!(totalQuantitySampled.getText().toString()).matches(quantityLiftedPattern)) {
Toast.makeText(getActivity(), "Sample Quantity should 5 digit upto 3 decimal place only", Toast.LENGTH_SHORT).show();
totalQuantitySampled.setText("");
}
else if (!isValidFloat(totalQuantitySampled.getText().toString())) {
Toast.makeText(getActivity(), "Total Quantity Sampled input is invalid", Toast.LENGTH_SHORT).show();
} else if (typeSampling.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Type Sampling", Toast.LENGTH_SHORT).show();
} else {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} else {
try {
if (totalQuantityLifted.getText().toString().length() > 0){
lifted_value = (Double.parseDouble(totalQuantityLifted.getText().toString()) * 1000);
}
}catch (Exception e){
e.printStackTrace();
}
try {
if (subsidiaryName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Subsidiary Name", Toast.LENGTH_SHORT).show();
} else if (areaName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Area Name", Toast.LENGTH_SHORT).show();
} else if (locationName.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Location Name", Toast.LENGTH_SHORT).show();
} else if (selectedDate == null) {
Toast.makeText(getActivity(), "Select Date of Collection", Toast.LENGTH_SHORT).show();
} else if (liftingType.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Mode", Toast.LENGTH_SHORT).show();
} /*else if (auctionType_spinner.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Auction Type", Toast.LENGTH_SHORT).show();
}*/ /*else if (totalQuantityLifted.getText().length() == 0) {
Toast.makeText(getActivity(), "Enter Total Quantity Lifted", Toast.LENGTH_SHORT).show();
} *//*else if (!(totalQuantityLifted.getText().toString()).matches(quantityLiftedPattern)) {
Toast.makeText(getActivity(), "Quantity Lifted should 5 digit upto 2 decimal place only", Toast.LENGTH_SHORT).show();
totalQuantityLifted.setText("");
} else if (!isValidFloat(totalQuantityLifted.getText().toString())) {
Toast.makeText(getActivity(), "Total Quantity Lifted input is invalid", Toast.LENGTH_SHORT).show();
}*/ else if (totalQuantitySampled.getText().length() == 0) {
Toast.makeText(getActivity(), "Enter Total Quantity Sampled", Toast.LENGTH_SHORT).show();
} else if (!(totalQuantitySampled.getText().toString()).matches(quantityLiftedPattern)) {
Toast.makeText(getActivity(), "Sample Quantity should 5 digit upto 2 decimal place only", Toast.LENGTH_SHORT).show();
totalQuantitySampled.setText("");
} else if (!isValidFloat(totalQuantitySampled.getText().toString())) {
Toast.makeText(getActivity(), "Total Quantity Sampled input is invalid", Toast.LENGTH_SHORT).show();
} else if (typeSampling.getSelectedItemId() == 0) {
Toast.makeText(getActivity(), "Select Type Sampling", Toast.LENGTH_SHORT).show();
}/* else if (totalQuantityLifted.getText().toString().length() > 0 && lifted_value < Double.parseDouble(totalQuantitySampled.getText().toString())) {
Toast.makeText(getActivity(), "Sample Quantity should be less than or equal to Quantity Lifted", Toast.LENGTH_SHORT).show();
totalQuantitySampled.setText("");
}*/
else {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
public boolean isValidFloat(String value) {
try {
float temp = Float.valueOf(value);
} catch (Exception e) {
return false;
}
return true;
}
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
year = year;
month = monthOfYear + 1;
day = dayOfMonth;
selectedDate = FormatConversionHelper.getFormatedDateTime(day + "-" + month + "-" + year, "dd-MM-yyyy", "dd-MM-yyyy");
Log.e("date", "selectDate after change " + selectedDate);
dateCollection.setText(selectedDate);
dateCollection.setTextColor(getResources().getColor(R.color.colorDarkGrey));
}
};
@Override
public void onDatabaseResSuccess(JSONObject jsonObject, int reqCode) {
switch (reqCode) {
case Constants.SELECT_ALL_SUBSIDIARIES: {
try {
if (jsonObject != null) {
Logger.json(jsonObject.toString());
Gson gson = new Gson();
Type listType = new TypeToken<List<Subsidiary>>() {
}.getType();
subsidiaryList = gson.fromJson(jsonObject.getJSONArray("data").toString(), listType);
for (Subsidiary subsidiary : subsidiaryList) {
subsidiaryNameList.add(subsidiary.getName());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
case Constants.SELECT_AREA_BY_SUBSIDIARY: {
try {
if (jsonObject != null) {
Logger.json(jsonObject.toString());
Gson gson = new Gson();
Type listType = new TypeToken<List<Area>>() {
}.getType();
areaList = gson.fromJson(jsonObject.getJSONArray("data").toString(), listType);
for (Area area : areaList) {
areaNameList.add(area.getName());
}
areaNameAdapter.notifyDataSetChanged();
if (areaReturn != null && areaReturn.length() > 0) {
int spinnerPosition = areaNameAdapter.getPosition(areaReturn);
areaReturn = null;
areaName.setSelection(spinnerPosition);
if (areaList != null && spinnerPosition > 0) {
getLocationList(areaList.get(spinnerPosition - 1).getId());
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
case Constants.SELECT_LOCATIONS_BY_AREA: {
try {
if (jsonObject != null) {
Logger.json(jsonObject.toString());
Gson gson = new Gson();
Type listType = new TypeToken<List<Location>>() {
}.getType();
locationsList = gson.fromJson(jsonObject.getJSONArray("data").toString(), listType);
for (Location location : locationsList) {
locationNameList.add(location.getName());
locationCodeList.add(location.getLocation_code());
}
locationNameAdapter.notifyDataSetChanged();
if (locationReturn != null && locationReturn.length() > 0) {
int spinnerPosition = locationNameAdapter.getPosition(locationReturn);
locationReturn = null;
locationName.setSelection(spinnerPosition);
}
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case Constants.INSERT_SAMPLE: {
if (jsonObject != null) {
try {
sampleID = String.valueOf(jsonObject.getLong("sampleId"));
PreferenceHelper.putInteger(Constants.SP_KEY_CURRENT_COLLECTION_ID, Integer.valueOf(sampleID));
// Toast.makeText(getActivity(), "Sample Detail Saved at " + sampleID, Toast.LENGTH_SHORT).show();
if (submit_status.equalsIgnoreCase("yes")) {
mCallback.openCustomerFrag(sampleID, firstTime, liftingType.getSelectedItem().toString(), overRideSamplingTypeIssue);
}Log.e("sampleID_sa", sampleID + " : " + Boolean.valueOf(firstTime));
} catch (JSONException e) {
e.printStackTrace();
}
}
break;
}
case Constants.UPDATE_SAMPLE: {
// Toast.makeText(mCallback, "Sample data updated", Toast.LENGTH_SHORT).show();
Log.e("sampleID_sa", sampleID + " : " + Boolean.valueOf(firstTime));
if (submit_status.equalsIgnoreCase("yes")){
try {
mCallback.openCustomerFrag(sampleID, firstTime, liftingType.getSelectedItem().toString(), overRideSamplingTypeIssue);
}catch (Exception e){
e.printStackTrace();
}
}
}
case Constants.SELECT_SAMPLE_BY_ID: {
if (jsonObject != null) {
Logger.d(jsonObject);
getData(jsonObject);
}
}
}
}
@Override
public void onResSuccess(JSONObject jsonObject, int reqCode) {
Log.e("ResSuccess", jsonObject + " : " + reqCode);
switch (reqCode) {
case Constants.REQ_POST_CHECK_LOGIN:
try {
response = jsonObject;
editModeBoolean = response.getBoolean("editMode");
if (editModeBoolean) {
returnJson = response.getString("return");
editMode = "true";
// getData();
Log.e(TAG, Boolean.toString(editModeBoolean) + " : " + returnJson);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
@Override
public void onResFailure(String errCode, String errMsg, int reqCode, JSONObject jsonObject) {
Log.e("ResFailure", reqCode + " : " + errMsg);
Toast.makeText(getActivity(), errMsg, Toast.LENGTH_SHORT).show();
switch (reqCode) {
case Constants.REQ_POST_CHECK_LOGIN:
Intent in = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
startActivity(in);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().finish();
break;
}
}
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
String session;
final String TAG = "SampleDetailFrag";
private void checkSession() {
if (PreferenceHelper.contains("session")) {
session = (PreferenceHelper.getString("session", "NA"));
Log.i(TAG, "session " + session);
if (PreferenceHelper.getInteger(Constants.SP_KEY_CURRENT_COLLECTION_ID, 0) > 0) {
sampleID = String.valueOf(PreferenceHelper.getInteger(Constants.SP_KEY_CURRENT_COLLECTION_ID));
getSampleDataFromDB(PreferenceHelper.getInteger(Constants.SP_KEY_CURRENT_COLLECTION_ID));
}
// getDataFromSession(session);
} else {
Log.i(TAG, "session NA");
Toast.makeText(getActivity(), "Please Login", Toast.LENGTH_SHORT).show();
Intent in = new Intent(getActivity().getApplicationContext(), LoginActivity.class);
startActivity(in);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().finish();
}
}
private void getSampleDataFromDB(int localSampleId) {
SampleDBHelper sampleDBHelper = new SampleDBHelper(AppDatabase.getAppDatabase(getActivity()), this);
sampleDBHelper.getSampleById(localSampleId, Constants.SELECT_SAMPLE_BY_ID);
}
//TODO don't get the data from session, get the selected sampling record data from local DB
private void getDataFromSession(String session) {
Volley volley = Volley.getInstance();
JSONObject jsonObject = null;
volley.postSession(Constants.apiCheckLogin, jsonObject, this, session, Constants.REQ_POST_CHECK_LOGIN);
}
public void saveIntoPrefs(String key, String value) {
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.PREF_NAME, getActivity().MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(key, value);
edit.commit();
}
public String getFromPrefs(String key) {
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.PREF_NAME, getActivity().MODE_PRIVATE);
return prefs.getString(key, "");
}
public class DecimalInputTextWatcher implements TextWatcher {
private String mPreviousValue;
private int mCursorPosition;
private boolean mRestoringPreviousValueFlag;
private int mDigitsAfterZero;
private EditText mEditText;
public DecimalInputTextWatcher(EditText editText, int digitsAfterZero) {
mDigitsAfterZero = digitsAfterZero;
mEditText = editText;
mPreviousValue = "";
mRestoringPreviousValueFlag = false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (!mRestoringPreviousValueFlag) {
mPreviousValue = s.toString();
mCursorPosition = mEditText.getSelectionStart();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!mRestoringPreviousValueFlag) {
if (!isValid(s.toString())) {
mRestoringPreviousValueFlag = true;
restorePreviousValue();
}
} else {
mRestoringPreviousValueFlag = false;
}
}
private void restorePreviousValue() {
mEditText.setText(mPreviousValue);
mEditText.setSelection(mCursorPosition);
}
private boolean isValid(String s) {
Pattern patternWithDot = Pattern.compile("[0-9]*((\\.[0-9]{0," + mDigitsAfterZero + "})?)||(\\.)?");
Pattern patternWithComma = Pattern.compile("[0-9]*((,[0-9]{0," + mDigitsAfterZero + "})?)||(,)?");
Matcher matcherDot = patternWithDot.matcher(s);
Matcher matcherComa = patternWithComma.matcher(s);
return matcherDot.matches() || matcherComa.matches();
}
}
}
| [
"ankitmiglani10@gmail.com"
] | ankitmiglani10@gmail.com |
9daa78786d1057fec08dea48edb1d16476347578 | ca0e9689023cc9998c7f24b9e0532261fd976e0e | /src/com/tencent/mm/ah/w.java | 3a8f86602d2b42f437ff51cc8b4541815ef02e99 | [] | no_license | honeyflyfish/com.tencent.mm | c7e992f51070f6ac5e9c05e9a2babd7b712cf713 | ce6e605ff98164359a7073ab9a62a3f3101b8c34 | refs/heads/master | 2020-03-28T15:42:52.284117 | 2016-07-19T16:33:30 | 2016-07-19T16:33:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 271 | java | package com.tencent.mm.ah;
import com.tencent.mm.ar.g.b;
final class w
implements g.b
{
public final String[] lW()
{
return ac.aqU;
}
}
/* Location:
* Qualified Name: com.tencent.mm.ah.w
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"reverseengineeringer@hackeradmin.com"
] | reverseengineeringer@hackeradmin.com |
6bbbeb221ef138bf5ab3a19e5b2a040580789a64 | 7babc8d969e1e0878a1917901b10c1777c128b03 | /ddl-concurrency/src/main/java/com/ddl/concurrency/designpattern/immutable/ImmutableTest.java | 933f75b3fc33e1d50364ef43783171ff2a5b753c | [] | no_license | vigour0423/ddlall | 430912dde1a3cd881d29b017f2952ec4b727d852 | 7915abf5f9e93391cefdbb8d75952b6755fcca48 | refs/heads/master | 2022-12-25T05:29:28.990336 | 2020-05-14T15:43:05 | 2020-05-14T15:43:05 | 154,122,468 | 0 | 2 | null | 2022-12-16T09:45:08 | 2018-10-22T10:05:15 | Java | UTF-8 | Java | false | false | 610 | java | package com.ddl.concurrency.designpattern.immutable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ImmutableTest {
private final int age;
private final String name;
private final List<String> list;
public ImmutableTest(int age, String name) {
this.age = age;
this.name = name;
list = new ArrayList<>();
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public List<String> getList() {
return Collections.unmodifiableList(list);
}
} | [
"489582986@qq.com"
] | 489582986@qq.com |
dbdf18a49bcd1c2464f96eb62e2e24feb4c8d098 | babf81c29cede6d3f2600a7ec9d6e1c16daf836c | /app/src/main/java/com/example/taxipot_android/domain/usecase/ReportSelReasonUseCaseImpl.java | 08dc7de0d748bc1c6d69c883aac95f4b969da0b4 | [] | no_license | TaxiPot/TaxiPot_Android | 1a3b75a6f1250d61ada99381c815071487ff6272 | f930ba577751fa20217024f457008afb159fdb1e | refs/heads/master | 2020-07-07T10:03:38.448034 | 2019-12-02T11:06:05 | 2019-12-02T11:06:05 | 203,319,809 | 4 | 2 | null | 2019-11-30T19:59:57 | 2019-08-20T07:07:50 | Java | UTF-8 | Java | false | false | 641 | java | package com.example.taxipot_android.domain.usecase;
import com.example.taxipot_android.domain.entity.Report;
import com.example.taxipot_android.domain.repository.ReportSelReasonRepository;
import io.reactivex.observers.DisposableObserver;
public class ReportSelReasonUseCaseImpl extends ReportSelReasonUseCase<Report> {
private ReportSelReasonRepository repository;
public ReportSelReasonUseCaseImpl(ReportSelReasonRepository repository) {
this.repository = repository;
}
@Override
public void doReport(int num, DisposableObserver disposable) {
execute(repository.doReport(num),disposable);
}
}
| [
"nwar0825@naver.com"
] | nwar0825@naver.com |
309853ebd2799c13ef46b1101117a64c4a50920e | 163e7b1662d28385ce7482fbc7e92d2bba86136a | /src/RemplacementImpossibleException.java | af8f1dd2e8a879823fc867c898ac21d7d4544c36 | [] | no_license | WissemeAkli/QuizPlateform | e37c349e538e2787ac7c6f67327add407313827b | 76430d2a30dd32e160e658fbef46d73112447519 | refs/heads/master | 2020-09-21T21:08:37.797563 | 2019-11-29T22:44:16 | 2019-11-29T22:44:16 | 224,931,056 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263 | java | public class RemplacementImpossibleException extends Exception {
public RemplacementImpossibleException (){
System.out.println("Le nombre maximal de questions abordant cette notion est déja atteint! \nOn ne peut remplacer aucune question");
}
}
| [
"gw_akli@esi.dz"
] | gw_akli@esi.dz |
0be3ffc09c7e85fef62a12f05211aeefff1d0c2e | 94530bf3b4f3406c0eed7d631cdef301d04b4e31 | /app/src/main/java/com/nanchen/rxjava2examples/practice/main.java | 8b9afd30fb1aa01cf3602728f6b844079051026a | [
"Apache-2.0"
] | permissive | GeJieZhang/RxJava2Examples-master | df6ee89fd90071e48dd82a362f1f968e7e2e1392 | b2cb8fb970b31a76dc720d147f64c1e70080ba7b | refs/heads/master | 2021-07-13T01:09:17.755854 | 2017-10-12T05:13:34 | 2017-10-12T05:13:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,986 | java | package com.nanchen.rxjava2examples.practice;
import android.util.Log;
import com.nanchen.rxjava2examples.practice.bean.Result;
import java.io.File;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by TR 105 on 2017/8/4.
*/
public class main {
public static void main(String[] args) {
// HttpClient httpClient = new HttpClient();
// httpClient.getRectService().getManagerData(1, 10, 1024).enqueue(new Callback<BaseResponse<Result>>() {
// @Override
// public void onResponse(Call<BaseResponse<Result>> call, Response<BaseResponse<Result>> response) {
//
//
// List<Result> list = response.body().rest;
//
// for (Result result : list) {
// System.out.print(result.getImagesUrls());
// }
// }
//
// @Override
// public void onFailure(Call<BaseResponse<Result>> call, Throwable t) {
//
// }
// });
new HttpClient()
.getRectService()
.getManagerData(1, 10, 1024)
.subscribe(new Consumer<BaseResponse<Result>>() {
@Override
public void accept(BaseResponse<Result> baseResponse) throws Exception {
Log.e("================", baseResponse.rest.toString());
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.e("================", throwable.getMessage());
}
});
}
}
| [
"1241577948@qq.com"
] | 1241577948@qq.com |
5b0b4bcd3452c957ac2fd49f5f7e0167e2640476 | 3a3a46a7441cd672170f051f7cb0091af34a71b0 | /src/volume_007_Problem_700_to_799/Problem_748.java | 81c3b3fe08fd4901137c346c44e69220123890b8 | [] | no_license | saddathasan/uvaSolved | d39454861dd73dfac8806243cb978b4f7fec7058 | 8f8665d2bce701d302491714a0bf57159dc63615 | refs/heads/master | 2020-03-12T15:09:08.043720 | 2018-04-23T11:08:13 | 2018-04-23T11:08:13 | 130,684,012 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,029 | java | /**
*
*/
package volume_007_Problem_700_to_799;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Scanner;
/**
* @author Saddat Hasan
*
*
*Exponentiation
*/
public class Problem_748 {
public static void main(String[] args) throws IOException {
Scanner k = new Scanner(System.in);
StringBuffer sb = new StringBuffer("");
String m = "";
while (k.hasNext()) {
String str = k.next();
int ex = k.nextInt();
BigDecimal bd = new BigDecimal(str);
BigDecimal result=bd.pow(ex);
result = zeros(result);
String temp = result.toPlainString();
if (temp.charAt(0) == '0') {
temp = temp.substring(1);
}
sb.append(temp).append("\n");
}
System.out.print(sb);
}
public static BigDecimal zeros(BigDecimal number) {
try {
while (true) {
number = number.setScale(number.scale() - 1);
}
}
catch (ArithmeticException e) {
}
return number;
}
}
| [
"dr.zola@hydra-machine.local"
] | dr.zola@hydra-machine.local |
0f312bca701a35ee82dc6297cb4bcae6d66ab03d | d280800ca4ec277f7f2cdabc459853a46bf87a7c | /spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java | 4ac118630e0a6e3bcf32dc8e15bfe4bd0b11a684 | [
"Apache-2.0"
] | permissive | qqqqqcjq/spring-boot-2.1.x | e5ca46d93eeb6a5d17ed97a0b565f6f5ed814dbb | 238ffa349a961d292d859e6cc2360ad53b29dfd0 | refs/heads/master | 2023-03-12T12:50:11.619493 | 2021-03-01T05:32:52 | 2021-03-01T05:32:52 | 343,275,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,401 | java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.servlet;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Abstract base for {@link AbstractFilterRegistrationBean} tests.
*
* @author Phillip Webb
*/
public abstract class AbstractFilterRegistrationBeanTests {
@Mock
ServletContext servletContext;
@Mock
FilterRegistration.Dynamic registration;
@Before
public void setupMocks() {
MockitoAnnotations.initMocks(this);
given(this.servletContext.addFilter(anyString(), any(Filter.class))).willReturn(this.registration);
}
@Test
public void startupWithDefaults() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter());
verify(this.registration).setAsyncSupported(true);
verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
@Test
public void startupWithSpecifiedValues() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.setName("test");
bean.setAsyncSupported(false);
bean.setInitParameters(Collections.singletonMap("a", "b"));
bean.addInitParameter("c", "d");
bean.setUrlPatterns(new LinkedHashSet<>(Arrays.asList("/a", "/b")));
bean.addUrlPatterns("/c");
bean.setServletNames(new LinkedHashSet<>(Arrays.asList("s1", "s2")));
bean.addServletNames("s3");
bean.setServletRegistrationBeans(Collections.singleton(mockServletRegistration("s4")));
bean.addServletRegistrationBeans(mockServletRegistration("s5"));
bean.setMatchAfter(true);
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("test"), getExpectedFilter());
verify(this.registration).setAsyncSupported(false);
Map<String, String> expectedInitParameters = new HashMap<>();
expectedInitParameters.put("a", "b");
expectedInitParameters.put("c", "d");
verify(this.registration).setInitParameters(expectedInitParameters);
verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/a", "/b", "/c");
verify(this.registration).addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "s4", "s5", "s1",
"s2", "s3");
}
@Test
public void specificName() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.setName("specificName");
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("specificName"), getExpectedFilter());
}
@Test
public void deducedName() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter());
}
@Test
public void disable() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.setEnabled(false);
bean.onStartup(this.servletContext);
verify(this.servletContext, never()).addFilter(eq("mockFilter"), getExpectedFilter());
}
@Test
public void setServletRegistrationBeanMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletRegistrationBeans(null))
.withMessageContaining("ServletRegistrationBeans must not be null");
}
@Test
public void addServletRegistrationBeanMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException()
.isThrownBy(() -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null))
.withMessageContaining("ServletRegistrationBeans must not be null");
}
@Test
public void setServletRegistrationBeanReplacesValue() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean(mockServletRegistration("a"));
bean.setServletRegistrationBeans(
new LinkedHashSet<ServletRegistrationBean<?>>(Arrays.asList(mockServletRegistration("b"))));
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), false, "b");
}
@Test
public void modifyInitParameters() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.addInitParameter("a", "b");
bean.getInitParameters().put("a", "c");
bean.onStartup(this.servletContext);
verify(this.registration).setInitParameters(Collections.singletonMap("a", "c"));
}
@Test
public void setUrlPatternMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlPatterns(null))
.withMessageContaining("UrlPatterns must not be null");
}
@Test
public void addUrlPatternMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException().isThrownBy(() -> bean.addUrlPatterns((String[]) null))
.withMessageContaining("UrlPatterns must not be null");
}
@Test
public void setServletNameMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletNames(null))
.withMessageContaining("ServletNames must not be null");
}
@Test
public void addServletNameMustNotBeNull() {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
assertThatIllegalArgumentException().isThrownBy(() -> bean.addServletNames((String[]) null))
.withMessageContaining("ServletNames must not be null");
}
@Test
public void withSpecificDispatcherTypes() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD);
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD),
false, "/*");
}
@Test
public void withSpecificDispatcherTypesEnumSet() throws Exception {
AbstractFilterRegistrationBean<?> bean = createFilterRegistrationBean();
EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD);
bean.setDispatcherTypes(types);
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForUrlPatterns(types, false, "/*");
}
protected abstract Filter getExpectedFilter();
protected abstract AbstractFilterRegistrationBean<?> createFilterRegistrationBean(
ServletRegistrationBean<?>... servletRegistrationBeans);
protected final ServletRegistrationBean<?> mockServletRegistration(String name) {
ServletRegistrationBean<?> bean = new ServletRegistrationBean<>();
bean.setName(name);
return bean;
}
}
| [
"caverspark@163.com"
] | caverspark@163.com |
65583bbe580e9912ed37c8e7be42b6f82e6fe312 | 4771edd416f5e3f8cfc99f6652de4e761f61429b | /VideoProject/src/com/video/videoproject/toptab/TextDrawable.java | f02b18d2d3c7631d39e504bdfd16d42fa52e4b9e | [] | no_license | HotBloodMan/CommonCode | 26453bc3ba325663be78d4dd4a5afc83e60285d1 | 3198b2b48da39b21e7295c0bf6db5aac7db18622 | refs/heads/master | 2020-05-21T23:55:22.128001 | 2016-12-04T07:11:17 | 2016-12-04T07:11:17 | 62,364,448 | 6 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,495 | java | package com.video.videoproject.toptab;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.TypedValue;
/**
* A Drawable object that draws text.
* A TextDrawable accepts most of the same parameters that can be applied to
* {@link android.widget.TextView} for displaying and formatting text.
*
* Optionally, a {@link Path} may be supplied on which to draw the text.
*
* A TextDrawable has an intrinsic size equal to that required to draw all
* the text it has been supplied, when possible. In cases where a {@link Path}
* has been supplied, the caller must explicitly call
* {@link #setBounds(android.graphics.Rect) setBounds()} to provide the Drawable
* size based on the Path constraints.
*/
public class TextDrawable extends Drawable {
/* Platform XML constants for typeface */
private static final int SANS = 1;
private static final int SERIF = 2;
private static final int MONOSPACE = 3;
/* Resources for scaling values to the given device */
private Resources mResources;
/* Paint to hold most drawing primitives for the text */
private TextPaint mTextPaint;
/* Layout is used to measure and draw the text */
private StaticLayout mTextLayout;
/* Alignment of the text inside its bounds */
private Layout.Alignment mTextAlignment = Layout.Alignment.ALIGN_NORMAL;
/* Optional path on which to draw the text */
private Path mTextPath;
/* Stateful text color list */
private ColorStateList mTextColors;
/* Container for the bounds to be reported to widgets */
private Rect mTextBounds;
/* Text string to draw */
private CharSequence mText = "";
/* Attribute lists to pull default values from the current theme */
private static final int[] themeAttributes = {
android.R.attr.textAppearance
};
private static final int[] appearanceAttributes = {
android.R.attr.textSize,
android.R.attr.typeface,
android.R.attr.textStyle,
android.R.attr.textColor
};
public TextDrawable(Context context) {
super();
//Used to load and scale resource items
mResources = context.getResources();
//Definition of this drawables size
mTextBounds = new Rect();
//Paint to use for the text
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.density = mResources.getDisplayMetrics().density;
mTextPaint.setDither(true);
int textSize = 15;
ColorStateList textColor = null;
int styleIndex = -1;
int typefaceIndex = -1;
//Set default parameters from the current theme
TypedArray a = context.getTheme().obtainStyledAttributes(themeAttributes);
int appearanceId = a.getResourceId(0, -1);
a.recycle();
TypedArray ap = null;
if (appearanceId != -1) {
ap = context.obtainStyledAttributes(appearanceId, appearanceAttributes);
}
if (ap != null) {
for (int i=0; i < ap.getIndexCount(); i++) {
int attr = ap.getIndex(i);
switch (attr) {
case 0: //Text Size
textSize = a.getDimensionPixelSize(attr, textSize);
break;
case 1: //Typeface
typefaceIndex = a.getInt(attr, typefaceIndex);
break;
case 2: //Text Style
styleIndex = a.getInt(attr, styleIndex);
break;
case 3: //Text Color
textColor = a.getColorStateList(attr);
break;
default:
break;
}
}
ap.recycle();
}
setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000));
setRawTextSize(textSize);
Typeface tf = null;
switch (typefaceIndex) {
case SANS:
tf = Typeface.SANS_SERIF;
break;
case SERIF:
tf = Typeface.SERIF;
break;
case MONOSPACE:
tf = Typeface.MONOSPACE;
break;
}
setTypeface(tf, styleIndex);
}
/**
* Set the text that will be displayed
* @param text Text to display
*/
public void setText(CharSequence text) {
if (text == null) text = "";
mText = text;
measureContent();
}
/**
* Return the text currently being displayed
*/
public CharSequence getText() {
return mText;
}
/**
* Return the current text size, in pixels
*/
public float getTextSize() {
return mTextPaint.getTextSize();
}
/**
* Set the text size. The value will be interpreted in "sp" units
* @param size Text size value, in sp
*/
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
/**
* Set the text size, using the supplied complex units
* @param unit Units for the text size, such as dp or sp
* @param size Text size value
*/
public void setTextSize(int unit, float size) {
float dimension = TypedValue.applyDimension(unit, size,
mResources.getDisplayMetrics());
setRawTextSize(dimension);
}
/*
* Set the text size, in raw pixels
*/
private void setRawTextSize(float size) {
if (size != mTextPaint.getTextSize()) {
mTextPaint.setTextSize(size);
measureContent();
}
}
/**
* Return the horizontal stretch factor of the text
*/
public float getTextScaleX() {
return mTextPaint.getTextScaleX();
}
/**
* Set the horizontal stretch factor of the text
* @param size Text scale factor
*/
public void setTextScaleX(float size) {
if (size != mTextPaint.getTextScaleX()) {
mTextPaint.setTextScaleX(size);
measureContent();
}
}
/**
* Return the current text alignment setting
*/
public Layout.Alignment getTextAlign() {
return mTextAlignment;
}
/**
* Set the text alignment. The alignment itself is based on the text layout direction.
* For LTR text NORMAL is left aligned and OPPOSITE is right aligned.
* For RTL text, those alignments are reversed.
* @param align Text alignment value. Should be set to one of:
*
* {@link Layout.Alignment#ALIGN_NORMAL},
* {@link Layout.Alignment#ALIGN_NORMAL},
* {@link Layout.Alignment#ALIGN_OPPOSITE}.
*/
public void setTextAlign(Layout.Alignment align) {
if (mTextAlignment != align) {
mTextAlignment = align;
measureContent();
}
}
/**
* Sets the typeface and style in which the text should be displayed.
* Note that not all Typeface families actually have bold and italic
* variants, so you may need to use
* {@link #setTypeface(Typeface, int)} to get the appearance
* that you actually want.
*/
public void setTypeface(Typeface tf) {
if (mTextPaint.getTypeface() != tf) {
mTextPaint.setTypeface(tf);
measureContent();
}
}
/**
* Sets the typeface and style in which the text should be displayed,
* and turns on the fake bold and italic bits in the Paint if the
* Typeface that you provided does not have all the bits in the
* style that you specified.
*
*/
public void setTypeface(Typeface tf, int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style);
} else {
tf = Typeface.create(tf, style);
}
setTypeface(tf);
// now compute what (if any) algorithmic styling is needed
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
setTypeface(tf);
}
}
/**
* Return the current typeface and style that the Paint
* using for display.
*/
public Typeface getTypeface() {
return mTextPaint.getTypeface();
}
/**
* Set a single text color for all states
* @param color Color value such as {@link Color#WHITE} or {@link Color#argb(int, int, int, int)}
*/
public void setTextColor(int color) {
setTextColor(ColorStateList.valueOf(color));
}
/**
* Set the text color as a state list
* @param colorStateList ColorStateList of text colors, such as inflated from an R.color resource
*/
public void setTextColor(ColorStateList colorStateList) {
mTextColors = colorStateList;
updateTextColors(getState());
}
/**
* Optional Path object on which to draw the text. If this is set,
* TextDrawable cannot properly measure the bounds this drawable will need.
* You must call {@link #setBounds(int, int, int, int) setBounds()} before
* applying this TextDrawable to any View.
*
* Calling this method with <code>null</code> will remove any Path currently attached.
*/
public void setTextPath(Path path) {
if (mTextPath != path) {
mTextPath = path;
measureContent();
}
}
/**
* Internal method to take measurements of the current contents and apply
* the correct bounds when possible.
*/
private void measureContent() {
//If drawing to a path, we cannot measure intrinsic bounds
//We must resly on setBounds being called externally
if (mTextPath != null) {
//Clear any previous measurement
mTextLayout = null;
mTextBounds.setEmpty();
} else {
//Measure text bounds
double desired = Math.ceil( Layout.getDesiredWidth(mText, mTextPaint) );
mTextLayout = new StaticLayout(mText, mTextPaint, (int)desired,
mTextAlignment, 1.0f, 0.0f, false);
mTextBounds.set(0, 0, mTextLayout.getWidth(), mTextLayout.getHeight());
}
//We may need to be redrawn
invalidateSelf();
}
/**
* Internal method to apply the correct text color based on the drawable's state
*/
private boolean updateTextColors(int[] stateSet) {
int newColor = mTextColors.getColorForState(stateSet, Color.WHITE);
if (mTextPaint.getColor() != newColor) {
mTextPaint.setColor(newColor);
return true;
}
return false;
}
@Override
protected void onBoundsChange(Rect bounds) {
//Update the internal bounds in response to any external requests
mTextBounds.set(bounds);
}
@Override
public boolean isStateful() {
/*
* The drawable's ability to represent state is based on
* the text color list set
*/
return mTextColors.isStateful();
}
@Override
protected boolean onStateChange(int[] state) {
//Upon state changes, grab the correct text color
return updateTextColors(state);
}
@Override
public int getIntrinsicHeight() {
//Return the vertical bounds measured, or -1 if none
if (mTextBounds.isEmpty()) {
return -1;
} else {
return (mTextBounds.bottom - mTextBounds.top);
}
}
@Override
public int getIntrinsicWidth() {
//Return the horizontal bounds measured, or -1 if none
if (mTextBounds.isEmpty()) {
return -1;
} else {
return (mTextBounds.right - mTextBounds.left);
}
}
@Override
public void draw(Canvas canvas) {
final Rect bounds = getBounds();
final int count = canvas.save();
canvas.translate(bounds.left, bounds.top);
if (mTextPath == null) {
//Allow the layout to draw the text
mTextLayout.draw(canvas);
} else {
//Draw directly on the canvas using the supplied path
canvas.drawTextOnPath(mText.toString(), mTextPath, 0, 0, mTextPaint);
}
canvas.restoreToCount(count);
}
@Override
public void setAlpha(int alpha) {
if (mTextPaint.getAlpha() != alpha) {
mTextPaint.setAlpha(alpha);
}
}
@Override
public int getOpacity() {
return mTextPaint.getAlpha();
}
@Override
public void setColorFilter(ColorFilter cf) {
if (mTextPaint.getColorFilter() != cf) {
mTextPaint.setColorFilter(cf);
}
}
}
| [
"18303011272@163.com"
] | 18303011272@163.com |
2c2b0862982ac10164ea967d4138768f7630cac1 | f82ead00217d73aba5d2a9c7299c1544b693f5b1 | /juc01-basic/src/main/java/com/wujing/concurrency/信号法/TestPrintAB.java | 4858c2cb2f19fb20432d0f0282114784a64cc87a | [] | no_license | wuguojun119/juc-study | 47c407515cfa17722bbf2fbc606597be913bf04c | 58d3706aacb31bca78eebe487b03e829181c55bc | refs/heads/master | 2022-05-20T14:48:59.655449 | 2020-04-18T05:59:35 | 2020-04-18T05:59:35 | 256,282,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,253 | java | package com.wujing.concurrency.信号法;
/**
* 生产者消费者模式 -> 信号法
*
* 需要 : 轮流打印 AB 内容, 生产者, 消费者, 信号资源
* @author: wj
*/
public class TestPrintAB {
public static void main(String[] args) {
Product product = new Product();
Producer producer = new Producer(product);
Consumer consumer = new Consumer(product);
producer.start();
consumer.start();
}
}
/**
* 产品, 信号资源类
*/
class Product {
// 是否有产品信号标记
private boolean flag = false;
/*
生产, 打印字母A
*/
public synchronized void produce() {
// 1. 如果有产品
while (flag) {
// 1.1 等待消费者消费
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 2. 如果没有产品
// 2.1 生产者生产产品
System.out.println("---生产者生产: AAAA---");
this.flag = true;
// 1.2 通知消费者消费
this.notify();
}
/*
消费, 打印字母B
*/
public synchronized void consume() {
// 1. 如果没有有产品
while (!flag) {
// 1.1 等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 2. 如果有产品
// 2.1 消费者消费产品
System.out.println("===消费者消费: BBBB===");
this.flag = false;
// 1.2 通知生产者生产
this.notifyAll();
}
}
/**
* 生产者
*/
class Producer extends Thread {
Product product;
public Producer(Product product) {
this.product = product;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
product.produce();
}
}
}
/**
* 消费者
*/
class Consumer extends Thread {
Product product;
public Consumer(Product product) {
this.product = product;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
product.consume();
}
}
}
| [
"wuguojun119@126.com"
] | wuguojun119@126.com |
1f2be84a7e1b575403a1a8f106fcb7322976932e | 55d2cf1eb3003c51e7d6d6473a2ea2ef3647da84 | /libraryWaterfairy/src/main/java/com/waterfairy/widget/chart/BaseChartView.java | a5f7bd808207255737c53bf344365f83f8607759 | [] | no_license | waterfaity/WaterFairyLibrary | aa0d68bceec1395817fb41fbfd9f6f3d1394aa35 | 1161c5f186a8b4b050a0e9a0edf820e7f7ceb6be | refs/heads/master | 2023-02-19T12:41:31.760660 | 2021-01-19T02:09:01 | 2021-01-19T02:09:01 | 327,326,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,283 | java | package com.waterfairy.widget.chart;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import com.waterfairy.widget.baseview.BaseView;
import com.waterfairy.widget.baseview.Coordinate;
import com.waterfairy.widget.baseview.Entity;
import com.waterfairy.widget.utils.CanvasUtils;
import com.waterfairy.widget.utils.GestureFlingTool;
import com.waterfairy.widget.utils.RectUtils;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
/**
* @author water_fairy
* @email 995637517@qq.com
* @date 2018/6/8 13:45
* @info:
*/
public class BaseChartView extends BaseView implements GestureFlingTool.OnFlingListener {
protected int[] colors = new int[]{
Color.parseColor("#0182FF"),
Color.parseColor("#0AD1A8"),
Color.parseColor("#04912a"),
Color.parseColor("#c904b5"),
Color.parseColor("#008380"),
Color.parseColor("#ec4f01"),
Color.parseColor("#afac00"),
Color.parseColor("#c40d00"),
Color.parseColor("#ac7300"),
Color.parseColor("#52af0b"),
Color.parseColor("#04a2f7"),
Color.parseColor("#ffb254"),
Color.parseColor("#74c9f7"),
Color.parseColor("#a260ff"),
Color.parseColor("#ff62f5"),
Color.parseColor("#fa629a"),
Color.parseColor("#e1855d"),
Color.parseColor("#5e59f9")
};
private OnScrollListener onScrollListener;
private static final String TAG = "lineChartView";
//传入数据
private List<List<Entity>> mDataList;//输入数据
private int maxValue;
//data
protected List<List<Coordinate>> mCoordinateList;//数据坐标
private List<Coordinate> mDataInfoCoordinateList;//数据信息展示的坐标
private List<Entity> mYLineList;//Y轴线坐标
private int mWidthEntity;//间隔
protected int mTextSize;
private boolean showInfo = true;//展示坐标的具体内容
private boolean isShowingInfo;//展示坐标的具体内容的状态
//坐标
protected int scrollX; //滚动距离
private int maxScrollX;
protected int deviationStartX;//x 坐标左偏移量
protected int deviationEndX;//x 坐标右偏移量
protected int bottomLine;//底部y坐标(0刻度线)
protected int leftLine;//左侧x坐标(刻度线)
protected int rightLine;//右侧x坐标(右侧绘图区域)
private int topLine;//上侧y坐标(上侧绘图区域)
private int yNum = 4;//y轴个数
private int xMaxNum = 10;//x轴最大个数
protected int xNum;//x轴显示个数
protected int startPos = 0;//x轴开始绘制位置
protected int perWidth;//x间隔
protected int dNumDrawXText = 1;//每n个画x轴坐标
private int textWidth;
protected int textHeight;
private int chinaTextWidth;
private float perValueHeight;
//画笔
protected Paint mPaintChart;
protected Paint mPaintLineY;
protected Paint mPaintText;
private Paint mPaintInfo;
//用于判断是否是水平滑动
private float downY;
private float downX;
//rect
// private RectF mInfoRect;
private RectUtils.TextRectFBean mInfoTextBean;
//data
private boolean parentDisTouch = false;
protected List<String> xTitles;
private int mSelectPos;
//颜色
private int mColorInfoBg;//提示信息背景颜色
private int mColorNormalText;//文本颜色 坐标颜色
private int mColorLineSelect;//选中的位置的 垂直线的颜色
//titles
private List<String> typeTitles;//类型文本list
private ArrayList<String> titlesWithScore;//有得分的类型文本list 选中提示的信息
//多类型
protected boolean isMulti;
//------- 类型提示 右侧 / 底部
public static final int TYPE_DIR_NONE = 0;
private static final int TYPE_DIR_LEFT = 1;
public static final int TYPE_DIR_RIGHT = 2;
private static final int TYPE_DIR_TOP = 3;
public static final int TYPE_DIR_BOTTOM = 4;
private int typeTextDir;//类型文字方向
private float mTypeTextWidth;//类型文本宽
private float mTypeTextHeight;//高
private RectF typeTextListRectF;//类型文本边框
private RectUtils.TextRectFBean typeTitleBean;//类型文本bean
private GestureDetector gestureDetector;
private GestureFlingTool gestureFlingTool;
private boolean freshScrollState = true;
//-------
public BaseChartView(Context context) {
this(context, null);
}
public BaseChartView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
getDensity();
initText();
initColor();
initPaint();
}
private void initColor() {
mColorInfoBg = Color.parseColor("#CCFFFFFF");
mColorNormalText = Color.parseColor("#454545");
mColorLineSelect = Color.parseColor("#66454545");
}
/**
* 计算文本相关
*/
private void initText() {
mTextSize = (int) (getDensity() * 10);
Rect textRect = getTextRect("0", mTextSize);
textHeight = Math.abs(textRect.bottom + textRect.top);
textWidth = textRect.right + textRect.left;
chinaTextWidth = getTextRect("正", mTextSize).width();
}
protected void initPaint() {
mPaintLineY = new Paint();
mPaintLineY.setColor(Color.parseColor("#999999"));
mPaintLineY.setStrokeWidth(density);
mPaintText = new Paint();
mPaintText.setColor(mColorNormalText);
mPaintText.setTextSize(mTextSize);
mPaintText.setAntiAlias(true);
mPaintInfo = new Paint();
mPaintInfo.setColor(Color.parseColor("#289456"));
mPaintInfo.setAntiAlias(true);
mPaintInfo.setStrokeWidth(density * 1);
mPaintChart = new Paint();
mPaintChart.setColor(Color.parseColor("#289456"));
mPaintChart.setAntiAlias(true);
mPaintChart.setStrokeWidth(density * 1);
}
public void iniLineColor(int color) {
mPaintInfo.setColor(color);
}
public void setDeviationStartX(int deviationStartX) {
this.deviationStartX = deviationStartX;
}
public void setDeviationEndX(int deviationEndX) {
this.deviationEndX = deviationEndX;
}
public List<List<Entity>> getDataList() {
return mDataList;
}
public void addData(List<Entity> dataList, int maxValue) {
if (mDataList == null) mDataList = new ArrayList<>();
mDataList.add(dataList);
setData(mDataList, maxValue);
}
public void setSingleData(List<Entity> dataList, int maxValue) {
mDataList = new ArrayList<>();
mDataList.add(dataList);
this.maxValue = maxValue;
setData(mDataList, maxValue);
}
public void setData(List<List<Entity>> mDataList, int maxValue) {
this.maxValue = maxValue;
this.mDataList = mDataList;
isMulti = mDataList.size() > 1;
if (mDataList.size() > 0) {
List<Entity> entities = mDataList.get(0);
xTitles = new ArrayList<>();
for (int i = 0; i < entities.size(); i++) {
Entity entity = entities.get(i);
xTitles.add(entity.name);
}
}
}
public void fresh() {
requestLayout();
invalidate();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = right - left;
height = bottom - top;
if (width != 0 && height != 0) {
calcData();
}
}
/**
* 计算数据坐标
*/
protected void calcData() {
//计算 typeText
calcTypeText();
//一般计算
calcNormal();
//计算y轴
calcY();
//计算x轴
calcX();
//计算位置
reCalcTypeText();
}
/**
* 由 typeTextDir 计算具体坐标
*/
private void reCalcTypeText() {
if (typeTextListRectF != null) {
switch (typeTextDir) {
case TYPE_DIR_LEFT:
case TYPE_DIR_RIGHT:
if (typeTextDir == TYPE_DIR_LEFT) {
typeTextListRectF.left = leftLine - mTypeTextWidth;
typeTextListRectF.right = leftLine;
} else {
typeTextListRectF.left += rightLine;
typeTextListRectF.right += rightLine;
}
int dx = bottomLine - topLine;
if (typeTextListRectF.height() < (dx)) {
float dx2 = (dx - typeTextListRectF.height()) / 2;
typeTextListRectF.top += dx2;
typeTextListRectF.bottom += dx2;
}
break;
case TYPE_DIR_TOP:
case TYPE_DIR_BOTTOM:
if (typeTextDir == TYPE_DIR_TOP) {
typeTextListRectF.top = topLine - mTypeTextHeight;
typeTextListRectF.bottom = bottomLine;
} else {
Rect textRect = getTextRect("正", mTextSize);
typeTextListRectF.top += (bottomLine + 2 * textRect.height());
typeTextListRectF.bottom += (bottomLine + 2 * textRect.height());
}
int centerX = getWidth() / 2;
typeTextListRectF.left = centerX - mTypeTextWidth / 2;
typeTextListRectF.right = centerX + mTypeTextWidth / 2;
break;
}
}
}
/**
* 计算typeTitleBean 主要是rect 不是具体位置
*/
private void calcTypeText() {
if (typeTitles != null && typeTitles.size() > 0 && typeTextDir != TYPE_DIR_NONE) {
boolean isTypeTextVer = typeTextDir == TYPE_DIR_LEFT || typeTextDir == TYPE_DIR_RIGHT;
typeTitleBean = RectUtils.getTextRectFBean(typeTitles, mTextSize, 0.5F, getWidth(), isTypeTextVer ? 10 : 0, isTypeTextVer ? 0 : 20, true,
isTypeTextVer);
typeTextListRectF = typeTitleBean.rectF;
mTypeTextWidth = typeTextListRectF.width();
mTypeTextHeight = typeTextListRectF.height();
}
}
private void calcNormal() {
if (yNum < 1) yNum = 1;
if (maxValue <= 0) maxValue = 100;
rightLine = (int) (width - textWidth * 2 - getPaddingRight() - (typeTextDir == TYPE_DIR_RIGHT ? mTypeTextWidth : 0));
leftLine = (int) ((("" + maxValue).length() + 2) * textWidth + getPaddingLeft() + (typeTextDir == TYPE_DIR_LEFT ? mTypeTextWidth : 0));
}
private void calcY() {
//计算y轴坐标 上留 一个字符高度 下留2个字符高度
for (int i = 0; i < yNum; i++) {
if ((maxValue + i) % yNum == 0) {
int tempMaxValue = maxValue + i;
//设置底部线
bottomLine = (int) (height - 3 * textHeight - getPaddingBottom() - (typeTextDir == TYPE_DIR_BOTTOM ? mTypeTextHeight : 0));
topLine = (int) (textHeight * 2 + getPaddingTop() + (typeTextDir == TYPE_DIR_TOP ? mTypeTextHeight : 0));
int perHeight = (bottomLine - topLine) / yNum;
perValueHeight = (bottomLine - topLine) / (float) tempMaxValue;
mYLineList = new ArrayList<>();
for (int j = 0; j < yNum + 1; j++) {
Entity entity = new Entity();
//y坐标
entity.value = bottomLine - j * perHeight;
//y显示文字
entity.name = tempMaxValue / yNum * j + "";
mYLineList.add(entity);
}
}
}
}
private void calcX() {
if (mDataList != null && mDataList.size() > 0) {
List<Entity> entities = mDataList.get(0);
//计算数据坐标
mCoordinateList = new ArrayList<>();
int tempLineWidth = (rightLine - leftLine) - (deviationStartX + deviationEndX);
xNum = entities.size();
if (xNum > xMaxNum) xNum = xMaxNum;
if (xNum == 1) {
//只有一个
for (int i = 0; i < mDataList.size(); i++) {
List<Entity> entitiesTemp = mDataList.get(i);
Entity entity = entitiesTemp.get(0);
List<Coordinate> list = new ArrayList<>();
list.add(new Coordinate(deviationStartX + leftLine + (tempLineWidth / 2), (int) (bottomLine - entity.getValue() * perValueHeight), entity.getValue(), entity.getName()));
mCoordinateList.add(list);
}
} else {
perWidth = tempLineWidth / (xNum - 1);
for (int j = 0; j < mDataList.size(); j++) {
List<Entity> entityList = mDataList.get(j);
List<Coordinate> list = new ArrayList<>();
for (int i = 0; i < entityList.size(); i++) {
Entity entity = entityList.get(i);
list.add(new Coordinate(deviationStartX + leftLine + i * perWidth, (int) (bottomLine - entity.getValue() * perValueHeight), entity.getValue(), entity.getName()));
}
mCoordinateList.add(list);
}
maxScrollX = perWidth * (mCoordinateList.get(0).size() - xNum) + deviationStartX - deviationEndX;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaintText.setColor(mColorNormalText);
//绘制y轴
drawY(canvas);
//绘制x轴
drawX(canvas);
//绘制typeText
drawTypeText(canvas);
//绘制提示信息
drawInfo(canvas);
}
private void drawTypeText(Canvas canvas) {
// CanvasUtils.drawCorner(canvas, typeTitleBean.rectF, 10, 2, mColorNormalText, mColorInfoBg, mPaintLine);
CanvasUtils.drawHorTextList(canvas, typeTitleBean, colors, mPaintText);
}
/**
* 点击某个位置 出现提示信息
*
* @param canvas
*/
private void drawInfo(Canvas canvas) {
if (showInfo && isShowingInfo && typeTitles != null) {
//绘制选中的pos 垂直线
mPaintInfo.setColor(mColorLineSelect);
canvas.drawLine(mInfoTextBean.centerX, topLine, mInfoTextBean.centerX, bottomLine, mPaintInfo);
//背景绘制 - 圆角
CanvasUtils.drawCorner(canvas, mInfoTextBean.rectF, 10, 2, mColorNormalText, mColorInfoBg, mPaintInfo);
//提示内容
CanvasUtils.drawHorTextList(canvas, mInfoTextBean, colors, mPaintText);
}
}
protected void drawX(Canvas canvas) {
if (mCoordinateList == null || mCoordinateList.size() == 0) return;
List<Coordinate> coordinates = mCoordinateList.get(0);
if (coordinates == null || coordinates.size() == 0) return;
int maxPos = startPos + xNum;
if (dNumDrawXText < 0) dNumDrawXText = 1;
for (int j = 0; j < mCoordinateList.size(); j++) {
List<Coordinate> coordinateList = mCoordinateList.get(j);
for (int i = startPos; i < maxPos + 1 && i < coordinateList.size(); i++) {
Coordinate coordinate = coordinateList.get(i);
int currentX = coordinate.x + scrollX;
//绘制 图
drawChart(canvas, coordinateList, i, currentX, mCoordinateList.size(), j);
//最后一个数据集合绘制刻度
if (j == mCoordinateList.size() - 1) {
canvas.drawLine(currentX, bottomLine, currentX, bottomLine + textHeight / 2, mPaintLineY);
String xTitle = "";
if (xTitles != null && xTitles.size() > i) {
xTitle = xTitles.get(i);
} else {
xTitle = coordinate.text;
}
if (i % dNumDrawXText == 0 && !TextUtils.isEmpty(xTitle)) {
Rect textRect = getTextRect(xTitle, mTextSize);
int width = textRect.right + Math.abs(textRect.left);
int height = Math.abs(textRect.bottom - textRect.top);
canvas.drawText(xTitle, currentX - width / 2, bottomLine + height * 2F, mPaintText);
}
}
}
}
}
/**
* @param canvas 画布
* @param currentCoordinateList 当前数据集合的坐标
* @param currentIndex 当前数据下标
* @param currentX 当前x坐标
* @param mulDataSize 数据集合总数
* @param mulDataIndex 当前数据集合下标
*/
protected void drawChart(Canvas canvas, List<Coordinate> currentCoordinateList, int currentIndex, int currentX, int mulDataSize, int mulDataIndex) {
}
private void drawY(Canvas canvas) {
canvas.drawLine(leftLine, getPaddingTop() + textHeight, leftLine, bottomLine, mPaintLineY);
if (mYLineList == null) return;
for (int i = 0; i < mYLineList.size(); i++) {
Entity entity = mYLineList.get(i);
canvas.drawLine(leftLine, entity.getValue(), rightLine, entity.getValue(), mPaintLineY);
canvas.drawText(entity.getName(), textWidth + getPaddingLeft(), entity.getValue() + textHeight / 2, mPaintText);
}
}
public void setNumDrawXText(int dNumDrawXText) {
this.dNumDrawXText = dNumDrawXText;
}
float lastMoveX = 0;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (gestureDetector == null) {
gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (gestureFlingTool == null) {
gestureFlingTool = new GestureFlingTool();
gestureFlingTool.setOnFlingListener(BaseChartView.this);
}
gestureFlingTool.startFling(e1, e2, velocityX, velocityY);
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// calcTapIndex(e.getX());
return super.onSingleTapUp(e);
}
});
}
gestureDetector.onTouchEvent(event);
if (action == MotionEvent.ACTION_DOWN) {
if (gestureFlingTool != null && gestureFlingTool.isFling()) {
gestureFlingTool.stop();
}
freshScrollState = true;
downY = event.getY();
downX = event.getX();
lastMoveX = event.getX();
getParent().requestDisallowInterceptTouchEvent(parentDisTouch);
} else if (action == MotionEvent.ACTION_MOVE) {
isShowingInfo = false;
handleMove(event.getX());
if (onScrollListener != null && freshScrollState) {
float dx = Math.abs(event.getX() - downX);
float dy = Math.abs(event.getY() - downY);
if (dx >= 5 || dy >= 5) {
freshScrollState = false;
boolean isHor = dx > dy;
onScrollListener.onScroll(isHor);
}
}
} else if (action == MotionEvent.ACTION_UP) {
float touchX = event.getX() + Math.abs(scrollX);
if (mCoordinateList != null && mCoordinateList.size() > 0) {
List<Coordinate> list = mCoordinateList.get(0);
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
Coordinate coordinate = list.get(i);
if (touchX > coordinate.x - perWidth / 2 && touchX < coordinate.x + perWidth / 2) {
mSelectPos = i;
if (onPosClickListener != null)
onPosClickListener.onLineClick(i, coordinate.x + scrollX, event.getY());
if (showInfo && typeTitles != null) {
onTouchPos(i, coordinate.x + scrollX, event.getY());
invalidate();
}
return true;
}
}
}
}
}
return true;
}
private void onTouchPos(int pos, int x, float y) {
if (isShowingInfo) {
isShowingInfo = false;
} else {
isShowingInfo = true;
//计算展示的位置
if (mDataList != null && mDataList.size() > 0) {
titlesWithScore = new ArrayList<>();
for (int i = 0; i < mDataList.size(); i++) {
List<Entity> entities = mDataList.get(i);
String title = "";
if (typeTitles.size() > i) title = typeTitles.get(i);
if (entities != null && entities.size() > pos) {
Entity entity = entities.get(pos);
String text = title + ":" + entity.getValue();
titlesWithScore.add(text);
}
}
mInfoTextBean = RectUtils.getTextRectFBean(titlesWithScore, mTextSize, 0.2F, 0, 10, 0, true, true);
mInfoTextBean.rectF = RectUtils.getRectF(mInfoTextBean.rectF, x, y, leftLine, topLine, rightLine, bottomLine);
mInfoTextBean.centerX = x;
mInfoTextBean.centerY = y;
}
}
invalidate();
}
private void handleMove(float touchX) {
float dx = touchX - lastMoveX;
if (dx == 0 || xNum <= 1) return;
scrollX += (touchX - lastMoveX);
if (scrollX > 0) scrollX = 0;
else if (scrollX < -maxScrollX) scrollX = -maxScrollX;
startPos = -scrollX / perWidth;
if (startPos < 0) startPos = 0;
lastMoveX = touchX;
invalidate();
}
public void setParentDisTouch(boolean parentDisTouch) {
this.parentDisTouch = parentDisTouch;
}
public void setXTitles(List<String> titles) {
this.xTitles = titles;
}
public void setShowInfo(boolean showInfo) {
this.showInfo = showInfo;
}
private OnPosClickListener onPosClickListener;
public void setOnPosClickListener(OnPosClickListener onPosClickListener) {
this.onPosClickListener = onPosClickListener;
}
public OnPosClickListener getOnPosClickListener() {
return onPosClickListener;
}
public void setTypeTitles(List<String> typeTitles) {
this.typeTitles = typeTitles;
}
@Override
public void onFlingStart(float x, float y) {
}
@Override
public void onFling(float x, float y) {
handleMove(x);
}
@Override
public void onFlingEnd() {
}
public void setXMaxNum(int xMaxNum) {
this.xMaxNum = xMaxNum;
}
public interface OnPosClickListener {
void onLineClick(int pos, float x, float y);
}
public void setTypeTextDir(int typeTextDir) {
this.typeTextDir = typeTextDir;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
public interface OnScrollListener {
void onScroll(boolean isHorScroll);
}
}
| [
"995637517@qq.com"
] | 995637517@qq.com |
2bd837b94f260f44989fa683c481f7f8fb73cc2d | a5026575cda665451bb6f42343bf443b77da1041 | /app/src/main/java/com/zht/lazyload/LazyLoadFragmnet.java | 7f0e520bf5724dd2f3316aa01c198bb782d196b7 | [] | no_license | zhtoo/LazyLoad | d3c08e4373866a8cf51e648000712b4ef69ec7cb | 79fca97fbd332901cee82d48501a59eab099df66 | refs/heads/master | 2021-05-02T15:19:11.788758 | 2018-02-11T09:07:09 | 2018-02-11T09:07:09 | 120,694,214 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,900 | java | package com.zht.lazyload;
import android.support.v4.app.Fragment;
/**
* 作者:zhanghaitao on 2018/2/8 09:47
* 邮箱:820159571@qq.com
*
* @describe:懒加载模式的Fragment
*/
public abstract class LazyLoadFragmnet extends Fragment {
// mark :to judge fragment if is init complete
// 标志位 :用以判断"初始化"动作是否完成
protected boolean isPrepared;
// mark : to judge fragment if is visible
// 标志位 :用以判断当面是否可见
protected boolean isVisible;
/**
* en :to judge if is visible to user
* zh :判断Fragment是否对用户显示
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
this.isVisible = true;
onVisible();
} else {
this.isVisible = false;
onInvisible();
}
}
/**
* en : when the fragment is not visible to user
* zh : 当Fragment不显示的时调用
*/
protected void onInvisible() {
}
/**
* en : when the fragment is visible to user lazyload
* zh : 当Fragment显示的时候调用
*/
protected void onVisible() {
// 如果没初始化好或者不可见,则return
if (isPrepared && isVisible) {
lazyLoad();
}
}
/**
* en : when the fragment init is complete
* zh : 当Fragment初始化完成后调用
*/
protected void ready() {
isPrepared = true;
if (isVisible) {
lazyLoad();
}
}
/**
* en : when fragment init is complete and is visible
* zh : 初始化完成 且 页面可见,则执行本方法
*/
protected abstract void lazyLoad();
}
| [
"3108003368@qq.com"
] | 3108003368@qq.com |
3cc3379ddf5c3a39a4ac69e72762734e2567f745 | 6a1edd42014bb0576c3f9bab94c28e195a4190ac | /learningmaterials/app/src/main/java/com/gec/learningmaterials/mech/III/sem2.java | c73ffab3281c00b3f01282bd66e00dc6ada0cd68 | [] | no_license | sksrvskr/apssdc-project | 37dae04432443d03915a585b1a6b5ab3623154e8 | 89128021c6f1e60732c19f0f528091d1700f988d | refs/heads/main | 2023-06-14T17:50:18.247625 | 2021-07-09T06:26:07 | 2021-07-09T06:26:07 | 382,881,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,129 | java | package com.gec.learningmaterials.mech.III;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import com.gec.learningmaterials.R;
import com.google.android.material.appbar.CollapsingToolbarLayout;
public class sem2 extends AppCompatActivity {
Button I,II,III,IV,V,VI,VII,VIII;
LinearLayout ll1,ll2,ll3,ll4;
CardView c1,c2,c3,c4,c5,c6,c7,c8;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolBarLayout.setTitle("SEM2");
toolBarLayout.setContentScrimResource(R.color.colorAccent);
ll4 = findViewById(R.id.lil4);
ll4.setVisibility(View.INVISIBLE);
}
} | [
"sksrvskr@gmail.com"
] | sksrvskr@gmail.com |
62adb02a7a6979c3f5fa9fa5a9fda175bc3ca689 | c68d76541f0a44656bf7716ef8e8dee6e50e37da | /app/src/main/java/com/korzh/poehali/activity_debug.java | 632439ecf4001427bb8901ba0055734d8c7b52a3 | [] | no_license | VladimirKorzh/Poehali | ffe2e74ecc0c74628fccc004398ff177010b571a | e0fec38cabb6675d1cb090051e1042fc3750d807 | refs/heads/master | 2020-05-14T11:54:08.436048 | 2014-07-14T02:38:01 | 2014-07-14T02:38:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,115 | java | //package com.korzh.poehali;
//
//import android.app.AlertDialog;
//import android.content.Context;
//import android.content.DialogInterface;
//import android.graphics.Color;
//import android.location.Location;
//import android.location.LocationManager;
//import android.os.Bundle;
//import android.os.Handler;
//import android.speech.tts.TextToSpeech;
//import android.support.v7.app.ActionBarActivity;
//import android.view.Menu;
//import android.view.MenuItem;
//import android.view.View;
//
//import com.google.android.gms.maps.CameraUpdateFactory;
//import com.google.android.gms.maps.GoogleMap;
//import com.google.android.gms.maps.SupportMapFragment;
//import com.google.android.gms.maps.model.BitmapDescriptorFactory;
//import com.google.android.gms.maps.model.Circle;
//import com.google.android.gms.maps.model.CircleOptions;
//import com.google.android.gms.maps.model.Marker;
//import com.google.android.gms.maps.model.MarkerOptions;
//import com.korzh.poehali.common.interfaces.LocationBroadcaster;
//import com.korzh.poehali.common.network.MessageConsumer;
//import com.korzh.poehali.common.network.MessageProducer;
//import com.korzh.poehali.common.network.NetworkMessage;
//import com.korzh.poehali.common.network.packets.OrderPacket;
//import com.korzh.poehali.common.network.packets.UserLocationPacket;
//import com.korzh.poehali.common.network.packets.frames.LocationJson;
//import com.korzh.poehali.common.network.packets.frames.OrderDetailsJson;
//import com.korzh.poehali.common.network.packets.frames.UserJson;
//import com.korzh.poehali.common.util.C;
//import com.korzh.poehali.common.util.G;
//import com.korzh.poehali.common.util.U;
//
//import java.util.Random;
//
//
//public class activity_debug extends ActionBarActivity {
// private final String TAG = getClass().getSimpleName();
// private Context c;
//
// private LocationBroadcaster locationBroadcaster = null;
//
// private MessageConsumer orderConsumer = null;
// private MessageConsumer policeConsumer = null;
//
// private GoogleMap googleMap = null;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_debug);
// c = this;
//
// // global handler singleton
// new G(c);
//
//// locationBroadcaster = new LocationBroadcaster(c);
// setUpMapIfNeeded();
// }
//
//
//
//
// private void setUpMapIfNeeded() {
// // Do a null check to confirm that we have not already instantiated the map.
// if (googleMap == null) {
// // Try to obtain the map from the SupportMapFragment.
// googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
// .getMap();
// // Check if we were successful in obtaining the map.
// if (googleMap != null) {
// setUpMap();
// }
// }
// }
//
// private void setUpMap() {
// // Hide the zoom controls as the button panel will cover it.
// googleMap.getUiSettings().setZoomControlsEnabled(true);
// googleMap.getUiSettings().setAllGesturesEnabled(false);
// googleMap.setTrafficEnabled(true);
//
// // Uses a colored icon.
// final Marker mKiev = googleMap.addMarker(new MarkerOptions()
// .position(C.LOCATION_KIEV)
// .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
//
// Circle circle = googleMap.addCircle(new CircleOptions()
// .center(C.LOCATION_KIEV)
// .radius(C.ORDER_SEARCH_RADIUS)
// .strokeWidth(0)
// .strokeColor(Color.LTGRAY)
// .fillColor(C.SEARCH_CIRCLE_COLOR));
//
//
// googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(C.LOCATION_KIEV, C.DEFAULT_MAP_ZOOM));
// }
// case R.id.btnCreateOrderFarAway:
//
// Handler handler = new Handler();
// Runnable placeOrderFarAway = new Runnable(){
// public void run(){
// NetworkMessage msg = new NetworkMessage();
// msg.setExchange(C.DEFAULT_ORDERS_EXCHANGE);
// msg.setExchangeType("direct");
// G g = G.getInstance();
// Location myLocation = g.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//
// UserJson user = new UserJson(true);
// LocationJson origin = new LocationJson(C.LOCATION_KIEV.latitude,C.LOCATION_KIEV.longitude);
// LocationJson destination = new LocationJson(myLocation.getLatitude(),myLocation.getLongitude());
// OrderDetailsJson orderDetails = new OrderDetailsJson(36.0f);
//
// OrderPacket order = new OrderPacket(user,origin,destination,orderDetails);
//
// msg.setData(order.toString());
// MessageProducer messageProducer = new MessageProducer();
// messageProducer.execute(msg);
// }
// };
// handler.post(placeOrderFarAway);
// break;
//
// case R.id.btnCreateOrderNearBy:
// Handler handler1 = new Handler();
// Runnable placeOrderNearBy = new Runnable() {
// public void run() {
// NetworkMessage msg = new NetworkMessage();
// msg.setExchange(C.DEFAULT_ORDERS_EXCHANGE);
// msg.setExchangeType("direct");
// G g = G.getInstance();
// Location myLocation = g.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//
// UserJson user = new UserJson(true);
// LocationJson origin = new LocationJson(myLocation.getLatitude(),myLocation.getLongitude());
// LocationJson destination = new LocationJson(C.LOCATION_KIEV.latitude,C.LOCATION_KIEV.longitude);
// OrderDetailsJson orderDetails = new OrderDetailsJson(36.0f);
//
// OrderPacket order = new OrderPacket(user,origin,destination,orderDetails);
//
// msg.setData(order.toString());
// MessageProducer messageProducer = new MessageProducer();
// messageProducer.execute(msg);
// }
// };
// handler1.post(placeOrderNearBy);
// break;
//
// case R.id.btnCreateOrderRandom:
// Handler handler2 = new Handler();
// Runnable placeRandomOrder = new Runnable() {
// public void run() {
// NetworkMessage msg = new NetworkMessage();
// msg.setExchange(C.DEFAULT_ORDERS_EXCHANGE);
// msg.setExchangeType("direct");
//
// UserJson user = new UserJson(true);
// LocationJson origin = U.getRandomLocation(C.LOCATION_KIEV.latitude,C.LOCATION_KIEV.longitude,20000);
// LocationJson destination = U.getRandomLocation(C.LOCATION_KIEV.latitude,C.LOCATION_KIEV.longitude,20000);
// Random rnd = new Random();
// OrderDetailsJson orderDetails = new OrderDetailsJson(rnd.nextInt(50)+36);
//
// OrderPacket order = new OrderPacket(user,origin,destination,orderDetails);
//
// msg.setData(order.toString());
// MessageProducer messageProducer = new MessageProducer();
// messageProducer.execute(msg);
// }
// };
// handler2.post(placeRandomOrder);
// break;
//
// case R.id.btnCreateRandomTaxiDriversLocations:
// LocationJson locationFrame;
// for (int i=0; i<10; ++i){
// locationFrame = U.getRandomLocation(C.LOCATION_KIEV.latitude,C.LOCATION_KIEV.longitude,20000);
// NetworkMessage msg = new NetworkMessage();
// msg.setExchange(C.DEFAULT_LOCATIONS_EXCHANGE);
// msg.setExchangeType("direct");
//
// Random rnd = new Random();
// UserJson user = new UserJson(rnd.nextBoolean());
// UserLocationPacket pkt = new UserLocationPacket(user,locationFrame);
//
// msg.setData(pkt.toString());
// MessageProducer messageProducer = new MessageProducer();
// messageProducer.execute(msg);
// }
// break;
// case R.id.btnSendRandomPoliceLocations:
//// Handler handler3 = new Handler();
//// Runnable SendPoliceLocation = new Runnable() {
//// public void run() {
//// for (int i=0; i<10; ++i) {
////
//// }
//// }
//// };
//// handler3.post(SendPoliceLocation);
// break;
//
// }
// }
//
//
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.test, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//}
| [
"vladimirkorshak@gmail.com"
] | vladimirkorshak@gmail.com |
cde079c6ca06bbfcdae3d44ca8948c5439cad539 | ea64400e00838707649a7c8a199d43256f1899df | /LinkListDemo/ReverseList.java | 930dfa8c305bb640c018acbc7bbd1673ab5d23d9 | [] | no_license | yuyingyingmax/LeetCode | 97f13107591139f5449430ca1a56808113f8b09b | fafb0577202e28a53dbe7cea11b436b6332d20c2 | refs/heads/master | 2020-04-11T03:52:17.786354 | 2019-02-25T11:41:08 | 2019-02-25T11:41:08 | 161,492,467 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 966 | java | package simple;
/*
第206题
*/
public class ReverseList {
/*
我的方法1:头插法,顺序将每个节点从头部插入,从而构造一个逆序的链表
*/
public ListNode reverseList(ListNode head){
if(head==null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = head.next;
ListNode q = head;
head.next = null;
while(p!=null){
q= dummy.next;
dummy.next = p;
p=p.next;
dummy.next.next = q;
}
head = dummy.next;
return head;
}
/*
方法2:递归
*/
public ListNode reverseList_two(ListNode head){
if(head == null || head.next==null){
return head;
}
ListNode p = head.next;
ListNode rehead = reverseList_two(p);
p.next = head;
head.next = null;
return rehead;
}
}
| [
"583084557@qq.com"
] | 583084557@qq.com |
efcadaf82982eb7a8e0f101d9cc43da727c37bf0 | ed7323c1a9e230cb96298130899286193a29cd66 | /src/OOP/Student.java | 5d1929675c45c479c3e2dc1f15d0df1d9ad69cb6 | [] | no_license | Ahmed01011989/java- | 5094599f7f14acb098b756713ce65b978c45992f | dd42c323f4eeabe286fec3eeb813d2deeff29be9 | refs/heads/master | 2023-01-01T11:54:44.659901 | 2020-10-28T00:46:50 | 2020-10-28T00:46:50 | 305,143,200 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 214 | java | package OOP;
public class Student {
//oop -
//Encopsoltion-data hiding
//polymorphism
//inheritance
//abstaction
String name ;
int id ;
public void setNameOfStudent(){
}
}
| [
"73070696+Ahmed01011989@users.noreply.github.com"
] | 73070696+Ahmed01011989@users.noreply.github.com |
24f5b533053c751fe629ff8e7b283e1320ffe4a4 | 6e2a22ef77812729eb20a8ec7f0d22e42acdeaf2 | /ComparatorLambda/src/comparatorlambda/TrafficCard.java | f62c3c4290b4bcdf5551903e4d274172c30f5df2 | [] | no_license | schatze/tira2020 | 7bd7d5301cdd64fc2a502972e62c270416a9961e | 7346857f47899caab9c5cbe31519fbaca7d5327b | refs/heads/master | 2021-05-26T01:49:38.510067 | 2020-04-27T10:08:03 | 2020-04-27T10:08:03 | 254,005,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 893 | 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 comparatorlambda;
import java.util.*;
/**
*
* @author kamaj
*/
public class TrafficCard{
int mTravellerNumber;
String mOwnerName;
float mBalance;
public TrafficCard(int tNumber, String oName, float balance){
mTravellerNumber = tNumber;
mOwnerName = oName;
mBalance = balance;
}
@Override
public String toString(){
return "owner: "+mOwnerName+" number: "+mTravellerNumber+" balance: "+mBalance;
}
public int getTravellerNumber() {
return mTravellerNumber;
}
public String getOwnerName() {
return mOwnerName;
}
public float getBalance() {
return mBalance;
}
}
| [
"oskar@schatz.fi"
] | oskar@schatz.fi |
3432ea52b532810b56b8079af5cbc7b88d198616 | 8e8fc0348d8fc014e8ecf831c16b1b8f91e401c5 | /src/main/java/com/pokerstar/api/domain/mapper/agent/AgentWithdrawOrderMapper.java | e48868be8e8dfb9b080f47b8a9b94dfb59bcaed0 | [] | no_license | sosososmall/api | f603e747859c303db6a04663adadb3b48b105be9 | 550ea4e66b32abf16f41540e69993c37645090a7 | refs/heads/master | 2023-03-19T02:39:31.711641 | 2021-03-01T05:31:27 | 2021-03-01T05:31:27 | 330,849,830 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 833 | java | package com.pokerstar.api.domain.mapper.agent;
import com.pokerstar.api.domain.entity.agent.AgentWithdrawOrder;
import com.pokerstar.api.domain.model.agent.AgentWithdrawOrderOperationBO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component("agentWithdrawOrderMapper")
public interface AgentWithdrawOrderMapper {
boolean addAgentWithdrawOrder(AgentWithdrawOrder entity);
int deleteAgentWithdrawOrder(int agentWithdrawOrderId);
List<AgentWithdrawOrder> getAllAgentWithdrawOrder();
int updateAgentWithdrawOrderStatus(@Param("agentWithdrawOrderId") int agentWithdrawOrderId, @Param("status") int status);
int updateAgentWithdrawOrderOperation(AgentWithdrawOrderOperationBO param);
}
| [
"@qq.com"
] | @qq.com |
f7ff028cb2c4d6f8d1682de091f8853e3c0de744 | d1a9868e448136151d0375f8267e31ebaf35980e | /src/main/java/com/baidu/langshiquan/ioc/autowire/UserDao.java | 567550c83bfa92c2169dd18f83d93e61434f41ec | [] | no_license | z521598/spring-ioc_aop-design | e2b5338d6693501a883555f0bc42816a27652baf | cd23cb60c1625f4957fe39415c897435cfad4b49 | refs/heads/master | 2021-01-02T22:35:20.440456 | 2018-08-25T10:53:42 | 2018-08-25T10:53:42 | 99,348,389 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 256 | java | package com.baidu.langshiquan.ioc.autowire;
import com.baidu.langshiquan.ioc.User;
/**
* Created by langshiquan on 17/9/27.
*/
public class UserDao {
public void save(User user) {
System.out.println(user.toString() + "has saved");
}
}
| [
"langshiquan@baidu.com"
] | langshiquan@baidu.com |
6de36df589d5286af5d71916009c189a689f5fe1 | c0c60df3dfe94ab7e3f1c5cc1d861aea44e96aef | /src/ipfstest/Home.java | 1e7212998f3855f45792884c305eab3dcab3d0d8 | [] | no_license | stella505/IPFSTesting | f8c28a3861cc665aea8ae8036b2195e9173761e2 | 33af6f7e3c8f593370d5ae3255b14fb9426ea47a | refs/heads/master | 2020-03-17T22:46:58.500216 | 2018-05-24T21:45:35 | 2018-05-24T21:45:35 | 134,018,107 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,404 | 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 ipfstest;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author miaoshiwu
*/
public class Home extends javax.swing.JFrame {
/**
* Creates new form Home
*/
public Home() {
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the system?", "Exit Program Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
public Home(String s) {
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
this.jLabel3.setText("Welcome " + "stella");
this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the system?", "Exit Program Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton4 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton4.setText("jButton4");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("id");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("IPFS bootstat");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("connected peers");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton5.setText("Transfer Files");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("close IPFS");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Malayalam MN", 0, 13)); // NOI18N
jLabel3.setText("USRNAME FIELD");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(126, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(5, 5, 5)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jButton5)
.addGap(18, 18, 18)
.addComponent(jButton6)
.addContainerGap(58, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
IPFSFunc newIpfs = new IPFSFunc();// TODO add your handling code here:
try {
newIpfs.IPFSwarmpeers();
} catch (InterruptedException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
IPFSFunc newIpfs = new IPFSFunc();// TODO add your handling code here:
try {
newIpfs.ShowIPFSInfo();
} catch (IOException ex) {
Logger.getLogger(connectPage.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
FileTransfer fileTransfer = new FileTransfer();
fileTransfer.setVisible(true);// TODO add your handling code here:
}//GEN-LAST:event_jButton5ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel3;
// End of variables declaration//GEN-END:variables
}
| [
"miaoshiwu@miaoshis-mbp.home"
] | miaoshiwu@miaoshis-mbp.home |
eff40099fdb987e905724056d3a04237aa626cbf | 60416ddfc2ec70451712c063157271001851767c | /app/src/main/java/com/example/guest999/firebasenotification/adapters/DataAdapter.java | af2dda77481c988920cfa8d792c2d8a7a76e3765 | [] | no_license | HIREN4131KINAL/ShareDemo | f2261e7fdfd31a15026d6e35ddad91a582dd07a2 | 19bb0f33cabc56ad4f09e35096d33675fef8fbd9 | refs/heads/master | 2021-01-12T06:00:41.171805 | 2016-12-16T08:52:00 | 2016-12-16T08:52:00 | 77,269,570 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 48,042 | java | package com.example.guest999.firebasenotification.adapters;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.guest999.firebasenotification.Config;
import com.example.guest999.firebasenotification.R;
import com.example.guest999.firebasenotification.utilis.CheckConnection;
import com.example.guest999.firebasenotification.utilis.Delete_Data;
import com.example.guest999.firebasenotification.utilis.DownloadCallBack;
import com.example.guest999.firebasenotification.utilis.DownloadTaskIMG;
import com.example.guest999.firebasenotification.utilis.DownloadTaskPDF;
import com.example.guest999.firebasenotification.utilis.MarshmallowPermissions;
import com.example.guest999.firebasenotification.utilis.SharedPreferenceManager;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import io.netopen.hotbitmapgg.library.view.RingProgressBar;
import static com.example.guest999.firebasenotification.Config.PhoneFromDevice;
/**
* Created by Harshad and Modified by Joshi Tushar and Hiren
*/
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements DownloadCallBack {
private static final int REQUEST_WRITE_STORAGE = 112;
private static final int RESULT_LOAD_FILE = 0;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_CODE_PICK_CONTACTS = 99;
private static final int REQUEST_TEXT = 7;
private static DownloadTaskIMG downloadTask;
private static DownloadTaskPDF downloadPdf;
private static ArrayList<HashMap<String, String>> file_paths = new ArrayList<>();
private SwipyRefreshLayout swipeRefreshLayout;
private Boolean chkVisibility = false;
private ImagePick image;
private File extStore;
private String ImageFileName, localPaTH, FileName;
private DownloadCallBack downloadCallBack;
private File myFile, LocalFile, myFile_;
private LayoutInflater inflater = null;
private Context context;
private MarshmallowPermissions marshmallowPermissions;
private FilePick file;
private Delete_Data delete_data;
public DataAdapter(Context mcontext, ArrayList<HashMap<String, String>> file_paths, SwipyRefreshLayout swipeRefreshLayout) {
this.context = mcontext;
inflater = LayoutInflater.from(context);
DataAdapter.file_paths = file_paths;
downloadCallBack = this;
this.swipeRefreshLayout = swipeRefreshLayout;
marshmallowPermissions = new MarshmallowPermissions((Activity) context);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemViewType(int position) {
// Log.e("getItemViewType:pos ", String.valueOf(position));
Log.e("IS this PDF ?", String.valueOf(file_paths.get(position).get(Config.TAG_DATA).endsWith(".pdf")));
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
return RESULT_LOAD_FILE;
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".png") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".jpg") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".jpeg")) {
return RESULT_LOAD_IMAGE;
} else if (file_paths.get(position).get(Config.TAG_DATA).contains("::")) {
return REQUEST_CODE_PICK_CONTACTS;
} else {
return REQUEST_TEXT;
}
}
private void NoApplicationAvailable(final int position) {
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
builder.setTitle("Warning");
builder.setMessage("No Application available to view this file");
builder.setIcon(R.drawable.error);
builder.setPositiveButton("Download",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String appPackageName = context.getPackageName(); // getPackageName() from Context or Activity object
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.rarlab.rar&hl=en" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.rarlab.rar&hl=en" + appPackageName)));
}
} else {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=cn.wps.moffice_eng&hl=en" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=cn.wps.moffice_eng&hl=en" + appPackageName)));
}
}
}
});
builder.setNegativeButton("Not Now",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
android.support.v7.app.AlertDialog dialog = builder.create();
// display dialog
try {
dialog.show();
} catch (Exception ed) {
ed.printStackTrace();
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
Log.e("layout code: ", viewType + "");
if (viewType == RESULT_LOAD_FILE) {
v = inflater
.inflate(R.layout.raw_file, parent, false);
return new FilePick(v);
} else if (viewType == RESULT_LOAD_IMAGE) {
v = inflater
.inflate(R.layout.raw_image, parent, false);
return new ImagePick(v);
} else if (viewType == REQUEST_CODE_PICK_CONTACTS) {
v = inflater
.inflate(R.layout.raw_contact, parent, false);
return new ContactPick(v);
} else {
v = inflater
.inflate(R.layout.raw_text, parent, false);
return new TextSend(v);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.setIsRecyclable(false);
//for Internet
CheckConnection cd;
IntentFilter filter;
String ad_date = file_paths.get(position).get(Config.CURRENT_DATE);
String ad_time = file_paths.get(position).get(Config.CURRENT_TIME);
String file_size = file_paths.get(position).get(Config.KEY_FILE_SIZE);
PhoneFromDevice = SharedPreferenceManager.getDefaults("phone", context);
Log.e("onBindViewHolder:pos ", String.valueOf(position));
if (holder instanceof FilePick) {
file = (FilePick) holder;
final String pdfname = file_paths.get(position).get(Config.TAG_DATA).replace("http://www.laxmisecurity.com/android/uploads/", "");
FileName = file.temp.getText().toString();
extStore = Environment.getExternalStorageDirectory();
myFile_ = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + FileName);
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf")) {
file.file_type_image.setBackgroundResource(R.drawable.pdf);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc")) {
file.file_type_image.setBackgroundResource(R.drawable.word);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt")) {
file.file_type_image.setBackgroundResource(R.drawable.txt);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt")) {
file.file_type_image.setBackgroundResource(R.drawable.ppt);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx")) {
file.file_type_image.setBackgroundResource(R.drawable.ppt);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
file.file_type_image.setBackgroundResource(R.drawable.zip);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
file.file_type_image.setBackgroundResource(R.drawable.xls);
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
file.file_type_image.setBackgroundResource(R.drawable.rar);
}
file.temp.setText(pdfname.substring(10));
file.textview_time.setText(ad_time);
file.textview_date.setText(ad_date);
file.txt_file_size.setText(file_size);
if (!file_paths.get(position).get(Config.KEY_PHONE).equals(PhoneFromDevice)) {
//for receive file
file.status.setText(R.string.received);
file.txt_file_size.setTextColor(Color.GRAY);
try {
file.outgoing_layout_bubble.setGravity(Gravity.START | Gravity.BOTTOM);
file.linearLayout.setGravity(Gravity.START | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
file.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incomin_normal);
} else {
// do something else
file.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incoming_normal);
}
file.outgoing_layout_bubble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//for downloading pdf 07-10-2016
localPaTH = file_paths.get(position).get(Config.KEY_LOCAL_PATH);
LocalFile = new File(localPaTH);
FileName = file.temp.getText().toString();
extStore = Environment.getExternalStorageDirectory();
myFile_ = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + pdfname.substring(10));
// File myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + file.temp.getText().toString());
if (myFile_.exists()) {
// Toast.makeText(context, "File already Exists in " + myFile, Toast.LENGTH_SHORT).show();
try {
// File pdfFile = new File(Environment.getExternalStorageDirectory() + "/FileSharing/" + pdfname ); // -> filename
//file.outgoing_layout_bubble.removeView(file.myButton);
Uri path = Uri.fromFile(myFile_);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf")) {
pdfIntent.setDataAndType(path, "application/pdf");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc")) {
pdfIntent.setDataAndType(path, "application/msword");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt")) {
pdfIntent.setDataAndType(path, "text/plain");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-powerpoint");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/zip");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-excel");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
pdfIntent.setDataAndType(path, "application/x-rar-compressed");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/octet-stream");
}
// file.myButton.setVisibility(INVISIBLE);
context.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
NoApplicationAvailable(position);
}
} else {
extStore = Environment.getExternalStorageDirectory();
//myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + ImageFileName);
myFile_ = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + pdfname.substring(10));
if (!myFile_.exists()) {
if (marshmallowPermissions.checkIfAlreadyhavePermission()) {
// execute this when the downloader must be fired
downloadPdf = new DownloadTaskPDF(context, Config.INTERNAL_IMAGE_PATH_URI, "" + pdfname.substring(10), downloadCallBack, swipeRefreshLayout);
// downloadTask.execute("http://ia.tranetech.ae:82/upload/uploads/five-point-someone-chetan-bhagat_ebook.pdf", "" + finalHolder.tv_paper_name.getText().toString() + ".pdf");
downloadPdf.execute(file_paths.get(position).get(Config.TAG_DATA), "" + pdfname.substring(10));
} else {
marshmallowPermissions.requestpermissions();
}
} else {
try {
// File pdfFile = new File(Environment.getExternalStorageDirectory() + "/FileSharing/" + pdfname ); // -> filename
//file.outgoing_layout_bubble.removeView(file.myButton);
Uri path = Uri.fromFile(myFile_);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf")) {
pdfIntent.setDataAndType(path, "application/pdf");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc")) {
pdfIntent.setDataAndType(path, "application/msword");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt")) {
pdfIntent.setDataAndType(path, "text/plain");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-powerpoint");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/zip");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-excel");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
pdfIntent.setDataAndType(path, "application/x-rar-compressed");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/octet-stream");
}
// file.myButton.setVisibility(INVISIBLE);
context.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
NoApplicationAvailable(position);
}
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
//for sent files
file.status.setText(R.string.sent);
try {
file.outgoing_layout_bubble.setGravity(Gravity.END | Gravity.BOTTOM);
file.linearLayout.setGravity(Gravity.END | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
file.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoin_normal);
} else {
// do something else
file.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoing_normal);
}
file.temp.setTextColor(Color.WHITE);
file.txt_file_size.setTextColor(Color.WHITE);
file.textview_time.setTextColor(Color.WHITE);
file.textview_date.setTextColor(Color.WHITE);
file.status.setTextColor(Color.WHITE);
} catch (Exception e) {
e.printStackTrace();
}
//for image download on click.
file.outgoing_layout_bubble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
localPaTH = file_paths.get(position).get(Config.KEY_LOCAL_PATH);
LocalFile = new File(localPaTH);
FileName = file.temp.getText().toString();
extStore = Environment.getExternalStorageDirectory();
//myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + ImageFileName);
myFile_ = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + pdfname.substring(10));
// File myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah File/" + file.temp.getText().toString());
if (LocalFile.exists()) {
// Toast.makeText(context, "File already Exists in " + myFile, Toast.LENGTH_SHORT).show();
try {
// File pdfFile = new File(Environment.getExternalStorageDirectory() + "/FileSharing/" + pdfname ); // -> filename
//file.outgoing_layout_bubble.removeView(file.myButton);
Uri path = Uri.fromFile(LocalFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf")) {
pdfIntent.setDataAndType(path, "application/pdf");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc")) {
pdfIntent.setDataAndType(path, "application/msword");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt")) {
pdfIntent.setDataAndType(path, "text/plain");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-powerpoint");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/zip");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-excel");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
pdfIntent.setDataAndType(path, "application/x-rar-compressed");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/octet-stream");
}
// file.myButton.setVisibility(INVISIBLE);
context.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
NoApplicationAvailable(position);
}
} else {
if (!myFile_.exists()) {
if (marshmallowPermissions.checkIfAlreadyhavePermission()) {
// execute this when the downloader must be fired
downloadPdf = new DownloadTaskPDF(context, Config.INTERNAL_IMAGE_PATH_URI, "" + pdfname.substring(10), downloadCallBack, swipeRefreshLayout);
// downloadTask.execute("http://ia.tranetech.ae:82/upload/uploads/five-point-someone-chetan-bhagat_ebook.pdf", "" + finalHolder.tv_paper_name.getText().toString() + ".pdf");
downloadPdf.execute(file_paths.get(position).get(Config.TAG_DATA), "" + pdfname.substring(10));
} else {
marshmallowPermissions.requestpermissions();
}
} else {
try {
// File pdfFile = new File(Environment.getExternalStorageDirectory() + "/FileSharing/" + pdfname ); // -> filename
//file.outgoing_layout_bubble.removeView(file.myButton);
Uri path = Uri.fromFile(myFile_);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pdf")) {
pdfIntent.setDataAndType(path, "application/pdf");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".docx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".doc")) {
pdfIntent.setDataAndType(path, "application/msword");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".txt")) {
pdfIntent.setDataAndType(path, "text/plain");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".ppt")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-powerpoint");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".pptx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/zip");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xls")) {
pdfIntent.setDataAndType(path, "application/vnd.ms-excel");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".xlsx")) {
pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar")) {
pdfIntent.setDataAndType(path, "application/x-rar-compressed");
} else if (file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".rar") || file_paths.get(position).get(Config.TAG_DATA).toLowerCase().endsWith(".zip")) {
pdfIntent.setDataAndType(path, "application/octet-stream");
}
// file.myButton.setVisibility(INVISIBLE);
context.startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
NoApplicationAvailable(position);
}
}
}
}
});
}
file.outgoing_layout_bubble.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
file.dialog = new Dialog(context);
file.dialog.setContentView(R.layout.dialog_del);
file.dialog.setTitle("Select Action");
file.dialog.findViewById(R.id.lv_del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Delet_data(position, file_paths.size());
file.dialog.dismiss();
}
});
// show dialog on screen
//contactPick.dialog.getWindow().getAttributes().windowAnimations = animationSource;
file.dialog.show();
return false;
}
});
} else if (holder instanceof ImagePick) {
// below code changed by Hiren please ask if you want to modified.
try {
image = (DataAdapter.ImagePick) holder;
ImageFileName = file_paths.get(position).get(Config.TAG_DATA).replace(Config.INTERNAL_IMAGE_PATH_URI, "");
extStore = Environment.getExternalStorageDirectory();
myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah Images/" + ImageFileName.substring(10));
localPaTH = file_paths.get(position).get(Config.KEY_LOCAL_PATH);
LocalFile = new File(localPaTH);
image.txt_img_size.setText(file_size);
image.textview_time.setText(ad_time);
image.textview_date.setText(ad_date);
PhoneFromDevice = SharedPreferenceManager.getDefaults("phone", context);
if (!file_paths.get(position).get(Config.KEY_PHONE).equals(PhoneFromDevice)) {
image.status.setText(R.string.received);
image.outgoing_layout_bubble.setGravity(Gravity.LEFT | Gravity.BOTTOM);
image.linearLayout.setGravity(Gravity.LEFT | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
image.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incomin_normal);
} else {
// do something else
image.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incoming_normal);
}
// coding for recived items
// below code created by Hiren please ask if you want to delete it.
if (!myFile.exists()) {
chkVisibility = true;
Change_VisiBility(chkVisibility);
try {
Glide.with(context.getApplicationContext())
.load(file_paths.get(position).get(Config.TAG_DATA))
.placeholder(R.drawable.placeholder)
.override(18, 18)
.error(R.drawable.placeholder)
.crossFade()
.centerCrop()
.into(image.score);
} catch (Exception e) {
e.printStackTrace();
}
} else {
chkVisibility = false;
Change_VisiBility(chkVisibility);
try {
Glide.with(context.getApplicationContext())
.load(myFile)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.crossFade()
.centerCrop()
.into(image.score);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
// coding for sent items
image.status.setText(R.string.sent);
image.outgoing_layout_bubble.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
image.linearLayout.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
image.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoin_normal);
} else {
// do something else
image.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoing_normal);
}
image.status.setTextColor(Color.WHITE);
image.textview_time.setTextColor(Color.WHITE);
image.textview_date.setTextColor(Color.WHITE);
//below code created by Hiren please ask if you want to delete it.
localPaTH = file_paths.get(position).get(Config.KEY_LOCAL_PATH);
LocalFile = new File(localPaTH);
if (LocalFile.exists()) {
chkVisibility = false;
Change_VisiBility(chkVisibility);
try {
Glide.with(context.getApplicationContext())
.load(LocalFile)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.crossFade()
.centerCrop()
.into(image.score);
} catch (Exception e) {
e.printStackTrace();
}
} else {
//below code created by Hiren please ask if you want to delete it.
ImageFileName = file_paths.get(position).get(Config.TAG_DATA).replace(Config.INTERNAL_IMAGE_PATH_URI, "");
extStore = Environment.getExternalStorageDirectory();
myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah Images/" + ImageFileName.substring(10));
if (!myFile.exists()) {
// image.spinwheel.setVisibility(View.VISIBLE);
chkVisibility = true;
Change_VisiBility(chkVisibility);
try {
Glide.with(context.getApplicationContext())
.load(file_paths.get(position).get(Config.TAG_DATA))
.placeholder(R.drawable.placeholder)
.override(18, 18)
.error(R.drawable.placeholder)
.crossFade()
.centerCrop()
.into(image.score);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// image.spinwheel.setVisibility(View.INVISIBLE);
chkVisibility = false;
Change_VisiBility(chkVisibility);
try {
Glide.with(context.getApplicationContext())
.load(myFile)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.crossFade()
.centerCrop()
.into(image.score);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//for image download on click.
image.outgoing_layout_bubble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//below code created by Hiren please ask if you want to delete it.
localPaTH = file_paths.get(position).get(Config.KEY_LOCAL_PATH);
LocalFile = new File(localPaTH);
//below code created by Hiren please ask if you want to delete it.
ImageFileName = file_paths.get(position).get(Config.TAG_DATA).replace(Config.INTERNAL_IMAGE_PATH_URI, "");
extStore = Environment.getExternalStorageDirectory();
myFile = new File(extStore.getAbsolutePath() + "/P L Shah/P L Shah Images/" + ImageFileName.substring(10));
if (myFile.exists()) {
chkVisibility = false;
Change_VisiBility(chkVisibility);
Uri path = Uri.fromFile(myFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "image/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application in your device available to view", Toast.LENGTH_SHORT).show();
}
} else {
if (!myFile.exists()) {
if (marshmallowPermissions.checkIfAlreadyhavePermission()) {
// execute this when the downloader must be fired
downloadTask = new DownloadTaskIMG(context, Config.INTERNAL_IMAGE_PATH_URI, "" + ImageFileName, downloadCallBack, swipeRefreshLayout);
downloadTask.execute();
} else {
marshmallowPermissions.requestpermissions();
}
} else {
chkVisibility = false;
Change_VisiBility(chkVisibility);
Uri path = Uri.fromFile(myFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "image/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application in your device available to view", Toast.LENGTH_SHORT).show();
}
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
image.outgoing_layout_bubble.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
image.dialog = new Dialog(context);
image.dialog.setContentView(R.layout.dialog_del);
image.dialog.setTitle("Select Action");
image.dialog.findViewById(R.id.lv_del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Delet_data(position, file_paths.size());
image.dialog.dismiss();
}
});
// show dialog on screen
//contactPick.dialog.getWindow().getAttributes().windowAnimations = animationSource;
image.dialog.show();
return false;
}
});
} else if (holder instanceof ContactPick) {
try {
final String Contact_name = file_paths.get(position).get(Config.TAG_DATA);
final ContactPick contactPick = (ContactPick) holder;
String[] splited = Contact_name.split("::");
final String phone_no = splited[0];
final String phone_name = splited[1];
try {
Log.e("onBindViewHolder: ", phone_no);
Log.e("onBindViewHolder: ", phone_name);
} catch (Exception e) {
e.printStackTrace();
}
try {
contactPick.no.setText(phone_no);
contactPick.name.setText(phone_name);
contactPick.textview_time.setText(ad_time);
contactPick.textview_date.setText(ad_date);
} catch (Exception e) {
e.printStackTrace();
}
if (!file_paths.get(position).get(Config.KEY_PHONE).equals(PhoneFromDevice)) {
contactPick.status.setText(R.string.received);
contactPick.outgoing_layout_bubble.setGravity(Gravity.START | Gravity.BOTTOM);
contactPick.linearLayout.setGravity(Gravity.START | Gravity.BOTTOM);
contactPick.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incoming_normal);
contactPick.outgoing_layout_bubble.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
contactPick.dialog = new Dialog(context);
contactPick.dialog.setContentView(R.layout.dialog_contact);
contactPick.dialog.setTitle("Select Action");
contactPick.dialog.findViewById(R.id.lv_call).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone_no));
Log.e("onClick: ", phone_no);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
context.startActivity(callIntent);
contactPick.dialog.dismiss();
}
});
contactPick.dialog.findViewById(R.id.lv_del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Delet_data(position, file_paths.size());
contactPick.dialog.dismiss();
}
});
contactPick.dialog.findViewById(R.id.lv_add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT,
ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(ContactsContract.Intents.Insert.NAME, phone_name);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone_no);
context.startActivity(intent);
contactPick.dialog.dismiss();
}
});
// show dialog on screen
//contactPick.dialog.getWindow().getAttributes().windowAnimations = animationSource;
contactPick.dialog.show();
return false;
}
});
} else {
contactPick.status.setText(R.string.sent);
contactPick.outgoing_layout_bubble.setGravity(Gravity.END | Gravity.BOTTOM);
contactPick.linearLayout.setGravity(Gravity.END | Gravity.BOTTOM);
contactPick.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoing_normal);
contactPick.status.setTextColor(Color.WHITE);
contactPick.no.setTextColor(Color.WHITE);
contactPick.name.setTextColor(Color.WHITE);
contactPick.textview_time.setTextColor(Color.WHITE);
contactPick.textview_date.setTextColor(Color.WHITE);
contactPick.outgoing_layout_bubble.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
contactPick.dialog = new Dialog(context);
contactPick.dialog.setContentView(R.layout.dialog_contact);
contactPick.dialog.setTitle("Select Action");
contactPick.dialog.findViewById(R.id.lv_call).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone_no));
Log.e("onClick: ", phone_no);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
context.startActivity(callIntent);
contactPick.dialog.dismiss();
}
});
contactPick.dialog.findViewById(R.id.lv_del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Delet_data(position, file_paths.size());
contactPick.dialog.dismiss();
}
});
contactPick.dialog.findViewById(R.id.lv_add).setVisibility(View.GONE);
contactPick.dialog.findViewById(R.id.contact_divider).setVisibility(View.GONE);
// show dialog on screen
//contactPick.dialog.getWindow().getAttributes().windowAnimations = animationSource;
contactPick.dialog.show();
return false;
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (holder instanceof TextSend) {
try {
final String Contact_name = file_paths.get(position).get(Config.TAG_DATA);
final TextSend textSend = (TextSend) holder;
try {
textSend.msg.setText(Contact_name);
textSend.textview_time.setText(ad_time);
textSend.textview_date.setText(ad_date);
} catch (Exception e) {
e.printStackTrace();
}
if (!file_paths.get(position).get(Config.KEY_PHONE).equals(PhoneFromDevice)) {
textSend.status.setText(R.string.received);
textSend.outgoing_layout_bubble.setGravity(Gravity.START | Gravity.BOTTOM);
textSend.linearLayout.setGravity(Gravity.START | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
textSend.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incomin_normal);
} else {
// do something else
textSend.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_incoming_normal);
}
} else {
textSend.status.setText(R.string.sent);
textSend.outgoing_layout_bubble.setGravity(Gravity.END | Gravity.BOTTOM);
textSend.linearLayout.setGravity(Gravity.END | Gravity.BOTTOM);
boolean tabletSize = context.getResources().getBoolean(R.bool.tablet);
if (tabletSize) {
// do something
textSend.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoin_normal);
} else {
// do something else
textSend.outgoing_layout_bubble.setBackgroundResource(R.drawable.balloon_outgoing_normal);
}
textSend.status.setTextColor(Color.WHITE);
textSend.msg.setTextColor(Color.WHITE);
textSend.textview_time.setTextColor(Color.WHITE);
textSend.textview_date.setTextColor(Color.WHITE);
}
textSend.outgoing_layout_bubble.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
textSend.dialog = new Dialog(context);
textSend.dialog.setContentView(R.layout.dialog_del);
textSend.dialog.setTitle("Select Action");
textSend.dialog.findViewById(R.id.lv_del).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Delet_data(position, file_paths.size());
textSend.dialog.dismiss();
}
});
// show dialog on screen
//contactPick.dialog.getWindow().getAttributes().windowAnimations = animationSource;
textSend.dialog.show();
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void Delet_data(int position, int size) {
if (CheckConnection.ni != null) {
String adid = file_paths.get(position).get(Config.ad_id);
delete_data = new Delete_Data(context, adid, swipeRefreshLayout);
file_paths.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, size);
notifyDataSetChanged();
} else {
Toast.makeText(context, "No Internet Available", Toast.LENGTH_LONG).show();
}
}
@Override
public int getItemCount() {
return file_paths.size();
}
@Override
public void onDownloadComplete() {
notifyDataSetChanged();
}
private void Change_VisiBility(Boolean chkVisibility) {
if (chkVisibility) {
image.txt_img_size.setVisibility(View.VISIBLE);
image.rl_img_size.setVisibility(View.VISIBLE);
image.rpb_img_size.setVisibility(View.VISIBLE);
image.ib_img_size.setVisibility(View.VISIBLE);
} else {
image.txt_img_size.setVisibility(View.INVISIBLE);
image.rl_img_size.setVisibility(View.INVISIBLE);
image.rpb_img_size.setVisibility(View.INVISIBLE);
image.ib_img_size.setVisibility(View.INVISIBLE);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View itemView) {
super(itemView);
}
}
private class FilePick extends ViewHolder {
TextView temp, txt_file_size;
TextView status, textview_time, textview_date;
LinearLayout outgoing_layout_bubble;
LinearLayout linearLayout;
ImageView file_type_image;
private Dialog dialog;
FilePick(View v) {
super(v);
this.temp = (TextView) v.findViewById(R.id.file_name);
this.status = (TextView) v.findViewById(R.id.send_receive);
this.txt_file_size = (TextView) v.findViewById(R.id.txt_file_size);
this.textview_time = (TextView) v.findViewById(R.id.textview_time);
this.textview_date = (TextView) v.findViewById(R.id.textview_date);
this.outgoing_layout_bubble = (LinearLayout) v.findViewById(R.id.outgoing_layout_bubble);
this.linearLayout = (LinearLayout) v.findViewById(R.id.mainlinearlayout);
this.file_type_image = (ImageView) v.findViewById(R.id.file_image);
}
}
private class ImagePick extends ViewHolder {
private RingProgressBar rpb_img_size;
private ImageButton ib_img_size;
// private ProgressBar spinwheel;
private RelativeLayout rl_img_size;
private ImageView score;
private Dialog dialog;
private TextView status, textview_time, textview_date, txt_img_size;
private LinearLayout outgoing_layout_bubble;
private LinearLayout linearLayout;
ImagePick(View v) {
super(v);
this.txt_img_size = (TextView) v.findViewById(R.id.txt_img_size);
this.ib_img_size = (ImageButton) v.findViewById(R.id.ib_img_size);
this.rpb_img_size = (RingProgressBar) v.findViewById(R.id.rpb_img_size);
this.rl_img_size = (RelativeLayout) v.findViewById(R.id.rl_img_size);
this.score = (ImageView) v.findViewById(R.id.image_list);
this.status = (TextView) v.findViewById(R.id.send_receive);
this.textview_time = (TextView) v.findViewById(R.id.textview_time);
this.textview_date = (TextView) v.findViewById(R.id.textview_date);
this.outgoing_layout_bubble = (LinearLayout) v.findViewById(R.id.outgoing_layout_bubble);
this.linearLayout = (LinearLayout) v.findViewById(R.id.mainlinearlayout);
}
}
private class ContactPick extends ViewHolder {
TextView status, textview_time, textview_date, no, name;
LinearLayout outgoing_layout_bubble;
LinearLayout linearLayout;
private Dialog dialog;
ContactPick(View v) {
super(v);
this.no = (TextView) v.findViewById(R.id.contact_no);
this.name = (TextView) v.findViewById(R.id.contact_name);
this.status = (TextView) v.findViewById(R.id.send_receive);
this.textview_time = (TextView) v.findViewById(R.id.textview_time);
this.textview_date = (TextView) v.findViewById(R.id.textview_date);
this.outgoing_layout_bubble = (LinearLayout) v.findViewById(R.id.outgoing_layout_bubble);
this.linearLayout = (LinearLayout) v.findViewById(R.id.mainlinearlayout);
}
}
private class TextSend extends ViewHolder {
TextView status, textview_time, textview_date, msg;
LinearLayout outgoing_layout_bubble;
LinearLayout linearLayout;
private Dialog dialog;
TextSend(View v) {
super(v);
this.msg = (TextView) v.findViewById(R.id.client_text);
this.status = (TextView) v.findViewById(R.id.send_receive);
this.textview_time = (TextView) v.findViewById(R.id.textview_time);
this.textview_date = (TextView) v.findViewById(R.id.textview_date);
this.outgoing_layout_bubble = (LinearLayout) v.findViewById(R.id.outgoing_layout_bubble);
this.linearLayout = (LinearLayout) v.findViewById(R.id.mainlinearlayout);
}
}
}
| [
"hiren7884@gmail.com"
] | hiren7884@gmail.com |
4c2bfd1da40c2a7aa9ad2274ea747a38d2d14c27 | 42bc36469b9c931d0633633495be7d137e99c90a | /src/main/java/org/garen/oss/exception/GlobalExceptionHandler.java | 6c7fc7e9fdf43de26712b2154f5268c8a206ca32 | [] | no_license | GarenGosling/oss-rest-app | 915469a585171e93fc983ac2c43d792b45a20fba | 1a6db9595ca7d64f5e2f2dc5501f16faa9fb3ff1 | refs/heads/master | 2021-09-09T01:58:10.343916 | 2018-03-13T08:26:00 | 2018-03-13T08:26:00 | 103,112,661 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,540 | java | package org.garen.oss.exception;
import org.garen.oss.mybatis.exception.DBException;
import org.garen.oss.swagger.model.ErrorModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
public class GlobalExceptionHandler {
protected Logger LOGGER = LoggerFactory.getLogger(getClass());
//TODO error log
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public ErrorModel exceptionHandler(Exception e, HttpServletResponse response) {
LOGGER.error("Exception-{}", e.getMessage());
e.printStackTrace();
ErrorModel resp = new ErrorModel();
resp.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
resp.setMessage("服务器异常,请联系管理员:" + e.getMessage());
return resp;
}
@ExceptionHandler(value = {BusinessException.class})
@ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定
public ErrorModel exceptionHandler(BusinessException e, HttpServletResponse response) {
LOGGER.error("BusinessException - {}", e.getMessage());
ErrorModel resp = new ErrorModel();
resp.setCode( e.getCode());
resp.setMessage( e.getMessage());
return resp;
}
@ExceptionHandler(value = {DBException.class})
@ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定
public ErrorModel exceptionHandler(DBException e, HttpServletResponse response) {
LOGGER.error("DBException - {}", e.getMessage());
ErrorModel resp = new ErrorModel();
resp.setCode( HttpStatus.INTERNAL_SERVER_ERROR.value());
resp.setMessage( e.getMessage());
return resp;
}
@ExceptionHandler(value = {BadRequestException.class})
@ResponseBody //在返回自定义相应类的情况下必须有,这是@ControllerAdvice注解的规定
public ErrorModel exceptionHandler(BadRequestException e, HttpServletResponse response) {
LOGGER.error("BadRequestException - {}", e.getMessage());
ErrorModel resp = new ErrorModel();
resp.setCode( e.getCode());
resp.setMessage( e.getMessage());
return resp;
}
}
| [
"liuxueliang@yingu.com"
] | liuxueliang@yingu.com |
18d6515a3ad092512d66a88181d825af7eb07f0b | e952b3e5603dbcee320055cb454e9d0bcde50e79 | /app/src/main/java/com/koreait/myapplication/ch10/MovieListActivity.java | c7e9c78842c7dc5e0075039b6c2da0e8ad66a299 | [] | no_license | processUser/android | d068801528a72ffae83b6ce1d98efb3856551137 | bd94216b1f6b916fc3776114f37bb1f3507337e9 | refs/heads/main | 2023-08-23T21:25:09.892886 | 2021-10-26T02:14:25 | 2021-10-26T02:14:25 | 417,010,644 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,181 | java | package com.koreait.myapplication.ch10;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.koreait.myapplication.R;
import com.koreait.myapplication.ch10.searchmoviemodel.MovieListResultBodyVO;
import com.koreait.myapplication.ch10.searchmoviemodel.MovieVO;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MovieListActivity extends AppCompatActivity {
private Retrofit rf;
private final String KEY = "c368df0859f6194cec7d22fe3a4756dc";
private MovieListAdapter adapter;
private RecyclerView rvList;
private final String ITEM_PER_PAGE = "20";
private int curpage = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
rf = new Retrofit.Builder()
.baseUrl("https://www.kobis.or.kr/kobisopenapi/webservice/rest/")
.addConverterFactory(GsonConverterFactory.create())
.build();
rvList = findViewById(R.id.rvList);
rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(!recyclerView.canScrollVertically(1) && newState==RecyclerView.SCROLL_STATE_IDLE){
Log.i("myLog", "스크롤 끝!");
getList();
}
}
});
adapter = new MovieListAdapter();
rvList.setAdapter(adapter);
getList();
}
private void getList() {
KobisService service = rf.create(KobisService.class);
Call<MovieListResultBodyVO> call = service.searchMovieList(KEY, ITEM_PER_PAGE, curpage++);
call.enqueue(new Callback<MovieListResultBodyVO>() {
@Override
public void onResponse(Call<MovieListResultBodyVO> call, Response<MovieListResultBodyVO> response) {
if(response.isSuccessful()){
MovieListResultBodyVO result = response.body();
List<MovieVO> list = result.getMovieListResult().getMovieList();
for(MovieVO vo : list) {
adapter.addItem(vo);
}
adapter.notifyDataSetChanged();
} else {
Log.e("myLog","통신 오류");
}
}
@Override
public void onFailure(Call<MovieListResultBodyVO> call, Throwable t) {
//통신 실패
Log.e("myLog","통신 실패");
}
});
}
}
class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MyViewHolder>{
static private List<MovieVO> list = new ArrayList<>();
public void addItem(MovieVO vo){
list.add(vo);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.item_movie, parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
MovieVO obj = list.get(position);
holder.setItem(obj);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String movieCd=obj.getMovieCd();
Log.i("myLog",movieCd);
Intent intent = new Intent(v.getContext(), MovieDetailActivity.class);
intent.putExtra("movieCd", movieCd);
v.getContext().startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder{
private TextView tvMovieNm;
private TextView tvRepNationNm;
private TextView tvMovieNmEn;
private TextView RepGenreNm;
public MyViewHolder(View v){
super(v);
tvMovieNm = v.findViewById(R.id.tvMovieNm);
tvRepNationNm = v.findViewById(R.id.tvRepNationNm);
tvMovieNmEn = v.findViewById(R.id.tvMovieNmEn);
RepGenreNm = v.findViewById(R.id.RepGenreNm);
}
public void setItem(MovieVO vo){
tvMovieNm.setText(vo.getMovieNm());
tvRepNationNm.setText(vo.getRepNationNm());
tvMovieNmEn.setText(vo.getMovieNmEn());
RepGenreNm.setText(vo.getRepGenreNm());
}
}
} | [
"gitacc33@gmail.com"
] | gitacc33@gmail.com |
32f7fdaa0371ea9d9467e734abe3631e5e97c03d | 16c885354a0e095894420c799aa9615e9a7b9845 | /uSearch/src/uSearch/CreateItems.java | 4295d7427ec48a955856dd41aa3b252a2f625dec | [
"MIT"
] | permissive | NishanthRaveendran/uSearch | 45cb62795fc57efffa317bdb3e6ad6f301bd5f7c | 9499839cde41b4d36bc0fad482d7fbf9f036f61d | refs/heads/master | 2020-05-21T03:59:38.885839 | 2019-05-10T02:24:38 | 2019-05-10T02:24:38 | 185,902,401 | 0 | 0 | MIT | 2019-05-10T02:12:16 | 2019-05-10T02:12:16 | null | UTF-8 | Java | false | false | 3,008 | java | package uSearch;
/**
* Library of functions to create corresponding items used in the program from a
* list describing it.
*/
public class CreateItems {
/**
* Used to create products from list of strings take from data set.
*
* @param productString List of strings of product data
* @return List of products made from list of strings
*/
public static Product[] createProducts(String[] productstring) {
Product[] products = new Product[productstring.length];
for (int j = 0; j < products.length; j++) {
String[] tempsplit1 = productstring[j].split(", group:");
String[] leftsplit = tempsplit1[0].split(", title:");
String[] leftleftsplit = leftsplit[0].split(":");
String asin = leftleftsplit[1].strip();
String title = leftsplit[1].strip();
String[] tempsplit = tempsplit1[1].split(":");
String[] tempsplit2 = tempsplit[0].split(",");
String group = tempsplit2[0].strip();
tempsplit2 = tempsplit[1].split(",");
String[] similar = null;
String[] testnull = tempsplit2[0].split(" ");
if (Integer.parseInt(testnull[0].strip()) != 0) {
similar = new String[testnull.length - 1];
for (int i = 1; i < testnull.length; i++) {
similar[i - 1] = testnull[i];
}
}
double rating = Double.parseDouble((tempsplit[2].strip()));
products[j] = new Product(asin, title, group, similar, rating);
}
return products;
}
/**
* Used to create reviews from list of strings take from data set.
*
* @param productString List of strings of review data
* @return List of reviews made from list of strings
*/
public static Review[] createReviews(String[] reviewstring) {
Review[] reviews = new Review[reviewstring.length];
for (int j = 0; j < reviewstring.length; j++) {
String[] tempsplit1 = reviewstring[j].split(", \"reviewText\":");
String[] tempsplit = tempsplit1[0].split(":");
String[] tempsplit2 = tempsplit[2].split(",");
String asin = tempsplit2[0].replaceAll("\"", "").strip();
tempsplit2 = tempsplit[3].split(",");
String reviewerName = tempsplit2[0].replaceAll("\"", "").strip();
String[] rightsplit = tempsplit1[1].split(", \"summary\":");
String[] leftsplit = rightsplit[0].split(", \"overall\":");
String reviewText = leftsplit[0].replaceAll("\"", "").strip();
double overall = Double.parseDouble(leftsplit[1].replaceAll("\"", "").strip());
String[] rightrightsplit = rightsplit[1].split(", \"unixReviewTime\":");
String summary = rightrightsplit[0].replaceAll("\"", "").strip();
tempsplit2 = rightrightsplit[1].split(", \"reviewTime\":");
int unixTime = Integer.parseInt(tempsplit2[0].replaceAll("\"", "").strip());
String temp = tempsplit2[1].replaceAll("}", "").strip();
String reviewTime = temp.replaceAll("\"", "").strip();
reviews[j] = new Review(asin, reviewerName, reviewText, overall, reviewTime, unixTime, summary);
}
return reviews;
}
} | [
"shesan24@hotmail.ca"
] | shesan24@hotmail.ca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.