text stringlengths 10 2.72M |
|---|
package tiny0.asint;
import tiny0.asint.TinyASint.*;
public interface Procesamiento {
void procesa(Asig asig);
void procesa(Resta exp);
void procesa(Mul exp);
void procesa(Div exp);
void procesa(Id exp);
void procesa(Decs_muchas decs);
void procesa(Decs_una decs);
void procesa(Prog_sin_decs prog);
void procesa(Prog_entero prog);
void procesa(Asigs_muchas asigs);
void procesa(Asigs_una asigs);
void procesa(Decs decs);
void procesa(Entero entero);
void procesa(Real real);
void procesa(CTrue cTrue);
void procesa(CFalse cFalse);
void procesa(Suma suma);
void procesa(And and);
void procesa(Or or);
void procesa(Lt lt);
void procesa(Gt gt);
void procesa(Leq leq);
void procesa(Geq geq);
void procesa(Eq eq);
void procesa(Neq neq);
void procesa(Not not);
void procesa(Neg neg);
void procesa(Prog_sin_asigs prog_sin_asigs);
void procesa(CBool cBool);
void procesa(CReal cReal);
void procesa(CInt cInt);
} |
package com.github.netudima.jmeter.junit.report;
import java.io.IOException;
import org.w3c.dom.Element;
public class AlternateJtlToJUnitReportTransformer {
public void transform(String jtlFile, String junitReportFile, String testSuiteName) throws IOException {
try (final AlternateDomXmlJUnitReportWriter writer
= new AlternateDomXmlJUnitReportWriter(junitReportFile, testSuiteName)) {
AlternateJtlFileReader reader = new AlternateJtlFileReader();
reader.parseCsvJtl(jtlFile, new AlternateJtlRecordProcessor() {
@Override
public void process(Element suite, JtlRecord jtlRecord) {
writer.write(suite, jtlRecord);
}
@Override
public Element processSuite(String suiteName) {
return writer.createSuite(suiteName);
}
});
}
}
public void transform(String jtlFile, String junitReportFile) throws IOException {
transform(jtlFile, junitReportFile, "");
}
}
|
package zm.gov.moh.core.repository.database.dao.domain;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import zm.gov.moh.core.repository.database.entity.domain.Concept;
import zm.gov.moh.core.repository.database.entity.domain.ConceptAnswer;
@Dao
public interface ConceptDao {
//get by concept id
@Query("SELECT * FROM concept")
List<Concept> getAll();
//get by concept id
@Query("SELECT concept_id FROM concept WHERE uuid = :uuid")
Long getConceptIdByUuid(String uuid);
@Query("SELECT concept_id FROM concept WHERE uuid = :uuid")
LiveData<Long> getConceptIdByUuidAsync(String uuid);
@Query("SELECT concept_id FROM concept WHERE uuid IN (:uuid)")
LiveData<List<Long>> getConceptIdByUuidObservable(List<String> uuid);
@Query("SELECT concept_id FROM concept WHERE uuid IN (:uuid)")
List<Long> getConceptIdByUuid(List<String> uuid);
@Query("SELECT uuid FROM concept WHERE concept_id = :conceptId")
String getConceptUuidById(long conceptId);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Concept... concepts);
}
|
package hirondelle.web4j.model;
import hirondelle.web4j.BuildImpl;
import hirondelle.web4j.request.Formats;
import hirondelle.web4j.request.RequestParameter;
import hirondelle.web4j.ui.translate.Translator;
import hirondelle.web4j.util.Args;
import hirondelle.web4j.util.EscapeChars;
import hirondelle.web4j.util.Util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
Informative message presented to the end user.
<P>This class exists in order to hide the difference between <em>simple</em> and
<em>compound</em> messages.
<P><a name="SimpleMessage"></a><b>Simple Messages</b><br>
Simple messages are a single {@link String}, such as <tt>'Item deleted successfully.'</tt>.
They are created using {@link #forSimple(String)}.
<P><a name="CompoundMessage"></a><b>Compound Messages</b><br>
Compound messages are made up of several parts, and have parameters. They are created
using {@link #forCompound(String, Object...)}. A compound message
is usually implemented in Java using {@link java.text.MessageFormat}. <span class="highlight">
However, <tt>MessageFormat</tt> is not used by this class, to avoid the following issues </span>:
<ul>
<li> the dreaded apostrophe problem. In <tt>MessageFormat</tt>, the apostrophe is a special
character, and must be escaped. This is highly unnatural for translators, and has been a
source of continual, bothersome errors. (This is the principal reason for not
using <tt>MessageFormat</tt>.)
<li>the <tt>{0}</tt> placeholders start at <tt>0</tt>, not <tt>1</tt>. Again, this is
unnatural for translators.
<li>the number of parameters cannot exceed <tt>10</tt>. (Granted, it is not often
that a large number of parameters are needed, but there is no reason why this
restriction should exist.)
<li>in general, {@link MessageFormat} is rather complicated in its details.
</ul>
<P><a name="CustomFormat"></a><b>Format of Compound Messages</b><br>
This class defines an alternative format to that defined by {@link java.text.MessageFormat}.
For example,
<PRE>
"At this restaurant, the _1_ meal costs _2_."
"On _2_, I am going to Manon's place to see _1_."
</PRE>
Here,
<ul>
<li>the placeholders appear as <tt>_1_</tt>, <tt>_2_</tt>, and so on.
They start at <tt>1</tt>, not <tt>0</tt>, and have no upper limit. There is no escaping
mechanism to allow the placeholder text to appear in the message 'as is'. The <tt>_i_</tt>
placeholders stand for an <tt>Object</tt>, and carry no format information.
<li>apostrophes can appear anywhere, and do not need to be escaped.
<li>the formats applied to the various parameters are taken from {@link Formats}.
If the default formatting applied by {@link Formats} is not desired, then the caller
can always manually format the parameter as a {@link String}. (The {@link Translator} may be used when
a different pattern is needed for different Locales.)
<li>the number of parameters passed at runtime must match exactly the number of <tt>_i_</tt>
placeholders
</ul>
<P><b>Multilingual Applications</b><br>
Multilingual applications will need to ensure that messages can be successfully translated when
presented in JSPs. In particular, some care must be exercised to <em>not</em> create
a <em>simple</em> message out of various pieces of data when a <em>compound</em> message
should be used instead. See {@link #getMessage(Locale, TimeZone)}.
As well, see the <a href="../ui/translate/package-summary.html">hirondelle.web4j.ui.translate</a>
package for more information, in particular the
{@link hirondelle.web4j.ui.translate.Messages} tag used for rendering <tt>AppResponseMessage</tt>s,
even in single language applications.
<P><b>Serialization</b><br>
This class implements {@link Serializable} to allow messages stored in session scope to
be transferred over a network, and thus survive a failover operation.
<i>However, this class's implementation of Serializable interface has a minor defect.</i>
This class accepts <tt>Object</tt>s as parameters to messages. These objects almost always represent
data - String, Integer, Id, DateTime, and so on, and all such building block classes are Serializable.
If, however, the caller passes an unusual message parameter object which is not Serializable, then the
serialization of this object (if it occurs), will fail.
<P>The above defect will likely not be fixed since it has large ripple effects, and would seem to cause
more problems than it would solve. In retrospect, this the message parameters passed to
{@link #forCompound(String, Object[])} should likely have been typed as Serializable, not Object.
*/
public final class AppResponseMessage implements Serializable {
/**
<a href="#SimpleMessage">Simple message</a> having no parameters.
<tt>aSimpleText</tt> must have content.
*/
public static AppResponseMessage forSimple(String aSimpleText){
return new AppResponseMessage(aSimpleText, NO_PARAMS);
}
/**
<a href="#CompoundMessage">Compound message</a> having parameters.
<P><tt>aPattern</tt> follows the <a href="#CustomFormat">custom format</a> defined by this class.
{@link Formats#objectToTextForReport} will be used to format all parameters.
@param aPattern must be in the style of the <a href="#CustomFormat">custom format</a>, and
the number of placeholders must match the number of items in <tt>aParams</tt>.
@param aParams must have at least one member; all members must be non-null, but may be empty
{@link String}s.
*/
public static AppResponseMessage forCompound(String aPattern, Object... aParams){
if ( aParams.length < 1 ){
throw new IllegalArgumentException("Compound messages must have at least one parameter.");
}
return new AppResponseMessage(aPattern, aParams);
}
/**
Return either the 'simple text' or the <em>formatted</em> pattern with all parameter data rendered,
according to which factory method was called.
<P>The configured {@link Translator} is used to localize
<ul>
<li>the text passed to {@link #forSimple(String)}
<li>the pattern passed to {@link #forCompound(String, Object...)}
<li>any {@link hirondelle.web4j.request.RequestParameter} parameters passed to {@link #forCompound(String, Object...)}
are localized by using {@link Translator} on the return value of {@link RequestParameter#getName()}
(This is intended for displaying localized versions of control names.)
</ul>
<P>It is highly recommended that this method be called <em>late</em> in processing, in a JSP.
<P>The <tt>Locale</tt> should almost always come from
{@link hirondelle.web4j.BuildImpl#forLocaleSource()}.
The <tt>aLocale</tt> parameter is always required, even though there are cases when it
is not actually used to render the result.
*/
public String getMessage(Locale aLocale, TimeZone aTimeZone){
String result = null;
Translator translator = BuildImpl.forTranslator();
Formats formats = new Formats(aLocale, aTimeZone);
if( fParams.isEmpty() ){
result = translator.get(fText, aLocale);
}
else {
String localizedPattern = translator.get(fText, aLocale);
List<String> formattedParams = new ArrayList<String>();
for (Object param : fParams){
if ( param instanceof RequestParameter ){
RequestParameter reqParam = (RequestParameter)param;
String translatedParamName = translator.get(reqParam.getName(), aLocale);
formattedParams.add( translatedParamName );
}
else {
//this will escape any special HTML chars in params :
formattedParams.add( formats.objectToTextForReport(param).toString() );
}
}
result = populateParamsIntoCustomFormat(localizedPattern, formattedParams);
}
return result;
}
/**
Return an unmodifiable <tt>List</tt> corresponding to the <tt>aParams</tt> passed to
the constructor.
<P>If no parameters are being used, then return an empty list.
*/
public List<Object> getParams(){
return Collections.unmodifiableList(fParams);
}
/**
Return either the 'simple text' or the pattern, according to which factory method
was called. Typically, this method is <em>not</em> used to present text to the user (see {@link #getMessage}).
*/
@Override public String toString(){
return fText;
}
@Override public boolean equals(Object aThat){
Boolean result = ModelUtil.quickEquals(this, aThat);
if ( result == null ){
AppResponseMessage that = (AppResponseMessage) aThat;
result = ModelUtil.equalsFor(this.getSignificantFields(), that.getSignificantFields());
}
return result;
}
@Override public int hashCode(){
return ModelUtil.hashCodeFor(getSignificantFields());
}
// PRIVATE
/** Holds either the simple text, or the custom pattern. */
private final String fText;
/** List of Objects holds the parameters. Empty List if no parameters used. */
private final List<Object> fParams;
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("_(\\d)+_");
private static final Object[] NO_PARAMS = new Object[0];
private static final Logger fLogger = Util.getLogger(AppResponseMessage.class);
private static final long serialVersionUID = 1000L;
private AppResponseMessage(String aText, Object... aParams){
fText = aText;
fParams = Arrays.asList(aParams);
validateState();
}
private void validateState(){
Args.checkForContent(fText);
if (fParams != null && fParams.size() > 0){
for(Object item : fParams){
if ( item == null ){
throw new IllegalArgumentException("Parameters to compound messages must be non-null.");
}
}
}
}
/**
@param aFormattedParams contains Strings ready to be placed in to the pattern. The index <tt>i</tt> of the
List matches the <tt>_i_</tt> placeholder. The size of aFormattedParams must match the number of
placeholders.
*/
private String populateParamsIntoCustomFormat(String aPattern, List<String> aFormattedParams){
StringBuffer result = new StringBuffer();
fLogger.finest("Populating " + Util.quote(aPattern) + " with params " + Util.logOnePerLine(aFormattedParams));
Matcher matcher = PLACEHOLDER_PATTERN.matcher(aPattern);
int numMatches = 0;
while ( matcher.find() ) {
++numMatches;
if(numMatches > aFormattedParams.size()){
String message = "The number of placeholders exceeds the number of available parameters (" + aFormattedParams.size() + ")";
fLogger.severe(message);
throw new IllegalArgumentException(message);
}
matcher.appendReplacement(result, getReplacement(matcher, aFormattedParams));
}
if(numMatches < aFormattedParams.size()){
String message = "The number of placeholders (" + numMatches + ") is less than the number of available parameters (" + aFormattedParams.size() + ")";
fLogger.severe(message);
throw new IllegalArgumentException(message);
}
matcher.appendTail(result);
return result.toString();
}
private String getReplacement(Matcher aMatcher, List<String> aFormattedParams){
String result = null;
String digit = aMatcher.group(1);
int idx = Integer.parseInt(digit);
if(idx <= 0){
throw new IllegalArgumentException("Placeholder digit should be 1,2,3... but takes value " + idx);
}
if(idx > aFormattedParams.size()){
throw new IllegalArgumentException("Placeholder index for _" + idx + "_ exceeds the number of available parameters (" + aFormattedParams.size() + ")");
}
result = aFormattedParams.get(idx - 1);
return EscapeChars.forReplacementString(result);
}
private Object[] getSignificantFields(){
return new Object[] {fText, fParams};
}
/**
Always treat de-serialization as a full-blown constructor, by validating the final state of the deserialized object.
*/
private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException {
aInputStream.defaultReadObject();
validateState();
}
}
|
package iks.pttrns.factory.ingridients;
public class ThinCrustDough extends Dough {
}
|
package com.screens;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
//Class imports
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.classes.LeaderboardPair;
import com.kroy.Kroy;
/**
* Screen displays the results of the game and prompts for new highscore.
*/
public class ResultScreen extends BasicScreen {
protected Texture texture;
protected Skin skin2;
private String displayText;
public int score;
public ArrayList<LeaderboardPair> leaderboard;
public TextField field;
public String name;
/**
* Constructor
*
* @param game The game object that the screen will be displayed on.
* @param score The score from the end of the game.
*/
public ResultScreen(final Kroy game, final int score) {
super(game);
skin2 = new Skin(Gdx.files.internal("skin/uiskin2.json"), atlas);
if (GameScreen.gameWon && !GameScreen.gameLost){
displayText = "YOU WIN! Your score is " + GameScreen.score;
}
else if(!GameScreen.gameWon && GameScreen.gameLost ){
displayText = "YOU LOSE";
}
this.score = score;
this.leaderboard = new ArrayList<LeaderboardPair>();
try{
this.leaderboard = readLeaderboardFile();
}
catch(final Exception e){
}
}
/**
* Given the new name, saves the new highscore to the internal leaderboard.
*
* @param leaderboard The internal leaderboard to be changed.
* @param name The name for the new highscore.
*
* @return The list of pairs that form the leaderboard.
*/
public ArrayList<LeaderboardPair> updateInternalLeaderboard(final ArrayList<LeaderboardPair> leaderboard, final String name){
final ArrayList<LeaderboardPair> outputPairs = new ArrayList<>();
boolean notWritten = true;
for (final LeaderboardPair pair: leaderboard ){
if (pair.score < this.score && notWritten){
outputPairs.add(new LeaderboardPair(name, this.score));
notWritten = false;
}
else {
outputPairs.add(pair);
}
}
return outputPairs;
}
/**
* Check if the score large enough to be included in the leaderboard.
*
* @param leaderboard
*
* @return boolean true if score is greater than last leaderboard score, otherwise false.
*/
public boolean wantNickname(final ArrayList<LeaderboardPair> leaderboard){
return leaderboard.get(leaderboard.size()-1).score < this.score;
}
/**
* Reads the leaderboard file into memory and saves the values in an arraylist data structure.
*
* @return An arraylist of pairs that contain the information in the leaderboard file.
*/
public ArrayList<LeaderboardPair> readLeaderboardFile() throws IOException {
//read names and scores, add to
BufferedReader reader;
final File leaderboardFile = new File("leaderboard.txt");
reader = new BufferedReader(new FileReader(leaderboardFile));
final ArrayList<LeaderboardPair> pairs = new ArrayList<LeaderboardPair>();
String line;
String[] pair;
line = reader.readLine();
while (line != null){
pair = line.split(",");
pairs.add(new LeaderboardPair(pair[0], Integer.parseInt(pair[1])));
line = reader.readLine();
}
reader.close();
return pairs;
}
/**
* Stores the given leaderboard in the leaderboard file.
*
* @param outputList The leaderboard data structure to be saved.
*/
public void writeLeaderboardFile(final ArrayList<LeaderboardPair> outputList) throws IOException{
final File leaderboardFile = new File("leaderboard.txt");
final FileWriter fileWriter = new FileWriter(leaderboardFile);
final BufferedWriter writer = new BufferedWriter(fileWriter);
String outputString = "";
for (final LeaderboardPair pair : outputList) {
outputString = outputString + pair.name + "," + pair.score + "\n";
}
writer.write(outputString);
writer.close();
}
/**
* Displays all the buttons and text on the screen.
*/
@Override
public void show() {
// Allow stage to control screen inputs.
Gdx.input.setInputProcessor(stage);
// Create table to arrange buttons.
final Table buttonTable = new Table();
buttonTable.setFillParent(true);
buttonTable.center();
// Create buttons
final TextButton menuButton = new TextButton("Menu", skin);
TextButton enterNameButton = null;
if (wantNickname(leaderboard)) {
enterNameButton = new TextButton("Enter", skin);
enterNameButton.addListener(new ClickListener(){
@Override
//transition to game screen
public void clicked(final InputEvent event, final float x, final float y){
final String input = field.getText();
name = input;
leaderboard = updateInternalLeaderboard(leaderboard,name);
try {
writeLeaderboardFile(leaderboard);
} catch (final IOException e) {
e.printStackTrace();
}
game.setScreen(new LeaderboardScreen(game));
dispose();
}
});
}
//Create labels
final Label winLabel = new Label(displayText, skin2);
winLabel.setFontScale(2,2);
final Label newHighscoreLabel = new Label("New Highscore! Enter your nickname to add to leaderboard",skin2);
newHighscoreLabel.setFontScale(1.5f,1.5f);
winLabel.setAlignment (Align.center);
newHighscoreLabel.setAlignment (Align.center);
// Increase size of text
menuButton.setTransform(true);
menuButton.scaleBy(0.25f);
// Add listeners
menuButton.addListener(new ClickListener(){
@Override
//transition to game screen
public void clicked(final InputEvent event, final float x, final float y){
game.setScreen(new MainMenuScreen(game));
dispose();
}
});
// Add buttons to table and style them
buttonTable.add(winLabel).padBottom(40).padRight(40).width(150).height(150);
buttonTable.row();
//add text field if nickname wanted
if (wantNickname(leaderboard)) {
field = new TextField("", skin );;
field.setPosition(24,73);
field.setSize(88, 14);
buttonTable.add(newHighscoreLabel).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(field).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(enterNameButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
}
buttonTable.add(menuButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
// Add table to stage
stage.addActor(buttonTable);
}
/**
* Implements a click confirmer.
*/
class ConfirmClick extends ClickListener{
/**
* Constructor
*
* @param event The event to be handled.
* @param x The x value.
* @param y The y value.
* @param field The field to be read.
* @param name The new name.
*/
public void clicked(final InputEvent event, final float x, final float y, final TextField field, final String name) {
Gdx.app.log("button","clicked");
}
}
}
|
package com.example.chloerainezeller.project2;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class SearchActivity extends AppCompatActivity {
private Context myContext;
private Spinner dietRestrictionSpinner;
private Spinner servingSpinner;
private Spinner prepTimeSpinner;
private Button searchButton;
private String dietSelection;
private String servingSelection;
private String prepTimeSelection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
myContext = this;
searchButton = findViewById(R.id.searchButton);
//get the spinner from the xml.
dietRestrictionSpinner = findViewById(R.id.dietRestrictionSpinner);
servingSpinner = findViewById(R.id.servingSpinner);
prepTimeSpinner = findViewById(R.id.prepTimeSpinner);
ArrayList<Recipe> recipes = Recipe.getRecipesFromFile("recipes.json", this);
ArrayList<String> dietOptions = new ArrayList<>();
dietOptions.add("");
for (int i = 0; i < recipes.size(); i++) {
String dietOption = recipes.get(i).label;
if (!dietOptions.contains(dietOption)) {
dietOptions.add(dietOption);
}
}
ArrayList<String> servingOptions = new ArrayList<>();
servingOptions.add("");
servingOptions.add("less than 4");
servingOptions.add("4-6");
servingOptions.add("7-9");
servingOptions.add("more than 10");
ArrayList<String> prepTimeOptions = new ArrayList<>();
prepTimeOptions.add("");
prepTimeOptions.add("less than 30 minutes");
prepTimeOptions.add("less than 1 hour");
prepTimeOptions.add("more than 1 hour");
ArrayAdapter<String> dietRestrictionAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_dropdown_item, dietOptions);
ArrayAdapter<String> servingAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_dropdown_item, servingOptions);
ArrayAdapter<String> prepTimeAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_dropdown_item, prepTimeOptions);
dietRestrictionSpinner.setAdapter(dietRestrictionAdapter);
servingSpinner.setAdapter(servingAdapter);
prepTimeSpinner.setAdapter(prepTimeAdapter);
}
public void searchQuery(View view) {
String dietSetting = dietRestrictionSpinner.getSelectedItem().toString();
String servingSetting = servingSpinner.getSelectedItem().toString();
String prepTimeSetting = prepTimeSpinner.getSelectedItem().toString();
ArrayList<Recipe> recipes = Recipe.getRecipesFromFile("recipes.json", this);
ArrayList<Recipe> searchResults = getSearchResults(dietSetting, servingSetting,
prepTimeSetting, recipes);
Bundle extra = new Bundle();
extra.putSerializable("searchResults", searchResults);
Intent intent = new Intent(myContext, ResultActivity.class);
intent.putExtra("searchResults", extra);
startActivity(intent);
}
public ArrayList<String> getUniquePrepTimes(ArrayList<Recipe> recipeList) {
ArrayList<String> prepOptions = new ArrayList<>();
// make an arrayList of all the unique prepTime options in the JSON file
for (int i = 0; i < recipeList.size(); i++) {
String prep = recipeList.get(i).prepTime;
if (!prepOptions.contains(prep)) {
prepOptions.add(prep);
}
}
return prepOptions;
}
// creates an arrayList of all the unique types of servings from the JSON file
public ArrayList<String> getUniqueServings(ArrayList<Recipe> recipeList) {
ArrayList<String> servingOptions = new ArrayList<>();
for (int i = 0; i < recipeList.size(); i++) {
String serving = recipeList.get(i).servings;
if (!servingOptions.contains(serving)) {
servingOptions.add(serving);
}
}
return servingOptions;
}
// Creates a HashMap that maps from the category dropdowns to an ArrayList of all prepTimes
// that satisfy that list of dropdowns
public HashMap<String, ArrayList<String>> makePrepMap(ArrayList<Recipe> recipeList) {
ArrayList<String> prepOptions = getUniquePrepTimes(recipeList);
ArrayList<String> thirtyMinsLess = new ArrayList<>();
ArrayList<String> lessOneHour = new ArrayList<>();
ArrayList<String> moreOneHour = new ArrayList<>();
for (int i = 0; i < prepOptions.size(); i++) {
String currentUniquePrepTime = prepOptions.get(i);
String[] words = currentUniquePrepTime.split(" ");
if (words[1].equals("minutes")) { // then it should go in
lessOneHour.add(currentUniquePrepTime);
if (Integer.parseInt(words[0]) <= 30) {
thirtyMinsLess.add(currentUniquePrepTime);
}
}
else {
moreOneHour.add(currentUniquePrepTime);
}
}
HashMap<String, ArrayList<String>> prepMap = new HashMap<>();
prepMap.put("less than 30 minutes", thirtyMinsLess);
prepMap.put("less than 1 hour", lessOneHour);
prepMap.put("more than 1 hour", moreOneHour);
return prepMap;
}
// Creates a HashMap that maps from the actual serving tag in JSON, to the user's input
public HashMap<Integer, String> makeServingMap(ArrayList<Recipe> recipeList) {
HashMap<Integer, String> servingMap = new HashMap<>();
ArrayList<String> servingOptions = getUniqueServings(recipeList); // list of unique servings
for (int i = 0; i < servingOptions.size(); i++) {
int currentServing = Integer.parseInt(servingOptions.get(i));
if (currentServing < 4) {
servingMap.put(currentServing, "less than 4");
}
else if (currentServing >= 4) {
if (currentServing <= 6) {
servingMap.put(currentServing, "4-6");
}
else if (currentServing > 6) {
if (currentServing <= 9) {
servingMap.put(currentServing, "7-9");
}
else if (currentServing >= 10) {
servingMap.put(currentServing, "more than 10");
}
}
}
}
return servingMap;
}
// when the submit button is clicked.
// Makes a final ArrayList of recipes that match the search queries
public ArrayList<Recipe> getSearchResults(String diet, String serving, String prep,
ArrayList<Recipe> recipeList) {
ArrayList<Recipe> searchResults = new ArrayList<Recipe>(recipeList);
HashMap<String, ArrayList<String>> prepMap = makePrepMap(recipeList);
HashMap<Integer, String> servingMap = makeServingMap(recipeList);
for (int i = 0; i < searchResults.size(); i++) {
Recipe curRecipe = searchResults.get(i);
if (!diet.equals("")) {
if (!diet.equals(curRecipe.label)) {
searchResults.remove(curRecipe);
i--;
continue;
}
}
// gets the arrayList of acceptable prepTimes that match the input
ArrayList<String> acceptablePrepTimes = prepMap.get(prep);
if (!prep.equals("")) {
// if the list of acceptable prepTimes doesn't have the prepTime of the current
// recipe, then remove it
if (!acceptablePrepTimes.contains(curRecipe.prepTime)) {
searchResults.remove(curRecipe);
i--;
continue;
}
}
if (!serving.equals("")) {
// get the category that the current recipe falls into
int curRecipeServing = Integer.parseInt(curRecipe.servings);
String curRecipeCategory = servingMap.get(curRecipeServing);
// if the serving the user chose is the same as the serving corresponding to the
// current Recipe, then leave it in the list
if (!curRecipeCategory.equals(serving)) {
searchResults.remove(curRecipe);
i--;
continue;
}
}
}
return searchResults;
}
}
|
package com.love_li2.recognizenotes.view;
import com.love_li2.recognizenotes.R;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PainoKeyboard extends LinearLayout implements OnClickListener {
String TAG = "PainoKeyboard";
private int whiteKeyWidth = 0, blackeyWidth = 0, keyHeight = 0, keyNums = 16;
Button[] whiteKeys = new Button[7];
Button[] blackKeys = new Button[5];
int beginIndex = 0, endIndex = 6;
public PainoKeyboard(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public PainoKeyboard(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PainoKeyboard(Context context) {
super(context);
init(context);
}
public void setBeginAndEnd(int b, int e) {
beginIndex = b;
endIndex = e;
if (beginIndex == 5) {
blackKeys[3].setVisibility(View.GONE);
} else if (endIndex == 0) {
blackKeys[0].setVisibility(View.GONE);
}
}
private void init(Context context) {
setOrientation(LinearLayout.HORIZONTAL);
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Point outSize = new Point();
wm.getDefaultDisplay().getSize(outSize);
whiteKeyWidth = outSize.x / keyNums;
blackeyWidth = whiteKeyWidth * 5 / 7;
keyHeight = whiteKeyWidth * 5;
for (int i = 0; i < 7; i++) {
whiteKeys[i] = new Button(context);
whiteKeys[i].setId(i);
whiteKeys[i].setPadding(0, 0, 0, 0);
whiteKeys[i].setOnClickListener(this);
whiteKeys[i].setBackgroundResource(R.drawable.key_background);
addView(whiteKeys[i]);
}
for (int i = 0; i < 5; i++) {
blackKeys[i] = new Button(context);
blackKeys[i].setId(i + 7);
blackKeys[i].setPadding(0, 0, 0, 0);
blackKeys[i].setOnClickListener(this);
blackKeys[i].setBackgroundColor(Color.BLACK);
addView(blackKeys[i]);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(whiteKeyWidth * (endIndex - beginIndex + 1), keyHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
for (int i = 0; i < 7; i++) {
whiteKeys[i].layout((i - beginIndex) * whiteKeyWidth, 0, (i - beginIndex + 1) * whiteKeyWidth, keyHeight);
}
blackKeys[0].layout((int) (whiteKeyWidth * (0.5 - beginIndex)), 0, (int) (whiteKeyWidth * (0.5 - beginIndex)) + blackeyWidth, keyHeight / 3 * 2);
blackKeys[1].layout((int) (whiteKeyWidth * (1.7 - beginIndex)), 0, (int) (whiteKeyWidth * (1.7 - beginIndex)) + blackeyWidth, keyHeight / 3 * 2);
blackKeys[2].layout((int) (whiteKeyWidth * (3.45 - beginIndex)), 0, (int) (whiteKeyWidth * (3.45 - beginIndex)) + blackeyWidth, keyHeight / 3 * 2);
blackKeys[3].layout((int) (whiteKeyWidth * (4.65 - beginIndex)), 0, (int) (whiteKeyWidth * (4.65 - beginIndex)) + blackeyWidth, keyHeight / 3 * 2);
blackKeys[4].layout((int) (whiteKeyWidth * (5.85 - beginIndex)), 0, (int) (whiteKeyWidth * (5.85 - beginIndex)) + blackeyWidth, keyHeight / 3 * 2);
}
@Override
public void onClick(View v) {
}
}
|
import java.util.Scanner; //import scanner
public class IDCard
{
public static void main(String[]args)
{
//instantiate format
IDCard form = new IDCard();
//insantiate new Scanner object "kb"
Scanner kb = new Scanner(System.in);
//user input
System.out.println("Enter your first name");
String first = kb.nextLine();
System.out.println("Enter your last name");
String last = kb.nextLine();
System.out.println("Enter your title");
String title = kb.nextLine();
System.out.println("Enter the school site");
String site = kb.nextLine();
System.out.println("Enter the school year");
String year = kb.nextLine();
System.out.println("What is your subject?");
String subject = kb.nextLine();
//formating ID Card
System.out.println("***************************************");
form.format(site, year);
form.format(first, last);
form.format(title, subject);
System.out.println("***************************************");
}
public void format(String item0, String item1)
{
System.out.printf("* %15s\t%15s *\n", item0, item1);
}
} |
package javadecompiler.constantpool.type;
public class ConstantUtf8
{
public String utf8String;
public int utfLen;
public ConstantUtf8( int utfLen, String utf8String )
{
this.utfLen = utfLen;
this.utf8String = utf8String;
}
} |
package br.unisal.controllers;
import java.io.IOException;
import br.unisal.util.Util;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import br.unisal.util.Constantes;
import br.unisal.util.Erro;
import br.unisal.dao.FilmeDAO;
import br.unisal.dao.UsuarioDAO;
import br.unisal.model.Filme;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "InicioController", description = "Controlador para ir para o início", urlPatterns = "/inicio")
public class InicioController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -2664599753751370793L;
private static final FilmeDAO FILME_DAO = FilmeDAO.getInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
List<Filme> filmes = new ArrayList<>();
try {
filmes = FILME_DAO.findAll();
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e.toString());
}
req.setAttribute("filmes", filmes);
String page = Constantes.raizPages + "inicio.jsp";
RequestDispatcher rs = req.getRequestDispatcher(page);
rs.forward(req, resp);
}
} |
package com.afl.common;
import java.util.Scanner;
public class NumberHelper {
public static final int THREE = 3;
public static final int FIVE = 5;
// Read the input aruments
public static int getNumberFromUser() {
System.out.println("Enter the input number");
Scanner input = new Scanner(System.in);
return input.nextInt();
}
}
|
package com.example.cse.makeupapp;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
@Database(entities = CosmeticModel.class,version = 1,exportSchema = false)
public abstract class CosmeticDatabase extends RoomDatabase {
public abstract CosmeticDao movieDao();
private static CosmeticDatabase instance;
public static CosmeticDatabase getInstance(Context context){
if(instance==null){
instance=Room.databaseBuilder(context,CosmeticDatabase.class,"roomLiveDatabase")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build();
}
return instance;
}
}
|
package com.zhouyi.business.core.service;
import com.alibaba.fastjson.JSON;
import com.zhouyi.business.core.common.ReturnCode;
import com.zhouyi.business.core.dao.LedenEquipmentMapper;
import com.zhouyi.business.core.dao.SysUnitMapper;
import com.zhouyi.business.core.dao.SysUserMapper;
import com.zhouyi.business.core.exception.BusinessException;
import com.zhouyi.business.core.model.*;
import com.zhouyi.business.core.utils.JWTUtil;
import com.zhouyi.business.core.utils.MD5Util;
import com.zhouyi.business.core.utils.TokenUtil;
import com.zhouyi.business.core.vo.SysUserVo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* @author 李秸康
* @ClassNmae: SysUserServiceImpl
* @Description: TODO
* @date 2019/6/20 17:10
* @Version 1.0
**/
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserRoleService sysUserRoleService;
@Autowired
private SysUnitMapper sysUnitMapper;
@Autowired
private LedenEquipmentMapper ledenEquipmentMapper;
@Autowired
private JWTUtil jwtUtil;
final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 删除系统用户信息
*
* @param userCode 用户编码
* @return
*/
@Override
public Boolean deleteByPrimaryKey(String userCode) {
return sysUserMapper.deleteByPrimaryKey(userCode) == 1 ? true : false;
}
/**
* 完整新增用户信息
*
* @param sysUser
* @return
*/
@Override
public Boolean insert(SysUser sysUser) {
return sysUserMapper.insert(sysUser) == 1 ? true : false;
}
/**
* 根据用户编码查询用户信息
*
* @param userCode
* @return
*/
@Override
public SysUser searchSysUser(String userCode) {
return sysUserMapper.getSysUserByUserAccount(userCode);
}
/**
* 完整修改用户信息
*
* @param sysUser
* @return
*/
@Override
public Boolean modifySysUser(SysUser sysUser) {
return sysUserMapper.updateByPrimaryKey(sysUser) == 1 ? true : false;
}
/**
* 用户登陆业务
*
* @param userAccount
* @param userPassword
* @return
*/
@Override
public SysUser login(String userAccount, String userPassword, HttpServletResponse response,String equipmentMac) throws BusinessException {
SysUser sysUser = null;
try {
sysUser = sysUserMapper.getSysUserByUserAccount(userAccount);
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(ReturnCode.ERROR_04);
}
//用户不存在情况
if (sysUser == null)
throw new BusinessException(ReturnCode.ERROR_1001);
//用户被封禁情况
if (sysUser.getDeleteFlag().equals("1"))
throw new BusinessException(ReturnCode.ERROR_1030);
/**
* 将密码md5加密加盐后比对
*/
String newPassword = MD5Util.MD5(userPassword, sysUser.getSalt());
if (sysUser.getUserPassword().equals(newPassword) == false)
throw new BusinessException(ReturnCode.Error_1025);
String unitCode = sysUser.getUserUnitCode();
//查看该用户所在的部门是否启用
SysUnit sysUnit = sysUnitMapper.selectByPrimaryKey(unitCode);
if (sysUnit.getDeleteFlag().equals("1"))
throw new BusinessException(ReturnCode.ERROR_1029);
//如果用户登陆成功,则签发token信息
/**
* 修改2019-6-25签发
*/
Object[] resultObject=jwtUtil.createJwtToken(sysUser);
String token = resultObject[1].toString();
sysUser.setExpDate((Date)resultObject[0]);
logger.info("签发token:" + token);
//获取cookie,进行写入
TokenUtil.setCookie("token", token, response);
if (StringUtils.isNotEmpty(equipmentMac)){
LedenEquipment ledenEquipment = ledenEquipmentMapper.selectEquipmentByMac(equipmentMac);
sysUser.setLedenEquipment(ledenEquipment);
}
return sysUser;
}
/**
* 系统分页查询信息
*
* @param conditions
* @return
*/
@Override
public PageData<SysUser> searchSysUserPage(Map<String, Object> conditions) {
List<SysUser> list = sysUserMapper.listSysUserByConditions(conditions);
Integer totalCount = sysUserMapper.getSysUserCountByConditions(conditions);
PageData<SysUser> pageData = new PageData<>(list, totalCount, (int) conditions.get("pSize"));
return pageData;
}
/**
* 用户注册接口
* 开启事务处理
*
* @param sysUserVo
* @return
*/
@Override
@Transactional
public Boolean sysUserRegister(SysUserVo sysUserVo) throws Exception {
//验证账户是否重复
if (sysUserMapper.getSysUserAccountCount(sysUserVo.getUserAccount()) == 1) {
throw new BusinessException(ReturnCode.ERROR_1031);
}
sysUserVo.setCreateDatetime(new Date());
String userCode = UUID.randomUUID().toString().substring(0, 32);
sysUserVo.setUserCode(userCode);
modifyUserRoles(sysUserVo);
//设置创建时间
//获取一个盐值
String salt = MD5Util.generateSalt(sysUserVo.getUserAccount());
String newPassword = MD5Util.MD5(sysUserVo.getUserPassword(), salt);
sysUserVo.setSalt(salt);
sysUserVo.setUserPassword(newPassword);
return sysUserMapper.insertSelective(sysUserVo) == 1 ? true : false;
}
/**
* 用户账户查重
*
* @param userAccount
* @return
*/
@Override
public boolean checkUserAccount(String userAccount) {
return sysUserMapper.getSysUserAccountCount(userAccount) == 1 ? true : false;
}
/**
* 密码校验
*
* @param userAccount
* @param userPassword
* @return
*/
@Override
public boolean checkUserPassword(String userAccount, String userPassword) {
SysUser sysUser = sysUserMapper.getSysUserByUserAccount(userAccount);
if (sysUser == null) {
throw new BusinessException(ReturnCode.ERROR_1001);
}
//加密输入的密码和原有的比对
String tempPassword = MD5Util.MD5(userPassword, sysUser.getSalt());
if (!sysUser.getUserPassword().equals(tempPassword))
return false;
return true;
}
/**
* 选择性修改
*
* @param sysUserVo
* @return
*/
@Override
public Boolean modifySysUserSelective(SysUserVo sysUserVo) throws Exception {
//修改角色信息
if (sysUserVo.getRoleIds() != null)
modifyUserRoles(sysUserVo);
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(sysUserVo, sysUser);
sysUser.setUpdateDatetime(new Date());
sysUser.setUpdateUserId(sysUser.getUserCode());
return sysUserMapper.updateByPrimaryKeySelective(sysUser) == 1 ? true : false;
}
public void modifyUserRoles(SysUserVo sysUserVo) throws Exception {
//删除原有角色
if (
sysUserVo.getUserCode() != null && sysUserRoleService.deleteRolesById(sysUserVo.getUserCode()) == false) {
throw new Exception("删除原有角色失败");
}
//添加新的角色信息
//循环创建角色对象
for (String roleId : sysUserVo.getRoleIds()) {
//构建一个角色对象
SysUserRole sysUserRole = new SysUserRole(
UUID.randomUUID().toString().substring(0, 32),
sysUserVo.getUserCode(),
roleId,
"0",
sysUserVo.getCreateUserId(),
new Date()
);
//进行新增操作
sysUserRoleService.saveData(sysUserRole);
}
}
public static void main(String[] args) {
Student student = new Student();
student.setName("duchengxu");
String[] ar = new String[]{"fsd", "fds"};
student.setBooks(ar);
System.out.println(JSON.toJSONString(student));
}
@Data
static class Student {
private String name;
private String[] books;
}
}
|
package com.gerray.fmsystem.ManagerModule.Lessee;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
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.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.gerray.fmsystem.LesseeModule.LesCreate;
import com.gerray.fmsystem.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Objects;
public class LesseeFragment extends Fragment {
FirebaseRecyclerOptions<LesCreate> options;
FirebaseRecyclerAdapter<LesCreate, LesseeRecyclerViewHolder> adapter;
DatabaseReference dbRef;
DatabaseReference ref;
FirebaseAuth auth;
public LesseeFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onStart() {
super.onStart();
adapter.startListening();
adapter.notifyDataSetChanged();
// Check if user is signed in (non-null) and update UI accordingly.
// FirebaseUser currentUser = auth.getCurrentUser();
}
@Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_lessee, container, false);
FloatingActionButton addLessee = view.findViewById(R.id.fab_lessee);
addLessee.setOnClickListener(v -> startActivity(new Intent(getActivity(), SearchLessee.class)));
auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
assert currentUser != null;
dbRef = FirebaseDatabase.getInstance().getReference().child("FacilityOccupants").child(currentUser.getUid());
options = new FirebaseRecyclerOptions.Builder<LesCreate>().setQuery(dbRef, LesCreate.class).build();
adapter = new FirebaseRecyclerAdapter<LesCreate, LesseeRecyclerViewHolder>(options) {
@SuppressLint("LogNotTimber")
@Override
protected void onBindViewHolder(@NonNull LesseeRecyclerViewHolder holder, int position, @NonNull LesCreate model) {
holder.room.setText(model.getRoom());
holder.activity.setText(model.getActivityType());
holder.contactName.setText(model.getContactName());
holder.lesseeName.setText(model.getLesseeName());
holder.itemView.setOnClickListener(v -> {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setMessage(model.getLesseeName())
.setCancelable(false)
.setPositiveButton("View Profile", (dialog, which) -> {
// startActivity(new Intent(getContext(), ViewLessee.class)
// .putExtra("lesseeID", model.getLesseeID()));
Intent intent = new Intent(getActivity(),ViewLessee.class);
intent.putExtra("lesseeID",model.getUserID());
startActivity(intent);
})
.setNegativeButton("Remove Lessee", (dialog, which) -> {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("FacilityOccupants").child(currentUser.getUid());
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child(model.room).exists())
{
snapshot.getRef().removeValue()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Lessee Removed", Toast.LENGTH_SHORT).show();
ref = FirebaseDatabase.getInstance().getReference().child("Facilities").child(currentUser.getUid()).child("Profile");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child("occupancyNo").exists()) {
final int occNo = Integer.parseInt(Objects.requireNonNull(snapshot.child("occupancyNo").getValue()).toString());
int newCode = occNo + 1;
ref.child("occupancyNo").setValue(newCode);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
} else {
Log.d("Delete Asset", "Asset couldn't be deleted");
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
});
AlertDialog alert = alertDialog.create();
alert.setTitle("Facility Lessees");
alert.show();
//
});
}
@NonNull
@Override
public LesseeRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new LesseeRecyclerViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.lessee_cards, parent, false));
}
}
;
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
adapter.startListening();
return view;
}
} |
package ch.fhnw.edu.cpib.cst;
import ch.fhnw.edu.cpib.cst.interfaces.IFactor;
import ch.fhnw.edu.cpib.cst.interfaces.IFactorNTS;
import ch.fhnw.edu.cpib.scanner.Ident;
import ch.fhnw.edu.cpib.scanner.interfaces.IToken;
// factor ::= IDENT factorNTS
public class FactorIdent extends Production implements IFactor {
protected final IToken T_ident;
protected final IFactorNTS N_factorNTS;
public FactorIdent(final IToken t_ident, final IFactorNTS n_factorNTS) {
T_ident = t_ident;
N_factorNTS = n_factorNTS;
}
@Override public ch.fhnw.edu.cpib.ast.interfaces.IFactor toAbsSyntax() {
return N_factorNTS.toAbsSyntax((Ident) T_ident);
}
}
|
package edu.kit.pse.osip.simulation.view.main;
import edu.kit.pse.osip.core.model.base.Motor;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
/**
* This class visualizes the mixing motor in the MixTank.
*
* @version 1.0
* @author Niko Wilhelm
*/
public class MotorDrawer extends RotatingControlDrawer {
/**
* The center of the drawer.
*/
private Point2D position;
/**
* The actual, represented motor.
*/
private Motor motor;
private double relRadius;
/**
* Generates a new drawer object for motors.
*
* @param pos The center of the drawer.
* @param motor The motor to draw.
* @param cols The number of columns in which the tanks are ordered.
*/
public MotorDrawer(Point2D pos, Motor motor, int cols) {
super(pos, motor.getRPM());
this.motor = motor;
this.position = pos;
relRadius = ViewConstants.MOTOR_RADIUS / cols;
}
@Override
public final void draw(GraphicsContext context, double timeDiff) {
setSpeed(motor.getRPM());
updateDegrees(timeDiff, ViewConstants.MOTOR_SPEED_FACTOR);
Canvas canvas = context.getCanvas();
double totalWidth = canvas.getWidth();
double totalHeight = canvas.getHeight();
// Points 1 and 3 make up the first line inside the motor.
double point1xPos = (position.getX() - relRadius) * totalWidth;
double point1yPos = position.getY() * totalHeight - 2 * ViewConstants.MOTOR_LINE_WIDTH;
double point3xPos = (position.getX() + relRadius) * totalWidth;
double point3yPos = point1yPos;
// Points 2 and 4 make up the second line inside the motor.
double point2xPos = position.getX() * totalWidth;
double point2yPos = (position.getY() - relRadius) * totalHeight
- (totalWidth - totalHeight) * relRadius - 2 * ViewConstants.MOTOR_LINE_WIDTH;
double point4xPos = point2xPos;
double point4yPos = (position.getY() + relRadius) * totalHeight
+ (totalWidth - totalHeight) * relRadius - 2 * ViewConstants.MOTOR_LINE_WIDTH;
// The absolute center values of the motor.
double centerX = position.getX() * totalWidth;
double centerY = position.getY() * totalHeight - 2 * ViewConstants.MOTOR_LINE_WIDTH;
//First draw the motor in white, slightly thicker than the result is supposed to be.
//This leads to a white outline and visibility in all cases.
context.setStroke(Color.WHITE);
context.setLineWidth(ViewConstants.MOTOR_LINE_WIDTH + 2);
context.strokeLine(rotateX(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateY(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateX(point3xPos, centerX, point3yPos, centerY, getDegrees()),
rotateY(point3xPos, centerX, point3yPos, centerY, getDegrees()));
context.strokeLine(rotateX(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateY(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateX(point4xPos, centerX, point4yPos, centerY, getDegrees()),
rotateY(point4xPos, centerX, point4yPos, centerY, getDegrees()));
context.strokeOval(point1xPos, point2yPos, relRadius * 2 * totalWidth, relRadius * 2 * totalWidth);
context.setStroke(Color.BLACK);
context.setLineWidth(ViewConstants.MOTOR_LINE_WIDTH);
// Draw the two rotated lines.
context.strokeLine(rotateX(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateY(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateX(point3xPos, centerX, point3yPos, centerY, getDegrees()),
rotateY(point3xPos, centerX, point3yPos, centerY, getDegrees()));
context.strokeLine(rotateX(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateY(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateX(point4xPos, centerX, point4yPos, centerY, getDegrees()),
rotateY(point4xPos, centerX, point4yPos, centerY, getDegrees()));
// There would be not much sense in rotating a circle.
context.strokeOval(point1xPos, point2yPos, relRadius * 2 * totalWidth, relRadius * 2 * totalWidth);
}
}
|
package com.kunsoftware.entity;
public class Ground {
private Integer id;
private String name;
private Integer destination;
private String type;
private String groundDescribe;
private String linkMain;
private String remark;
private String imagePath;
private String qualificationImagePath;
private String frontDeskRecommend;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDestination() {
return destination;
}
public void setDestination(Integer destination) {
this.destination = destination;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getGroundDescribe() {
return groundDescribe;
}
public void setGroundDescribe(String groundDescribe) {
this.groundDescribe = groundDescribe;
}
public String getLinkMain() {
return linkMain;
}
public void setLinkMain(String linkMain) {
this.linkMain = linkMain;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getQualificationImagePath() {
return qualificationImagePath;
}
public void setQualificationImagePath(String qualificationImagePath) {
this.qualificationImagePath = qualificationImagePath;
}
public String getFrontDeskRecommend() {
return frontDeskRecommend;
}
public void setFrontDeskRecommend(String frontDeskRecommend) {
this.frontDeskRecommend = frontDeskRecommend;
}
} |
package com.worldbank.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.NonNull;
@Data
@NoArgsConstructor
@EqualsAndHashCode
public class Student {
@NonNull
private String name;
private int roll;
}
|
package hanbitex;
/**
* 2016. 4. 16. Sum10.java cheonbora@naver.com story :1부터 10까지의합
*/
public class Sum10 {
public static void main(String[] args) {
int sum = 0;
// sum = 1 + 2 + 3 + 4 + 5 + 6 + 7+ 8 + 9 + 10;
for (int i = 1; i <= 10; i += 2) {
sum += i;
// System.out.print(i+"\t");
}
System.out.println("1부터 10까지의 홀수 합 =" + sum);
sum = 0;
for (int i = 2; i <= 10; i += 2) {
sum += i;
// System.out.print(i+"\t");
System.out.println("1부터 10까지의 홀수 합 =" + sum);
}
}
} |
package com.bitbus.fantasyprep;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class FantasyPrepApplication {
@Autowired
private PlayerProjectionsLoader playerProjectionsLoader;
@Autowired
private DefaultAuctionValuesLoader defaultAuctionValuesLoader;
public static void main(String[] args) throws IOException {
ConfigurableApplicationContext ctx = SpringApplication.run(FantasyPrepApplication.class, args);
FantasyPrepApplication application = ctx.getBean(FantasyPrepApplication.class);
application.run();
}
private void run() throws IOException {
playerProjectionsLoader.load();
defaultAuctionValuesLoader.load();
}
}
|
package ua.nure.timoshenko.summaryTask4.db;
import static org.junit.Assert.*;
import org.junit.Test;
import ua.nure.timoshenko.summaryTask4.db.entity.Order;
public class StatusTest {
@Test
public void testGetStatus() {
Order order = new Order();
order.setStatusID(1);
assertEquals(Status.PAID, Status.getStatus(order));
}
@Test
public void testGetName() {
String status = "paid";
assertEquals(status, Status.values()[1].getName());
}
@Test
public void coverEnum() {
Status.valueOf(Status.values()[0].name());
}
}
|
package com.wenny.animation;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Interpolator;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewAnimator;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Context context;
private Button button;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
image = (ImageView) findViewById(R.id.image);
context = this;
button.setOnClickListener(this);
}
private void startValueAnimator(){
ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(200);
anim.start();
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float)animation.getAnimatedValue();
image.setTranslationX(animatedValue);
}
});
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
//动画启动时调用
}
@Override
public void onAnimationEnd(Animator animation) {
//当动画结束时调用
}
@Override
public void onAnimationCancel(Animator animation) {
//当动画被取消调用,被取消的动画还会调用onAnimationEnd方法
}
@Override
public void onAnimationRepeat(Animator animation) {
//当动画重演调用
}
});
}
private void startObjectAnimator(){
// ObjectAnimator.ofFloat(image,"rotationX",0.0f,180f)
// .setDuration(100)
// .start();
// new IntEvaluator()
ObjectAnimator objectAnimator = ObjectAnimator.ofObject(image,"translationX",new MyTypeEvaluator(),0,200);
objectAnimator.setDuration(500);
objectAnimator.start();
}
private void animatorSet(){
ObjectAnimator moveIn = ObjectAnimator.ofFloat(image, "translationX", -500f, 0f);
ObjectAnimator rotate = ObjectAnimator.ofFloat(image, "rotation", 0f, 360f);
ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(image, "alpha", 1f, 0f, 1f);
AnimatorSet animSet = new AnimatorSet();
//三个动画按顺序执行
// animSet.play(rotate).with(fadeInOut).after(moveIn);
//三个动画同时执行
animSet.playTogether(moveIn,rotate,fadeInOut);
animSet.setDuration(5000);
animSet.start();
}
private void startViewAnimator(){
TranslateAnimation rotateAnimation = new TranslateAnimation(0,200,0,0);
rotateAnimation.setDuration(500);
//创建对于的插值器
MyInterpolator interpolator = new MyInterpolator();
//设置插值器
rotateAnimation.setInterpolator(interpolator);
image.startAnimation(rotateAnimation);
// Animation animation = AnimationUtils.loadAnimation(context,R.anim.view_anin);
// image.startAnimation(animation);
}
private void startDrawableAnimator(){
// 通过逐帧动画的资源文件获得AnimationDrawable示例
// AnimationDrawable animationDrawable =(AnimationDrawable) getResources().getDrawable(R.drawable.animation_loading);
// image.setImageDrawable(animationDrawable);
// animationDrawable.start();
AnimationDrawable drawable = new AnimationDrawable();
drawable.addFrame(getResources().getDrawable(R.drawable.loading_1),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_2),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_3),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_4),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_5),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_6),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_7),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_8),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_9),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_10),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_11),100);
drawable.addFrame(getResources().getDrawable(R.drawable.loading_12),100);
drawable.setOneShot(true);
image.setImageDrawable(drawable);
drawable.start();
}
@Override
public void onClick(View v) {
startObjectAnimator();
}
}
|
package com.workshops.controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.workshops.database.Configdb;
import com.workshops.database.ShopDetail;
import com.workshops.database.WS_USER;
@Controller
public class ShopController {
@RequestMapping("/shop")
public ModelAndView shop(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
if(session.getAttribute("WS_USER")==null){
return new ModelAndView("redirect:/home");
}else{
Connection conn = Configdb.getConnectionDB();
List<ShopDetail> list_shop = new ArrayList<ShopDetail>();
String query = "SELECT ITEM_ID, ITEM_NAME, ITEM_PRICE, POKEBALL_QTY FROM WS_SHOP";
try {
PreparedStatement preparedStmt = conn.prepareStatement(query);
ResultSet resultSet = null;
resultSet = preparedStmt.executeQuery();
while (resultSet.next()) {
ShopDetail shopDetail = new ShopDetail();
shopDetail.setITEM_ID(resultSet.getInt("ITEM_ID"));
shopDetail.setITEM_NAME(resultSet.getString("ITEM_NAME"));
shopDetail.setITEM_PRICE(resultSet.getInt("ITEM_PRICE"));
shopDetail.setPOKEBALL_QTY(resultSet.getInt("POKEBALL_QTY"));
list_shop.add(shopDetail);
}
} catch (SQLException e) {
e.printStackTrace();
}
session.setAttribute("list_shop", list_shop);
return new ModelAndView("shop");}
}
@RequestMapping("/paymentTransaction")
public ModelAndView pay(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws JSONException {
String json_data = request.getParameter("transactionPaymentData");
JSONObject transactionPaymentData = new JSONObject(json_data);
int ITEM_ID = transactionPaymentData.getInt("ITEM_ID");
int pocketSlot_purchased = transactionPaymentData.getInt("pocketslot_qty");
String transactionID = transactionPaymentData.getString("transactionID");
WS_USER WS_USER = (WS_USER) session.getAttribute("WS_USER");
Connection conn = Configdb.getConnectionDB();
int id = 0;
String query = "insert into WS_PURCHASE_TRANSACTION(USER_ID , ITEM_ID , TRANSACTION_ID , PURC_DATETIME) "
+ " values(?,?,?,SYSDATETIME())";
try {
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setInt(1, WS_USER.getUSER_ID());
preparedStmt.setInt(2, ITEM_ID);
preparedStmt.setString(3, transactionID);
preparedStmt.execute();
ResultSet rs = preparedStmt.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
} else {
throw new SQLException("Creating user failed, no ID obtained.");
}
} catch (SQLException e) {
e.printStackTrace();
}
WS_USER.setCURRENT_POCKET_SLOT(WS_USER.getCURRENT_POCKET_SLOT()+pocketSlot_purchased);
updateCurrentPocketSlot(WS_USER);
return new ModelAndView("shop");
}
public void updateCurrentPocketSlot(WS_USER WS_USER) {
try {
Connection conn = Configdb.getConnectionDB();
String query = "UPDATE WS_USER SET CURRENT_POCKET_SLOT=? "
+ " WHERE USER_ID = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, WS_USER.getCURRENT_POCKET_SLOT());
preparedStmt.setInt(2, WS_USER.getUSER_ID());
preparedStmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Num of month: ");
int a = scan.nextInt();
if (a == 1 || a == 2 || a == 12){
System.out.println("winter!");
}else if(a == 3 || a == 4 || a == 5){
System.out.println("spring!");
}else if(a == 6 || a == 7 || a == 8){
System.out.println("summer!");
}else if(a ==9 || a == 10 || a == 11){
System.out.println("autumn!");
}
}
}
|
package com.takshine.wxcrm.controller;
import java.net.URLDecoder;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.takshine.core.service.CRMService;
import com.takshine.wxcrm.base.common.ErrCode;
import com.takshine.wxcrm.base.util.StringUtils;
import com.takshine.wxcrm.base.util.UserUtil;
import com.takshine.wxcrm.domain.Customer;
import com.takshine.wxcrm.domain.Rival;
import com.takshine.wxcrm.message.error.CrmError;
import com.takshine.wxcrm.message.sugar.CustomerAdd;
import com.takshine.wxcrm.message.sugar.CustomerResp;
import com.takshine.wxcrm.message.sugar.RivalAdd;
import com.takshine.wxcrm.message.sugar.RivalResp;
import com.takshine.wxcrm.service.Customer2SugarService;
import com.takshine.wxcrm.service.Rival2SugarService;
/**
* 竞争对手 页面控制器
* @author dengbo
*/
@Controller
@RequestMapping("/rival")
public class RivalController {
// 日志
protected static Logger logger = Logger.getLogger(RivalController.class.getName());
@Autowired
@Qualifier("cRMService")
private CRMService cRMService;
/**
* 保存竞争对手
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Rival obj, HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("RivalController save method id =>" + obj.getId());
//rowId
CrmError crmErr = cRMService.getSugarService().getRival2SugarService().addRival(obj);
String rowId = crmErr.getRowId();
if(null != rowId && !"".equals(rowId)){
request.setAttribute("openId", obj.getOpenId());
request.setAttribute("publicId", obj.getPublicId());
}
return "redirect:/oppty/detail?openId="+obj.getOpenId()+"&publicId="+obj.getPublicId()+"&rowId="+obj.getOpptyid()+"&orgId="+obj.getOrgId();
}
/**
* 添加竞争对手
* @param request
* @param response
* @return
*/
@RequestMapping("/get")
public String get(HttpServletRequest request,HttpServletResponse response) throws Exception{
String openId =request.getParameter("openId");
String publicId = request.getParameter("publicId");
String crmId = request.getParameter("crmId");
String orgId = request.getParameter("orgId");
String viewtype = request.getParameter("viewtype");
String currpage = request.getParameter("currpage");
String pagecount = request.getParameter("pagecount");
String customerid = request.getParameter("customerid");
String customername = request.getParameter("customername");
if(StringUtils.isNotNullOrEmptyStr(customername)){
customername = URLDecoder.decode(customername,"UTF-8");
customername = new String(customername.getBytes("ISO-8859-1"),"UTF-8");
}
currpage = (null == currpage ? "1" : currpage);
pagecount = (null == pagecount ? "10" : pagecount);
viewtype = (viewtype == null) ? "competitorview" : viewtype;
String opptyid = request.getParameter("opptyid");
logger.info("RivalController get method openId =>" + openId);
logger.info("RivalController get method publicId =>" + publicId);
logger.info("RivalController get method crmId =>" + crmId);
if(StringUtils.isNotNullOrEmptyStr(crmId)){
//查询客户信息
Customer sche = new Customer();
sche.setCrmId(crmId);
sche.setViewtype(viewtype);
sche.setCurrpage(currpage);
sche.setPagecount(pagecount);
sche.setOpptyid(opptyid);
sche.setOpenId(UserUtil.getCurrUser(request).getOpenId());
// 查询返回结果
CustomerResp cResp = cRMService.getSugarService().getCustomer2SugarService().getCustomerList(sche,
"WX");
List<CustomerAdd> cList = cResp.getCustomers();
request.setAttribute("crmId", crmId);
request.setAttribute("acctList", cList);
request.setAttribute("opptyid", opptyid);
request.setAttribute("openId", openId);
request.setAttribute("publicId", publicId);
request.setAttribute("orgId", orgId);
request.setAttribute("customerid", customerid);
request.setAttribute("customername", customername);
return "rival/add";
}else{
throw new Exception("错误编码:" + ErrCode.ERR_CODE_1001001 + ",错误描述:" + ErrCode.ERR_MSG_UNBIND);
}
}
/**
* 竞争对手 list页面
* @param request
* @param response
* @return
*/
@RequestMapping("/list")
public String list(HttpServletRequest request,HttpServletResponse response) throws Exception{
logger.info("RivalController acclist method begin=>");
String openId = request.getParameter("openId");
String publicId = request.getParameter("publicId");
String currpage = request.getParameter("currpage");
String pagecount = request.getParameter("pagecount");
String opptyid = request.getParameter("opptyid");
currpage = (null == currpage ? "1" : currpage);
pagecount = (null == pagecount ? "10" : pagecount);
logger.info("RivalController acclist method openId =>" + openId);
logger.info("RivalController acclist method publicId =>" + publicId);
logger.info("RivalController list method currpage =>" + currpage);
logger.info("RivalController list method pagecount =>" + pagecount);
//绑定对象
String crmId= UserUtil.getCurrUser(request).getCrmId();
logger.info("crmId:-> is =" + crmId);
//获取绑定的账户 在sugar系统的id
if(!"".equals(crmId)){
Rival rival = new Rival();
rival.setCrmId(crmId);
rival.setPagecount(pagecount);
rival.setCurrpage(currpage);
rival.setOpptyid(opptyid);
RivalResp pResp = cRMService.getSugarService().getRival2SugarService().getRivalList(rival,"WEB");
String errorCode = pResp.getErrcode();
if(ErrCode.ERR_CODE_0.equals(errorCode)){
List<RivalAdd> list = pResp.getRivals();
//放到页面上
if(null != list && list.size() > 0){
request.setAttribute("rivalList", list);
}else{
//throw new Exception("错误编码:" + ErrCode.ERR_CODE_1001003 + ",错误描述:" + ErrCode.ERR_MSG_ARRISEMPTY);
}
}else{
//throw new Exception("错误编码:" + pResp.getErrcode() + ",错误描述:" + pResp.getErrmsg());
}
}else{
//throw new Exception("错误编码:" + ErrCode.ERR_CODE_1001001 + ",错误描述:" + ErrCode.ERR_MSG_UNBIND);
}
//requestinfo
request.setAttribute("openId", openId);
request.setAttribute("publicId", publicId);
request.setAttribute("pagecount", pagecount);
request.setAttribute("currpage", currpage);
request.setAttribute("opptyid", opptyid);
request.setAttribute("crmId", crmId);
return "rival/list";
}
/**
* 异步查询所有的竞争对手个数
* @param request
* @param response
* @return
*/
@RequestMapping(value="/alist")
@ResponseBody
public String alist(HttpServletRequest request,HttpServletResponse response) throws Exception{
logger.info("RivalController alist method begin=>");
String openId = request.getParameter("openId");
String publicId = request.getParameter("publicId");
String opptyid = request.getParameter("opptyid");
logger.info("RivalController alist method openId =>" + openId);
logger.info("RivalController alist method publicId =>" + publicId);
String crmId = UserUtil.getCurrUser(request).getCrmId();
logger.info("crmId:-> is =" + crmId);
//error 对象
CrmError crmErr = new CrmError();
//获取绑定的账户 在sugar系统的id
if(null != crmId && !"".equals(crmId)){
Rival rival = new Rival();
rival.setCrmId(crmId);
rival.setOpptyid(opptyid);
RivalResp pResp = cRMService.getSugarService().getRival2SugarService().getRivalList(rival,"WEB");
List<RivalAdd> list = pResp.getRivals();
if(list!=null&&list.size()>0){
crmErr.setErrorCode(ErrCode.ERR_CODE_0);
crmErr.setErrorMsg(ErrCode.ERR_MSG_SUCC);
crmErr.setRowCount(list.size() + "");
}else{
crmErr.setErrorCode(ErrCode.ERR_CODE_1001003);
crmErr.setErrorMsg(ErrCode.ERR_MSG_ARRISEMPTY);
}
}else{
crmErr.setErrorCode(ErrCode.ERR_CODE_1001001);
crmErr.setErrorMsg(ErrCode.ERR_MSG_UNBIND);
}
return JSONObject.fromObject(crmErr).toString();
}
/**
* 删除竞争对手
* @return
*/
@RequestMapping("/del")
public String delRival(Rival rival,HttpServletRequest request,HttpServletResponse response){
String openId = request.getParameter("openId");
String publicId = request.getParameter("publicId");
String opptyid = rival.getOpptyid();
CrmError err = cRMService.getSugarService().getRival2SugarService().delRival(rival);
if(ErrCode.ERR_CODE_0.equals(err.getErrorCode())){
request.setAttribute("openId", openId);
request.setAttribute("publicId", publicId);
request.setAttribute("opptyid", opptyid);
}
return "redirect:/rival/list?opptyid="+opptyid+"&openId="+openId+"&publicId="+publicId;
}
}
|
package com.bingo.code.example.design.strategy.rewrite;
/**
* �����㷨ʵ�֣�Ϊ�¿ͻ���������ͨ�ͻ�����Ӧ���ļ۸�
*/
public class NormalCustomerStrategy implements Strategy{
public double calcPrice(double goodsPrice) {
System.out.println("�����¿ͻ���������ͨ�ͻ���û���ۿ�");
return goodsPrice;
}
}
|
package com.sneaker.mall.api.model;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class UserTotal extends BaseModel<Long> {
/**
* 订单数量
*/
private int orderCount = 0;
/**
* 供应商数量
*/
private int supplierCount = 0;
/**
* 收藏数量
*/
private int favCount;
public int getOrderCount() {
return orderCount;
}
public void setOrderCount(int orderCount) {
this.orderCount = orderCount;
}
public int getSupplierCount() {
return supplierCount;
}
public void setSupplierCount(int supplierCount) {
this.supplierCount = supplierCount;
}
public int getFavCount() {
return favCount;
}
public void setFavCount(int favCount) {
this.favCount = favCount;
}
}
|
package com.cat.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author xukaiqiangpc
*
*/
@Entity
@Table(name = "basicconfiguration")
public class BasicConfiguration implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2143146458653158871L;
private Integer basicConfigurationId;
public void setBasicConfigurationId(Integer basicConfigurationId) {
this.basicConfigurationId = basicConfigurationId;
}
private int webSiteClose;
private String closeWebSiteReason;
private String webSiteName;
private String webSiteUrl;
private String indexFileName;
@Column
public String getWebSiteUrl() {
return webSiteUrl;
}
public void setWebSiteUrl(String webSiteUrl) {
this.webSiteUrl = webSiteUrl;
}
@Column
public String getIndexFileName() {
return indexFileName;
}
public void setIndexFileName(String indexFileName) {
this.indexFileName = indexFileName;
}
@Column
public String getWebSiteName() {
return webSiteName;
}
public void setWebSiteName(String webSiteName) {
this.webSiteName = webSiteName;
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column
public Integer getBasicConfigurationId() {
return basicConfigurationId;
}
@Column
public String getCloseWebSiteReason() {
return closeWebSiteReason;
}
@Column
public int getWebSiteClose() {
return webSiteClose;
}
public void setWebSiteClose(int webSiteClose) {
this.webSiteClose = webSiteClose;
}
public void setCloseWebSiteReason(String closeWebSiteReason) {
this.closeWebSiteReason = closeWebSiteReason;
}
}
|
package com.example.windows10now.muathe24h.networking;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.windows10now.muathe24h.util.Constant;
/**
* Created by Windows 10 Now on 11/22/2017.
*/
public abstract class TaseNetWorkBase<T extends Object> {
private Context mContext;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private String session;
public TaseNetWorkBase(Context mContext) {
this.mContext = mContext;
sharedPreferences = mContext.getSharedPreferences(Constant.MuaThe24h_SHARED_PREFRENCES,
Context.MODE_PRIVATE);
session = sharedPreferences.getString(Constant.ACCESS_TOKEN, "");
editor = sharedPreferences.edit();
}
protected void saveAccessToken(String token) {
editor.putString(Constant.ACCESS_TOKEN, token);
editor.apply();
}
protected void removeAccessToken() {
editor.putString(Constant.ACCESS_TOKEN, "");
editor.apply();
}
}
|
package uuu.totalbuy.test;
/*
* 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.
*/
/**
*
* @author Administrator
*/
public class TestWhile {
public static void main(String[] args) {
// for (int i=1;i<10;i++){
// System.out.println("i = " + i);
// }
int i = 1;
while (i < 10) {
if (i == 3 || i == 8 || i == 9) {
i++;
continue;
}
System.out.println("i = " + i++);
}
do {
System.out.println("i = " + i++);
} while (i < 10);
}
}
|
public class MyCircle {
private MyPoint center;
private int radius=1;
public MyCircle(int x, int y, int radius) {
this.center=new MyPoint(x,y);
this.radius=radius;
}
public MyCircle(MyPoint center, int radius) {
this.center=center;
this.radius=radius;
}
public int getRadius() {
return this.radius;
}
public void setRadius(int radius) {
this.radius=radius;
}
public MyPoint getCenter() {
return this.center;
}
public void setCenter(MyPoint center) {
this.center=center;
}
public int getCenterX() {
return this.center.getX();
}
public int getCenterY() {
return this.center.getY();
}
public void setCenterXY(int x, int y) {
this.center.setXY(x, y);
}
public double getArea() {
double resultado=Math.PI * radius * radius;
return resultado;
}
public String toString() {
String resultado = "Circle @ "+this.center+" radius="+this.radius+"; area="+this.getArea();
return resultado;
}
public boolean equals(MyCircle other) {
boolean resultado=false;
if(other!=null) {
resultado=(this.center == other.getCenter()) && (this.radius == other.getRadius());
}
return resultado;
}
}
|
package com.example.lockwood.techTest.aws;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.document.*;
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Component
public class DynamoDb {
private Table table;
private AmazonDynamoDB client;
private DynamoDB dynamoDB;
private DynamoDBMapper mapper;
{
client = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build();
dynamoDB = new DynamoDB(client);
table = dynamoDB.getTable("ticket");
mapper = new DynamoDBMapper(client);
}
public boolean createId(String ticket) {
Item item=new Item()
.withPrimaryKey("ticket",ticket)
.withBoolean("valid",true);
PutItemSpec itemSpec=new PutItemSpec()
.withItem(item)
.withConditionExpression("attribute_not_exists(#ps)")
.withNameMap(new NameMap()
.with("#ps","ticket"));
try{
table.putItem(itemSpec);
return true;
}
catch(ConditionalCheckFailedException e){
logServiceError(e);
return false;
}
catch (AmazonClientException ace) {
logClientError(ace);
return false;
}
}
public Long getTotalTickets() {
Long totalItemCount = 0l;
ScanResult result = new ScanResult();
do {
ScanRequest req = new ScanRequest();
req.setTableName("ticket");
if (result != null) {
req.setExclusiveStartKey(result.getLastEvaluatedKey());
}
result = client.scan(req);
totalItemCount += result.getItems().size();
} while (result.getLastEvaluatedKey() != null);
System.out.println("Result size: " + totalItemCount);
return totalItemCount;
}
public boolean findValidTicket(String ticket) {
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1", ticket);
ItemCollection<ScanOutcome> items = null;
try {
items = table.scan("ticket = :val1",
"ticket, valid",
null,
expressionAttributeValues);
} catch (AmazonServiceException ase) {
logServiceError(ase);
} catch (AmazonClientException ace) {
logClientError(ace);
}
if (items != null) {
Iterator<Item> iterator = items.iterator();
if (iterator.hasNext()) {
return iterator.next().getBoolean("valid");
}
}
return false;
}
public boolean invalidateTicket(String ticket) {
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("ticket", ticket)
.withConditionExpression("ticket = :ticket")
.withUpdateExpression("set valid = :valid")
.withValueMap(new ValueMap().withBoolean(":valid", false).withString( ":ticket", ticket))
.withReturnValues(ReturnValue.UPDATED_NEW);
try {
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
if(outcome.getItem() == null){
return false;
}
return true;
}
catch (Exception e) {
System.err.println(e.getMessage());
return false;
}
}
private void logServiceError(AmazonServiceException ase){
System.err.println("Could not complete operation");
System.err.println("Error Message: " + ase.getMessage());
System.err.println("HTTP Status: " + ase.getStatusCode());
System.err.println("AWS Error Code: " + ase.getErrorCode());
System.err.println("Error Type: " + ase.getErrorType());
System.err.println("Request ID: " + ase.getRequestId());
}
private void logClientError(AmazonClientException ace){
System.err.println("Internal error occurred communicating with DynamoDB");
System.out.println("Error Message: " + ace.getMessage());
}
} |
package com.example.demo.EndPoints;
import com.example.demo.DTO.Table.TableReponse;
import com.example.demo.DTO.Table.TableRequest;
import com.example.demo.Services.TableServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/api/table")
public class TableRest {
private TableServiceImpl tableService;
@Autowired
public TableRest(TableServiceImpl tableService) {
super();
this.tableService = tableService;
}
@GetMapping
public List<TableReponse> getAll(){
return tableService.getAllEntity();
}
@GetMapping("/{id}")
public TableReponse getById(@PathVariable("id") long id){
return tableService.getEntityById(id);
}
@PostMapping
public TableReponse addTable(@RequestBody TableRequest table){
return tableService.addTable(table);
}
@DeleteMapping("/{id}")
public String deleteById(@PathVariable("id") long id) {
return tableService.deleteTable( id);
}
@PostMapping("/{id}")
public TableReponse updateTable(@PathVariable("id") long id, @RequestBody TableRequest newTable) {
return tableService.updateTable(id, newTable);
}
@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity <String> handleNoSuchElementException(NoSuchElementException e) {
return new ResponseEntity<String>( e.getMessage(),HttpStatus.NOT_FOUND);
}
}
|
package com.TestProject;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import pages.*;
public class cube {
private WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
@Test
public void testtestclass() throws Exception {
LoginPage.loginAsAdmin(driver);
MyWall.openEditProfilePage(driver);
UserProfile.setReshuflePopUpOff(driver);
MyWall.openMywall(driver);
String id="3583";
Thread.sleep(1000);
driver.get("http://qa.TestProject.com/members/auto_admin/mywall/?item_id=" + id);
Thread.sleep(2000);
MyWall.openCube(driver, id);
Thread.sleep(1000);
try {
assertEquals("Quick poll:", driver.findElement(By.cssSelector("h2")).getText());
assertEquals("When you find yourself on your own, how does it feel?", driver.findElement(By.cssSelector("p")).getText());
assertEquals("Energizing; so much to do, so little time.", driver.findElement(By.cssSelector("li.ilm_tester_answer.answer_5660 > label > span.ilm_tester_answer_title")).getText());
assertEquals("Boring; I don't know what to do by myself.", driver.findElement(By.cssSelector("li.ilm_tester_answer.answer_5661 > label > span.ilm_tester_answer_title")).getText());
assertEquals("Scary; I hate being alone.", driver.findElement(By.cssSelector("li.ilm_tester_answer.answer_5662 > label > span.ilm_tester_answer_title")).getText());
assertEquals("", driver.findElement(By.xpath("//input[@value='Answer']")).getText());
} catch (Exception e) {
// TODO Auto-generated catch block
fail("Cube content has changed or SP was not opened");
e.printStackTrace();
}
//Solve the cube
try {
driver.findElement(By.cssSelector("li.ilm_tester_answer.answer_5660 > label > input[name=\"ilm_tester[ilm_test][values]\"]")).click();
driver.findElement(By.xpath("//input[@value='Answer']")).click();
Thread.sleep(5000);
assertEquals("Thanks for your input!", driver.findElement(By.cssSelector("p.answer-notes")).getText());
assertEquals("Personalize", driver.findElement(By.linkText("Personalize")).getText());
assertEquals("Cube-IT", driver.findElement(By.linkText("Cube-IT")).getText());
driver.findElement(By.linkText("Cube-IT")).click();
Thread.sleep(5000);
assertTrue(driver.getPageSource().contains("<span>10</span>"));
} catch (Exception e) {
// TODO Auto-generated catch block
fail("Cube solving failed or cube was already solved");
e.printStackTrace();
}
//Clear user data
try {
driver.get("http://qa.TestProject.com/wp/wp-admin/profile.php");
assertEquals("Profile", driver.findElement(By.cssSelector("h2")).getText());
driver.findElement(By.linkText("Reset user CUBE-IT data")).click();
Thread.sleep(500);
} catch (Exception e) {
// TODO Auto-generated catch block
fail("User data was not cleared");
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
}
} |
package com.swetha.wishesapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class GreetingActivity extends AppCompatActivity {
TextView name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_greeting);
name =findViewById(R.id.wishes_text);
Intent i = getIntent();
String friendName = i.getStringExtra("KEY");
name.append(friendName);
}
} |
package integerSet;
/**
* This class provides methods to interact with a set of integers
* implemented using a normal array of integers.
* You <b>should</b> at least modify the
* methods <code>member</code> (is an integer in the set)
* and <code>insert</code> (add a new integer to the set).
* You may add new methods if you so wish.
*/
public class IntegerSet {
// You may define new variables here if needed
/**
* Returns <code>true</code> if the array <code>setArray</code>
* contains <code>element</code>.
* <p>
* This method <strong>must</strong> be implemented using
* <em>recursion</em>. That is, you are not allowed to use
* iterators, <code>for</code> loops, <code>while</code> loops
* and similar techniques to implement member, rather you should
* call a method defined by you recursively.
* <p>
* Note that the <code>null</code>
* reference indicates that the array does not contain an element
* at that position.
*/
public static boolean member2(int element, Integer setArray[],int indice) {
if (indice<=setArray.length-1){
if(setArray[indice]!=null && setArray[indice]==element)
return true;
else
return member2(element,setArray,++indice);
}
else
return false;
}
public static boolean member(int element, Integer setArray[]) {
if (setArray==null || setArray.length==0)
return false;
else
return member2(element,setArray,0);
}
/**
* Inserts the integer <code>element</code>
* in the <code>setArray</code> array argument, if it not
* already present (and if there is space to insert it).
* Integers can be inserted in array cells which contain <code>null</code>.
* <p>
* Returns <code>true</code> if the element was inserted,
* and <code>false</code> otherwise (the integer was already in
* the array, or there is no space in the array).
* <p>
* This method <strong>must</strong> be implemented <em>without</em>
* using recursion. That is, you should use a <code>for</code> loop,
* or a <code>while</code> loop to implement insert, you should
* not use recursion nor should you use iterators.
* <p>
* You <em>may</em> however call your method
* <code>member</code> to check whether the array
* already contains the element to add.
*/
public static boolean insert(int element, Integer setArray[]) {
boolean resultado=false;
for(int i=0;i<=setArray.length-1;i++){
if(setArray[i]==null && !member(element,setArray)){
setArray[i]=element;
resultado=true;
}
}
return resultado;
}
}
|
//************** Oct 23- P1*************
package ConstructorConcept;
public class Employee {
public static void main(String[] args) {
System.out.println("hello");
Employee e1=new Employee();
Employee e2=new Employee(10);
Employee e3=new Employee(10, "Selenium");
}
//Constructor of a class
//constructor name is same as class name
//Looks like a function, but it is not a function
//a function may or may not return a value but a constructor will never return a value
//no void or return keyword
//constructors can be overloaded.. duplicate constructors are not allowed
//Constructors are called when an object is created...
public Employee() {// default or 0 parameter const...
System.out.println("default emp cons..");
System.out.println("Hello Emp");
}
public Employee(int i) {
System.out.println("one parameter constructor");
}
public Employee(int i, String p) {
System.out.println("2 parameter constructor");
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class wb extends a {
public LinkedList<auj> iXe = new LinkedList();
public LinkedList<aum> rBr = new LinkedList();
protected final int a(int i, Object... objArr) {
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.d(1, 8, this.iXe);
aVar.d(2, 8, this.rBr);
return 0;
} else if (i == 1) {
return (f.a.a.a.c(1, 8, this.iXe) + 0) + f.a.a.a.c(2, 8, this.rBr);
} else {
byte[] bArr;
if (i == 2) {
bArr = (byte[]) objArr[0];
this.iXe.clear();
this.rBr.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
wb wbVar = (wb) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
auj auj = new auj();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = auj.a(aVar4, auj, a.a(aVar4))) {
}
wbVar.iXe.add(auj);
}
return 0;
case 2:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
aum aum = new aum();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = aum.a(aVar4, aum, a.a(aVar4))) {
}
wbVar.rBr.add(aum);
}
return 0;
default:
return -1;
}
}
}
}
}
|
package net.julisapp.riesenkrabbe.views.supportViews;
import android.content.Context;
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 com.google.firebase.crash.FirebaseCrash;
import butterknife.BindView;
import butterknife.ButterKnife;
import net.julisapp.riesenkrabbe.R;
public class ErrorReportActivity extends AppCompatActivity {
@BindView(R.id.bugreport_text)
EditText mBugreport;
@BindView(R.id.bugreport_button)
Button mSendBug;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_error_report);
ButterKnife.bind(this);
final Context context = this;
mSendBug.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String errorReport = mBugreport.getText().toString();
mBugreport.setText("");
String thankyouNote = getString(R.string.bugreport_thankyou);
Toast.makeText(context, thankyouNote, Toast.LENGTH_SHORT).show();
FirebaseCrash.report(new Exception(errorReport));
}
});
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
import com.tencent.mm.a.o;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.account.a.a.a;
import com.tencent.mm.plugin.account.friend.a.ao;
import com.tencent.mm.plugin.account.friend.a.ap;
import com.tencent.mm.plugin.account.friend.ui.f.1;
import com.tencent.mm.pluginsdk.ui.applet.a$a;
import com.tencent.mm.sdk.platformtools.x;
class f$1$1 implements a$a {
final /* synthetic */ 1 eMO;
f$1$1(1 1) {
this.eMO = 1;
}
public final void a(boolean z, boolean z2, String str, String str2) {
x.i("MicroMsg.QQFriendAdapterCaseB", "cpan ok:%b hasSendVerify:%b username:%s gitemId:%s", new Object[]{Boolean.valueOf(z), Boolean.valueOf(z2), str, str2});
long longValue = new o(o.cx(str2)).longValue();
ao bK = ((ap) ((a) g.n(a.class)).getQQListStg()).bK(longValue);
if (z && bK != null) {
bK.username = str;
}
if (bK != null) {
bK.dHO = 2;
x.d("MicroMsg.QQFriendAdapterCaseB", "f :%s", new Object[]{bK.toString()});
((ap) ((a) g.n(a.class)).getQQListStg()).a(longValue, bK);
this.eMO.eMN.WT();
} else {
x.w("MicroMsg.QQFriendAdapterCaseB", "cpan qq friend is null. qq:%s", new Object[]{str2});
}
if (z && bK != null) {
f.pC(str);
}
}
}
|
package ie.brewer.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
public class Beer {
@NotBlank(message="SKU is Mandatory")
private String sku;
@NotBlank(message="Name is Mandatory")
private String beerName;
@Size(min=10, max=50, message="Description should be more than 10 and less than 50 characters")
private String description;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getBeerName() {
return beerName;
}
public void setBeerName(String beerName) {
this.beerName = beerName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package collectionpackage;
import java.util.Comparator;
public class EmployeeComparator implements Comparator {
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Employee e1 =(Employee)o1;
Employee e2 =(Employee)o2;
if(e1.age>e2.age)
return -1;
else if(e1.age<e2.age)
return 1;
else
return 0;
}
}
|
package thuc_hanh.Comparator;
|
package org.gbif.kvs;
import java.io.Closeable;
/**
* Store of V data indexed by a key (byte[]).
*
* @param <K> type of key elements
* @param <V> type of elements stored
*/
public interface KeyValueStore<K, V> extends Closeable {
/**
* Obtains the associated data/payload to the key parameter, as byte[].
*
* @param key identifier of element to be retrieved
* @return the element associated with key, null otherwise
*/
V get(K key);
}
|
package com.yunhe.cargomanagement.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunhe.cargomanagement.dao.PurCommMapper;
import com.yunhe.cargomanagement.entity.PurComm;
import com.yunhe.cargomanagement.service.IPurCommService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @program: tradesteward
* @description: 进货详情中间表
* @author: 史江浩
* @create: 2019-01-23 19:22
**/
@Service("purCommService")
public class PurCommServiceImpl extends ServiceImpl<PurCommMapper,PurComm> implements IPurCommService {
@Resource
private PurCommMapper purCommMapper;
@Override
public int insertPurComm(PurComm purComm) {
return purCommMapper.insert(purComm);
}
@Override
public int updatePurCommByPuId(int puhId,int puId) {
return purCommMapper.updatePurCommByPuId(puhId,puId);
}
@Override
public int updatePurCommByPuhId(int warhoureId, int puhId) {
return purCommMapper.updatePurCommByPuhId(warhoureId,puhId);
}
@Override
public int[] selectPcGeshuByWId(int id) {
return purCommMapper.selectPcGeshuByWId(id);
}
@Override
public int[] selectComIdByWId(int id) {
return purCommMapper.selectComIdByWId(id);
}
}
|
package com.springbootmybatis.controller;
import com.springbootmybatis.mapper.AccessoryMapper;
import com.springbootmybatis.model.AccessoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
//附件表
@RequestMapping("/accessory")
@RestController
public class AccessoryController {
@Autowired
AccessoryMapper accessoryMapper;
@RequestMapping("/getAccessories")
public List<AccessoryEntity> getAll(){
return accessoryMapper.getAll();
}
@RequestMapping("/getOne/{id}")
public AccessoryEntity getOne(@PathVariable long id){
return accessoryMapper.getOne(id);
}
}
|
package wirtualnySwiat.grafika;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class OknoDialogowe extends JDialog implements ActionListener {
private final int oknoWys, oknoSzer;
private JTextField poleTekstowe;
private String tekst;
OknoDialogowe(Frame okno, String tytul) {
super(okno, tytul, true);
Dimension wymiaryEkranu = Toolkit.getDefaultToolkit().getScreenSize();
this.oknoWys = (int) wymiaryEkranu.getHeight()/6;
this.oknoSzer = (int) wymiaryEkranu.getWidth()/3;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setResizable(false);
setSize(oknoSzer, oknoWys);
setLocation((int) (wymiaryEkranu.getWidth()/2 - oknoSzer/2), (int) (wymiaryEkranu.getHeight()/2 - oknoWys/2));
setLayout(new FlowLayout());
JLabel info = new JLabel("Podaj nazwę zapisu: ");
info.setFont(new Font("Calibri", Font.BOLD, 30));
info.setPreferredSize(new Dimension(oknoSzer*9/10, oknoWys/6));
add(info);
poleTekstowe = new JTextField();
poleTekstowe.setFont(new Font("Calibri", Font.BOLD, 30));
poleTekstowe.setPreferredSize(new Dimension(oknoSzer*9/10, oknoWys/6));
add(poleTekstowe);
JButton okButton = new JButton("OK");
okButton.setFont(new Font("Calibri", Font.BOLD, 30));
okButton.setPreferredSize(new Dimension(oknoSzer/4, oknoWys/6));
okButton.addActionListener(this);
add(okButton);
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
tekst = poleTekstowe.getText();
setVisible(false);
dispose();
}
String dialoguj() {
setVisible(true);
return tekst;
}
}
|
package thirtydaysofcode;
import util.HashTable;
import java.util.HashMap;
import java.util.Scanner;
/**
* Created by wendy on 9/15/18.
*/
public class RansomNoteAgain {
// Complete the checkMagazine function below.
static void checkMagazine(String[] magazine, String[] note) {
HashTable mapWords = new HashTable();
for (int i = 0; i < magazine.length; i++) {
String key = magazine[i];
Integer wordCount = mapWords.get(key);
if(wordCount == null) {
mapWords.put(key, 1);
} else {
mapWords.replace(key, wordCount+=1);
}
}
for (int i = 0; i < note.length; i++) {
String key = note[i];
Integer wordCount = mapWords.get(key);
System.out.print(key + " " + wordCount);
if(wordCount == null || wordCount == 0) {
System.out.print("No");
return;
} else {
mapWords.replace(key, wordCount-1);
}
}
System.out.print("Yes");
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] mn = scanner.nextLine().split(" ");
int m = Integer.parseInt(mn[0]);
int n = Integer.parseInt(mn[1]);
String[] magazine = new String[m];
String[] magazineItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < m; i++) {
String magazineItem = magazineItems[i];
magazine[i] = magazineItem;
}
String[] note = new String[n];
String[] noteItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
String noteItem = noteItems[i];
note[i] = noteItem;
}
checkMagazine(magazine, note);
scanner.close();
}
}
|
package com.tencent.mm.openim.b;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.openim.PluginOpenIM;
import com.tencent.mm.plugin.appbrand.jsapi.bc;
import com.tencent.mm.plugin.mmsight.segment.FFmpegMetadataRetriever;
import com.tencent.mm.protocal.c.afs;
import com.tencent.mm.protocal.c.aft;
import com.tencent.mm.protocal.c.as;
import com.tencent.mm.protocal.c.ayc;
import com.tencent.mm.protocal.c.cgb;
import com.tencent.mm.protocal.c.db;
import com.tencent.mm.sdk.platformtools.x;
import java.util.Iterator;
import java.util.LinkedList;
public final class c extends l implements k {
String aem;
public final b diG;
private e diJ;
String eus;
private LinkedList<String> eut = new LinkedList();
public c(String str, String str2, LinkedList<String> linkedList) {
a aVar = new a();
aVar.dIG = new afs();
aVar.dIH = new aft();
aVar.uri = "/cgi-bin/micromsg-bin/getopenimresource";
aVar.dIF = bc.CTRL_INDEX;
this.diG = aVar.KT();
this.eus = str;
this.aem = str2;
this.eut.addAll(linkedList);
int size = 10 - this.eut.size();
if (size > 0) {
this.eut.addAll(((PluginOpenIM) g.n(PluginOpenIM.class)).getWordingInfoStg().x(size, str2));
}
afs afs = (afs) this.diG.dID.dIL;
afs.hva = str;
afs.aem = str2;
afs.rJC = this.eut;
x.i("MicroMsg.NetSceneGetOpenIMResource", "init NetSceneGetOpenIMResource appid:%s, lang:%s, initWordingIDs:%s, wordidList:%s", new Object[]{str, str2, o(linkedList), o(this.eut)});
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
public final int getType() {
return bc.CTRL_INDEX;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetSceneGetOpenIMResource", "onGYNetEnd : errType : %d, errCode : %d, errMsg : %s, appid:%s, lang:%s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str, this.eus, this.aem});
if (i2 == 0 && i3 == 0) {
aft aft = (aft) this.diG.dIE.dIL;
as asVar = aft.rJE;
x.i("MicroMsg.NetSceneGetOpenIMResource", "onGYNetEnd acct_type_resource url:%d, word:%d", new Object[]{Integer.valueOf(asVar.raL.size()), Integer.valueOf(asVar.raK.size())});
com.tencent.mm.openim.d.a aVar = new com.tencent.mm.openim.d.a();
aVar.field_acctTypeId = asVar.raJ;
aVar.field_language = this.aem;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getAccTypeInfoStg().b(aVar, new String[]{"acctTypeId", FFmpegMetadataRetriever.METADATA_KEY_LANGUAGE});
aVar.field_accTypeRec = asVar;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getAccTypeInfoStg().a(aVar);
db dbVar = aft.rJD;
x.i("MicroMsg.NetSceneGetOpenIMResource", "onGYNetEnd appid_resource funcFlag:%d, url:%d, word:%d", new Object[]{Integer.valueOf(dbVar.rde), Integer.valueOf(dbVar.raL.size()), Integer.valueOf(dbVar.raK.size())});
com.tencent.mm.openim.d.c cVar = new com.tencent.mm.openim.d.c();
cVar.field_appid = this.eus;
cVar.field_language = this.aem;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().b(cVar, new String[]{"appid", FFmpegMetadataRetriever.METADATA_KEY_LANGUAGE});
cVar.field_appRec = dbVar;
cVar.field_acctTypeId = asVar.raJ;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getAppIdInfoStg().a(cVar);
Iterator it = dbVar.raL.iterator();
while (it.hasNext()) {
ayc ayc = (ayc) it.next();
if ("openim_desc_icon".equals(ayc.aAL)) {
((com.tencent.mm.openim.a.b) g.l(com.tencent.mm.openim.a.b.class)).oC(ayc.url);
}
}
x.i("MicroMsg.NetSceneGetOpenIMResource", "onGYNetEnd wording_id_resource word:%d", new Object[]{Integer.valueOf(aft.rJF.size())});
Iterator it2 = aft.rJF.iterator();
while (it2.hasNext()) {
cgb cgb = (cgb) it2.next();
com.tencent.mm.openim.d.e eVar = new com.tencent.mm.openim.d.e();
eVar.field_appid = this.eus;
eVar.field_wordingId = cgb.sAz;
eVar.field_language = this.aem;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getWordingInfoStg().b(eVar, new String[]{"appid", "wordingId", FFmpegMetadataRetriever.METADATA_KEY_LANGUAGE});
eVar.field_wording = cgb.bSc;
eVar.field_pinyin = cgb.mcD;
eVar.field_quanpin = cgb.sAA;
g.Ek();
((PluginOpenIM) g.n(PluginOpenIM.class)).getWordingInfoStg().a(eVar);
}
this.diJ.a(i2, i3, str, this);
return;
}
this.diJ.a(i2, i3, str, this);
}
private static String o(LinkedList<String> linkedList) {
String str = "size:" + linkedList.size() + "[";
Iterator it = linkedList.iterator();
while (true) {
String str2 = str;
if (!it.hasNext()) {
return str2 + "]";
}
str = str2 + ((String) it.next()) + ",";
}
}
}
|
package Dominio;
import java.sql.ResultSet;
import Persistencia.Agente_BD;
public class Actividad_DAO {
private static Actividad_DAO ActividadDAO;
private static Agente_BD agenteBD;
private Actividad_DAO()throws Exception{
agenteBD= Agente_BD.getAgente();
}
public static Actividad_DAO getActividadDAO() throws Exception{
if(ActividadDAO==null)
ActividadDAO = new Actividad_DAO();
return ActividadDAO;
}
public void borrar (String nombre) throws Exception{
agenteBD.delete("DELETE FROM Actividades WHERE nombre='"+nombre +"';");
}
public void modificar(Actividad actividad) throws Exception{
agenteBD.update("UPDATE Actividades SET hora_inicio='"+actividad.getHora_inicio()+"',hora_fin='"+actividad.getHora_fin()
+ "',lugar='" + actividad.getLugar() + "',max_personas='" + actividad.getMax_personas() +
"' WHERE nombre='"+actividad.getNombre()+"';");
}
public Actividad leer(String nombre) throws Exception{
ResultSet resultado = agenteBD.read("SELECT nombre, hora_inicio, hora_fin, lugar, max_personas FROM Actividades WHERE nombre='"
+nombre+"';");
Actividad actividad = new Actividad(resultado.getString(0), Integer.parseInt(resultado.getString(1)),
Integer.parseInt(resultado.getString(2)), resultado.getString(3),
Integer.parseInt(resultado.getString(4)));
return actividad;
}
public void anadir(Actividad actividad)throws Exception{
agenteBD.create("INSERT INTO Actividades VALUES('"+actividad.getNombre()+"','"+actividad.getHora_inicio()+
"','"+actividad.getHora_fin()+"','"+actividad.getLugar()+"','"+actividad.getMax_personas()+"');");
}
}
|
package com.jlxy.bllld.dao;
import com.jlxy.bllld.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
import static com.jlxy.bllld.utils.OrmConstans.UserTABLE;
/**
* Created by ORCHID on 2017/3/23.
*/
@Repository
public interface UserDao {
/**
* 查找符合Name和Password的对象
*
* @param Name 待查找用户名
* @param Password 待查找密码
* @return 返回查找的User对象,没有返回null
*/
@Select("select * from " + UserTABLE + " where name=#{Name} and password=#{Password}")
User selectByNameAndPassword(@Param("Name") String Name, @Param("Password") String Password);
/**
* 查找符合name的对象
*
* @param name 待查找用户name
* @return 返回查找的User对象,没有返回null
*/
@Select("select * from " + UserTABLE + " where name=#{name}")
User selectByName(String name);
/**
* 查找符合email的对象
*
* @param email 待查找用户email
* @return 返回查找的User对象,没有返回null
*/
@Select("select * from " + UserTABLE + " where email=#{email}")
User selectByEmail(String email);
/**
* 查找符合id的对象
*
* @param id 待查找用户id
* @return 返回查找的User对象,没有返回null
*/
@Select("select * from " + UserTABLE + " where uid=#{id}")
User selectById(@Param("id") int id);
/**
* 删除某个对象,在企业开发中,我们一般不做物理删除,只是添加某个字段对其数据进行可用控制
*
* @param id 待删除对象
* @return 返回受影响的条数
*/
@Delete("delete from " + UserTABLE + " where uid=#{id}")
int deleteById(@Param("id") int id);
/**
* update User对象
*
* @param user 待更新对象
*/
@Update("update " + UserTABLE + " set password=#{PassWord},name=#{Name},nick_name=#{NickName},sex=#{Sex},duty=#{Duty},email=#{Email},photo_url=#{PhotoUrl},used=#{Used},create_time=#{CreateTime} WHERE uid=#{Id}")
void update(User user);
/**
* 插入User对象
* @param user 待插入对象
*/
// INSERT INTO gp_user
// (password,name,nick_name,sex,duty,email,photo_url,used,create_time)
// VALUE (#{PassWord},#{Name},#{NickName},#{Sex},#{Duty},#{Email},#{PhotoUrl},#{Used},#{CreateTime})
@Insert("insert into "+UserTABLE+"(name,password,nick_name,sex,duty,email,photo_url,used,create_time) VALUES (#{PassWord},#{Name},#{NickName},#{Sex},#{Duty},#{Email},#{PhotoUrl},#{Used},#{CreateTime})")
@Options(useGeneratedKeys = true,keyProperty = "id")
int add(User user);
@Select("select * from "+UserTABLE)
List<User> selectAll();
}
|
package org.libreoffice.example.comp;
import com.sun.star.awt.XWindow;
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XSingleComponentFactory;
import com.sun.star.lib.uno.helper.Factory;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.rendering.XCanvas;
import com.sun.star.ui.XUIElement;
import com.sun.star.ui.XUIElementFactory;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.XComponentContext;
/**
* This is the factory that creates the sidebar panel that displays an analog clock.
*/
public class PanelFactory implements XUIElementFactory, XServiceInfo {
public static final String __serviceName = "org.apache.openoffice.sidebar.AnalogClockPanelFactory";
private static final String msURLhead = "private:resource/toolpanel/AnalogClockPanelFactory";
private static final String IMPLEMENTATION_NAME = PanelFactory.class.getName();
private static final String[] SERVICE_NAMES = { __serviceName };
// -----------------------------------------------------------------------------------------------
/**
* kommt zuerst
*
* @param xRegistryKey
* @return
*/
public static boolean __writeRegistryServiceInfo(XRegistryKey xRegistryKey) {
return Factory.writeRegistryServiceInfo(IMPLEMENTATION_NAME, SERVICE_NAMES, xRegistryKey);
}
/**
* Gives a factory for creating the service.<br>
* This method is called by the <code>JavaLoader</code><br>
*
* @return Returns a <code>XSingleServiceFactory</code> for creating the component.<br>
* @see com.sun.star.comp.loader.JavaLoader<br>
* @param sImplementationName The implementation name of the component.<br>
*/
public static XSingleComponentFactory __getComponentFactory(String sImplementationName) {
Log.Instance().println("__getComponentFactory " + sImplementationName);
XSingleComponentFactory xFactory = null;
if (sImplementationName.equals(IMPLEMENTATION_NAME)) {
xFactory = Factory.createComponentFactory(PanelFactory.class, SERVICE_NAMES);
}
return xFactory;
}
// ----------------------------------------------------------------------------------------------------------
public PanelFactory(final XComponentContext xContext) {
Log.Instance().println("WorkbenchPanelFactory constructor");
mxContext = xContext;
}
/**
* The main factory method has two parts: - Extract and check some values from the given arguments - Check the sResourceURL and create a panel for it.
*/
@Override
public XUIElement createUIElement(final String sResourceURL, final PropertyValue[] aArgumentList) throws NoSuchElementException, IllegalArgumentException {
Log.Instance().println("createUIElement " + sResourceURL);
// Reject all resource URLs that don't have the right prefix.
if (!sResourceURL.startsWith(msURLhead)) {
throw new NoSuchElementException(sResourceURL, this);
}
// Retrieve the parent window and canvas from the given argument list.
XWindow xParentWindow = null;
XCanvas xCanvas = null;
Log.Instance().println("processing " + aArgumentList.length + " arguments");
for (final PropertyValue aValue : aArgumentList) {
Log.Instance().println(" " + aValue.Name + " = " + aValue.Value);
if (aValue.Name.equals("ParentWindow")) {
try {
xParentWindow = (XWindow) AnyConverter.toObject(XWindow.class, aValue.Value);
} catch (IllegalArgumentException aException) {
Log.Instance().PrintStackTrace(aException);
}
} else if (aValue.Name.equals("Canvas")) {
xCanvas = (XCanvas) AnyConverter.toObject(XCanvas.class, aValue.Value);
}
}
// Check some arguments.
if (xParentWindow == null) {
throw new IllegalArgumentException("No parent window provided to the UIElement factory. Cannot create tool panel.", this, (short) 1);
}
// Create the panel.
final String sElementName = sResourceURL.substring(msURLhead.length() + 1);
if (sElementName.equals("AnalogClockPanel"))
return new UIElement(sResourceURL, new AnalogClockPanel(xParentWindow, mxContext, xCanvas));
else
return null;
}
@Override
public String getImplementationName() {
return IMPLEMENTATION_NAME;
}
@Override
public String[] getSupportedServiceNames() {
return SERVICE_NAMES;
}
@Override
public boolean supportsService(final String sServiceName) {
for (final String sSupportedServiceName : SERVICE_NAMES)
if (sSupportedServiceName.equals(sServiceName))
return true;
return false;
}
private final XComponentContext mxContext;
}
|
package com.yougou.merchant.api.active.vo;
import java.io.Serializable;
/**
* 审批商家报名vo
* @author zhang.wj
*
*/
public class MerchanteEnrollxamineVo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
//是否成功
private boolean isSuccess;
//错误原因
private String errorMsg;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
|
package textExcel;
import textExcel.TestsALL.Helper;
// initializes spreadsheet and parses the type of cell that's being
// created depending on user input
public class Spreadsheet implements Grid
{
private int numRows = 20;
private int numCols = 12;
private Cell[][] spreadsheet = new Cell[numRows][numCols];
public Spreadsheet() {
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
spreadsheet[row][col] = new EmptyCell();
}
}
}
@Override
// processes user input and incorporates into the textExcel spreadsheet
public String processCommand(String command)
{
String result = "";
if (command.equals("")) {
// does nothing in case of empty string being passed in
// clears either the entire grid or a single cell
} else if (command.split(" ", 2)[0].toLowerCase().equals("clear")) {
if (command.contains(" ")) {
String cellName = command.split(" ")[1];
SpreadsheetLocation cell = new SpreadsheetLocation(cellName);
spreadsheet[cell.getRow()][cell.getCol()] = new EmptyCell();
result = getGridText();
} else {
for (int i = 0; i < numRows; i++) {
for (char j = 0; j < numCols; j++) {
spreadsheet[i][j] = new EmptyCell();
}
}
result = getGridText();
}
// input entered is a cell location
} else if (Character.isLetter(command.charAt(0)) && Character.isDigit(command.charAt(1))) {
String cellName = command.split(" ", 3)[0];
SpreadsheetLocation cell = new SpreadsheetLocation(cellName);
if (command.contains("=")) {
String value = command.split(" ", 3)[2];
Cell target = spreadsheet[cell.getRow()][cell.getCol()];
// determines whether the cell contains text (TextCell or FormulaCell) or numbers (RealCell)
if (!Character.isDigit(value.charAt(0)) && value.charAt(0) != '-') {
// checks if the cell contains parentheses, in which case it would be a FormulaCell
if (value.charAt(0) == '(' && value.charAt(value.length() - 1) == ')') {
spreadsheet[cell.getRow()][cell.getCol()] = new FormulaCell(value, spreadsheet);
} else {
spreadsheet[cell.getRow()][cell.getCol()] = new TextCell(value);
}
} else {
// checks if cell has a percent sign (PercentCell) or a decimal/number (ValueCell)
if (value.contains("%")) {
spreadsheet[cell.getRow()][cell.getCol()] = new PercentCell(value);
} else if (value.contains(".") || Character.isDigit(value.charAt(0))
|| value.charAt(0) == '-') {
spreadsheet[cell.getRow()][cell.getCol()] = new ValueCell(value);
}
}
result = getGridText();
} else {
result = spreadsheet[cell.getRow()][cell.getCol()].fullCellText();
}
} else {
System.out.println("Unknown command. Type 'quit' to exit the program.");
}
return result;
}
@Override
public int getRows()
{
return numRows;
}
@Override
public int getCols()
{
return numCols;
}
@Override
public Cell getCell(Location loc)
{
return spreadsheet[loc.getRow()][loc.getCol()];
}
@Override
// displays the current grid of cells
public String getGridText() {
String grid = "";
// first row - column header
String firstRow = " |";
for (int i = 'A'; i <= 'L'; i++) {
firstRow += (char) i + " |";
}
grid += firstRow + "\n";
// the rest of the rows - table of values
for (int i = 0; i < numRows; i++) {
String row = "";
row += String.format("%-3s", i+1) + "|";
for (int j = 0; j < numCols; j++) {
row += spreadsheet[i][j].abbreviatedCellText() + "|";
}
grid += row + "\n";
}
return grid;
}
}
|
package function;
public class Function {
public double[][] arrayFilling(String a, String b, String c){
int n = Integer.parseInt(a);
int m = Integer.parseInt(b);
int s = Integer.parseInt(c);
int l = (Math.abs(n-m))/s;
double table[][] = new double[l][1];
return table;
}
public double[][] function(double a, double b, double h, double array[][]) {
for (double i = a; i < b; i += h) {
for (int j = 0; j < array.length; j++) {
}
}
return null;
}
}
|
package com.stem.dao;
import com.stem.entity.WxImageResource;
import com.stem.entity.WxImageResourceExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface WxImageResourceMapper {
int countByExample(WxImageResourceExample example);
int deleteByExample(WxImageResourceExample example);
int deleteByPrimaryKey(Integer id);
int insert(WxImageResource record);
int insertSelective(WxImageResource record);
List<WxImageResource> selectByExample(WxImageResourceExample example);
WxImageResource selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") WxImageResource record, @Param("example") WxImageResourceExample example);
int updateByExample(@Param("record") WxImageResource record, @Param("example") WxImageResourceExample example);
int updateByPrimaryKeySelective(WxImageResource record);
int updateByPrimaryKey(WxImageResource record);
void batchInsertTemp(List<WxImageResource> wir);
void clearTempTable();
void clearTable();
void synTable();
} |
package spring4.javaconfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import spring4.iocdemo.Config;
import spring4.iocdemo.UseFunctionService;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);//将配置类加载到容器中
UseFunctionService useFunctionService=context.getBean(UseFunctionService.class);//在容器中获取指定的bean
System.out.println(useFunctionService.sayHello("java"));
context.close();
}
}
|
package Genetic;
import java.util.*;
public class GeneticAl {
Random random = new Random();
private int randomIndividDigit = 10;//сколько мутантов появляется в новом поколении
private int generationDigit = 10;//сколько поколений
private int firstGenerationDigit = 50;//сколько особей в первом поколении
private int survivorsDigit = 10;//сколько выживает в каждом поколении после отбора
private int maxLoad;
private Item[] items;
public GeneticAl() {
}
public GeneticAl(int randomIndividDigit, int generationDigit, int firstGenerationDigit, int survivorsDigit) {
this.randomIndividDigit = randomIndividDigit;
this.generationDigit = generationDigit;
this.firstGenerationDigit = firstGenerationDigit;
this.survivorsDigit = survivorsDigit;
}
public void set(int mutantsDigit, int generationDigit, int firstGenerationDigit, int survivorsDigit) {
this.randomIndividDigit = mutantsDigit;
this.generationDigit = generationDigit;
this.firstGenerationDigit = firstGenerationDigit;
this.survivorsDigit = survivorsDigit;
}
public Fill fillKnapsackGenetic(int load, List<Item> items) {
this.items = new Item[items.size()];
this.items = items.toArray(this.items);
maxLoad = load;
return fillKnapsackGenetic().convertToFill();
}
public Individual fillKnapsackGenetic() {
Generation generation = new Generation();
//Эволюционируем заданное колличество раз
//Каждый раз выбираем из поколения лучший экземпляр
//На случай, если последнее поколение может не оказаться лучшим
for (int i = 0; i < generationDigit; i++)
generation.evolute();
return generation.bestIndividualInHistory;
}
//Особь
public class Individual {
byte[] gens;
int fitness;
int load;
Individual() {
load = 0;
fitness = 0;
gens = new byte[items.length];
int goFromStart = random.nextInt(3);
//1-с нуля
//2-c конца
//3-с центра
if (goFromStart == 1)
for (int i = 0; i < gens.length; i++) {
if (load + items[i].getWeight() > maxLoad)
gens[i] = 0;
else {
gens[i] = (byte) random.nextInt(2);
if (gens[i] == 1) {
load += items[i].getWeight();
fitness += items[i].getCost();
}
}
}
else if (goFromStart == 2)
for (int i = gens.length - 1; i >= 0; i--) {
if (load + items[i].getWeight() > maxLoad)
gens[i] = 0;
else {
gens[i] = (byte) random.nextInt(2);
if (gens[i] == 1) {
load += items[i].getWeight();
fitness += items[i].getCost();
}
}
}
else if (goFromStart == 3)
for (int i = 0; i < gens.length / 2 - 1; i++) {
gens[gens.length / 2 + i] = (byte) random.nextInt(2);
gens[gens.length / 2 - i] = (byte) random.nextInt(2);
if (gens.length / 2 + i == 1) {
load += items[gens.length / 2 + i].getWeight();
fitness += items[gens.length / 2 + i].getCost();
}
if (gens.length / 2 - i == 1) {
load += items[gens.length / 2 - i].getWeight();
fitness += items[gens.length / 2 - i].getCost();
}
}
}
Individual(byte[] gens, int load, int fitness) {
this.gens = gens;
this.load = load;
this.fitness = fitness;
}
//Скрещивание особей
private Individual cross(Individual opponent) {
byte[] gensOfChild = new byte[gens.length];
int load = 0;
int fitness = 0;
for (int i = 0; i < gens.length; i++)
if (gens[i] == opponent.gens[i]) {
gensOfChild[i] = gens[i];
if (gens[i] == 1) {
load += items[i].getWeight();
fitness += items[i].getCost();
}
} else {
gensOfChild[i] = (byte) random.nextInt(2);
if (gensOfChild[i] == 1) {
load += items[i].getWeight();
fitness += items[i].getCost();
}
}
return new Individual(gensOfChild, load, fitness);
}
//Мутации
private Individual mutantReverse() {
byte[] gensMutant = new byte[items.length];
int fitness = 0;
int load = 0;
for (int i = 0; i < items.length; i++) {
if (gens[i] == 1)
gensMutant[i] = 0;
else {
gensMutant[i] = 1;
load += items[i].getWeight();
fitness += items[i].getCost();
}
}
return new Individual(gensMutant, load, fitness);
}
private Individual mutantGensToLeft() {
byte[] gensMutant = new byte[items.length];
int fitness = 0;
int load = 0;
for (int i = 1; i < items.length; i++) {
gensMutant[i] = gens[i - 1];
}
gensMutant[0] = gens[gens.length - 1];
return new Individual(gensMutant, load, fitness);
}
Fill convertToFill() {
Set<Item> takenItems = new HashSet<>();
for (int i = 0; i < items.length; i++)
if (gens[i] == 1)
takenItems.add(items[i]);
return new Fill(fitness, takenItems);
}
@Override
public String toString() {
return "f: " + fitness + " w: " + load;
}
}
//Поколение
private class Generation {
List<Individual> individuals;
Individual bestIndividualInHistory;
Generation() {
individuals = new ArrayList<>();
//Первое поколение
for (int i = 0; i < firstGenerationDigit; i++)
individuals.add(new Individual());
byte[] gens = new byte[items.length];
for (int i = 0; i < gens.length; i++) {
gens[i] = 0;
}
bestIndividualInHistory = new Individual(gens, 0, 0);
}
private void evolute() {
for (int i = 0; i < randomIndividDigit; i++)
individuals.add(new Individual());
individuals = selection();
individuals.addAll(mutants());
individuals = selection();
individuals = crossing();
searchBestIndividuals();
}
private void searchBestIndividuals() {
for (Individual individual : individuals)
if (individual.fitness > bestIndividualInHistory.fitness && individual.load < maxLoad)
bestIndividualInHistory = individual;
}
private List<Individual> selection() {
List<Individual> survivorsIndividuals = new ArrayList<>(survivorsDigit);
for (int i = 0; i < survivorsDigit; i++) {
int removeIndex = 0;
Individual bestInGeneration = new Individual(new byte[items.length], 0, 0);
for (int j = 0; j < individuals.size(); j++) {
if (individuals.get(j).fitness > bestInGeneration.fitness && individuals.get(j).load <= maxLoad) {
bestInGeneration = new Individual(individuals.get(j).gens, individuals.get(j).load, individuals.get(j).fitness);
removeIndex = j;
}
}
survivorsIndividuals.add(bestInGeneration);
individuals.remove(removeIndex);
}
return survivorsIndividuals;
}
private List<Individual> crossing() {
List<Individual> nextGeneration = new ArrayList();
for (int i = 0; i < individuals.size(); i++)
for (int j = i + 1; j < individuals.size(); j++)
nextGeneration.add(individuals.get(i).cross(individuals.get(j)));
return nextGeneration;
}
//Мутации
private List<Individual> mutants() {
List<Individual> mutants = new ArrayList<>();
for (Individual individual : individuals) {
mutants.add(individual.mutantReverse());
mutants.add(individual.mutantGensToLeft());
}
return mutants;
}
}
}
|
package com.xxw.service.combine;
import com.xxw.entity.dto.MainPagelnfoDTO;
import com.xxw.entity.dto.Result;
/**
* @author xiongxianwei
* 2020/6/1 0001
*/
public interface HeadLineShopCategoryCombineService {
Result<MainPagelnfoDTO> getMainPagelnfo();
}
|
package testcase.emb;
import es.utils.mapper.Mapper;
import es.utils.mapper.exception.MappingException;
import es.utils.mapper.factory.builder.EMBuilder;
import es.utils.mapper.factory.builder.From;
import es.utils.mapper.impl.object.ClassMapper;
import from.ClassMapperFromTest;
import org.junit.jupiter.api.Test;
import to.ClassMapperToTest;
import static org.assertj.core.api.Assertions.assertThat;
public class EMB_Step0 {
@Test
public void shouldCreateEMBuilderStepFrom() throws MappingException {
Mapper mapper = new Mapper();
ClassMapper<ClassMapperFromTest,ClassMapperToTest> mapping = mapper.addForClass(ClassMapperFromTest.class,ClassMapperToTest.class);
From<ClassMapperFromTest,ClassMapperToTest> step1 = EMBuilder.using(mapper,mapping);
assertThat(step1).isNotNull()
.isExactlyInstanceOf(EMBuilder.class)
.isInstanceOf(From.class)
.hasFieldOrProperty("mapper")
.hasFieldOrProperty("mapping")
.hasFieldOrProperty("getter")
.hasFieldOrProperty("defaultInput")
.hasFieldOrProperty("transformer")
.hasFieldOrProperty("defaultOutput")
.hasFieldOrProperty("setter")
.hasFieldOrProperty("_elementMapper")
.hasFieldOrPropertyWithValue("mapper",mapper)
.hasFieldOrPropertyWithValue("mapping",mapping)
.hasAllNullFieldsOrPropertiesExcept("mapper","mapping");
}
}
|
package br.com.nozinho.dao.impl;
import javax.ejb.Stateless;
import br.com.nozinho.dao.UfDAO;
import br.com.nozinho.ejb.dao.impl.GenericDAOImpl;
import br.com.nozinho.model.Uf;
@Stateless
public class UfDAOImpl extends GenericDAOImpl<Uf, String> implements UfDAO{
}
|
package com.liyinghua.common;
/**
*
* @ClassName: StatusMessages
* @Description: 用户状态信息(是否禁用)
* @author:李英华
* @date: 2019年11月13日 下午7:40:12
*/
public class StatusMessages {
/**
* 信息编号
*/
private Integer wrongNumber;
/**
* 提示信息
*/
private String hint;
/**
*
*/
private Object date;
public Integer getWrongNumber() {
return wrongNumber;
}
public void setWrongNumber(Integer wrongNumber) {
this.wrongNumber = wrongNumber;
}
public String getHint() {
return hint;
}
public void setHint(String hint) {
this.hint = hint;
}
public Object getDate() {
return date;
}
public void setDate(Object date) {
this.date = date;
}
public StatusMessages(Integer wrongNumber, String hint, Object date) {
super();
this.wrongNumber = wrongNumber;
this.hint = hint;
this.date = date;
}
public StatusMessages() {
super();
// TODO Auto-generated constructor stub
}
}
|
package com.hb.rssai.view.me;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.hb.rssai.R;
import com.hb.rssai.base.BaseFragment;
import com.hb.rssai.presenter.BasePresenter;
import com.hb.rssai.presenter.SearchInfoPresenter;
import com.hb.rssai.view.iView.ISearchInfoView;
import com.hb.rssai.view.iView.SearchKeyWordListener;
import com.hb.rssai.view.widget.MyDecoration;
import butterknife.BindView;
public class SearchInfoFragment extends BaseFragment implements ISearchInfoView, SearchKeyWordListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
@BindView(R.id.search_info_recycler_view)
RecyclerView mSearchInfoRecyclerView;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private LinearLayoutManager infoManager;
private String keyWord = "";
public SearchInfoFragment() {
// Required empty public constructor
}
public static SearchInfoFragment newInstance(String param1, String param2) {
SearchInfoFragment fragment = new SearchInfoFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
protected void setAppTitle() {
}
@Override
protected BasePresenter createPresenter() {
return new SearchInfoPresenter(getContext(), this);
}
@Override
protected int providerContentViewId() {
return R.layout.fragment_search_info;
}
@Override
protected void initView(View rootView) {
infoManager = new LinearLayoutManager(getContext());
mSearchInfoRecyclerView.setLayoutManager(infoManager);
mSearchInfoRecyclerView.addItemDecoration(new MyDecoration(getContext(), LinearLayoutManager.VERTICAL));
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
protected void lazyLoad() {
}
@Override
public String getKeyWords() {
return keyWord;
}
@Override
public RecyclerView getInfoRecyclerView() {
return mSearchInfoRecyclerView;
}
@Override
public LinearLayoutManager getInfoManager() {
return infoManager;
}
@Override
public void setKeyWords(String val) {
keyWord = val;
((SearchInfoPresenter) mPresenter).refreshInfoList(val);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
|
import org.junit.Assert;
import org.junit.Test;
public class ExampleTest {
@Test
public void test() {
Assert.assertEquals(1,1);
}
}
|
package com.travelportal.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import play.db.jpa.JPA;
@Entity
@Table(name = "cancellation_date_diff")
public class CancellationDateDiff {
@Column(name = "id")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "date_diff")
private int dateDiff;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDateDiff() {
return dateDiff;
}
public void setDateDiff(int dateDiff) {
this.dateDiff = dateDiff;
}
public static CancellationDateDiff getById(int code) {
return (CancellationDateDiff) JPA.em()
.createQuery("select c from CancellationDateDiff c where id = ?1")
.setParameter(1, code).getSingleResult();
}
}
|
public class FindKthSmallestNumber{
public static void main(String args[]){
int array[] = {2,20,5,4,11,15};
int k = 6;
System.out.println(getSmallest(array,0,array.length-1,k-1));
}
public static int getSmallest(int array[],int left,int right,int k){
if(left <= right){
int pivot = partition(array,left,right);
System.out.println("pivot item ="+array[pivot]+" at position "+pivot);
if(pivot == k){
return array[pivot];
}
if(k < pivot){
return getSmallest(array,left,pivot-1,k);
}else{
return getSmallest(array,pivot+1, right,k);
}
}
return 0;
}
public static int partition(int array[],int left,int right){
int pivot = array[right];
int i =left-1;
int j=left;
while(j < right){
if(array[j] <= pivot){
i++;
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
j++;
}
int temp = array[i+1];
array[i+1] = array[right];
array[right] = temp;
return i+1;
}
} |
package com.tencent.mm.plugin.backup.backupmoveui;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.plugin.backup.a.g;
import com.tencent.mm.plugin.backup.c.a;
import com.tencent.mm.plugin.backup.c.a.1;
import com.tencent.mm.plugin.backup.c.b;
import com.tencent.mm.plugin.backup.g.d;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMWizardActivity;
public class BackupUI extends MMWizardActivity {
private static boolean gVG = false;
private al gUM = new al(Looper.getMainLooper(), new 4(this), true);
private Button gVF;
private TextView gVs;
private TextView gVu;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (!getIntent().getExtras().getBoolean("WizardRootKillSelf", false)) {
setMMTitle(R.l.backup_move);
h.mEJ.h(11788, new Object[]{Integer.valueOf(1)});
this.gVu = (TextView) findViewById(R.h.backup_move_status_content);
this.gVF = (Button) findViewById(R.h.backup_move_bt);
this.gVs = (TextView) findViewById(R.h.backup_move_bottom_btn);
b.arv();
Editor edit = b.aqU().edit();
edit.putInt("BACKUP_MOVE_CHOOSE_SELECT_TIME_MODE", 0);
edit.putInt("BACKUP_MOVE_CHOOSE_SELECT_CONTENT_TYPE", 0);
edit.putLong("BACKUP_MOVE_CHOOSE_SELECT_START_TIME", 0);
edit.putLong("BACKUP_MOVE_CHOOSE_SELECT_END_TIME", 0);
edit.commit();
if (b.arv().arz().gTz) {
b.arv().arz().aru();
} else {
a arz = b.arv().arz();
d.asG().asJ();
e.post(new 1(arz), "BakMoveChooseServer.calculateToChoose");
}
if (bi.oW(g.cQ(this))) {
this.gVu.setText(R.l.backup_status_content_no_wifi);
this.gVu.setTextColor(getResources().getColor(R.e.backup_red));
this.gVF.setEnabled(false);
gVG = false;
h.mEJ.h(11788, new Object[]{Integer.valueOf(2)});
} else {
this.gVu.setText(R.l.backup_status_content_open_wifi);
this.gVu.setTextColor(getResources().getColor(R.e.backup_green));
this.gVF.setEnabled(true);
gVG = true;
}
this.gVF.setOnClickListener(new 1(this));
this.gVs.setOnClickListener(new 2(this));
setBackBtn(new 3(this));
}
}
public void onStart() {
super.onStart();
this.gUM.J(5000, 5000);
}
public void onStop() {
super.onStop();
this.gUM.SO();
}
public void onDestroy() {
x.d("MicroMsg.BackupUI", "BackupUI onDestroy.");
super.onDestroy();
b.arv().arz().cancel();
b.arv().arz().art();
}
protected final int getLayoutId() {
return R.i.backup_ui;
}
}
|
package com.computerstudent.madpractical.Practical_16;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.computerstudent.madpractical.R;
public class timePiker extends AppCompatActivity {
TimePicker time;
TextView timeShow;
Button btnClick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_piker);
time=findViewById(R.id.timePicker);
timeShow=findViewById(R.id.timeShow);
btnClick=findViewById(R.id.btnTime);
time.setIs24HourView(true);
btnClick.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
int hour=time.getHour();
int min=time.getMinute();
timeShow.setText("Time : "+ hour +" : "+min);
}
});
}
} |
package br.com.amphibia.schedule.dao;
import org.springframework.data.repository.CrudRepository;
import br.com.amphibia.schedule.model.Usuario;
public interface UsuarioDAO extends CrudRepository<Usuario, Integer>{
public Usuario findByEmailAndSenha(String email, String senha);
public Usuario findByEmailOrRacf(String email, String racf);
}
|
package Process;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BlockingProcess implements Runnable {
protected final BlockingQueue writeQueue;
protected final Map<Integer, ObjectOutputStream> idMapOOS = new ConcurrentHashMap<>();//map id to socket
protected final Map<Integer, Socket> idMapSocket = new ConcurrentHashMap<>();//map id to socket
protected final Map<InetSocketAddress, Integer> ipMapId;//map ip to id
protected final Map<Integer, InetSocketAddress> idMapIp;//map id to ip
protected BlockingQueue deliverQueue = new LinkedBlockingQueue<Packet>(100);
protected final int selfID;
protected final InetSocketAddress addr;
protected final ServerSocket sock;
protected final int min_delay;
protected final int max_delay;
protected static final Logger LOGGER = Logger.getLogger(CausalOrderProcess.class.getName());
protected Lock writeLock = new ReentrantLock();
public BlockingProcess(BlockingQueue q, int selfID, ConcurrentHashMap<Integer, InetSocketAddress> map,
int min_delay, int max_delay) throws IOException {
this.addr = map.get(selfID);
sock = new ServerSocket();
sock.setOption(StandardSocketOptions.SO_REUSEADDR, true);
sock.setOption(StandardSocketOptions.SO_REUSEPORT, true);
sock.bind(this.addr);
this.selfID = selfID;
this.writeQueue = q;
this.max_delay = max_delay;
this.min_delay = min_delay;
idMapIp = map;
ipMapId = reverseMap(idMapIp);
LOGGER.setLevel(Level.FINEST);
LOGGER.info("Self PID: " + selfID);
}
/**
* This thread will spawn a thread to listen to a socket if a new connection is accepted.
*/
protected void startAcceptingThread() {
new Thread(() -> {
while (true) {
try {
Socket s = sock.accept();
Integer newID;
LOGGER.finest("accepting: " + s.getRemoteSocketAddress() + " is connected? " + s.isConnected());
if (!idMapOOS.containsValue(s)) {
newID = ipMapId.get(s.getRemoteSocketAddress());
System.out.println("incoming id: " + newID);
assert newID != null;
idMapOOS.put(newID, new ObjectOutputStream(s.getOutputStream()));
idMapSocket.put(newID, s);
new Thread(() -> {
try {
unicast_receive(newID, new byte[8]);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
} else {
throw new ConnectException("Already accept");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
System.out.println("accepting thread up");
}
/**
* This thread spawn three new thread
* 1.Accept new connection
* 2.Deliver packet
* 3.Send packet
*/
@Override
public void run() {
System.out.println("server is up");
System.out.println("listening on " + sock);
startAcceptingThread();
new Thread(new DeliverThread(deliverQueue, null)).start();// start a DeliverThread
while (true) {
try {
final String msg = (String) writeQueue.take();
final long delay = (long) (new Random().nextDouble() * (max_delay - min_delay)) + min_delay;
System.out.println("delay is: " + delay);
String parsed[] = msg.split("\\s+", 3);
if (parsed.length != 3)
throw new IllegalArgumentException();
if (parsed[0].equals("send")) {
if (idMapIp.containsKey(Integer.parseInt(parsed[1]))) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
unicast_send(Integer.parseInt(parsed[1]), parsed[2].getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}, delay);
} else {
LOGGER.warning("This PID is not exist");
}
} else {
throw new IllegalArgumentException();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
LOGGER.severe("not a legal command");
}
}
}
/**
* This function handle connection (client side). If this is the first message, the new established
* Socket need to be added to global maps. Otherwise, it just pull out the record from the map.
*
* @param dst
* @return
* @throws IOException
*/
protected final ObjectOutputStream handleSendConnection(int dst) throws IOException {
Socket s;
ObjectOutputStream oos = null;
if (idMapOOS.containsKey(dst)) {
oos = idMapOOS.get(dst);
} else {//this is first time connection
s = new Socket();
s.setOption(StandardSocketOptions.SO_REUSEPORT, true);
s.bind(addr);
InetSocketAddress id;
id = idMapIp.get(dst);
s.connect(id);
oos = new ObjectOutputStream(s.getOutputStream());
idMapOOS.put(dst, oos);
idMapSocket.put(dst, s);
new Thread(() -> {
try {
unicast_receive(ipMapId.get(s.getRemoteSocketAddress()), new byte[8]);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
return oos;
}
/**
* Handle unicast send. There is not much to say here.
*
* @param dst
* @param msg
* @throws IOException
*/
protected void unicast_send(int dst, byte[] msg) throws IOException {
System.out.println("sending msg : " + new String(msg) + " to dst: " + dst);
ObjectOutputStream oos;
oos = handleSendConnection(dst);
Packet p = new Packet(selfID, new String(msg));
if (dst == selfID) {
deliverQueue.add(p);
return;
}
writeLock.lock();
oos.flush();// TODO:Do we need flush?
oos.writeObject(p);
writeLock.unlock();
}
/**
* Handle receive. Once see a packet, put the packet in the queue
*
* @param dst
* @param msg
* @throws IOException
*/
protected void unicast_receive(int dst, byte[] msg) throws IOException {
Socket s = idMapSocket.get(dst);
System.out.println("listening to process " + s.getRemoteSocketAddress());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
while (true) {
Packet p = null;
try {
p = (Packet) ois.readObject();
System.out.println("get new packet");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
deliverQueue.add(p);
}
}
/**
* A helper function to "reverse" a map.
*
* @param map
* @return
*/
protected static Map<InetSocketAddress, Integer> reverseMap(Map<Integer, InetSocketAddress> map) {
Map<InetSocketAddress, Integer> map_r = new ConcurrentHashMap<>();
for (Map.Entry<Integer, InetSocketAddress> e : map.entrySet()) {
map_r.put(e.getValue(), e.getKey());
}
return map_r;
}
}
|
//package HW9;
import java.util.Random;
class NewPoint1 {
int x;
int y;
int z;
}
public class Eucledian_multithreaded extends Thread {
static int NoOfThreads = Runtime.getRuntime().availableProcessors();
static long milliSeconds = 0;
static double minDistance;
static NewPoint1 firstPoint = new NewPoint1();
static NewPoint1 secondPoint = new NewPoint1();
static NewPoint1[] pt;
int z;
NewPoint1[] newpt;
int div;
public static double[] mindistancethread = new double[NoOfThreads];
public static NewPoint1[][] threadPoint = new NewPoint1[NoOfThreads][2];
public Eucledian_multithreaded(int z, NewPoint1[] pt, int div) {
this.z = z;
this.newpt = pt;
this.div = div;
}
public static void init() {
milliSeconds = System.currentTimeMillis();
}
public void run() {
int start = z * div;
int end;
if (z < NoOfThreads)
end = start + div;
else
end = pt.length;
minDistance = DistanceBetweenPoints(pt[0], pt[1]);
firstPoint = pt[0];
secondPoint = pt[1];
for (int k = start; k < end; k++) {
for (int j = k + 1; j < pt.length; j++) {
if (!(pt[k].x == pt[j].x) && (pt[k].z == pt[j].z) && (pt[k].z == pt[j].z)) {
double r = DistanceBetweenPoints(pt[k], pt[j]);
if (r < minDistance) {
minDistance = r;
firstPoint = pt[k];
secondPoint = pt[j];
}
}
}
}
mindistancethread[z] = minDistance;
threadPoint[z][0] = firstPoint;
threadPoint[z][1] = secondPoint;
}
public static double DistanceBetweenPoints(NewPoint1 x, NewPoint1 y) {
double l = Math.sqrt(Math.pow((y.z - x.z), 2) + Math.pow((y.y - x.y), 2) + Math.pow((y.x - x.x), 2));
return l;
}
public static void GetRandomPoints(int points) {
pt = new NewPoint1[points]; //Point[] x = new Point[points];
Random position = new Random();
NewPoint1 t;
for (int i = 0; i < points; i++) {
t = new NewPoint1();
t.x = position.nextInt(1000);
t.y = position.nextInt(1000);
t.z = position.nextInt(1000);
pt[i] = new NewPoint1();
pt[i].x = t.x;
pt[i].y = t.y;
pt[i].z = t.z;
}
}
public static void FindMinDistance_Single(int points) {
minDistance = DistanceBetweenPoints(pt[0], pt[1]);
firstPoint = pt[0];
secondPoint = pt[1];
for (int i = 0; i < points; i++) {
for (int j = i + 1; j < points; j++) {
if (!(pt[i].x == pt[j].x) && (pt[i].z == pt[j].z) && (pt[i].z == pt[j].z)) {
double r = DistanceBetweenPoints(pt[i], pt[j]);
if (r < minDistance) {
minDistance = r;
firstPoint = pt[i];
secondPoint = pt[j];
}
}
}
}
System.out.println(minDistance);
System.out.println("Single Thread");
System.out.println("(" + firstPoint.x + "/" + firstPoint.y + "/" + firstPoint.z + ") (" + secondPoint.x + "/" + secondPoint.y + "/" + secondPoint.z + ") : " + (System.currentTimeMillis() - milliSeconds));
}
private static void FindMinDistance_Multi(int noofpoints) {
int div = noofpoints / NoOfThreads;
int f = div;
if (div < 2) {
NoOfThreads = noofpoints / 2;
div = noofpoints / NoOfThreads;
}
Eucledian_multithreaded[] thread = new Eucledian_multithreaded[NoOfThreads];
for (int i = 0; i < NoOfThreads; i++) {
thread[i] = new Eucledian_multithreaded(i, pt, div);
thread[i].start();
}
for (int i = 0; i < NoOfThreads; i++) {
try {
thread[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
double min = mindistancethread[0];
int threadIndex = 0;
if (f < 2) {
for (int i = 0; i < NoOfThreads; i++) {
if (min > mindistancethread[i]) {
min = mindistancethread[i];
threadIndex = i;
}
}
} else {
for (int i = 0; i < mindistancethread.length; i++) {
if (min > mindistancethread[i]) {
min = mindistancethread[i];
threadIndex = i;
}
}
}
System.out.println(mindistancethread[threadIndex]);
System.out.println("Multi Thread");
System.out.println("(" + threadPoint[threadIndex][0].x + "/" + threadPoint[threadIndex][0].y + "/" + threadPoint[threadIndex][0].z + ") (" + threadPoint[threadIndex][1].x + "/" + threadPoint[threadIndex][1].y + "/" + threadPoint[threadIndex][1].z + ") : " + (System.currentTimeMillis() - milliSeconds));
}
public static void main(String[] args) {
int noofpoints = Integer.parseInt(args[0]);
// int noofpoints = 2;
GetRandomPoints(noofpoints);
init();
FindMinDistance_Single(noofpoints);
System.out.println();
init();
FindMinDistance_Multi(noofpoints);
}
}
|
/*
* 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 registrationapp;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* @author Nitish Chauhan
*/
public class login extends javax.swing.JFrame {
/**
* Creates new form login
*/
public login() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is alwaysss
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
u = new javax.swing.JTextField();
p = new javax.swing.JPasswordField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(420, 340));
getContentPane().setLayout(null);
jPanel1.setBackground(new java.awt.Color(0, 51, 204));
jPanel2.setBackground(new java.awt.Color(0, 255, 255));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
u.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uActionPerformed(evt);
}
});
p.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pActionPerformed(evt);
}
});
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("User Id:");
jLabel4.setBackground(new java.awt.Color(255, 255, 255));
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setText("Password:");
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Reset");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 255, 255));
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setText("Login Form");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jButton2)
.addGap(107, 107, 107))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(u, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(p, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(98, 98, 98))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(u, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(p, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
getContentPane().add(jPanel1);
jPanel1.setBounds(180, 120, 220, 180);
jPanel6.setBackground(new java.awt.Color(255, 153, 255));
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Koala.jpg"))); // NOI18N
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 220, Short.MAX_VALUE)
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 125, Short.MAX_VALUE)
);
getContentPane().add(jPanel6);
jPanel6.setBounds(180, 0, 220, 120);
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/200818044125-7343.jpg"))); // NOI18N
getContentPane().add(jLabel5);
jLabel5.setBounds(0, 0, 180, 300);
pack();
}// </editor-fold>//GEN-END:initComponents
private void uActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_uActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try{
String s1=u.getText();
String s2=String.valueOf(p.getPassword());
db.DBConnect.checkLogin.setString(1, s1);
db.DBConnect.checkLogin.setString(2, s2);
ResultSet rs=db.DBConnect.checkLogin.executeQuery();
if(rs.next()){
new Register().setVisible(true);
dispose();
}
else{
JOptionPane.showMessageDialog(null,"invalid pass");
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void pActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_pActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
u.setText(null);
p.setText(null);
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.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 login().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel6;
private javax.swing.JPasswordField p;
private javax.swing.JTextField u;
// End of variables declaration//GEN-END:variables
}
|
package br.eti.ns.nssuite.requisicoes.bpe;
import br.eti.ns.nssuite.requisicoes._genericos.NaoEmbReq;
public class NaoEmbReqBPe extends NaoEmbReq {
public String chBPe;
}
|
package com.xuanxing.core.home.service.impl;
import com.xuanxing.core.home.service.IIndexService;
public class IndexServiceImpl implements IIndexService {
}
|
package jteller.estructuras;
import java.util.LinkedList;
import java.util.List;
public class Constructor {
private List<String> argumentos = new LinkedList<String>();
public Constructor() { }
public Constructor(final String ... argumentos) {
for (String argumento : argumentos) {
this.argumentos.add(argumento);
}
}
public List<String> getArgumentos() {
return this.argumentos;
}
}
|
package controller.util.collectors.impl;
import controller.constants.FrontConstants;
import controller.exception.WrongInputDataException;
import controller.util.collectors.DataCollector;
import domain.Admin;
import domain.User;
import org.apache.log4j.Logger;
import resource_manager.ResourceManager;
import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
public class AdminDataCollector extends DataCollector<Admin> {
private ResourceManager resourceManager = ResourceManager.INSTANCE;
private static final Logger logger = Logger.getLogger(AdminDataCollector.class);
@Override
public Admin retrieveData(HttpServletRequest request) throws WrongInputDataException {
logger.info("Retrieving bus data from request");
int counter = 5;
String name = request.getParameter(FrontConstants.NAME);
String surname = request.getParameter(FrontConstants.SURNAME);
String birth = request.getParameter(FrontConstants.BIRTH);
String degree = request.getParameter(FrontConstants.DEGREE);
String graduation = request.getParameter(FrontConstants.GRADUATION);
Admin admin = new Admin();
if (name != null && name.matches(resourceManager.getRegex("reg.name"))) {
admin.setName(name);
counter--;
}
if (surname != null && surname.matches(resourceManager.getRegex("reg.surname"))) {
admin.setSurname(surname);
counter--;
}
if (birth != null && birth.matches(resourceManager.getRegex("reg.birth"))
&& Date.valueOf(birth).compareTo(new Date(System.currentTimeMillis())) < 0) {
admin.setBirth(Date.valueOf(birth));
counter--;
}
if (degree != null && degree.matches(resourceManager.getRegex("reg.degree"))) {
admin.setDegree(degree);
counter--;
}
if (graduation != null && graduation.matches(resourceManager.getRegex("reg.graduation"))
&& Date.valueOf(graduation).compareTo(new Date(System.currentTimeMillis())) < 0) {
admin.setGraduation(Date.valueOf(graduation));
counter--;
}
try {
User user = new UserDataCollector().retrieveData(request);
admin.setUser(user);
} catch (WrongInputDataException e) {
admin.setUser((User) request.getAttribute(FrontConstants.USER));
request.setAttribute(FrontConstants.ADMIN, admin);
throw new WrongInputDataException(e);
}
if (counter != 0){
logger.warn("Not all input forms filled correctly");
request.setAttribute(FrontConstants.ADMIN, admin);
throw new WrongInputDataException("Not all input form filled correctly");
}
return admin;
}
}
|
package com.apress.todo.reactive;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
/**
* @author max.dokuchaev
*/
@Configuration
public class TaskRouter {
@Bean
public RouterFunction<ServerResponse> monoRouterFunction(TaskHandler taskHandler) {
return route(GET("/todo/{id}").and(accept(APPLICATION_JSON)),
taskHandler::getToDo)
.andRoute(GET("/todo").and(accept(APPLICATION_JSON)),
taskHandler::getAllTask)
.andRoute(POST("/todo").and(accept(APPLICATION_JSON)),
taskHandler::createNewTask);
}
}
|
class TesteJavaBasico
{
static {
System.out.println("bloco statico");
}
{
System.out.println("bloco NÃO estatico");
}
TesteJavaBasico()
{
System.out.println("construtor");
}
public static void main(String ...nomeQualquer)
{
//System.out.println("Antes de criar o objeto");
TesteJavaBasico t = new TesteJavaBasico();
//System.out.println("Depois de criar o objeto");
new TesteJavaBasico();
int a= a + 1;
}
}
|
package testCases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver.exe");
// Open Chrome
WebDriver driver = new ChromeDriver();
// Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.MILLISECONDS);
// Open url Tools QA
driver.get("https://demoqa.com/alerts");
// Maximize Browser
driver.manage().window().maximize();
driver.findElement(By.id("alertButton")).click();
//Accept Alert
driver.switchTo().alert().accept();
System.out.println("Done!");
//Kill Browser
driver.quit();
}
}
|
package by.ez.smm.web.security.util;
import java.security.SecureRandom;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import by.ez.smm.web.security.exception.AuthInternalException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Service
public class TokenUtils
{
private static final String ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final SecureRandom RANDOM = new SecureRandom();
@Value("${auth.secret.key}")
private String secretKey;
public String createToken(UserDetails userDetails, Long expiredTime)
{
long expires = System.currentTimeMillis() + 1000 * expiredTime;
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setExpiration(new Date(expires))
.signWith(SignatureAlgorithm.HS512, secretKey.getBytes())
.compact();
}
public String getUserNameFromToken(String authToken)
{
try
{
return Jwts.parser()
.setSigningKey(secretKey.getBytes())
.parseClaimsJws(authToken)
.getBody()
.getSubject();
}
catch (JwtException e)
{
throw new AuthInternalException("JWT exception", e);
}
}
public String generateCsrfToken()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 128; i++)
{
sb.append(ALLOWED_CHARACTERS.charAt(RANDOM.nextInt(ALLOWED_CHARACTERS.length())));
}
return sb.toString();
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.extension.event;
/**
* HasDocumentEvent
*
*
* @author jllort
*
*/
public interface HasMailEvent {
/**
* MailEventConstant
*
* @author jllort
*
*/
public static class MailEventConstant {
static final int EVENT_MAIL_CHANGED = 1;
static final int EVENT_PANEL_RESIZED = 2;
static final int EVENT_TAB_CHANGED = 3;
static final int EVENT_SECURITY_CHANGED = 4;
static final int EVENT_SET_VISIBLE_BUTTONS = 5;
static final int EVENT_MAIL_DELETED = 6;
static final int EVENT_KEYWORD_REMOVED = 7;
static final int EVENT_KEYWORD_ADDED = 8;
static final int EVENT_CATEGORY_ADDED = 9;
static final int EVENT_CATEGORY_REMOVED = 10;
private int type = 0;
/**
* DocumentEventConstant
*
* @param type
*/
private MailEventConstant(int type) {
this.type = type;
}
public int getType(){
return type;
}
}
MailEventConstant MAIL_CHANGED = new MailEventConstant(MailEventConstant.EVENT_MAIL_CHANGED);
MailEventConstant PANEL_RESIZED = new MailEventConstant(MailEventConstant.EVENT_PANEL_RESIZED);
MailEventConstant TAB_CHANGED = new MailEventConstant(MailEventConstant.EVENT_TAB_CHANGED);
MailEventConstant SECURITY_CHANGED = new MailEventConstant(MailEventConstant.EVENT_SECURITY_CHANGED);
MailEventConstant SET_VISIBLE_BUTTONS = new MailEventConstant(MailEventConstant.EVENT_SET_VISIBLE_BUTTONS);
MailEventConstant MAIL_DELETED = new MailEventConstant(MailEventConstant.EVENT_MAIL_DELETED);
MailEventConstant KEYWORD_REMOVED = new MailEventConstant(MailEventConstant.EVENT_KEYWORD_REMOVED);
MailEventConstant KEYWORD_ADDED = new MailEventConstant(MailEventConstant.EVENT_KEYWORD_ADDED);
MailEventConstant CATEGORY_ADDED = new MailEventConstant(MailEventConstant.EVENT_CATEGORY_ADDED);
MailEventConstant CATEGORY_REMOVED = new MailEventConstant(MailEventConstant.EVENT_CATEGORY_REMOVED);
/**
* @param event
*/
void fireEvent(MailEventConstant event);
} |
package capstone.abang.com.Register;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.vlk.multimager.activities.SinglePickActivity;
import com.vlk.multimager.utils.Constants;
import com.vlk.multimager.utils.Image;
import com.vlk.multimager.utils.Params;
import java.util.ArrayList;
import butterknife.ButterKnife;
import capstone.abang.com.Car_Owner.car_owner;
import capstone.abang.com.Models.CDFile;
import capstone.abang.com.Models.UDFile;
import capstone.abang.com.R;
import capstone.abang.com.Utils.Utility;
public class CarOwnerRegistration extends AppCompatActivity {
private ImageButton btnCompanyID;
private ImageButton btnLicenseID;
private Image companyImage;
private Image licenseImage;
private Uri companyURI;
private Uri licenseURI;
private Button btnUploadFiles;
int selectedColor;
private UDFile ownerDetails;
private int REQUEST_CAMERA = 0;
private int SELECT_FILE = 1;
private int holder = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_owner_registration);
setupWidgets();
getUserDetails();
btnCompanyID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder = 1;
selectImage();
}
});
btnLicenseID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder = 2;
selectImage();
}
});
btnUploadFiles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String companyHolder = getOCRText(companyURI).toLowerCase();
String licenseHolder = getOCRText(licenseURI).toLowerCase();
if(companyHolder.contains(ownerDetails.getUDFullname().toLowerCase()) && licenseHolder.contains(ownerDetails.getUDFullname().toLowerCase())
&& licenseHolder.contains("land transportation office")) {
if(hasFace(companyURI) && hasFace(licenseURI)) {
updateUserStatus();
}
else {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(CarOwnerRegistration.this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(CarOwnerRegistration.this);
}
builder.setTitle("Failed")
.setMessage("Please upload correct IDs")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.setCancelable(false)
.show();
}
}
else {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(CarOwnerRegistration.this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(CarOwnerRegistration.this);
}
builder.setTitle("Failed")
.setMessage("Please upload correct IDs")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.setCancelable(false)
.show();
}
}
});
}
private boolean hasFace(Uri uri) {
boolean hasFace = false;
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
if(bitmap != null) {
FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext())
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.build();
if(!faceDetector.isOperational()) {
Log.d("FACE DETECTION", "Is not operational");
hasFace = false;
}
else {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<Face> sparseArray = faceDetector.detect(frame);
hasFace = sparseArray.size() != 0 && sparseArray.size() == 1;
if(hasFace) {
Face face = sparseArray.valueAt(0);
float x1 = face.getPosition().x;
float y1 = face.getPosition().y;
float x2 = x1 + face.getWidth();
float y2 = y1 + face.getHeight();
RectF rectF = new RectF(x1, y1, x2, y2);
}
}
}
return hasFace;
}
private void updateUserStatus() {
final String uID = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("UDFile");
reference.child(uID).child("udDocuStatus").setValue("Validated");
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Photos").child(uID).child(companyURI.getLastPathSegment());
storageReference.putFile(companyURI)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = taskSnapshot.getDownloadUrl().toString();
reference.child(uID).child("udCompanyID").setValue(path);
}
});
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference("Photos").child(uID).child(licenseURI.getLastPathSegment());
storageReference1.putFile(licenseURI)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = taskSnapshot.getDownloadUrl().toString();
reference.child(uID).child("udlicenseID").setValue(path);
}
});
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(CarOwnerRegistration.this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(CarOwnerRegistration.this);
}
builder.setTitle("Success")
.setMessage("You are now complete with your registration!")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CarOwnerRegistration.this, car_owner.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.setCancelable(false)
.show();
}
private void getUserDetails() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("UDFile");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uID = FirebaseAuth.getInstance().getCurrentUser().getUid();
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(snapshot.getValue(UDFile.class).getUDUserCode().equalsIgnoreCase(uID)) {
setUDFile(snapshot.getValue(UDFile.class));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setUDFile(UDFile udFile) {
ownerDetails = udFile;
}
private String getOCRText(Uri uri) {
Bitmap bitmap = null;
String holder = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
//OCR
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if(!textRecognizer.isOperational()) {
Toast.makeText(this, "Could not get the text", Toast.LENGTH_SHORT).show();
}
else {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock myItems = items.valueAt(i);
stringBuilder.append(myItems.getValue());
}
holder = stringBuilder.toString();
}
return holder;
}
private void selectImage() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_custom_dialog);
TextView tvCamera = dialog.findViewById(R.id.tvCamera);
ImageView ivCamera = dialog.findViewById(R.id.iconCamera);
TextView tvGallery = dialog.findViewById(R.id.tvGallery);
ImageView ivGallery = dialog.findViewById(R.id.iconGallery);
tvCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean result = Utility.checkPermission(CarOwnerRegistration.this);
if(result) {
cameraIntent();
dialog.dismiss();
}
}
});
ivCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean result = Utility.checkPermission(CarOwnerRegistration.this);
if(result) {
cameraIntent();
dialog.dismiss();
}
}
});
tvGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean result = Utility.checkPermission(CarOwnerRegistration.this);
if(result) {
galleryIntent();
dialog.dismiss();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean result = Utility.checkPermission(CarOwnerRegistration.this);
if(result) {
galleryIntent();
dialog.dismiss();
}
}
});
dialog.show();
}
private void galleryIntent() {
ButterKnife.bind(this);
selectedColor = 4475389;
Intent intent = new Intent(this, SinglePickActivity.class);
Params params = new Params();
params.setCaptureLimit(1);
params.setPickerLimit(1);
params.setToolbarColor(selectedColor);
params.setActionButtonColor(selectedColor);
params.setButtonTextColor(selectedColor);
intent.putExtra(Constants.KEY_PARAMS, params);
intent.putExtra("activity","AD");
startActivityForResult(intent,SELECT_FILE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode == Activity.RESULT_OK) {
if(requestCode == SELECT_FILE) {
onGalleryIntent(intent);
}
else if(requestCode == REQUEST_CAMERA){
onCaptureImageResult(intent);
}
}
}
private void onGalleryIntent(Intent intent){
final ArrayList<Image> imagesList = intent.getParcelableArrayListExtra(Constants.KEY_BUNDLE_LIST);
if(holder == 1) {
final Image entity = imagesList.get(0);
companyImage = imagesList.get(0);
Glide.with(CarOwnerRegistration.this)
.load(entity.uri)
.apply(new RequestOptions()
.placeholder(com.vlk.multimager.R.drawable.image_processing)
.centerCrop()
)
.into(btnCompanyID);
companyURI = entity.uri;
}
else {
final Image entity = imagesList.get(0);
licenseImage = imagesList.get(0);
Glide.with(CarOwnerRegistration.this)
.load(entity.uri)
.apply(new RequestOptions()
.placeholder(com.vlk.multimager.R.drawable.image_processing)
.centerCrop()
)
.into(btnLicenseID);
licenseURI = entity.uri;
}
}
private void onCaptureImageResult(Intent data) {
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
if(holder == 1) {
btnCompanyID.setImageBitmap(bitmap);
btnCompanyID.setScaleType(ImageView.ScaleType.CENTER_CROP);
btnCompanyID.setBackgroundResource(0);
companyURI = data.getData();
}
else {
btnLicenseID.setImageBitmap(bitmap);
btnLicenseID.setScaleType(ImageView.ScaleType.CENTER_CROP);
btnLicenseID.setBackgroundResource(0);
licenseURI = data.getData();
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void setupWidgets() {
btnLicenseID = findViewById(R.id.imgViewLicenseID);
btnCompanyID = findViewById(R.id.imgViewCoopID);
btnUploadFiles = findViewById(R.id.btnUploadFiles);
}
}
|
/*
* Copyright 2011 Eric F. Savage, code@efsavage.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ajah.user.resetpw.data;
import org.springframework.stereotype.Repository;
import com.ajah.spring.jdbc.AbstractAjahDao;
import com.ajah.user.resetpw.ResetPasswordRequest;
import com.ajah.user.resetpw.ResetPasswordRequestId;
import com.ajah.util.AjahUtils;
/**
* Handles data operations for {@link ResetPasswordRequest} entities.
*
* @author <a href="http://efsavage.com">Eric F. Savage</a>, <a
* href="mailto:code@efsavage.com">code@efsavage.com</a>.
*
*/
@Repository
public class ResetPasswordRequestDao extends AbstractAjahDao<ResetPasswordRequestId, ResetPasswordRequest, ResetPasswordRequest> {
/**
* INSERTs a {@link ResetPasswordRequest}.
*
* @param resetPasswordRequest
* The {@link ResetPasswordRequest} to save, required.
* @return The number of rows affected.
*/
@Override
public int insert(final ResetPasswordRequest resetPasswordRequest) {
// TODO Necessary?
AjahUtils.requireParam(resetPasswordRequest, "resetPasswordRequest");
return this.jdbcTemplate.update("INSERT INTO pw_reset (pw_reset_id, user_id, created, code, status) VALUES (?,?,?,?,?)", new Object[] { resetPasswordRequest.getId().getId(),
resetPasswordRequest.getUserId().getId(), Long.valueOf(resetPasswordRequest.getCreated().getTime() / 1000), Long.valueOf(resetPasswordRequest.getCode()),
resetPasswordRequest.getStatus().getId() });
}
/**
* UPDATEs a {@link ResetPasswordRequest}.
*
* @param resetPasswordRequest
* The {@link ResetPasswordRequest} to save, required.
* @return The number of rows affected.
*/
@Override
public int update(final ResetPasswordRequest resetPasswordRequest) {
// TODO Necessary?
AjahUtils.requireParam(resetPasswordRequest, "resetPasswordRequest");
return this.jdbcTemplate.update("UPDATE pw_reset SET user_id = ?, created = ?, code = ?, status = ? WHERE pw_reset_id = ?",
new Object[] { resetPasswordRequest.getUserId().getId(), Long.valueOf(resetPasswordRequest.getCreated().getTime() / 1000), Long.valueOf(resetPasswordRequest.getCode()),
resetPasswordRequest.getStatus().getId(), resetPasswordRequest.getId().getId() });
}
}
|
package com.bluemingo.bluemingo.service;
import com.bluemingo.bluemingo.domain.UserVO;
import com.bluemingo.bluemingo.generic.GenericService;
public interface UserService extends GenericService<UserVO, Integer>{
}
|
package com.lupoiu.photoshooter;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
public class PhotoShooter extends ActionBarActivity {
public Button btntakephoto;
public Button btnsave;
public Button btnshare;
public Button btnvideo;
public ImageView ivdisplayphoto;
public SeekBar skbarChangeColor;
private ColorMatrix colorMatrix;
private ColorMatrixColorFilter filter;
private Paint paint;
private Canvas cv;
private File photofile;
private int TAKENPHOTO = 0;
Bitmap photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoshooter);
/*================*/
btntakephoto = (Button) findViewById(R.id.btn_takephoto);
btnsave = (Button) findViewById(R.id.btn_save);
btnshare = (Button) findViewById(R.id.btn_share);
btnvideo = (Button) findViewById(R.id.btn_takevideo);
ivdisplayphoto = (ImageView) findViewById(R.id.iv_displayphoto);
skbarChangeColor = (SeekBar) findViewById(R.id.skbarChandeColor);
skbarChangeColor.setMax(100);
skbarChangeColor.setKeyProgressIncrement(1);
skbarChangeColor.setProgress(50);
skbarChangeColor.setVisibility(View.GONE);
btntakephoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Get global path of the picture directory
File photostorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
photofile = new File(photostorage,(System.currentTimeMillis())+".jpg");
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //Intent to start camara
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photofile)); //send the path of the photo
startActivityForResult(i, TAKENPHOTO);
}
});
btnsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
btnshare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
btnvideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
skbarChangeColor.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
colorMatrix = new ColorMatrix();
filter = new ColorMatrixColorFilter(this.colorMatrix);
paint = new Paint();
paint.setColorFilter(filter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAKENPHOTO){ //if the photo has been taken with the camara.
try {
photo = (Bitmap) data.getExtras().get("data");
}catch (NullPointerException e){
photo = BitmapFactory.decodeFile(photofile.getAbsolutePath());
}
if (photo != null){ //show the photo
ivdisplayphoto.setImageBitmap(photo);
skbarChangeColor.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this, "Well, this is embarrassing.. Seems like I can't get the photo from your gallery", Toast.LENGTH_LONG).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import cn.edu.hebtu.software.sharemate.Adapter.FanAdapter;
import cn.edu.hebtu.software.sharemate.Bean.UserBean;
import cn.edu.hebtu.software.sharemate.R;
public class FanActivity extends AppCompatActivity {
private UserBean user;
private ImageView imageView;
private ListView listView;
private FanAdapter fanAdapter;
private List<UserBean> userList = new ArrayList<>();
private String path = null;
private ArrayList<Integer> type = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fan);
type = getIntent().getIntegerArrayListExtra("type");
findViews();
path = getResources().getString(R.string.server_path);
GetFan getFan = new GetFan();
getFan.execute(user);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FanActivity.this,MainActivity.class);
intent.putExtra("flag","my");
intent.putIntegerArrayListExtra("type",type);
intent.putExtra("userId",user.getUserId());
startActivity(intent);
}
});
}
//从数据库中取出当前用户的粉丝
public class GetFan extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
UserBean userBean = (UserBean) objects[0];
int userId = userBean.getUserId();
try {
URL url = new URL(path+"FanServlet?userId="+userId);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("contentType", "UTF-8");
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String res = br.readLine();
//解析JSON
JSONArray array = new JSONArray(res);
for(int i=0 ; i<array.length() ; i++){
JSONObject userObject = array.getJSONObject(i);
UserBean fan = new UserBean();
fan.setUserId(userObject.getInt("userId"));
fan.setUserName(userObject.getString("userName"));
fan.setUserPhotoPath(path+userObject.getString("userPhoto"));
fan.setUserIntroduce(userObject.getString("userIntro"));
fan.setStates(userObject.getBoolean("status"));
fan.setNoteCount(userObject.getInt("noteCount"));
fan.setFanCount(userObject.getInt("fanCount"));
fan.setFollowCount(userObject.getInt("followCount"));
fan.setLikeCount(userObject.getInt("likeCount"));
userList.add(fan);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
fanAdapter = new FanAdapter(FanActivity.this,R.layout.fan_item,userList,user,path);
listView.setAdapter(fanAdapter);
}
}
public void findViews(){
user = (UserBean) getIntent().getSerializableExtra("user");
listView = findViewById(R.id.root);
listView.setEmptyView((findViewById(R.id.empty_view)));
imageView = findViewById(R.id.back);
}
}
|
package com.apolo.webapp.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
/**
*
* @author raybm
*/
@Entity
@Table(name="rastreador")
public class Rastreador implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idrastreador;
@Column(name="nome", nullable = false)
private String nome;
@Column(name="x")
private double x;
@Column(name="y")
private double y;
@Column(name="potenciapaineis")
private double potenciapaineis;
@Column(name="ip")
private String ip;
@ManyToMany(mappedBy="rastreadores", fetch=FetchType.EAGER)
private List<Usuario> usuarios = new ArrayList<Usuario>();
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
public List<Usuario> getUsuarios() { return usuarios; }
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Column(name = "chave")
private String chave;
public String getChave() {
return chave;
}
public void setChave(String chave) {
this.chave = chave;
}
/* public Collection<UsuarioRastreador> getUsuarios() {
return usuarioRastreadorList;
}
public void setUsuarios(Collection<UsuarioRastreador> usuarioRastreadorList) {
this.usuarioRastreadorList = usuarioRastreadorList;
}
*/
public Integer getIdrastreador() {
return idrastreador;
}
public void setIdrastreador(Integer idrastreador) {
this.idrastreador = idrastreador;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getPotenciapaineis() {
return potenciapaineis;
}
public void setPotenciapaineis(double potenciapaineis) {
this.potenciapaineis = potenciapaineis;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + Objects.hashCode(this.idrastreador);
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 Rastreador other = (Rastreador) obj;
if (!Objects.equals(this.idrastreador, other.idrastreador)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Rasteador{" + "idrastreador=" + idrastreador + ", nome=" + nome + ", x=" + x + ", y=" + y + ", potenciapaineis=" + potenciapaineis + '}';
}
}
|
package day14;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class test6 {
public static void main(String[] args) {
Date d1 = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat();
System.out.println(sdf1.format(d1));
}
}
|
package p4_group_8_repo.Game_levels;
import javafx.collections.ObservableList;
import p4_group_8_repo.Game_actor.Turtle;
import p4_group_8_repo.Game_actor.WetTurtle;
import p4_group_8_repo.Game_scene.MyStage;
/**
* Class of Level 4
* @author Jun Yuan
*
*/
public class Level_4 {
/**
* Replace Turtles with WetTurtles
* @param background is the container for the scene
*/
public Level_4(MyStage background) {
ObservableList animation_list = background.getChildren();
animation_list.set(12, new Turtle(500, 376, -1.0, 130, 130));
animation_list.set(13, new Turtle(300, 376, -1.0, 130, 130));
animation_list.set(14, new WetTurtle(700, 376, -1.0, 130, 130));
System.out.println("1 Turtle changed to Wet Turtles\n");
}
}
|
package it.polimi.se2019.controller.weapons.ordered_effects;
import it.polimi.se2019.rmi.UserTimeoutException;
import it.polimi.se2019.controller.GameBoardController;
import it.polimi.se2019.controller.weapons.WeaponController;
import it.polimi.se2019.view.player.PlayerViewOnServer;
import java.util.ArrayList;
import java.util.List;
/**
* This is an abstract marker class, it doesn't have its own methods or
* attributes and is used to group the weapons in the game based on how they
* work.
* Ordered effects weapons have a primary effect and one or more effects that
* can be applied only if they satisfy particular conditions.
*
* @author Eugenio OStrovan
* @author Fabio Mauri
*/
public abstract class OrderedEffectsWeaponController extends WeaponController {
public OrderedEffectsWeaponController(GameBoardController g) {
super(g);
}
protected Integer numberOfOptionalEffects;
public List<Boolean> selectFiringMode(PlayerViewOnServer client) throws UserTimeoutException {
List<Boolean> firingModeFlags = new ArrayList<>();
firingModeFlags.add(true);
for(int a = 1; a<numberOfOptionalEffects; a++){
firingModeFlags.add(false);
}
/*
List<String> effects = new ArrayList<>();
for(int i = 0; i<numberOfOptionalEffects; i++){
effects.add("effect"+i);
}
Integer chosenEffect;
chosenEffect = client.chooseIndex(effects);
for(int k = 0; k<numberOfOptionalEffects; k++){
if(k<=chosenEffect){
firingModeFlags.add(k, true);
}
else{
firingModeFlags.add(k, false);
}
}
*/
return firingModeFlags;
}
} |
package com.tencent.mm.plugin.fav.ui.detail;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.fav.a.b;
import com.tencent.mm.plugin.fav.a.h.a;
import com.tencent.mm.protocal.c.vx;
class FavoriteImgDetailUI$4 implements OnClickListener {
final /* synthetic */ FavoriteImgDetailUI jcT;
FavoriteImgDetailUI$4(FavoriteImgDetailUI favoriteImgDetailUI) {
this.jcT = favoriteImgDetailUI;
}
public final void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("key_detail_info_id", FavoriteImgDetailUI.b(this.jcT).field_localId);
intent.putExtra("key_detail_data_id", ((vx) view.getTag()).jdM);
b.a(this.jcT.mController.tml, ".ui.FavImgGalleryUI", intent);
a aVar = this.jcT.jcb;
aVar.iVM++;
}
}
|
package com.service;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.Address;
import com.model.Customer;
import com.repository.CustomerRepository;
import com.utils.Utils;
@Transactional
@Service
public class ConsumerServiceImpl implements ConsumerService {
private final Logger LOG = LoggerFactory.getLogger(ConsumerServiceImpl.class);
@Autowired
private CustomerRepository customerRepository;
@Autowired
private Utils utils;
@Override
public void save(Customer customer) {
try {
String logMessage = String.format("customer details after masking %s", utils.maskCustomerDetailsWithStars(customer));
LOG.info(logMessage);
Address address = customer.getAddress();
customerRepository.save(address.getAddressLine1(), address.getAddressLine2(), address.getPostalCode(),
address.getStreet(), customer.getBirthdate(), customer.getCountry(), customer.getCountryCode(),
customer.getCustomerNumber(), customer.getCustomerStatus(), customer.getEmail(),
customer.getFirstName(), customer.getLastName(), customer.getMobileNumber());
LOG.info("customer details saved successfully");
customerRepository.insertAuditLog(customer.getCustomerNumber(), utils.getJsonString(customer));
LOG.info("insert AuditLog");
} catch (Exception e) {
LOG.error(e.toString());
customerRepository.insertErrorLog(e.getClass().toString(), e.getMessage(), utils.getJsonString(customer));
LOG.error("insert ErrorLog");
}
}
}
|
package models.academics.coursedefn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("ASSIGN")
public class Assignment extends Deliverable {
}
|
package securities_trading_platform.databaseActions;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* This class connects to the database, and creates table in the database if it is not
* already created. It then inserts or updates rows in the database when user presses
* buy button in the JTable tableTrading.
*/
public class BuyAction {
public BuyAction(String name_of_the_corporation, String trading_symbol, String stock_exchange, int quantity,
double buying_value) {
Connection con = null;
Statement statement = null;
try {
String ourTable = null;
// First, we need to add driver to the "Java Build Path" which can be downloaded from
// https://jdbc.postgresql.org/download.html
Class.forName("org.postgresql.Driver");
// 5432 is the port.
// stockstable is the name of the database that needs to be created before we run this app.
String url = "jdbc:postgresql://localhost:5432/stockstable";
String username = "postgres";
String password = "svetaana14";
con = DriverManager.getConnection(url, username, password);
statement = con.createStatement();
// First we need to check if the table with the name portfolio exists in our database
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "portfolio", null);
while (rs.next()) {
ourTable = rs.getString(3);
}
if (ourTable == null) {
// Create new table if it doesn't exist
statement.executeUpdate("CREATE TABLE portfolio" +
" (id BIGINT PRIMARY KEY, " +
" name_of_the_corporation TEXT, " +
" trading_symbol TEXT, " +
" stock_exchange TEXT, " +
" quantity INT, " +
" buying_value MONEY)");
}
ResultSet result = null;
// I know this is not perfect solution but I had problems with EXISTS
result = statement.executeQuery("SELECT * FROM portfolio WHERE trading_symbol = '"+trading_symbol+"'");
if (!result.isBeforeFirst()){ // Data does not exist, insert new row with the data
// nextval('zorannew') is used to auto-increase id by 1, every time new row is being added
// It is interested that buying_value needs to be divided by 10 for the German (Postgres database locale),
// but it doesn't need to be divided for the US locale
statement.executeUpdate("INSERT INTO portfolio VALUES (nextval('zorannew'), '"+name_of_the_corporation+"', "
+ "'"+trading_symbol+"', '"+stock_exchange+"', '"+quantity+"', '"+buying_value/10+"')");
}
else { // Data exists, just increase quantity and buying_value
statement.executeUpdate("UPDATE portfolio SET quantity = (quantity + '"+quantity+"'), buying_value = (buying_value + "
+ "'"+buying_value/10+"') WHERE trading_symbol = '"+trading_symbol+"'");
}
}
catch (SQLException e) {
System.out.println(e);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
finally { // objects must be closed, in this order: 1. statement, 2. connection
try {
if (statement != null) statement.close();
if (con != null) con.close();
}
catch (SQLException e) {
System.out.println(e);
}
}
}
} |
/*
* 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 membership.management;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rahul Verma
*/
public class CustomerControllerTest {
public CustomerControllerTest() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getInstance method, of class CustomerController.
*/
@Test
public void testGetInstance() {
System.out.println("getInstance");
CustomerController expResult = null;
CustomerController result = CustomerController.getInstance();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of viewCustomer method, of class CustomerController.
*/
@Test
public void testViewCustomer() throws Exception {
System.out.println("viewCustomer");
String unique_id = "";
CustomerController instance = new CustomerController();
instance.viewCustomer(unique_id);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of addCustomer method, of class CustomerController.
*/
@Test
public void testAddCustomer() {
System.out.println("addCustomer");
String firstName = "";
String lastName = "";
String email_address = "";
String Gender = "";
String phone_number = "";
String dateOfBirth = "";
String addressLine = "";
String City = "";
String Postcode = "";
String membership_type = "";
CustomerController instance = new CustomerController();
instance.addCustomer(firstName, lastName, email_address, Gender, phone_number, dateOfBirth, addressLine, City, Postcode, membership_type);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of updateCustomer method, of class CustomerController.
*/
@Test
public void testUpdateCustomer() {
System.out.println("updateCustomer");
String firstName = "";
String lastName = "";
String email_address = "";
String Gender = "";
String phone_number = "";
String dateOfBirth = "";
String addressLine = "";
String City = "";
String Postcode = "";
String membership_type = "";
String unique_id = "";
CustomerController instance = new CustomerController();
instance.updateCustomer(firstName, lastName, email_address, Gender, phone_number, dateOfBirth, addressLine, City, Postcode, membership_type, unique_id);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of deleteCustomer method, of class CustomerController.
*/
@Test
public void testDeleteCustomer() throws Exception {
System.out.println("deleteCustomer");
String unique_id = "";
CustomerController instance = new CustomerController();
instance.deleteCustomer(unique_id);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
|
package com.yoeki.kalpnay.hrporatal.all_employee;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yoeki.kalpnay.hrporatal.HomeMenu.EmployeeDetailActivity;
import com.yoeki.kalpnay.hrporatal.Payroll.Paystructuremodel;
import com.yoeki.kalpnay.hrporatal.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.List;
public class AllEmployeeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<AllEmployee_Model> allEmployeeList;
private Activity activity;
public AllEmployeeAdapter(Activity activity, List<AllEmployee_Model> allEmployeeList) {
this.activity = activity;
this.allEmployeeList = allEmployeeList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Inflating recycle view item layout
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_allemployee, parent, false);
return new ItemViewHolder(itemView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.textViewDesignation.setText(allEmployeeList.get(position).getDesignation());
itemViewHolder.textViewNAme.setText(allEmployeeList.get(position).getName());
itemViewHolder.linearLayoutContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(activity, AllEmployeeDetailActivity.class);
intent.putExtra("DETAIL", allEmployeeList.get(position).getName());
activity.startActivity(intent);
}
});
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return allEmployeeList.size();
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
TextView textViewDesignation, textViewNAme;
LinearLayout linearLayoutContainer;
public ItemViewHolder(View itemView) {
super(itemView);
textViewNAme = itemView.findViewById(R.id.textViewNAme);
textViewDesignation = itemView.findViewById(R.id.textViewDesignation);
linearLayoutContainer = itemView.findViewById(R.id.linearLayoutContainer);
}
}
}
|
package com.team6.app.quiz;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.team6.app.AccountService;
import com.team6.app.CharacterService;
import com.team6.app.Constants;
import com.team6.app.User;
@Controller
public class QuizController {
@Autowired
private QuizService quizService;
@Autowired
private AccountService accService;
@Autowired
private CharacterService charService;
@RequestMapping(value = "/quiz", method = RequestMethod.GET)
public ModelAndView showQuizzes() {
ModelAndView mv = new ModelAndView(Constants.QUIZZES_PATH_FILE);
mv.addObject("categories", quizService.getCategories());
mv.addObject("quizzes", quizService.getQuizzes());
return mv;
}
@RequestMapping(value = "/quiz/{quizId}", method = RequestMethod.GET)
public ModelAndView showQuiz(HttpServletRequest req,
@PathVariable String quizId) {
HttpSession sesh = req.getSession(false);
if (sesh == null) {
// Session invalid
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
String userId = (String) sesh.getAttribute("userid");
if (userId == null) {
// Session doesn't contain logged in user
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
User user = accService.findById(userId);
if (user == null) {
// User doesn't exist
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
ModelAndView mv = new ModelAndView(Constants.QUIZ_PATH_FILE);
Quiz quiz = quizService.getQuiz(quizId);
mv.addObject("quiz", quiz);
mv.addObject("questions", quiz.getQuestions());
mv.addObject("creator", accService.findById(quiz.getCreatorId()));
return mv;
}
@RequestMapping(value = "/quiz/{quizId}", method = RequestMethod.POST)
public ModelAndView evalQuiz(HttpServletRequest req,
@PathVariable String quizId,
@RequestParam(value = "answers[]") String[] answers) {
HttpSession sesh = req.getSession(false);
if (sesh == null) {
// Session invalid
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
String userId = (String) sesh.getAttribute("userid");
if (userId == null) {
// Session doesn't contain logged in user
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
Quiz quiz = quizService.getQuiz(quizId);
if (quiz == null) {
// Quiz doesn't exist
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
User user = accService.findById(userId);
if (user == null) {
// User doesn't exist
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
List<String> answersList = Arrays.asList(answers);
List<Boolean> feedback =
quizService.getQuizFeedback(quiz, answersList);
if (feedback == null) {
// Incompatible question/answer list lengths detected
return new ModelAndView(Constants.NOT_FOUND_PATH_FILE);
}
Integer expGained = charService.changeStats(userId, feedback, quiz.getDifficulty());
ModelAndView mv = new ModelAndView(Constants.QUIZ_RESULT_PATH_FILE);
mv.addObject("user", user);
mv.addObject("quiz", quiz);
mv.addObject("questions", quiz.getQuestions());
mv.addObject("answers", answersList);
mv.addObject("feedback", feedback);
mv.addObject("expGained", expGained);
return mv;
}
@RequestMapping(value = "/quiz/create", method = RequestMethod.GET)
public ModelAndView showCreateQuiz() {
ModelAndView mv = new ModelAndView(Constants.QUIZ_CREATE_PATH_FILE);
return mv;
}
@RequestMapping(value = "/quiz/create", method = RequestMethod.POST)
public ModelAndView createQuiz(
@RequestParam(value = "name") String name,
@RequestParam(value = "questions[]") String[] questions,
@RequestParam(value = "answers[]") String[] answers) {
quizService.createQuiz(name, Arrays.asList(questions), Arrays.asList(answers));
// ModelAndView mv = new ModelAndView(Constants.QUIZ_CREATE_PATH_FILE);
// return mv;
return new ModelAndView("redirect:/");
}
}
|
package map;
import helpers.DataConversionHelper;
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Node {
private List<Connection> neighbors;
private Position position;
public Node(Position position) {
this.position = position;
neighbors = new ArrayList<>();
}
public Node(Position position, List<Connection> neighbors) {
this.neighbors = neighbors;
this.position = position;
}
public void addNeighbor(Connection neighbor) {
neighbors.add(neighbor);
}
public void addAllNeighbors(List<Connection> neighbors) {
for (Connection c : neighbors) {
addNeighbor(c);
}
}
public List<Connection> getNeighbors() {
return Collections.unmodifiableList(neighbors);
}
public int getIndex(Map map) {
return map.getIndex(this);
}
public int byteSize() {
return 1 + 5 * neighbors.size();
}
public Position getPosition() {
return position;
}
public byte[] toBytes(Map map) {
byte[] bytes = new byte[this.byteSize()];
bytes[0] = DataConversionHelper.intToByteArray(neighbors.size(), 1)[0];
int offset = 1;
for (Connection c : neighbors) {
int connectionSize = c.byteSize();
System.arraycopy(c.toBytes(map), 0, bytes, offset, connectionSize);
offset += connectionSize;
}
return bytes;
}
public Connection getConnection(Node node2) {
for (Connection c : neighbors) {
if (c.getConnectingNode() == node2) {
return c;
}
}
return null;
}
}
|
package univ.m2acdi.apprentissageborel.util;
public final class Constante {
public static final String DATA_FILE_NAME = "data_file.json";
public static final String EXERCISE_FILE_NAME = "exercise.json";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.