hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
7e39f4a16095bb00fcc6b6c00e7982968170fc0e | 588 | package ru.job4j.pools.executorservice;
import org.junit.Test;
public class MailNotifyExecuteTest {
@Test
public void whenAddTwoUsersToPickSomeEmails() {
MailNotifyExecute mailNotifyExecute = new MailNotifyExecute(new EmailNotification());
mailNotifyExecute.addUserToMailNotification(new User("test1", "blablab@mail.ru"));
mailNotifyExecute.addUserToMailNotification(new User("test2", "another@mail.ru"));
mailNotifyExecute.addUserToMailNotification(new User("test3", "differntOne@mail.ru"));
mailNotifyExecute.setFinsih(true);
}
} | 34.588235 | 94 | 0.744898 |
1f683b4c471013546a223fd80dd4a7545e82d160 | 16,056 | /*
* Copyright (c) 2007, intarsys consulting GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of intarsys nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.intarsys.pdf.font;
import de.intarsys.cwt.font.afm.AFM;
import de.intarsys.cwt.font.afm.AFMChar;
import de.intarsys.pdf.cos.COSBasedObject;
import de.intarsys.pdf.cos.COSDictionary;
import de.intarsys.pdf.cos.COSName;
import de.intarsys.pdf.cos.COSObject;
import de.intarsys.pdf.encoding.Encoding;
import de.intarsys.pdf.encoding.SymbolEncoding;
import de.intarsys.tools.locator.ClassResourceLocator;
import de.intarsys.tools.locator.ILocator;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/**
* basic implementation for type 1 support
*/
public class PDFontType1 extends PDSingleByteFont {
/**
* The meta class implementation
*/
public static class MetaClass extends PDFont.MetaClass {
protected MetaClass(Class instanceClass) {
super(instanceClass);
}
@Override
protected COSBasedObject doCreateCOSBasedObject(COSObject object) {
return new PDFontType1(object);
}
}
/**
* Map of known alternative names for the builtin fonts
*/
public static final Map<String, String> FONT_ALIASES;
/**
* Map of known deprecated alternative names for the builtin fonts
*/
public static final Map<String, String> FONT_ALIASES_DEPRECATED;
public static String FONT_Courier = "Courier"; //$NON-NLS-1$
public static String FONT_Courier_Bold = "Courier-Bold"; //$NON-NLS-1$
public static String FONT_Courier_BoldOblique = "Courier-BoldOblique"; //$NON-NLS-1$
public static String FONT_Courier_Oblique = "Courier-Oblique"; //$NON-NLS-1$
public static String FONT_Helvetica = "Helvetica"; //$NON-NLS-1$
public static String FONT_Helvetica_Bold = "Helvetica-Bold"; //$NON-NLS-1$
public static String FONT_Helvetica_BoldOblique = "Helvetica-BoldOblique"; //$NON-NLS-1$
public static String FONT_Helvetica_Oblique = "Helvetica-Oblique"; //$NON-NLS-1$
public static String FONT_Symbol = "Symbol"; //$NON-NLS-1$
public static String FONT_Times_Bold = "Times-Bold"; //$NON-NLS-1$
public static String FONT_Times_BoldItalic = "Times-BoldItalic"; //$NON-NLS-1$
public static String FONT_Times_Italic = "Times-Italic"; //$NON-NLS-1$
public static String FONT_Times_Roman = "Times-Roman"; //$NON-NLS-1$
public static String FONT_ZapfDingbats = "ZapfDingbats"; //$NON-NLS-1$
public static final String[] FONT_BUILTINS = {FONT_Courier,
FONT_Courier_Bold,
FONT_Courier_BoldOblique,
FONT_Courier_Oblique,
FONT_Helvetica,
FONT_Helvetica_Bold,
FONT_Helvetica_BoldOblique,
FONT_Helvetica_Oblique,
FONT_Symbol,
FONT_Times_Bold,
FONT_Times_BoldItalic,
FONT_Times_Italic,
FONT_Times_Roman,
FONT_ZapfDingbats};
/**
* The meta class instance
*/
public static final MetaClass META = new MetaClass(MetaClass.class.getDeclaringClass());
private static Map<String, AFM> builtins = new HashMap<String, AFM>();
static {
FONT_ALIASES = new HashMap<String, String>();
// yourself
FONT_ALIASES.put(FONT_Courier, FONT_Courier);
FONT_ALIASES.put(FONT_Courier_Bold, FONT_Courier_Bold);
FONT_ALIASES.put(FONT_Courier_Oblique, FONT_Courier_Oblique);
FONT_ALIASES.put(FONT_Courier_BoldOblique, FONT_Courier_BoldOblique);
FONT_ALIASES.put(FONT_Helvetica, FONT_Helvetica);
FONT_ALIASES.put(FONT_Helvetica_Bold, FONT_Helvetica_Bold);
FONT_ALIASES.put(FONT_Helvetica_Oblique, FONT_Helvetica_Oblique);
FONT_ALIASES.put(FONT_Helvetica_BoldOblique, FONT_Helvetica_BoldOblique);
FONT_ALIASES.put(FONT_Times_Roman, FONT_Times_Roman);
FONT_ALIASES.put(FONT_Times_Bold, FONT_Times_Bold);
FONT_ALIASES.put(FONT_Times_Italic, FONT_Times_Italic);
FONT_ALIASES.put(FONT_Times_BoldItalic, FONT_Times_BoldItalic);
FONT_ALIASES.put(FONT_ZapfDingbats, FONT_ZapfDingbats);
FONT_ALIASES.put(FONT_Symbol, FONT_Symbol);
// abbreviations used in pdfmarks
FONT_ALIASES.put("Cour", FONT_Courier);
FONT_ALIASES.put("CoBo", FONT_Courier_Bold);
FONT_ALIASES.put("CoOb", FONT_Courier_Oblique);
FONT_ALIASES.put("CoBO", FONT_Courier_BoldOblique);
FONT_ALIASES.put("Helv", FONT_Helvetica);
FONT_ALIASES.put("HeBo", FONT_Helvetica_Bold);
FONT_ALIASES.put("HeOb", FONT_Helvetica_Oblique);
FONT_ALIASES.put("HeBO", FONT_Helvetica_BoldOblique);
FONT_ALIASES.put("TiRo", FONT_Times_Roman);
FONT_ALIASES.put("TiBo", FONT_Times_Bold);
FONT_ALIASES.put("TiIt", FONT_Times_Italic);
FONT_ALIASES.put("TiBI", FONT_Times_BoldItalic);
FONT_ALIASES.put("ZaDb", FONT_ZapfDingbats);
FONT_ALIASES.put("Symb", FONT_Symbol);
// valid alternatives (1.7 spec)
FONT_ALIASES.put("CourierNew", FONT_Courier);
FONT_ALIASES.put("CourierNew,Bold", FONT_Courier_Bold);
FONT_ALIASES.put("CourierNew,Italic", FONT_Courier_Oblique);
FONT_ALIASES.put("CourierNew,BoldItalic", FONT_Courier_BoldOblique);
FONT_ALIASES.put("Arial", FONT_Helvetica);
FONT_ALIASES.put("Arial,Bold", FONT_Helvetica_Bold);
FONT_ALIASES.put("Arial,Italic", FONT_Helvetica_Oblique);
FONT_ALIASES.put("Arial,BoldItalic", FONT_Helvetica_BoldOblique);
FONT_ALIASES.put("TimesNewRoman", FONT_Times_Roman);
FONT_ALIASES.put("TimesNewRoman,Bold", FONT_Times_Bold);
FONT_ALIASES.put("TimesNewRoman,Italic", FONT_Times_Italic);
FONT_ALIASES.put("TimesNewRoman,BoldItalic", FONT_Times_BoldItalic);
//
// deperecated maps
FONT_ALIASES_DEPRECATED = new HashMap<String, String>();
// alternatives given in pdf reference 1.4, no longer valid
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS", FONT_Times_Roman);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPSMT", FONT_Times_Roman);
FONT_ALIASES_DEPRECATED.put("TimesNewRoman-Bold", FONT_Times_Bold);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-Bold", FONT_Times_Bold);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-BoldMT", FONT_Times_Bold);
FONT_ALIASES_DEPRECATED.put("TimesNewRoman-Italic", FONT_Times_Italic);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-Italic", FONT_Times_Italic);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-ItalicMT", FONT_Times_Italic);
FONT_ALIASES_DEPRECATED.put("TimesNewRoman-BoldItalic", FONT_Times_BoldItalic);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-BoldItalic", FONT_Times_BoldItalic);
FONT_ALIASES_DEPRECATED.put("TimesNewRomanPS-BoldItalicMT", FONT_Times_BoldItalic);
FONT_ALIASES_DEPRECATED.put("CourierNewPSMT", FONT_Courier);
FONT_ALIASES_DEPRECATED.put("Courier,BoldItalic", FONT_Courier_BoldOblique);
FONT_ALIASES_DEPRECATED.put("CourierNew-BoldItalic", FONT_Courier_BoldOblique);
FONT_ALIASES_DEPRECATED.put("CourierNewPS-BoldItalicMT", FONT_Courier_BoldOblique);
FONT_ALIASES_DEPRECATED.put("Courier,Bold", FONT_Courier_Bold);
FONT_ALIASES_DEPRECATED.put("CourierNew-Bold", FONT_Courier_Bold);
FONT_ALIASES_DEPRECATED.put("CourierNewPS-BoldMT", FONT_Courier_Bold);
FONT_ALIASES_DEPRECATED.put("Courier,Italic", FONT_Courier_Oblique);
FONT_ALIASES_DEPRECATED.put("CourierNew-Italic", FONT_Courier_Oblique);
FONT_ALIASES_DEPRECATED.put("CourierNewPS-ItalicMT", FONT_Courier_Oblique);
FONT_ALIASES_DEPRECATED.put("Helvetica,Bold", FONT_Helvetica_Bold);
FONT_ALIASES_DEPRECATED.put("Helvetica-Italic", FONT_Helvetica_Oblique);
FONT_ALIASES_DEPRECATED.put("Helvetica,Italic", FONT_Helvetica_Oblique);
FONT_ALIASES_DEPRECATED.put("Helvetica-BoldItalic", FONT_Helvetica_BoldOblique);
FONT_ALIASES_DEPRECATED.put("Helvetica,BoldItalic", FONT_Helvetica_BoldOblique);
FONT_ALIASES_DEPRECATED.put("ArialMT", FONT_Helvetica);
FONT_ALIASES_DEPRECATED.put("Arial-Bold", FONT_Helvetica_Bold);
FONT_ALIASES_DEPRECATED.put("Arial-BoldMT", FONT_Helvetica_Bold);
FONT_ALIASES_DEPRECATED.put("Arial-Italic", FONT_Helvetica_Oblique);
FONT_ALIASES_DEPRECATED.put("Arial-ItalicMT", FONT_Helvetica_Oblique);
FONT_ALIASES_DEPRECATED.put("Arial-BoldItalic", FONT_Helvetica_BoldOblique);
FONT_ALIASES_DEPRECATED.put("Arial-BoldItalicMT", FONT_Helvetica_BoldOblique);
}
/**
* create a Type1 font object to be used in the pdf document
*
* @param name the name of the font to use
* @return the new font created
*/
public static PDFontType1 createNew(String name) {
PDFontType1 font = (PDFontType1) PDFontType1.META.createNew();
String baseFontName = PDFontType1.FONT_ALIASES.get(name);
if (baseFontName == null) {
baseFontName = PDFontType1.FONT_ALIASES_DEPRECATED.get(name);
if (baseFontName == null) {
baseFontName = name;
}
}
font.setBaseFont(baseFontName);
return font;
}
public static boolean isBuiltin(String name) {
return name != null && name.equals(FONT_ALIASES.get(name));
}
public static boolean isBuiltinAlias(String name) {
return FONT_ALIASES.get(name) != null;
}
public static boolean isBuiltinDeprecated(String name) {
return FONT_ALIASES_DEPRECATED.get(name) != null;
}
/**
* Lookup the {@link AFM} structure for the named builtin font.
*
* @param name
* @return the {@link AFM} structure for the named builtin font.
*/
public static synchronized AFM lookupBuiltinAFM(String name) {
String aliased = FONT_ALIASES.get(name);
if (aliased == null) {
aliased = FONT_ALIASES_DEPRECATED.get(name);
if (aliased == null) {
return null;
}
}
AFM result = builtins.get(aliased);
if (result == null) {
ILocator locator = new ClassResourceLocator(PDFontType1.class, aliased + ".afm");
try {
result = AFM.createFromLocator(locator);
builtins.put(aliased, result);
} catch (IOException e) {
PACKAGE.Log.log(Level.WARNING, "builtin font metrics '" + aliased + "' load error", e);
}
}
return result;
}
/**
* Create the receiver class from an already defined {@link COSDictionary}.
* NEVER use the constructor directly.
*
* @param object the PDDocument containing the new object
*/
protected PDFontType1(COSObject object) {
super(object);
}
/*
* (non-Javadoc)
*
* @see de.intarsys.pdf.pd.PDObject#cosGetExpectedSubtype()
*/
@Override
protected COSName cosGetExpectedSubtype() {
return CN_Subtype_Type1;
}
/*
* (non-Javadoc)
*
* @see de.intarsys.pdf.font.PDFont#createBuiltinFontDescriptor()
*/
@Override
protected PDFontDescriptor createBuiltinFontDescriptor() {
return new PDFontDescriptorAFM(lookupBuiltinAFM(getBaseFont().stringValue()));
}
/*
* (non-Javadoc)
*
* @see de.intarsys.pdf.font.PDFont#createBuiltInWidths(int[])
*/
@Override
protected int[] createBuiltInWidths(int[] result) {
AFM afm = lookupBuiltinAFM(getBaseFont().stringValue());
if (afm == null) {
return result;
}
if (getEncoding().isFontSpecificEncoding()) {
for (int i = 0; i < 256; i++) {
AFMChar afmChar = afm.getCharByCode(i);
if (afmChar != null) {
result[i] = afmChar.getWidth();
}
}
} else {
for (int i = 0; i < 256; i++) {
String glyphName = getEncoding().getGlyphName(i);
AFMChar afmChar = afm.getCharByName(glyphName);
if (afmChar != null) {
result[i] = afmChar.getWidth();
}
}
}
return result;
}
@Override
protected Encoding createDefaultEncoding() {
if ((getFontDescriptor() != null) && getFontDescriptor().isSymbolic()) {
return SymbolEncoding.UNIQUE;
}
AFM afm = lookupBuiltinAFM(getBaseFont().stringValue());
if (afm == null) {
return super.createDefaultEncoding();
} else {
return new AFMEncoding(afm);
}
}
@Override
protected int createFirstChar() {
// check if there is some undefined code
Encoding encoding = getEncoding();
for (int i = 0; i <= 255; i++) {
if (encoding.getDecoded(i) != -1) {
return i;
}
}
return 0;
}
@Override
protected int createLastChar() {
// check if there is some undefined code
Encoding encoding = getEncoding();
for (int i = 255; i >= 0; i--) {
if (encoding.getDecoded(i) != -1) {
return i;
}
}
// ??
return 0;
}
@Override
public String getFontNameNormalized() {
String name = super.getFontNameNormalized();
String alias = FONT_ALIASES.get(name);
if (alias != null) {
return alias;
}
alias = FONT_ALIASES_DEPRECATED.get(name);
if (alias != null) {
return alias;
}
return name;
}
@Override
public String getFontType() {
return "Type1";
}
@Override
public boolean isStandardFont() {
if (cosGetField(DK_FontDescriptor).isNull()) {
return true;
}
return Arrays.asList(FONT_BUILTINS).contains(cosGetField(DK_BaseFont));
}
}
| 40.648101 | 103 | 0.647982 |
c56798cad18e264464333268ceaa1fe2257c4801 | 1,801 | package de.j13g.manko.core.managers;
import de.j13g.manko.core.Placement;
import java.io.Serializable;
import java.util.HashMap;
// TODO Extract common methods compared to ScoreManager.
public class PlacementManager<E> implements Serializable {
private static final Placement DEFAULT_PLACEMENT = Placement.TBD;
private final HashMap<E, Placement> placements = new HashMap<>();
private final HashMap<Placement, E> winners = new HashMap<>();
public Placement setPlacement(E entrant, Placement placement) {
Placement oldPlacement = getOrDefault(entrant);
set(entrant, placement);
return oldPlacement;
}
public Placement resetPlacement(E entrant) {
Placement oldPlacement = getOrDefault(entrant);
reset(entrant);
return oldPlacement;
}
public Placement getPlacement(E entrant) {
return getOrDefault(entrant);
}
public E getEntrantByPlacement(Placement placement) {
if (!isValidWinnerPlacement(placement))
throw new IllegalArgumentException();
return winners.getOrDefault(placement, null);
}
private Placement getOrDefault(E entrant) {
return placements.getOrDefault(entrant, DEFAULT_PLACEMENT);
}
private void set(E entrant, Placement placement) {
placements.put(entrant, placement);
if (isValidWinnerPlacement(placement))
winners.put(placement, entrant);
}
private void reset(E entrant) {
Placement placement = placements.get(entrant);
placements.remove(entrant);
winners.remove(placement);
}
private boolean isValidWinnerPlacement(Placement placement) {
return placement == Placement.FIRST || placement == Placement.SECOND || placement == Placement.THIRD;
}
}
| 30.016667 | 109 | 0.694614 |
a36bfab024e4b9d77a4037a668c687f17eaf0ad1 | 228 | /**
* Application Controllers for a PlayFramework Model-View-Controller web application.
*
* @author Mark Nelson
* @see "Java in a Nutshell"
* @see http://www.playframework.com
* @since 6.0
*/
package controllers;
| 13.411765 | 85 | 0.688596 |
87978ced3800ca1111ec8621006f7134ab59d2f4 | 1,124 | //disabled
package net.izenith.Commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import net.izenith.Main.Vars;
public class Console implements HubCommand {
@Override
public String getName() {
return "console";
}
@Override
public String[] getAliases() {
return new String[] {"c","con"};
}
@Override
public void onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
if (args.length == 0){
sender.sendMessage(ChatColor.GREEN + "Insert Command.");
}
// Create a string for the message
String message = "";
// Add all arguments to the message
for(String arg : args){
message+=arg + " ";
}
// Send console message
Vars.main.getServer().dispatchCommand(Bukkit.getConsoleSender(), message);
}
@Override
public boolean onlyPlayers() {
return true;
}
@Override
public boolean hasPermission() {
return true;
}
@Override
public Permission getPermission() {
return new Permission("izenith.console");
}
}
| 18.129032 | 76 | 0.709075 |
cad2cddf131f32bc346cbe18208c48abbb6856db | 588 | package generics;
public class Exercise2 {
static Integer[] nums = {1, 2, 3, 4};
public static void main( String[] args ) throws Exception {
System.out.println(nums[0]);
System.out.println(nums[1]);
System.out.println(nums[2]);
System.out.println(nums[3]);
swap(nums,1,2);
System.out.println(nums[0]);
System.out.println(nums[1]);
System.out.println(nums[2]);
System.out.println(nums[3]);
}
public static <T> void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
| 21.777778 | 60 | 0.556122 |
2c568a66fe02dea9f98bdced009fd4b8cde4396f | 981 | /**
* Copyright 2020 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.account;
/**
* Exceptions thrown by {@link AccountService}. All exceptions are accompanied by a {@link AccountServiceErrorCode}.
*/
public class AccountServiceException extends Exception {
private final AccountServiceErrorCode error;
public AccountServiceException(String message, AccountServiceErrorCode error) {
super(message);
this.error = error;
}
public AccountServiceErrorCode getErrorCode() {
return error;
}
}
| 31.645161 | 116 | 0.747197 |
2cba0abb2e918c2e47c8eaedeadf8c02acd27817 | 1,304 | package com.blackjade.crm.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.blackjade.crm.model.Customer;
public interface CustomerDao {
public List<Customer> selectCustomerByUserNameAndPassword(@Param(value = "username") String username ,@Param(value = "password") String password);
public List<Customer> selectCustomerByEmailAndPassword(@Param(value = "email") String email ,@Param(value = "password") String password);
public int insertCustomer(Customer customer);
public int countUsername(@Param(value = "username") String username);
public int countEmail(@Param(value = "email") String email);
public int updateCustomerEmailVerify(@Param(value = "email") String email);
public Customer selectCustomerByUserName(@Param(value = "username") String username);
public int updatePasswordByEmail(Customer customer);
public Customer selectCustomerByIdAndPassword(@Param(value = "id") int id ,@Param(value = "password") String password);
public int modifyPasswordById(@Param(value = "id") int id ,@Param(value = "password") String password);
public int updateCustomerDetails(Customer customer);
public Customer selectCustomerById(@Param(value = "id") int id);
public Customer scanPersonalInformation(@Param(value = "id") int id);
}
| 35.243243 | 147 | 0.763804 |
184a7d8262f2d400c600c4bea81fd420ce980aad | 2,185 | package org.wangfeng.panda.app.framework;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wangfeng.panda.app.common.base.AppBaseController;
import org.wangfeng.panda.app.common.exception.RuleRuntimeException;
import org.wangfeng.panda.app.util.IpUtils;
import javax.servlet.http.HttpServletRequest;
/**
* User: wangfeng
* Date: 2020/8/24
*/
@Slf4j
@Component
@ControllerAdvice
@RestControllerAdvice
public class RuleExceptionHandler extends AppBaseController {
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Object defaultExceptionHandler(HttpServletRequest request, Exception e) throws Exception {
log.warn("服务端异常", e);
log.warn("RequestIP:[{}],RequestURI:[{}],QueryString:[{}],", IpUtils.getIpFromRequest(request),
request.getRequestURI(), request.getQueryString(), request.getHeader("Authorization"));
JsonObject object = new JsonObject();
object.addProperty("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
object.addProperty("message", "服务端异常");
return object.toString();
}
@ExceptionHandler(value = RuleRuntimeException.class)
@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
public Object RuleRuntimeExceptionHandler(HttpServletRequest request, Exception e) throws Exception {
log.warn("服务端异常", e);
log.warn("RequestIP:[{}],RequestURI:[{}],QueryString:[{}],", IpUtils.getIpFromRequest(request),
request.getRequestURI(), request.getQueryString(), request.getHeader("Authorization"));
JsonObject object = new JsonObject();
object.addProperty("code", HttpStatus.EXPECTATION_FAILED.value());
object.addProperty("message", e.getMessage());
return object.toString();
}
}
| 39.017857 | 105 | 0.747826 |
f87e7ef1b10e4d6f2d34ac29153a8e661be90442 | 18,689 | package com.squareup.spoon;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.CollectingOutputReceiver;
import com.android.ddmlib.DdmPreferences;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.InstallException;
import com.android.ddmlib.SyncService;
import com.android.ddmlib.logcat.LogCatMessage;
import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner;
import com.android.ddmlib.testrunner.ITestRunListener;
import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.squareup.spoon.adapters.TestIdentifierAdapter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import static com.android.ddmlib.FileListingService.FileEntry;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.squareup.spoon.Spoon.SPOON_SCREENSHOTS;
import static com.squareup.spoon.Spoon.SPOON_FILES;
import static com.squareup.spoon.SpoonLogger.logDebug;
import static com.squareup.spoon.SpoonLogger.logError;
import static com.squareup.spoon.SpoonLogger.logInfo;
import static com.squareup.spoon.SpoonUtils.GSON;
import static com.squareup.spoon.SpoonUtils.createAnimatedGif;
import static com.squareup.spoon.SpoonUtils.obtainDirectoryFileEntry;
import static com.squareup.spoon.SpoonUtils.obtainRealDevice;
/** Represents a single device and the test configuration to be executed. */
public final class SpoonDeviceRunner {
private static final String FILE_EXECUTION = "execution.json";
private static final String FILE_RESULT = "result.json";
private static final String DEVICE_SCREENSHOT_DIR = "app_" + SPOON_SCREENSHOTS;
private static final String DEVICE_FILE_DIR = "app_" + SPOON_FILES;
private static final String [] DEVICE_DIRS = {DEVICE_SCREENSHOT_DIR, DEVICE_FILE_DIR};
static final String TEMP_DIR = "work";
static final String JUNIT_DIR = "junit-reports";
static final String IMAGE_DIR = "image";
static final String FILE_DIR = "file";
private final File sdk;
private final File apk;
private final File testApk;
private final String serial;
private final boolean debug;
private final boolean noAnimations;
private final int adbTimeout;
private final List<String> instrumentationArgs;
private final String className;
private final String methodName;
private final IRemoteAndroidTestRunner.TestSize testSize;
private final File work;
private final File junitReport;
private final File imageDir;
private final File fileDir;
private final String classpath;
private final SpoonInstrumentationInfo instrumentationInfo;
private final List<ITestRunListener> testRunListeners;
/**
* Create a test runner for a single device.
*
* @param sdk Path to the local Android SDK directory.
* @param apk Path to application APK.
* @param testApk Path to test application APK.
* @param output Path to output directory.
* @param serial Device to run the test on.
* @param debug Whether or not debug logging is enabled.
* @param adbTimeout time in ms for longest test execution
* @param classpath Custom JVM classpath or {@code null}.
* @param instrumentationInfo Test apk manifest information.
* @param className Test class name to run or {@code null} to run all tests.
* @param methodName Test method name to run or {@code null} to run all tests. Must also pass
* {@code className}.
* @param testRunListeners Additional TestRunListener or empty list.
*/
SpoonDeviceRunner(File sdk, File apk, File testApk, File output, String serial, boolean debug,
boolean noAnimations, int adbTimeout, String classpath,
SpoonInstrumentationInfo instrumentationInfo, List<String> instrumentationArgs,
String className, String methodName, IRemoteAndroidTestRunner.TestSize testSize,
List<ITestRunListener> testRunListeners) {
this.sdk = sdk;
this.apk = apk;
this.testApk = testApk;
this.serial = serial;
this.debug = debug;
this.noAnimations = noAnimations;
this.adbTimeout = adbTimeout;
this.instrumentationArgs = instrumentationArgs;
this.className = className;
this.methodName = methodName;
this.testSize = testSize;
this.classpath = classpath;
this.instrumentationInfo = instrumentationInfo;
serial = SpoonUtils.sanitizeSerial(serial);
this.work = FileUtils.getFile(output, TEMP_DIR, serial);
this.junitReport = FileUtils.getFile(output, JUNIT_DIR, serial + ".xml");
this.imageDir = FileUtils.getFile(output, IMAGE_DIR, serial);
this.fileDir = FileUtils.getFile(output, FILE_DIR, serial);
this.testRunListeners = testRunListeners;
}
/** Serialize to disk and start {@link #main(String...)} in another process. */
public DeviceResult runInNewProcess() throws IOException, InterruptedException {
logDebug(debug, "[%s]", serial);
// Create the output directory.
work.mkdirs();
// Write our configuration to a file in the output directory.
FileWriter executionWriter = new FileWriter(new File(work, FILE_EXECUTION));
GSON.toJson(this, executionWriter);
executionWriter.close();
// Kick off a new process to interface with ADB and perform the real execution.
String name = SpoonDeviceRunner.class.getName();
Process process = new ProcessBuilder("java", "-Djava.awt.headless=true", "-cp", classpath, name,
work.getAbsolutePath()).start();
printStream(process.getInputStream(), "STDOUT");
printStream(process.getErrorStream(), "STDERR");
final int exitCode = process.waitFor();
logDebug(debug, "Process.waitFor() finished for [%s] with exitCode %d", serial, exitCode);
// Read the result from a file in the output directory.
FileReader resultFile = new FileReader(new File(work, FILE_RESULT));
DeviceResult result = GSON.fromJson(resultFile, DeviceResult.class);
resultFile.close();
return result;
}
private void printStream(InputStream stream, String tag) throws IOException {
BufferedReader stdout = new BufferedReader(new InputStreamReader(stream));
String s;
while ((s = stdout.readLine()) != null) {
logDebug(debug, "[%s] %s %s", serial, tag, s);
}
}
/** Execute instrumentation on the target device and return a result summary. */
public DeviceResult run(AndroidDebugBridge adb) {
String testPackage = instrumentationInfo.getInstrumentationPackage();
String testRunner = instrumentationInfo.getTestRunnerClass();
TestIdentifierAdapter testIdentifierAdapter = TestIdentifierAdapter.fromTestRunner(testRunner);
logDebug(debug, "InstrumentationInfo: [%s]", instrumentationInfo);
if (debug) {
SpoonUtils.setDdmlibInternalLoggingLevel();
}
DeviceResult.Builder result = new DeviceResult.Builder();
IDevice device = obtainRealDevice(adb, serial);
logDebug(debug, "Got realDevice for [%s]", serial);
// Get relevant device information.
final DeviceDetails deviceDetails = DeviceDetails.createForDevice(device);
result.setDeviceDetails(deviceDetails);
logDebug(debug, "[%s] setDeviceDetails %s", serial, deviceDetails);
DdmPreferences.setTimeOut(adbTimeout);
// Now install the main application and the instrumentation application.
try {
device.installPackage(apk.getAbsolutePath(), true);
} catch (InstallException e) {
logInfo("InstallException while install app apk on device [%s]", serial);
e.printStackTrace(System.out);
return result.markInstallAsFailed("Unable to install application APK.").build();
}
try {
device.installPackage(testApk.getAbsolutePath(), true);
} catch (InstallException e) {
logInfo("InstallException while install test apk on device [%s]", serial);
e.printStackTrace(System.out);
return result.markInstallAsFailed("Unable to install instrumentation APK.").build();
}
// Create the output directory, if it does not already exist.
work.mkdirs();
// Initiate device logging.
SpoonDeviceLogger deviceLogger = new SpoonDeviceLogger(device);
// Run all the tests! o/
try {
logDebug(debug, "About to actually run tests for [%s]", serial);
RemoteAndroidTestRunner runner = new RemoteAndroidTestRunner(testPackage, testRunner, device);
runner.setMaxtimeToOutputResponse(adbTimeout);
if (instrumentationArgs != null && instrumentationArgs.size() > 0) {
for (String pair : instrumentationArgs) {
String[] kvp = pair.split("=");
if (kvp.length != 2 || isNullOrEmpty(kvp[0]) || isNullOrEmpty(kvp[1])) {
continue;
}
runner.addInstrumentationArg(kvp[0], kvp[1]);
}
}
if (!isNullOrEmpty(className)) {
if (isNullOrEmpty(methodName)) {
runner.setClassName(className);
} else {
runner.setMethodName(className, methodName);
}
}
if (testSize != null) {
runner.setTestSize(testSize);
}
List<ITestRunListener> listeners = new ArrayList<ITestRunListener>();
listeners.add(new SpoonTestRunListener(result, debug, testIdentifierAdapter));
listeners.add(new XmlTestRunListener(junitReport));
if (testRunListeners != null) {
listeners.addAll(testRunListeners);
}
runner.run(listeners);
} catch (Exception e) {
result.addException(e);
}
mapLogsToTests(deviceLogger, result);
try {
logDebug(debug, "About to grab screenshots and prepare output for [%s]", serial);
pullDeviceFiles(device);
File screenshotDir = new File(work, DEVICE_SCREENSHOT_DIR);
File testFilesDir = new File(work, DEVICE_FILE_DIR);
if (screenshotDir.exists()) {
imageDir.mkdirs();
handleImages(result, screenshotDir);
FileUtils.deleteDirectory(screenshotDir);
}
if (testFilesDir.exists()) {
fileDir.mkdirs();
handleFiles(result, testFilesDir);
FileUtils.deleteDirectory(testFilesDir);
}
} catch (Exception e) {
result.addException(e);
}
logDebug(debug, "Done running for [%s]", serial);
return result.build();
}
private void handleImages(DeviceResult.Builder result, File screenshotDir) throws IOException {
logDebug(debug, "Moving screenshots to the image folder on [%s]", serial);
// Move all children of the screenshot directory into the image folder.
File[] classNameDirs = screenshotDir.listFiles();
if (classNameDirs != null) {
Multimap<DeviceTest, File> testScreenshots = ArrayListMultimap.create();
for (File classNameDir : classNameDirs) {
String className = classNameDir.getName();
File destDir = new File(imageDir, className);
FileUtils.copyDirectory(classNameDir, destDir);
// Get a sorted list of all screenshots from the device run.
List<File> screenshots = new ArrayList<File>(
FileUtils.listFiles(destDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE));
Collections.sort(screenshots);
// Iterate over each screenshot and associate it with its corresponding method result.
for (File screenshot : screenshots) {
String methodName = screenshot.getParentFile().getName();
DeviceTest testIdentifier = new DeviceTest(className, methodName);
DeviceTestResult.Builder builder = result.getMethodResultBuilder(testIdentifier);
if (builder != null) {
builder.addScreenshot(screenshot);
testScreenshots.put(testIdentifier, screenshot);
} else {
logError("Unable to find test for %s", testIdentifier);
}
}
}
logDebug(debug, "Generating animated gifs for [%s]", serial);
// Don't generate animations if the switch is present
if (!noAnimations) {
// Make animated GIFs for all the tests which have screenshots.
for (DeviceTest deviceTest : testScreenshots.keySet()) {
List<File> screenshots = new ArrayList<File>(testScreenshots.get(deviceTest));
if (screenshots.size() == 1) {
continue; // Do not make an animated GIF if there is only one screenshot.
}
File animatedGif = FileUtils.getFile(imageDir, deviceTest.getClassName(),
deviceTest.getMethodName() + ".gif");
createAnimatedGif(screenshots, animatedGif);
result.getMethodResultBuilder(deviceTest).setAnimatedGif(animatedGif);
}
}
}
}
private void handleFiles(DeviceResult.Builder result, File testFileDir) throws IOException {
File[] classNameDirs = testFileDir.listFiles();
if (classNameDirs != null) {
logInfo("Found class name dirs: " + classNameDirs);
Multimap<DeviceTest, File> testFiles = ArrayListMultimap.create();
for (File classNameDir : classNameDirs) {
String className = classNameDir.getName();
File destDir = new File(fileDir, className);
FileUtils.copyDirectory(classNameDir, destDir);
logInfo("Copied " + classNameDir + " to " + destDir);
// Get a sorted list of all files from the device run.
List<File> files = new ArrayList<File>(
FileUtils.listFiles(destDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE));
Collections.sort(files);
// Iterate over each file and associate it with its
// corresponding method result.
for (File file : files) {
String methodName = file.getParentFile().getName();
DeviceTest testIdentifier = new DeviceTest(className, methodName);
final DeviceTestResult.Builder resultBuilder
= result.getMethodResultBuilder(testIdentifier);
if (resultBuilder != null) {
resultBuilder.addFile(file);
logInfo("Added file as result: " + file + " for " + testIdentifier);
} else {
logError("Unable to find test for %s", testIdentifier);
}
}
}
}
}
/** Download all files from a single device to the local machine. */
private void pullDeviceFiles(IDevice device) throws Exception {
for (String dir : DEVICE_DIRS) {
pullDirectory(device, dir);
}
}
private void pullDirectory(final IDevice device, final String name) throws Exception {
// Output path on private internal storage, for KitKat and below.
FileEntry internalDir = getScreenshotDirOnInternalStorage(name);
logDebug(debug, "Internal path is " + internalDir.getFullPath());
// Output path on public external storage, for Lollipop and above.
FileEntry externalDir = getScreenshotDirOnExternalStorage(device, name);
logDebug(debug, "External path is " + externalDir.getFullPath());
// Sync test output files to the local filesystem.
logDebug(debug, "Pulling files from external dir on [%s]", serial);
String localDirName = work.getAbsolutePath();
adbPull(device, externalDir, localDirName);
logDebug(debug, "Pulling files from internal dir on [%s]", serial);
adbPull(device, internalDir, localDirName);
logDebug(debug, "Done pulling %s from on [%s]", name, serial);
}
private void adbPull(IDevice device, FileEntry remoteDirName, String localDirName) {
try {
device.getSyncService()
.pull(new FileEntry[] {remoteDirName}, localDirName,
SyncService.getNullProgressMonitor());
} catch (Exception e) {
logDebug(debug, e.getMessage(), e);
}
}
private FileEntry getScreenshotDirOnInternalStorage(final String dir) {
String appPackage = instrumentationInfo.getApplicationPackage();
String internalPath = "/data/data/" + appPackage + "/" + dir;
return obtainDirectoryFileEntry(internalPath);
}
private static FileEntry getScreenshotDirOnExternalStorage(IDevice device, final String dir)
throws Exception {
String externalPath = getExternalStoragePath(device) + "/" + dir;
return obtainDirectoryFileEntry(externalPath);
}
private static String getExternalStoragePath(IDevice device) throws Exception {
CollectingOutputReceiver pathNameOutputReceiver = new CollectingOutputReceiver();
device.executeShellCommand("echo $EXTERNAL_STORAGE", pathNameOutputReceiver);
return pathNameOutputReceiver.getOutput().trim();
}
/** Grab all the parsed logs and map them to individual tests. */
private static void mapLogsToTests(SpoonDeviceLogger deviceLogger, DeviceResult.Builder result) {
Map<DeviceTest, List<LogCatMessage>> logs = deviceLogger.getParsedLogs();
for (Map.Entry<DeviceTest, List<LogCatMessage>> entry : logs.entrySet()) {
DeviceTestResult.Builder builder = result.getMethodResultBuilder(entry.getKey());
if (builder != null) {
builder.setLog(entry.getValue());
}
}
}
/////////////////////////////////////////////////////////////////////////////
//// Secondary Per-Device Process /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/** De-serialize from disk, run the tests, and serialize the result back to disk. */
public static void main(String... args) {
if (args.length != 1) {
throw new IllegalArgumentException("Must be started with a device directory.");
}
try {
String outputDirName = args[0];
File outputDir = new File(outputDirName);
File executionFile = new File(outputDir, FILE_EXECUTION);
if (!executionFile.exists()) {
throw new IllegalArgumentException("Device directory and/or execution file doesn't exist.");
}
FileReader reader = new FileReader(executionFile);
SpoonDeviceRunner target = GSON.fromJson(reader, SpoonDeviceRunner.class);
reader.close();
AndroidDebugBridge adb = SpoonUtils.initAdb(target.sdk, target.adbTimeout);
DeviceResult result = target.run(adb);
AndroidDebugBridge.terminate();
// Write device result file.
FileWriter writer = new FileWriter(new File(outputDir, FILE_RESULT));
GSON.toJson(result, writer);
writer.close();
} catch (Throwable ex) {
logInfo("ERROR: Unable to execute test for target. Exception message: %s", ex.getMessage());
ex.printStackTrace(System.out);
System.exit(1);
}
}
}
| 41.623608 | 100 | 0.699502 |
657d1b6396ba3df9cda61e21182731f3869bdac6 | 3,216 |
package mage.cards.v;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.abilities.effects.common.RegenerateSourceEffect;
import mage.abilities.keyword.ScavengeAbility;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.players.Player;
import mage.target.common.TargetControlledCreaturePermanent;
/**
*
* @author jeffwadsworth
*/
public final class VarolzTheScarStriped extends CardImpl {
public VarolzTheScarStriped(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B}{G}");
addSuperType(SuperType.LEGENDARY);
this.subtype.add(SubType.TROLL);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Each creature card in your graveyard has scavenge. The scavenge cost is equal to its mana cost.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new VarolzTheScarStripedEffect()));
// Sacrifice another creature: Regenerate Varolz, the Scar-Striped.
this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new RegenerateSourceEffect(),
new SacrificeTargetCost(new TargetControlledCreaturePermanent(1, 1, StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE, true))));
}
private VarolzTheScarStriped(final VarolzTheScarStriped card) {
super(card);
}
@Override
public VarolzTheScarStriped copy() {
return new VarolzTheScarStriped(this);
}
}
class VarolzTheScarStripedEffect extends ContinuousEffectImpl {
VarolzTheScarStripedEffect() {
super(Duration.WhileOnBattlefield, Layer.AbilityAddingRemovingEffects_6, SubLayer.NA, Outcome.AddAbility);
staticText = "Each creature card in your graveyard has scavenge. The scavenge cost is equal to its mana cost";
}
VarolzTheScarStripedEffect(final VarolzTheScarStripedEffect effect) {
super(effect);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
if (controller != null) {
for (UUID cardId : controller.getGraveyard()) {
Card card = game.getCard(cardId);
if (card != null && card.isCreature()) {
ScavengeAbility ability = new ScavengeAbility(new ManaCostsImpl(card.getManaCost().getText()));
ability.setSourceId(cardId);
ability.setControllerId(card.getOwnerId());
game.getState().addOtherAbility(card, ability);
}
}
return true;
}
return false;
}
@Override
public VarolzTheScarStripedEffect copy() {
return new VarolzTheScarStripedEffect(this);
}
}
| 35.733333 | 143 | 0.704602 |
5615f6b73fa41a22832dcba6cef7f46829aeac44 | 2,209 | package com.spring.job.quartz.config;
import com.spring.job.quartz.job.SampleJob;
import com.spring.job.quartz.job.ScheduledJob1;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : zhayh
* @date : 2020-4-26 08:05
* @description : JobDetail 与 Trigger 需要成对出现
*/
@Configuration
public class SchedulerConfiguration {
public static class SimpleJobConfigure {
// 创建任务实例
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class)
.withIdentity("sampleJob")
.usingJobData("name", "niit") // 传递参数
.storeDurably() // 没有 Trigger 关联的时候任务是否被保留,还没 Trigger指向它,需要设为 true ,
.build();
}
// 创建触发器
@Bean
public Trigger sampleJobTrigger() {
// 简单的调度计划的构造器
SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(2) // 频率
.repeatForever(); // 次数
// Trigger 构造器
return TriggerBuilder.newTrigger()
.forJob(sampleJobDetail()) // 设置 Job
.withIdentity("sampleTrigger") // 设置触发器名称
.withSchedule(builder) // 设置调度器
.build();
}
}
public static class CronJobConfiguration {
@Bean
public JobDetail cronJob() {
return JobBuilder.newJob(ScheduledJob1.class)
.withIdentity("cronJob", "group1")
.storeDurably()
.build();
}
@Bean
public Trigger cronTrigger() {
// 1. 创建 基于 Quartz Cron 表达式的调度计划的构造器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
// 2. 创建 Trigger触发器
return TriggerBuilder.newTrigger()
.forJob(cronJob()) // 对应 Job 为 demoJob01
.withIdentity("trigger1", "group1") // 设置触发器和触发器组的名称
.withSchedule(scheduleBuilder)
.build();
}
}
}
| 33.469697 | 100 | 0.555455 |
29e6fa2b3a938412c39d74f54a2ce36738775650 | 2,212 | package org.yu.cloud.auth.service;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.yu.cloud.auth.constant.MessageConstant;
import org.yu.cloud.auth.domain.UserDO;
import org.yu.cloud.auth.dto.SecurityUser;
import org.yu.cloud.auth.repository.UserRepository;
/**
* 用户管理业务类
* Created by yu on 2020/6/19.
*/
@Service
public class UserServiceImpl implements UserDetailsService {
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
public UserServiceImpl(PasswordEncoder passwordEncoder, UserRepository userRepository) {
this.passwordEncoder = passwordEncoder;
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDO userDO = userRepository.findByUsername(username);
if (userDO == null) {
throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
}
SecurityUser securityUser = new SecurityUser(userDO);
if (!securityUser.isEnabled()) {
throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
} else if (!securityUser.isAccountNonLocked()) {
throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
} else if (!securityUser.isAccountNonExpired()) {
throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
} else if (!securityUser.isCredentialsNonExpired()) {
throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
}
return securityUser;
}
}
| 43.372549 | 93 | 0.776221 |
b06b269f71a09edb3815b912f8f7f6599169a6fa | 7,562 | /*
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2021 Cephetir
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*/
package me.cephetir.skyskipped.config;
import gg.essential.vigilance.Vigilant;
import gg.essential.vigilance.data.Property;
import gg.essential.vigilance.data.PropertyType;
import me.cephetir.skyskipped.features.impl.discordrpc.RPC;
import java.awt.*;
import java.io.File;
public class Config extends Vigilant {
@Property(
type = PropertyType.SWITCH,
name = "Chest Closer",
category = "Dungeons", subcategory = "Chest Closer",
description = "Chests in dungeon will close automatically."
)
public static boolean chestCloser = false;
@Property(
type = PropertyType.SWITCH,
name = "Chest Closer in Crystal Hollows",
category = "Dungeons", subcategory = "Chest Closer",
description = "Chests in Crystal Hollows will close automatically."
)
public static boolean chestCloserCH = false;
@Property(
type = PropertyType.SWITCH,
name = "Party chat swapper",
category = "Chat", subcategory = "Chat",
description = "Automatically swaps between party chat and global chat."
)
public static boolean chatSwapper = false;
@Property(
type = PropertyType.SWITCH,
name = "[NON] Rank",
category = "Chat", subcategory = "Chat",
description = "Adds the [NON] rank, given to people without a rank."
)
public static boolean nons = false;
@Property(
type = PropertyType.SWITCH,
name = "Discord RPC",
category = "Discord", subcategory = "Discord RPC",
description = "Shows status in discord."
)
public static boolean DRPC = true;
@Property(
type = PropertyType.SWITCH,
name = "Player ESP",
category = "Dungeons", subcategory = "Player ESP",
description = "Shows players through walls."
)
public static boolean playerESP = false;
@Property(
type = PropertyType.COLOR,
name = "Player ESP Color",
category = "Dungeons", subcategory = "Player ESP",
description = "Outline color for Player ESP."
)
public static Color espColor = Color.GREEN;
@Property(
type = PropertyType.SWITCH,
name = "Pizza Fail Safe",
category = "Hacks", subcategory = "Hacks",
description = "Failsafe macros in Pizza client."
)
public static boolean failSafe = false;
@Property(
type = PropertyType.SWITCH,
name = "Jump When Stuck",
category = "Hacks", subcategory = "Hacks",
description = "Jump in fail safe."
)
public static boolean failsafeJump = false;
@Property(
type = PropertyType.SWITCH,
name = "Block GS ability",
category = "Hacks", subcategory = "Hacks",
description = "Blocks Giant's sword ability."
)
public static boolean gsBlock = false;
@Property(
type = PropertyType.SWITCH,
name = "Name ping",
category = "Chat", subcategory = "Chat",
description = "Plays sound when someone says your name in chat."
)
public static boolean ping = false;
@Property(
type = PropertyType.SWITCH,
name = "Auto Leave Dungeon",
category = "Dungeons", subcategory = "Auto Leave",
description = "Runs /leavedungeon command after run ends."
)
public static boolean EndLeave = false;
@Property(
type = PropertyType.SWITCH,
name = "Auto Party FragBot when Dungeon ends",
category = "Dungeons", subcategory = "Auto Leave",
description = "Runs /fragrun command after run ends."
)
public static boolean EndParty = false;
@Property(
type = PropertyType.TEXT,
name = "FragBot Name",
category = "Dungeons", subcategory = "Auto Leave",
description = "FragBot IGN."
)
public static String BotName = "";
@Property(
type = PropertyType.NUMBER,
name = "Delay For \"Leave Dungeon\"",
category = "Dungeons", subcategory = "Auto Leave",
description = "Delay between going to lobby and to dungeon hub.",
increment = 10,
max = 10000
)
public static int delay = 2000;
@Property(
type = PropertyType.SWITCH,
name = "§4!!VERY SECRET MONEY EXPLOIT!!",
category = "SUPER SECRETS SETTINGS §4!(!DO NOT OPEN!)!", subcategory = "SUPER SECRETS SETTINGS §4!(!DO NOT ENABLE!)!",
description = "§kMAKES YOUR PURSE BLOW UP WITH BILLIONS OF COINS"
)
public static boolean coinsToggle = false;
@Property(
type = PropertyType.NUMBER,
name = "AMOUNT OF COINS DO YOU WANT",
category = "SUPER SECRETS SETTINGS §4!(!DO NOT OPEN!)!", subcategory = "§4SUPER SECRETS SETTINGS!",
description = "§4AMOUNT OF COINS YOU WANT",
max = Integer.MAX_VALUE,
increment = 10000000
)
public static int coins = 10000000;
@Property(
type = PropertyType.SWITCH,
name = "300 Score Ping",
category = "Visual", subcategory = "Visual",
description = "SBE like 300 score ping."
)
public static boolean scorePing = false;
@Property(
type = PropertyType.TEXT,
name = "300 Score Ping Text",
category = "Visual", subcategory = "Visual",
description = "Text to show when 300 score reached."
)
public static String pingText = "300 score reached! Btw sbe is cringe";
@Property(
type = PropertyType.SWITCH,
name = "Rabbit hat Ping",
category = "Visual", subcategory = "Visual",
description = "Ping on Watcher cleared."
)
public static boolean rabbitPing = false;
@Property(
type = PropertyType.SWITCH,
name = "Hide Pet Candies",
category = "Visual", subcategory = "Visual",
description = "Hide pet's candies counter in tooltip."
)
public static boolean hidePetCandies = false;
@Property(
type = PropertyType.SWITCH,
name = "Pets Overlay",
category = "Visual", subcategory = "Visual",
description = "Good looking overlay for pets menu.\n§cDon't use with small window size"
)
public static boolean petsOverlay = true;
public Config() {
super(new File("./config/skyskipped.toml"), "SkySkipped");
registerListener("DRPC", aBoolean -> new Thread(() -> {
try {
Thread.sleep(100L);
RPC.reset();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start());
addDependency("espColor", "playerESP");
addDependency("coins", "coinsToggle");
addDependency("pingText", "scorePing");
initialize();
}
}
| 33.021834 | 130 | 0.584237 |
0769c4ae382ea42c577f19a90e4e9dc5fca47a5d | 8,748 | package org.tm.pro.es;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class ElasticUtil {
private String baseUrl;
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getBaseRequest(String index, String type, String param) throws Exception {
StringBuffer sb = new StringBuffer(baseUrl);
if (index != null && !"".equals(index.trim())) {
sb.append(index);
if (type != null && !"".equals(type.trim())) {
sb.append("/").append(type);
}
}
if (param != null && !"".equals(param.trim())) {
sb.append("?").append(param);
}
HttpClient client = HttpClients.createDefault();
URI uri = new URI(sb.toString());
HttpGet httpGet = new HttpGet(uri);
HttpResponse response = client.execute(httpGet);
return EntityUtils.toString(response.getEntity());
}
public String postBaseRequest(String index, String type, String json) throws Exception {
StringBuffer sb = new StringBuffer(baseUrl);
sb.append(index).append("/").append(type).append("/_search");
HttpClient client = HttpClients.createDefault();
URI uri = new URI(sb.toString());
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
return EntityUtils.toString(response.getEntity());
}
public Map<String, Long> getHttpStatusInfo(String index, String type) {
Map<String, Long> data = new LinkedHashMap<>();
String json = "{" +
" \"query\": {" +
" \"bool\":{" +
" \"must_not\": [{" +
" \"terms\": {" +
" \"status_code\": [" +
" ]" +
" }" +
" } " +
" ]" +
" }" +
" }," +
" \"size\": 0," +
" \"aggs\": {" +
" \"types\": {" +
" \"terms\": {" +
" \"field\": \"status_code\"" +
" }" +
" }" +
" }" +
"}";
String result = null;
try {
result = postBaseRequest(index, type, json);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
return data;
}
JSONObject jsonObj = JSONObject.parseObject(result);
if (jsonObj != null) {
JSONObject aggregations = jsonObj.getJSONObject("aggregations");
JSONObject types = aggregations.getJSONObject("types");
JSONArray buckets = types.getJSONArray("buckets");
buckets.forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
JSONObject item = (JSONObject) obj;
data.put(item.getString("key"), item.getLong("doc_count"));
}
});
}
return data;
}
public Map<String, Object> getBackFlowInfo(String index, String type) {
Map<String, Object> data = new HashMap<>();
String json = "{" +
" \"query\": {" +
" \"bool\": {" +
" \"must\": [" +
" {" +
" \"terms\": {" +
" \"cache_stat\": [" +
" \"MISS\"," +
" \"HIT\" " +
" ]" +
" }" +
" }" +
" ]" +
" }" +
" }," +
" \"aggs\": {" +
" \"cache_stat_group_by\": {" +
" \"terms\": {" +
" \"field\": \"cache_stat\"" +
" }," +
" \"aggs\" : {" +
" \"sum_back_flow\" : {" +
" \"sum\" : { " +
" \"field\" : \"back_flow\"" +
" }" +
" }," +
" \"sum_out_flow\" : {" +
" \"sum\" : { " +
" \"field\" : \"out_flow\"" +
" }" +
" }" +
" }" +
" }," +
" \"sum_back_flow\" : {" +
" \"sum\" : { " +
" \"field\" : \"back_flow\"" +
" }" +
" }," +
" \"sum_out_flow\" : {" +
" \"sum\" : { " +
" \"field\" : \"out_flow\"" +
" }" +
" }" +
" }," +
" \"size\": 0" +
"}";
String result = null;
try {
result = postBaseRequest(index, type, json);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
return data;
}
JSONObject jsonObj = JSONObject.parseObject(result);
if (jsonObj != null) {
JSONObject aggregations = jsonObj.getJSONObject("aggregations");
JSONObject sumOutFlow = aggregations.getJSONObject("sum_out_flow");
data.put("sumOutFlow", sumOutFlow.getLongValue("value"));
JSONObject sumBackFlow = aggregations.getJSONObject("sum_back_flow");
data.put("sumBackFlow", sumBackFlow.getLongValue("value"));
JSONObject cacheStatGroupBy = aggregations.getJSONObject("cache_stat_group_by");
JSONArray buckets = cacheStatGroupBy.getJSONArray("buckets");
buckets.forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
Map<String, Object> _item = new HashMap<>();
JSONObject item = (JSONObject) obj;
_item.put("sumOutFlow", item.getJSONObject("sum_out_flow").getLongValue("value"));
_item.put("sumBackFlow", item.getJSONObject("sum_back_flow").getLongValue("value"));
data.put(item.getString("key"), _item);
}
});
}
return data;
}
public Map<String, Long> getCacheStatusInfo(String index, String type) {
Map<String, Long> data = new HashMap<>();
String json = "{" +
" \"query\": {" +
" \"bool\":{" +
" }" +
" }," +
" \"size\": 0," +
" \"aggs\": {" +
" \"types\": {" +
" \"terms\": {" +
" \"field\": \"cache_stat\"" +
" }" +
" }" +
" }" +
"}";
String result = null;
try {
result = postBaseRequest(index, type, json);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
return data;
}
JSONObject jsonObj = JSONObject.parseObject(result);
if (jsonObj != null) {
JSONObject aggregations = jsonObj.getJSONObject("aggregations");
JSONObject types = aggregations.getJSONObject("types");
JSONArray buckets = types.getJSONArray("buckets");
buckets.forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
JSONObject item = (JSONObject) obj;
data.put(item.getString("key"), item.getLong("doc_count"));
}
});
}
return data;
}
public Map<String, Long> getUrlInfo(String index, String type) {
Map<String, Long> data = new HashMap<>();
String json = "{" +
" \"query\": {" +
" \"bool\":{" +
" }" +
" }," +
" \"size\": 0," +
" \"aggs\": {" +
" \"types\": {" +
" \"terms\": {" +
" \"field\": \"url\"" +
" }" +
" }" +
" }" +
"}";
String result = null;
try {
result = postBaseRequest(index, type, json);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
return data;
}
JSONObject jsonObj = JSONObject.parseObject(result);
if (jsonObj != null) {
JSONObject aggregations = jsonObj.getJSONObject("aggregations");
JSONObject types = aggregations.getJSONObject("types");
JSONArray buckets = types.getJSONArray("buckets");
buckets.forEach(new Consumer<Object>() {
@Override
public void accept(Object obj) {
JSONObject item = (JSONObject) obj;
data.put(item.getString("key"), item.getLong("doc_count"));
}
});
}
return data;
}
/**
* GET /ppc_log_test-20170930/access/_search
{
"query": {
"bool":{
}
},
"size": 1,
"aggs": {
"types": {
"terms": {
"field": "domain"
},
"aggs": {
"cache_stat": {
"terms": {
"field": "domain"
}
},
"sum_out_flow": {
"sum": {
"field": "out_flow"
}
},
"sum_hit_out_flow": {
"sum": {
"field": "out_flow"
}
}
}
}
}
}
*/
} | 27.596215 | 90 | 0.511088 |
f75cfc63798a56315f7c65b1354c039056fad321 | 833 | /*
* Copyright 2012 Cyril A. Karpenko
*
* 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.redshape.utils.beans.bindings.annotations;
/**
* @author nikelin
* @date 25/04/11
* @package com.redshape.bindings.annotations
*/
public enum BindableAttributes {
LONGTEXT,
PASSWORD,
MULTICHOICE
}
| 28.724138 | 76 | 0.726291 |
70d5d6dc1e15ae06d61f4d631e08e45a317be5bd | 209 | class JavaUsage {
public static void main(String[] args) {
System.out.println(Foo.CONST);
Foo.s();
Foo.Bar.f();
Foo foo = new Foo(); // not usage of companion object
}
} | 26.125 | 61 | 0.555024 |
9ff83cba390b96fb365ee7bf666287e6d180d7ca | 443 | class A
{
int age=65;
String name="RAM";
void getData()
{
System.out.println(age+" "+name);
}
}
public class Super_keyword extends A
{
int age=25;
String name="Shyam";
Super_keyword()
{
System.out.println(name);
System.out.println(super.name);
}
void getData()
{
System.out.println(age+" "+name);
super.getData();
}
public static void main(String args[])
{
Super_keyword obj=new Super_keyword();
obj.getData();
}
} | 14.766667 | 40 | 0.659142 |
e035ef34a645977cbe9471952dabc14c1eb835ef | 689 | package com.imotspot.dashboard.tb.pageobjects;
import org.openqa.selenium.WebDriver;
import com.vaadin.testbench.ElementQuery;
import com.vaadin.testbench.TestBenchTestCase;
import com.vaadin.testbench.elements.ButtonElement;
public class TBLoginView extends TestBenchTestCase {
public TBLoginView(WebDriver driver) {
setDriver(driver);
}
public TBMainView login() {
getLoginButton().first().click();
return new TBMainView(driver);
}
public boolean isDisplayed() {
return getLoginButton().exists();
}
private ElementQuery<ButtonElement> getLoginButton() {
return $(ButtonElement.class).caption("Sign In");
}
}
| 24.607143 | 58 | 0.711176 |
547e82651224650118117dfd6c9e1f66528ca0d9 | 973 | package com.nwpu.sign_up_system.service;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
@Api(tags="实现News相关操作的Service组件")
public interface NewsService {
/**
* 发布一条新闻
*
* @param title
* @param date
* @param content
* @param sender
* @param tag
*/
@Transactional
String publishNews(String title, Date date, String content, String sender, String tag);
/**
* 指定删除某一条新闻动态
*
* @param id
* @return
*/
@Transactional
String deleteNews(int id);
/**
* 返回当前标签下的所有的新闻动态
*
* @param tag
* @return
*/
JSONObject findAllTagNews(String tag);
/**
* 返回所有的新闻
*
* @return
*/
JSONObject findAllNews();
/**
* @return title
*/
String findTitleById(int id);
}
| 18.018519 | 91 | 0.610483 |
3fad7651d86771dc2c1459e6de4a108747e177ae | 702 | package com.example.aula05.media.video;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
/**
* Simples teste do VideoView
*
*/
public class ExemploVideoView extends Activity {
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
VideoView v = new VideoView(this);
setContentView(v);
File sdcardDir = android.os.Environment.getExternalStorageDirectory();
File file = new File(sdcardDir, "gglass.mp4");
// "/mnt/sdcard/gglass.mp4"
String path = file.getAbsolutePath();
v.setVideoPath(path);
v.setMediaController(new MediaController(this));
v.requestFocus();
}
}
| 21.9375 | 72 | 0.740741 |
941f3f6dcd9eb8b82adf20326d7af66ecb4b20df | 165 |
package sagex.api;
public class Version {
public static final String VERSION = "9.2.8.1";
public static String GetVersion() {
return VERSION;
}
} | 20.625 | 51 | 0.654545 |
4722b45a49ed728dd79cc2ae0f93d6fe84776173 | 8,000 | package com.captstudios.games.tafl.core.screen;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.captstudios.games.tafl.core.TaflGame;
import com.captstudios.games.tafl.core.consts.Assets;
import com.captstudios.games.tafl.core.consts.Constants;
import com.captstudios.games.tafl.core.enums.AiType;
import com.captstudios.games.tafl.core.utils.DoubleTextureDrawable;
import com.roundtriangles.games.zaria.screen.AbstractScreen;
public class SettingsScreen extends AbstractScreen<TaflGame> {
ImageButton musicSelector;
ImageButton difficultySelector;
Sprite[] difficultyValues;
public SettingsScreen(final TaflGame game) {
super(game, game.mainMenuScreen, Constants.ScreenConstants.FADE_TIME);
}
@Override
public void initialize() {
Sprite background = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_BACKGROUNDS, Assets.Backgrounds.MENU);
setBackgroundImage(new Image(background));
Table table = new Table();
table.setFillParent(true);
table.defaults().space(game.deviceSettings.menuSpacing);
createMusicSelector(table);
createDifficultySelector(table);
if (Constants.GameConstants.DEBUG) {
table.debug();
}
stage.addActor(table);
createButtons();
}
private void createButtons() {
Table buttonTable = new Table();
buttonTable.right().bottom().setFillParent(true);
buttonTable.defaults().pad(game.deviceSettings.menuSpacing).size(game.deviceSettings.menuButtonHeight);
Sprite icon = game.graphicsService.getSprite(Assets.GraphicFiles.ATLAS_PIECES, Assets.Icons.BACK);
Button button = new ImageButton(new TextureRegionDrawable(new TextureRegion(icon)));
button.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.soundService.playSound(Assets.Sounds.CLICK_SOUND);
back();
}
});
buttonTable.add(button).expandX().left();
buttonTable.right().bottom().setFillParent(true);
icon = game.graphicsService.getSprite(Assets.GraphicFiles.ATLAS_PIECES, Assets.Icons.ABOUT);
button = game.createSwitchScreenButton(icon, this, game.aboutScreen);
buttonTable.add(button);
if (Constants.GameConstants.DEBUG) {
buttonTable.debug();
}
stage.addActor(buttonTable);
}
private void createMusicSelector(Table table) {
Sprite labelSprite = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.MUSIC);
Image imageLabel = new Image(new TextureRegionDrawable(new TextureRegion(labelSprite)));
float height = game.deviceSettings.menuLabelHeight;
float width = height * (imageLabel.getWidth() / imageLabel.getHeight());
table.add(imageLabel).spaceBottom(game.deviceSettings.menuSpacing).size(width, height).expandX().right();
Sprite on = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.ON);
Sprite off = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.OFF);
Sprite up = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.ButtonGraphics.ON_OFF_BLANK);
Sprite down = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.ButtonGraphics.ON_OFF_PRESSED);
musicSelector = new ImageButton(
new DoubleTextureDrawable(new TextureRegion(up), new TextureRegion(off)),
new DoubleTextureDrawable(new TextureRegion(down), new TextureRegion(on)),
new DoubleTextureDrawable(new TextureRegion(down), new TextureRegion(on)));
musicSelector.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
game.preferenceService.setMusicEnabled(musicSelector.isChecked());
game.soundService.playSound(Assets.Sounds.CLICK_SOUND);
}
});
height = game.deviceSettings.menuSelectorHeight;
width = height * (up.getWidth() / up.getHeight());
table.add(musicSelector).size(width, height).left();
table.row();
}
private void createDifficultySelector(Table table) {
Sprite labelSprite = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.LEVEL);
Image difficultyImageLabel = new Image(new TextureRegionDrawable(new TextureRegion(labelSprite)));
float height = game.deviceSettings.menuLabelHeight;
float width = height * (difficultyImageLabel.getWidth() / difficultyImageLabel.getHeight());
table.add(difficultyImageLabel).spaceBottom(game.deviceSettings.menuSpacing).size(width, height).expandX().right();
difficultyValues = new Sprite[] {
game.graphicsService.getSprite(Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.BEGINNER),
game.graphicsService.getSprite(Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.INTERMEDIATE),
game.graphicsService.getSprite(Assets.GraphicFiles.ATLAS_PIECES, Assets.TextGraphics.ADVANCED)
};
Sprite up = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.ButtonGraphics.PLAY_AS_BLANK);
Sprite down = game.graphicsService.getSprite(
Assets.GraphicFiles.ATLAS_PIECES, Assets.ButtonGraphics.PLAY_AS_PRESSED);
final AiType initialType = game.preferenceService.getAiType();
Sprite selectorTest = difficultyValues[initialType.ordinal()];
difficultySelector = new ImageButton(
new DoubleTextureDrawable(new TextureRegion(up), new TextureRegion(selectorTest)),
new DoubleTextureDrawable(new TextureRegion(down), new TextureRegion(selectorTest)));
height = game.deviceSettings.menuSelectorHeight;
width = height * (up.getWidth() / up.getHeight());
table.add(difficultySelector).size(width, height).expandX().left();
table.row();
}
@Override
public void show() {
super.show();
musicSelector.setChecked(game.preferenceService.isMusicEnabled());
updateDifficultySelector();
}
private void updateDifficultySelector() {
final AiType initialType = game.preferenceService.getAiType();
((DoubleTextureDrawable)difficultySelector.getStyle().imageDown).setInnerRegion(difficultyValues[initialType.ordinal()]);
((DoubleTextureDrawable)difficultySelector.getStyle().imageUp).setInnerRegion(difficultyValues[initialType.ordinal()]);
difficultySelector.addListener(new ChangeListener() {
int selected = initialType.ordinal();
@Override
public void changed(ChangeEvent event, Actor actor) {
selected = (selected + 1) % difficultyValues.length;
((DoubleTextureDrawable)difficultySelector.getStyle().imageDown).setInnerRegion(difficultyValues[selected]);
((DoubleTextureDrawable)difficultySelector.getStyle().imageUp).setInnerRegion(difficultyValues[selected]);
game.preferenceService.setAiType(AiType.values()[selected]);
game.soundService.playSound(Assets.Sounds.CLICK_SOUND);
}
});
}
}
| 43.715847 | 129 | 0.697 |
6b4fb87b9e14e4cd332032a9973f56ec502fc364 | 1,678 | package net.ddns.rkdawenterprises.brief4ijidea.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.impl.EditorImpl;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import static net.ddns.rkdawenterprises.brief4ijidea.MiscellaneousKt.get_editor_content_visible_area;
@SuppressWarnings({ "ComponentNotRegistered", "unused" })
public class Left_side_of_window_action
extends Plugin_action
{
public Left_side_of_window_action( String text,
String description )
{
super( text,
description );
}
/**
* Implement this method to provide your action handler.
*
* @param e Carries information on the invocation place
*/
@Override
public void actionPerformed( @NotNull AnActionEvent e )
{
Editor editor = e.getData( CommonDataKeys.EDITOR );
if( !( editor instanceof EditorImpl ) ) return;
Rectangle visible_area = get_editor_content_visible_area( editor );
Point cursor_point = editor.visualPositionToXY( editor.getCaretModel()
.getVisualPosition() );
Point window_left_at_line_point = new Point( visible_area.x, cursor_point.y );
VisualPosition window_left_at_line_visual_position = editor.xyToVisualPosition( window_left_at_line_point );
editor.getCaretModel().moveToVisualPosition( window_left_at_line_visual_position );
}
}
| 34.958333 | 116 | 0.70441 |
5b20c9530ee9468fe9ae8a7852433ef50fbd02cd | 2,965 | /**
* <copyright> </copyright>
*
* $Id$
*/
package orgomg.cwm.resource.multidimensional;
import org.eclipse.emf.common.util.EList;
import orgomg.cwm.objectmodel.core.Attribute;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Dimensioned Object</b></em>'. <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* DimensionedObject represents an attribute of Dimension.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link orgomg.cwm.resource.multidimensional.DimensionedObject#getDimension <em>Dimension</em>}</li>
* <li>{@link orgomg.cwm.resource.multidimensional.DimensionedObject#getSchema <em>Schema</em>}</li>
* </ul>
* </p>
*
* @see orgomg.cwm.resource.multidimensional.MultidimensionalPackage#getDimensionedObject()
* @model
* @generated
*/
public interface DimensionedObject extends Attribute {
/**
* Returns the value of the '<em><b>Dimension</b></em>' reference list. The
* list contents are of type
* {@link orgomg.cwm.resource.multidimensional.Dimension}. It is
* bidirectional and its opposite is '
* {@link orgomg.cwm.resource.multidimensional.Dimension#getDimensionedObject
* <em>Dimensioned Object</em>}'. <!-- begin-user-doc --> <!-- end-user-doc
* --> <!-- begin-model-doc --> Dimensions referencing DimensionedObjects.
* <!-- end-model-doc -->
*
* @return the value of the '<em>Dimension</em>' reference list.
* @see orgomg.cwm.resource.multidimensional.MultidimensionalPackage#getDimensionedObject_Dimension()
* @see orgomg.cwm.resource.multidimensional.Dimension#getDimensionedObject
* @model opposite="dimensionedObject"
* @generated
*/
EList<Dimension> getDimension();
/**
* Returns the value of the '<em><b>Schema</b></em>' container reference. It
* is bidirectional and its opposite is '
* {@link orgomg.cwm.resource.multidimensional.Schema#getDimensionedObject
* <em>Dimensioned Object</em>}'. <!-- begin-user-doc --> <!-- end-user-doc
* --> <!-- begin-model-doc --> Schema owning DimensionedObjects. <!--
* end-model-doc -->
*
* @return the value of the '<em>Schema</em>' container reference.
* @see #setSchema(Schema)
* @see orgomg.cwm.resource.multidimensional.MultidimensionalPackage#getDimensionedObject_Schema()
* @see orgomg.cwm.resource.multidimensional.Schema#getDimensionedObject
* @model opposite="dimensionedObject" required="true"
* @generated
*/
Schema getSchema();
/**
* Sets the value of the '{@link orgomg.cwm.resource.multidimensional.DimensionedObject#getSchema <em>Schema</em>}' container reference.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>Schema</em>' container reference.
* @see #getSchema()
* @generated
*/
void setSchema(Schema value);
} // DimensionedObject
| 37.531646 | 140 | 0.666442 |
0b6e3208697055d4d43e70b78aa25ffaae195c9b | 1,046 | /*
* Part of Homeglue (c) 2018 C. Ivan Cooper - https://github.com/4levity/homeglue
* Homeglue is free software. You can modify and/or distribute it under the terms
* of the Apache License Version 2.0: https://www.apache.org/licenses/LICENSE-2.0
*/
package net.forlevity.homeglue.testing;
import java.util.HashSet;
import java.util.concurrent.LinkedBlockingQueue;
/**
* PARTIAL IMPLEMENTATION of a blocking queue that ensures uniqueness of items in the queue.
*
* @param <T> item type
*/
public class LinkedUniqueQueue<T> extends LinkedBlockingQueue<T> {
private final HashSet<T> items = new HashSet<>();
@Override
public boolean offer(T t) {
synchronized (items) {
return !items.add(t) || super.offer(t);
}
}
@Override
public T take() throws InterruptedException {
T item = super.take();
synchronized (items) {
items.remove(item);
}
return item;
}
// TODO: delegate instead of extending, support all BlockingQueue interface
}
| 26.820513 | 92 | 0.665392 |
d1c509cc98b3fa6650237eb391bcc92a0c43b7ab | 5,211 | package com.udacity.jdnd.course3.critter.user;
import com.udacity.jdnd.course3.critter.customer.Customer;
import com.udacity.jdnd.course3.critter.customer.CustomerDTO;
import com.udacity.jdnd.course3.critter.customer.CustomerService;
import com.udacity.jdnd.course3.critter.employee.Employee;
import com.udacity.jdnd.course3.critter.employee.EmployeeDTO;
import com.udacity.jdnd.course3.critter.employee.EmployeeRequestDTO;
import com.udacity.jdnd.course3.critter.employee.EmployeeService;
import com.udacity.jdnd.course3.critter.pet.Pet;
import com.udacity.jdnd.course3.critter.pet.PetService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.DayOfWeek;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Handles web requests related to Users.
*
* Includes requests for both customers and employees. Splitting this into separate user and customer controllers
* would be fine too, though that is not part of the required scope for this class.
*/
@RestController
@RequestMapping("/user")
public class UserController {
private final CustomerService customerService;
private final EmployeeService employeeService;
private final PetService petService;
public UserController(CustomerService customerService, EmployeeService employeeService, PetService petService) {
this.customerService = customerService;
this.employeeService = employeeService;
this.petService = petService;
}
@PostMapping("/customer")
public CustomerDTO saveCustomer(@Valid @RequestBody CustomerDTO customerDTO){
customerDTO.setId(null);
Customer customer = convertCustomerDTOToCustomer(customerDTO);
customerService.saveCustomer(customer);
return convertCustomerToCustomerDTO(customer);
}
@GetMapping("/customer/{customerId}")
public CustomerDTO getCustomer(@PathVariable Long customerId) {
Customer customer = customerService.getCustomerById(customerId);
return convertCustomerToCustomerDTO(customer);
}
@GetMapping("/customer")
public List<CustomerDTO> getAllCustomers(){
List<Customer> customers = customerService.getAllCustomers();
return customers.stream().map(this::convertCustomerToCustomerDTO).collect(Collectors.toList());
}
@GetMapping("/customer/pet/{petId}")
public CustomerDTO getOwnerByPet(@PathVariable Long petId){
Customer customer = customerService.getOwnerByPet(petId);
return convertCustomerToCustomerDTO(customer);
}
@PostMapping("/employee")
public EmployeeDTO saveEmployee(@Valid @RequestBody EmployeeDTO employeeDTO) {
employeeDTO.setId(null);
Employee employee = convertEmployeeDTOToEmployee(employeeDTO);
employeeService.saveEmployee(employee);
return convertEmployeeToEmployeeDTO(employee);
}
@GetMapping("/employee/{employeeId}")
public EmployeeDTO getEmployee(@PathVariable Long employeeId) {
Employee employee = employeeService.getEmployeeById(employeeId);
return convertEmployeeToEmployeeDTO(employee);
}
@GetMapping("/employee")
public List<EmployeeDTO> getAllEmployees() {
List<Employee> employees = employeeService.getAllEmployees();
return employees.stream().map(this::convertEmployeeToEmployeeDTO).collect(Collectors.toList());
}
@PutMapping("/employee/{employeeId}")
public void setEmployeeAvailability(@RequestBody Set<DayOfWeek> daysAvailable, @PathVariable Long employeeId) {
employeeService.setEmployeeDaysAvailable(employeeId, daysAvailable);
}
@GetMapping("/employee/availability")
public List<EmployeeDTO> findEmployeesForService(@Valid @RequestBody EmployeeRequestDTO employeeRequestDTO) {
List<Employee> employees = employeeService.findEmployeesForService(
employeeRequestDTO.getSkills(), employeeRequestDTO.getDate());
return employees.stream().map(this::convertEmployeeToEmployeeDTO).collect(Collectors.toList());
}
private CustomerDTO convertCustomerToCustomerDTO(Customer customer) {
CustomerDTO customerDTO = new CustomerDTO();
BeanUtils.copyProperties(customer, customerDTO);
for (Pet pet : customer.getPets()) {
customerDTO.getPetIds().add(pet.getId());
}
return customerDTO;
}
private Customer convertCustomerDTOToCustomer(CustomerDTO customerDTO) {
Customer customer = new Customer();
BeanUtils.copyProperties(customerDTO, customer);
for (Long petId : customerDTO.getPetIds()) {
customer.getPets().add(petService.getPetById(petId));
}
return customer;
}
private EmployeeDTO convertEmployeeToEmployeeDTO(Employee employee) {
EmployeeDTO employeeDTO = new EmployeeDTO();
BeanUtils.copyProperties(employee, employeeDTO);
return employeeDTO;
}
private Employee convertEmployeeDTOToEmployee(EmployeeDTO employeeDTO) {
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee);
return employee;
}
}
| 40.395349 | 116 | 0.742084 |
1b7ff76949c34b942712c5c256ef63a9e39c5195 | 4,450 | /*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.muc.cluster;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
import org.jivesoftware.openfire.muc.MUCRole;
import org.jivesoftware.openfire.muc.spi.LocalMUCRole;
import org.jivesoftware.openfire.muc.spi.LocalMUCRoom;
import org.jivesoftware.util.cache.ExternalizableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Presence;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/**
* Task that broadcasts the presence of a room occupant to the occupants of the room
* being hosted by the cluster node. When a room occupant changes his presence an
* instance of this class will be sent to each cluster node and when executed a broadcast
* of the updated presence will be sent to local room occupants.
*
* @author Gaston Dombiak
*/
public class BroadcastPresenceRequest extends MUCRoomTask<Void> {
private static final Logger Log = LoggerFactory.getLogger( BroadcastPresenceRequest.class );
private Presence presence;
private JID userAddressSender;
private boolean isJoinPresence;
public BroadcastPresenceRequest() {
}
public BroadcastPresenceRequest(@Nonnull final LocalMUCRoom room, @Nonnull final MUCRole sender, @Nonnull final Presence presence, final boolean isJoinPresence) {
super(room);
this.userAddressSender = sender.getUserAddress();
this.presence = presence;
this.isJoinPresence = isJoinPresence;
if (!presence.getFrom().asBareJID().equals(room.getJID())) {
// At this point, the 'from' address of the to-be broadcasted stanza can be expected to be the role-address
// of the subject, or more broadly: it's bare JID representation should match that of the room. If that's not
// the case then there's a bug in Openfire. Catch this here, as otherwise, privacy-sensitive data is leaked.
// See: OF-2152
throw new IllegalArgumentException("Broadcasted presence stanza's 'from' JID " + presence.getFrom() + " does not match room JID: " + room.getJID());
}
}
public Presence getPresence() {
return presence;
}
public JID getUserAddressSender() {
return userAddressSender;
}
public boolean isJoinPresence() {
return isJoinPresence;
}
@Override
public Void getResult() {
return null;
}
@Override
public void run() {
// Execute the operation considering that we may still be joining the cluster
execute(new Runnable() {
@Override
public void run() {
try
{
getRoom().broadcast( BroadcastPresenceRequest.this );
}
catch ( Exception e )
{
Log.warn( "An unexpected exception occurred while trying to broadcast a presence update from {} in the room {}", presence.getFrom(), getRoom().getJID(), e );
}
}
});
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
ExternalizableUtil.getInstance().writeSerializable(out, (DefaultElement) presence.getElement());
ExternalizableUtil.getInstance().writeSerializable(out, userAddressSender);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in);
presence = new Presence(packetElement, true);
userAddressSender = (JID) ExternalizableUtil.getInstance().readSerializable(in);
}
}
| 37.083333 | 177 | 0.691236 |
3a52bad188b845a54f5514570bd68e2c253b10bf | 242 | package org.hongxi.whatsmars.boot.sample.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.hongxi.whatsmars.boot.sample.mybatisplus.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
| 26.888889 | 64 | 0.830579 |
1d5711925a6e66285dfeebf0c35c5e4ce88ddf62 | 1,452 | import java.util.Arrays;
public class Matrix {
public double[][] values;
public int height, width;
public Matrix(int pHeight, int pWidth) {
height = pHeight;
width = pWidth;
values = new double[height][width];
}
public Matrix(double[][] pValues) {
values = pValues;
height = values.length;
width = values[0].length;
}
public Matrix(double a, double b, double c) {
values = new double[][]{{a,b,c}};
height = values.length;
width = values[0].length;
}
public static Matrix multiplyMatricies(Matrix m1, Matrix m2) {
// System.out.println(m1.height + " * " + m1.width);
double returnableDoubles[][] = new double[m2.width][m1.height];
if (m1.width == m2.height) {
for (int i = 0; i < m1.height; i++) {
for (int j = 0; j < m2.width; j++) {
double currentValue = 0;
for (int k = 0; k < m1.width; k++) {
// System.out.println(m1.values[i][k] * m2.values[k][j]);
currentValue+=m1.values[i][k] * m2.values[k][j];
}
returnableDoubles[i][j]=currentValue;
System.out.println(currentValue);
}
}
}
System.out.println(Arrays.deepToString(returnableDoubles));
return new Matrix(returnableDoubles);
}
}
| 32.266667 | 80 | 0.512397 |
b5b1d3a2035e409cad2b0b64de91d9400a4c942b | 1,624 | package com.donkeycode.feign;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.donkeycode.core.response.ObjectResponse;
/**
* Service Auth 配置
*
* @author yanjun.xue
* @since 2019年6月25日
*/
@FeignClient(value = "${auth.serviceId}", configuration = {})
public interface ServiceAuthFeign {
/**
* 获取可以访问的服务
*
* @param serviceId
* @param secret
* @return
*/
@RequestMapping(value = "/client/myClient")
ObjectResponse<List<String>> getAllowedClient(@RequestParam("serviceId") String serviceId, @RequestParam("secret") String secret);
/**
* 获取 Token 值
*
* @param clientId
* @param secret
* @return
*/
@PostMapping(value = "/client/token")
ObjectResponse<?> getAccessToken(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret);
/**
* 验证服务PukKey
*
* @param clientId
* @param secret
* @return
*/
@PostMapping(value = "/client/servicePubKey")
ObjectResponse<byte[]> getServicePublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret);
/**
* 使用PubKey
*
* @param clientId
* @param secret
* @return
*/
@PostMapping(value = "/client/userPubKey")
ObjectResponse<byte[]> getUserPublicKey(@RequestParam("clientId") String clientId, @RequestParam("secret") String secret);
}
| 26.193548 | 134 | 0.67303 |
5474939ed30257256742f2bb0b9f7fe7662bc67f | 247 | package org.arend.ext.core.expr;
import org.arend.ext.core.context.CoreInferenceVariable;
public interface CoreInferenceReferenceExpression extends CoreExpression {
CoreInferenceVariable getVariable();
CoreExpression getSubstExpression();
}
| 27.444444 | 74 | 0.838057 |
2387bdbe587e203c8273ea5a52cad49f838b3137 | 1,350 | package com.clsaa.dop.server.application.controller;
import com.clsaa.dop.server.application.config.HttpHeadersConfig;
import com.clsaa.dop.server.application.service.ImageService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebFlux;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* 镜像API接口实现类
* </p>
*
* @author Bowen
* @since 2019-3-12
*/
@RestController
@CrossOrigin
@EnableSwagger2WebFlux
public class ImageController {
@Autowired
private ImageService imageService;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ApiOperation(value = "查询代码仓库地址", notes = "查询代码仓库地址")
@GetMapping(value = "/image_url_list")
public List<String> getImageUrlList(@RequestHeader(HttpHeadersConfig.HttpHeaders.X_LOGIN_USER) Long loginUser) {
logger.info("[getImageUrlList] Request coming: loginUser={}",loginUser);
return this.imageService.getImageUrls(loginUser);
}
}
| 30.681818 | 116 | 0.785926 |
4585f167d7849779404c5db5f6f63f4d48462f91 | 2,151 | package com.penglecode.xmodule.master4j.spring.beans.instantiation.xmlconfig;
import com.penglecode.xmodule.master4j.spring.beans.instantiation.*;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.io.ClassRelativeResourceLoader;
/**
* Spring Bean实例化过程示例 (基于XML配置)
*
*
* @author pengpeng
* @version 1.0
* @date 2020/9/11 21:50
*/
public class BeanInstantiationProcessExample1 {
public static void main(String[] args) {
ConfigurableConversionService conversionService = (ConfigurableConversionService) DefaultConversionService.getSharedInstance();
conversionService.addConverter(new StringToDurationConverter());
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.setConversionService(conversionService); //设置全局类型转换ConversionService
beanFactory.registerCustomEditor(ServerConfig.class, ServerConfigPropertyEditor.class); //注册自定义的属性编辑器
beanFactory.addBeanPostProcessor(new BeanInstantiationBeanPostProcessor()); //添加Bean实例化相关的自定义BeanPostProcessor
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(BeanInstantiationProcessExample1.class);
beanDefinitionReader.loadBeanDefinitions(resourceLoader.getResource("applicationContext1.xml")); //加载bean的定义
String[] beanNames = beanFactory.getBeanDefinitionNames();
for(String beanName : beanNames) {
System.out.println(beanFactory.getBeanDefinition(beanName));
}
String beanName = "tomcatWebServer";
AbstractWebServer webServer = (AbstractWebServer) beanFactory.getBean(beanName);
System.out.println(webServer);
System.out.println(webServer.getSessionTimeout());
beanFactory.destroySingleton(beanName);
}
}
| 45.765957 | 135 | 0.788935 |
2f05d9fae7e50345c95f4e49c7447305b4cbfcf5 | 1,085 | package b.p.b.a0.j;
import b.p.b.a0.d;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class f extends d {
/* renamed from: i reason: collision with root package name */
public final /* synthetic */ int f6520i;
/* renamed from: j reason: collision with root package name */
public final /* synthetic */ List f6521j;
/* renamed from: k reason: collision with root package name */
public final /* synthetic */ d f6522k;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public f(d dVar, String str, Object[] objArr, int i2, List list) {
super(str, objArr);
this.f6522k = dVar;
this.f6520i = i2;
this.f6521j = list;
}
public void a() {
Objects.requireNonNull(this.f6522k.f6501q);
try {
this.f6522k.y.s(this.f6520i, a.CANCEL);
synchronized (this.f6522k) {
this.f6522k.A.remove(Integer.valueOf(this.f6520i));
}
} catch (IOException unused) {
}
}
}
| 28.552632 | 89 | 0.606452 |
6e182c68a50c81bc7a867ee4d678fc4b83cf59b8 | 10,415 | /*
* InlineBlockBox.java
* Copyright (c) 2005-2011 Radek Burget
*
* CSSBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CSSBox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CSSBox. If not, see <http://www.gnu.org/licenses/>.
*
* Created on 16.10.2011, 22:51:58 by radek
*/
package org.fit.cssbox.layout;
import java.awt.Graphics2D;
import cz.vutbr.web.css.CSSProperty;
import cz.vutbr.web.css.CSSProperty.Overflow;
import cz.vutbr.web.css.NodeData;
import cz.vutbr.web.css.TermLengthOrPercent;
import org.w3c.dom.Element;
/**
* A box corresponding to an inline-block element.
*
* @author radek
*/
public class InlineBlockBox extends BlockBox implements InlineElement
{
/** vertical box alignment specified by the style */
private CSSProperty.VerticalAlign valign;
/** parent LineBox assigned during layout */
private LineBox linebox;
/** The baseline offset of the contents */
protected int baseline;
/* current layout parametres */
private int availw;
private boolean force;
public InlineBlockBox(Element n, Graphics2D g, VisualContext ctx)
{
super(n, g, ctx);
isblock = false;
}
public InlineBlockBox(InlineBox src)
{
super(src);
isblock = false;
}
@Override
public void setStyle(NodeData s)
{
super.setStyle(s);
loadInlineStyle();
}
public CSSProperty.VerticalAlign getVerticalAlign()
{
return valign;
}
public void setLineBox(LineBox linebox)
{
this.linebox = linebox;
}
public LineBox getLineBox()
{
return linebox;
}
public int getLineboxOffset()
{
return 0;
}
//========================================================================
public int getMaxLineHeight()
{
return getHeight();
}
public int getBaselineOffset()
{
return baseline;
}
public int getBelowBaseline()
{
return getHeight() - baseline;
}
public int getTotalLineHeight()
{
return getHeight();
}
public int getHalfLead()
{
return 0;
}
public int getFirstLineLength()
{
return getMaximalContentWidth();
}
public int getLastLineLength()
{
return getMaximalContentWidth();
}
public boolean containsLineBreak()
{
return false;
}
public boolean finishedByLineBreak()
{
return false;
}
public boolean collapsedCompletely()
{
return false;
}
//========================================================================
@Override
public void setIgnoreInitialWhitespace(boolean b)
{
if (endChild > startChild)
getSubBox(startChild).setIgnoreInitialWhitespace(b);
}
@Override
public boolean doLayout(int availw, boolean force, boolean linestart)
{
this.availw = availw;
this.force = force;
super.doLayout(availw, force, linestart);
if (force || fitsSpace())
{
//inline-block baseline as defined in
//http://www.w3.org/TR/CSS22/visudet.html#propdef-vertical-align
if (getOverflowX() == Overflow.VISIBLE)
{
baseline = getLastInlineBoxBaseline(this);
if (baseline == -1)
baseline = getHeight();
else
{
baseline += getContentOffsetY();
if (baseline > getHeight()) baseline = getHeight();
}
}
else
{
//inline-block boxes with overflow different from visible use the bottom margin edge as baseline
baseline = getHeight();
}
return true;
}
else
return false;
}
@Override
protected void layoutInline()
{
if (force || fitsSpace()) //do not layout if we don't fit the available space
super.layoutInline();
}
@Override
protected void layoutBlocks()
{
if (force || fitsSpace()) //do not layout if we don't fit the available space
super.layoutBlocks();
}
/**
* Checks wheter the block fits the available space
* @return <code>true</code> when there is enough space to fit the block
*/
private boolean fitsSpace()
{
return availw >= totalWidth();
}
@Override
public boolean hasFixedWidth()
{
return wset; //the width should not be computed from the parent
}
@Override
public int getMinimalContentWidthLimit()
{
int ret;
if (wset)
ret = content.width;
else if (min_size.width != -1)
ret = min_size.width;
else
ret = 0;
return ret;
}
@Override
protected void computeWidthsInFlow(TermLengthOrPercent width, boolean auto, boolean exact, int contw, boolean update)
{
//The same as for absolutely positioned boxes (shrink-to-fit or explicitely set)
CSSDecoder dec = new CSSDecoder(ctx);
if (width == null) auto = true; //no value behaves as "auto"
boolean mleftauto = style.getProperty("margin-left") == CSSProperty.Margin.AUTO;
TermLengthOrPercent mleft = getLengthValue("margin-left");
boolean mrightauto = style.getProperty("margin-right") == CSSProperty.Margin.AUTO;
TermLengthOrPercent mright = getLengthValue("margin-right");
if (!widthComputed) update = false;
if (auto)
{
if (exact) wset = false;
if (!update)
content.width = dec.getLength(width, auto, 0, 0, contw);
}
else
{
if (exact)
{
wset = true;
wrelative = width.isPercentage();
}
content.width = dec.getLength(width, auto, 0, 0, contw);
}
//auto margins are treated as zero
margin.left = dec.getLength(mleft, mleftauto, 0, 0, contw);
margin.right = dec.getLength(mright, mrightauto, 0, 0, contw);
}
@Override
public void absolutePositions()
{
updateStackingContexts();
if (isDisplayed())
{
//x coordinate is taken from the content edge
absbounds.x = getParent().getAbsoluteContentX() + bounds.x;
//y coordinate -- depends on the vertical alignment
if (valign == CSSProperty.VerticalAlign.TOP)
{
absbounds.y = linebox.getAbsoluteY();
}
else if (valign == CSSProperty.VerticalAlign.BOTTOM)
{
absbounds.y = linebox.getAbsoluteY() + linebox.getMaxBoxHeight() - getHeight();
}
else //other positions -- set during the layout. Relative to the parent content edge.
{
absbounds.y = getParent().getAbsoluteContentY() + bounds.y;
}
//consider the relative position
if (position == POS_RELATIVE)
{
absbounds.x += leftset ? coords.left : (-coords.right);
absbounds.y += topset ? coords.top : (-coords.bottom);
}
//update the width and height according to overflow of the parent
absbounds.width = bounds.width;
absbounds.height = bounds.height;
//repeat for all valid subboxes
for (int i = startChild; i < endChild; i++)
getSubBox(i).absolutePositions();
}
}
/**
* Loads the basic style properties related to the inline elements.
*/
protected void loadInlineStyle()
{
valign = style.getProperty("vertical-align");
if (valign == null) valign = CSSProperty.VerticalAlign.BASELINE;
}
@Override
public void draw(DrawStage turn)
{
if (displayed)
{
if (!this.formsStackingContext())
{
switch (turn)
{
case DRAW_NONINLINE:
case DRAW_FLOAT:
//everything is drawn in the DRAW_INLINE phase as a new stacking context
break;
case DRAW_INLINE:
if (isVisible())
getViewport().getRenderer().renderElementBackground(this);
drawStackingContext(true);
break;
}
}
}
}
//========================================================================
/**
* Recursively finds the baseline of the last in-flow box.
* @param root the element to start search in
* @return The baseline offset in the element content or -1 if there are no in-flow boxes.
*/
private int getLastInlineBoxBaseline(ElementBox root)
{
//find last in-flow box
Box box = null;
for (int i = root.getSubBoxNumber() - 1; i >= 0; i--)
{
box = root.getSubBox(i);
if (box.isInFlow())
break;
else
box = null;
}
if (box != null)
{
if (box instanceof Inline)
{
//System.out.println(box + ":I: " + (box.getContentY() + ((Inline) box).getBaselineOffset()));
return box.getContentY() + ((Inline) box).getBaselineOffset();
}
else
{
//System.out.println(box + ":B: " + (box.getContentY() + getLastInlineBoxBaseline((ElementBox) box)));
return box.getContentY() + getLastInlineBoxBaseline((ElementBox) box);
}
}
else
return -1; //no inline box found
}
}
| 27.773333 | 121 | 0.546135 |
6235f120792aed83ff825abc98fd89d67e55c709 | 2,029 | package br.com.itau.casadocodigo.cadastrocliente.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
@Entity
public class Compra {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Positive
private BigDecimal total;
private BigDecimal totalComDesconto;
@NotNull
@Size(min = 1)
@ElementCollection
private List<Itens> itens;
@OneToOne
@JoinColumn(name = "id")
private Cliente cliente;
@Deprecated
public Compra() {
}
public Compra(@NotNull @Positive BigDecimal total, BigDecimal totalComDesconto, @NotNull @Size(min = 1) List<Itens> itens) {
this.total = total;
this.totalComDesconto = totalComDesconto;
this.itens = itens;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public BigDecimal getTotalComDesconto() {
return totalComDesconto;
}
public void setTotalComDesconto(BigDecimal totalComDesconto) {
this.totalComDesconto = totalComDesconto;
}
public List<Itens> getItens() {
return itens;
}
public void setItens(List<Itens> itens) {
this.itens = itens;
}
//1
public void aplicaDesconto(CupomDesconto cupomDesconto) {
BigDecimal percentualDesconto = cupomDesconto.getPercentualDesconto();
BigDecimal valorDoPercentual = percentualDesconto.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_DOWN);
BigDecimal valorDoDesconto = this.total.multiply(valorDoPercentual).setScale(2, RoundingMode.HALF_DOWN);
this.totalComDesconto = this.total.subtract(valorDoDesconto);
}
}
| 26.012821 | 128 | 0.687531 |
803fbc378adaa03a3ec8e90c3287ad028173145f | 409 | package controller.commands;
import controller.PaymentService;
public class SetPaymentPasswordCommand extends PaymentServiceCommand {
private final String password;
public SetPaymentPasswordCommand(PaymentService receiver, String password) {
super(receiver);
this.password = password;
}
@Override
public void execute() {
receiver.setPassword(password);
}
}
| 22.722222 | 80 | 0.726161 |
fd8c8a2d690b87540362e3ab02f23d5ef5b5c613 | 342 | package l2f.gameserver.listener.actor.door;
import l2f.gameserver.listener.CharListener;
import l2f.gameserver.model.instances.DoorInstance;
/**
* @author VISTALL
* @date 21:03/04.07.2011
*/
public interface OnOpenCloseListener extends CharListener
{
void onOpen(DoorInstance doorInstance);
void onClose(DoorInstance doorInstance);
}
| 21.375 | 57 | 0.795322 |
c5f13db0c2f36c69c2f6683c276b7da4510d6307 | 7,206 | package sc.gys.wcx.and.details;
import android.Manifest;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Build;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import sc.gys.wcx.and.R;
import sc.gys.wcx.and.tools.Configfile;
import java.io.File;
import java.io.FileOutputStream;
@ContentView(R.layout.activity_web_history)
public class WebHistoryActivity extends AppCompatActivity {
@ViewInject(R.id.mWebViewHistory)
WebView mWebView;
private String mType;
private String id;
private String companyName;
private String table;
/* 处理toolbar 开始 version=2 */
/* include 里面的点击事件 */
@ViewInject(R.id.toolbar_callbank)
ImageView mImageView_bank;
@ViewInject(R.id.toolbar_callbank_text)
TextView mBankTextView;
@ViewInject(R.id.mToolbar_text)
TextView mTextView;
/* 处理toolbar 结束 */
@ViewInject(R.id.mHistoryWeb_test_url)
TextView mHistoryWeb_test_url;
String[] mPermissions = new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};
private String mUrl; //再上层适配器中已经做了全地址拼接
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_web_history);
ViewUtils.inject(this);
//权限检查
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
int i = ActivityCompat.checkSelfPermission(this, mPermissions[0]);
if(i != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,mPermissions,1);
}else {
Configfile.Log(this,"您之前拒绝了此权限,请到设置--权限开通系列权限");
}
}
/* 获取父类参数 */
getParment();
/* 设置标题 */
mTextView.setText(table);
/* 检查地址 */
mHistoryWeb_test_url.setText("当前访问地址为:"+mUrl);
Log.e("DATA","WebHistoryActivity >>> "+mUrl+" >>> "+mType);
/* 设置网页基本参数 */
setWebView();
mWebView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Configfile.Log(WebHistoryActivity.this,"当前为长按保存图片和选择打印机");
printPDF();
return true;
}
});
}
/* 返回 */
@OnClick({R.id.toolbar_callbank})
public void oncklinkViewImage(View v){
/* 返回首页需要单位ID参数 */
/* 获取固定xmlId 存储的单位id值 */
SharedPreferences xmlId = getSharedPreferences("xmlId", Context.MODE_PRIVATE);
String xmlIdString = xmlId.getString("id", "0");
Log.e("DATA","haredPreferences()" + xmlIdString);
Intent intent = new Intent(this, SelectDetailsActivity.class);
intent.putExtra("bank_id",3);
intent.putExtra("id",xmlIdString);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
}
/* 返回 */
@OnClick({R.id.toolbar_callbank_text})
public void oncklinkViewTextView(View v){
Intent intent = new Intent(this, SelectDetailsActivity.class);
intent.putExtra("bank_id",3);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent,ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
}
private void setWebView() {
WebSettings webSettings = mWebView.getSettings();
//如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
webSettings.setJavaScriptEnabled(true);
//设置自适应屏幕,两者合用
webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
//其他细节操作
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
webSettings.setAllowFileAccess(true); //设置可以访问文件
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
// TODO: 2018/6/5 加载地址
Log.e("DATA","WebHistoryActivity >>>适配器传递的地址 "+mUrl);
mWebView.loadUrl(mUrl);
}
public void getParment() {
Bundle bundle = getIntent().getExtras();
id = bundle.getString("id");
companyName = bundle.getString("companyName");
table = bundle.getString("table");
mUrl = bundle.getString("url");
}
/* 屏幕长按事件 */
public void printPDF() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = mWebView.createPrintDocumentAdapter();
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
saveImage();
} else {
Toast.makeText(getApplicationContext(), "当前系统不支持该功能", Toast.LENGTH_SHORT).show();
}
}
/**
* 保存图片
*/
public void saveImage() {
Picture picture = mWebView.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
File file = new File("/sdcard/" + "page.jpg");
if(file.exists()){
file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file.getAbsoluteFile());
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
}
}
}
| 34.478469 | 95 | 0.662226 |
b6082c059ba2b118a7e42ef3df43f184fd1d7b9c | 5,467 | package seedu.address.logic.parser.event;
import static seedu.address.commons.core.Messages.MESSAGE_DATE_INVALID;
import static seedu.address.commons.core.Messages.MESSAGE_DATE_START_AFTER_END;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_DATE_1;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_DATE_STRING_1;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_DAYTIME_1;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_END_DATE_1;
import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_1;
import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_3;
import static seedu.address.logic.commands.CommandTestUtil.VALID_DATE_4;
import static seedu.address.logic.commands.CommandTestUtil.VALID_DAYTIME_1;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EVENT_TIME;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseCorrectIndexFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseCorrectIndexSuccess;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseInvalidIndexFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseNegativeIndexFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseNoIndexAndFieldFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseNoIndexFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseZeroIndexFailure;
import static seedu.address.logic.parser.ParserUtil.MESSAGE_INVALID_INDEX;
import static seedu.address.testutil.TypicalEventDates.OCT_19_2019;
import static seedu.address.testutil.TypicalEventDates.OCT_20_2019;
import static seedu.address.testutil.TypicalEventDates.OCT_22_2019;
import static seedu.address.testutil.TypicalEventDayTimes.TIME_0800_TO_1800;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_EVENT;
import org.junit.jupiter.api.Test;
import seedu.address.logic.commands.event.AssignDateCommand;
import seedu.address.model.event.EventDayTime;
class AssignDateCommandParserTest {
private static final String MAP_MUSICAL_WITH_DATE_RANGE = " " + VALID_DATE_1 + VALID_DATE_3 + VALID_DAYTIME_1;
private static final String MAP_MUSICAL_WITH_TARGET_DATE = " " + VALID_DATE_1 + VALID_DAYTIME_1;
private static final String MAP_MUSICAL_WITHOUT_DATE = " " + VALID_DAYTIME_1;
private static final String MESSAGE_INVALID_FORMAT =
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AssignDateCommand.MESSAGE_USAGE);
private AssignDateCommandParser parser = new AssignDateCommandParser();
@Test
void parse_allFieldsPresent_success() {
//target date stated
assertParseCorrectIndexSuccess(parser, MAP_MUSICAL_WITH_TARGET_DATE,
new AssignDateCommand(INDEX_FIRST_EVENT, OCT_20_2019, TIME_0800_TO_1800));
//range stated
assertParseCorrectIndexSuccess(parser, MAP_MUSICAL_WITH_DATE_RANGE,
new AssignDateCommand(INDEX_FIRST_EVENT, OCT_20_2019, OCT_22_2019, TIME_0800_TO_1800));
//date not stated
assertParseCorrectIndexSuccess(parser, MAP_MUSICAL_WITHOUT_DATE,
new AssignDateCommand(INDEX_FIRST_EVENT, TIME_0800_TO_1800));
}
@Test
void parse_invalidArgs_throwsParseException() {
assertParseNoIndexAndFieldFailure(parser, MESSAGE_INVALID_FORMAT);
assertParseNegativeIndexFailure(parser, MAP_MUSICAL_WITH_TARGET_DATE, MESSAGE_INVALID_INDEX);
assertParseZeroIndexFailure(parser, MAP_MUSICAL_WITH_TARGET_DATE, MESSAGE_INVALID_INDEX);
assertParseInvalidIndexFailure(parser, MAP_MUSICAL_WITH_TARGET_DATE, MESSAGE_INVALID_INDEX);
assertParseNoIndexAndFieldFailure(parser, MESSAGE_INVALID_FORMAT);
}
@Test
void parse_compulsoryFieldMissing_failure() {
//missing index
assertParseNoIndexFailure(parser, MAP_MUSICAL_WITH_TARGET_DATE, MESSAGE_INVALID_FORMAT);
//correct index, missing time, have target date
assertParseCorrectIndexFailure(parser, VALID_DATE_1, MESSAGE_INVALID_FORMAT);
//missing start date, have end date
assertParseCorrectIndexFailure(parser, VALID_DATE_3 + VALID_DAYTIME_1, MESSAGE_INVALID_FORMAT);
}
@Test
void parse_invalidValues_throwsParseException() {
//target date is not valid
assertParseCorrectIndexFailure(parser, PREFIX_DATE + INVALID_DATE_1 + VALID_DAYTIME_1,
String.format(MESSAGE_DATE_INVALID, INVALID_DATE_STRING_1));
//start and end date is not valid
assertParseCorrectIndexFailure(parser, PREFIX_DATE + INVALID_DATE_1
+ INVALID_END_DATE_1 + VALID_DAYTIME_1,
String.format(MESSAGE_DATE_INVALID, INVALID_DATE_STRING_1));
//time is not valid
assertParseCorrectIndexFailure(parser, MAP_MUSICAL_WITHOUT_DATE + PREFIX_EVENT_TIME + INVALID_DAYTIME_1,
EventDayTime.MESSAGE_CONSTRAINTS);
//dates and time is valid, but startDate > endDate
assertParseCorrectIndexFailure(parser, PREFIX_DATE + VALID_DATE_1
+ VALID_DATE_4 + VALID_DAYTIME_1,
String.format(MESSAGE_DATE_START_AFTER_END, OCT_20_2019, OCT_19_2019));
}
}
| 54.128713 | 114 | 0.798793 |
b32098cad30fa141ca135995044f87c629db896f | 4,175 | package agentes;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import main.Main;
import modelos.ListaFuncionarios;
import modelos.Tarefa;
import modelos.TarefaStatus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class Testador extends Agent {
private ArrayList<Tarefa> tarefas = new ArrayList<Tarefa>();
private String nome;
public Testador() {
}
protected void setup() {
nome = (String)getArguments()[0];
ACLMessage tarefaMsg = new ACLMessage(ACLMessage.INFORM);
for (Programador p : ListaFuncionarios.getProgramadores()){
tarefaMsg.addReceiver(p.getAID());
}
tarefaMsg.setLanguage("Português");
tarefaMsg.setOntology("Aviso");
tarefaMsg.setContent("Novo Testador");
addBehaviour(new TickerBehaviour(this, Main.delay) {
public void onTick() {
ACLMessage msg = myAgent.receive();
if (msg != null) {
System.out.println(nome +" recebeu nova tarefa");
try {
if (Tarefa.class.isInstance(msg.getContentObject())) {
Tarefa p = (Tarefa) msg.getContentObject();
tarefas.add(p);
System.out.println("Testador "+nome+" recebeu uma nova tarefa!");
} else{
System.out.println("Nao era tarefa");
}
} catch (UnreadableException e) {
System.out.println("Falha ao ler objeto serializado");
e.printStackTrace();
}
}
if (tarefas.size() > 0) {
tarefas.get(0).setTempoTeste(tarefas.get(0).getTempoTeste() + 1);
System.out.println("Testador "+nome + " trabalhou por uma hora na tarefa "+tarefas.get(0).getId() + " restante: "+ (tarefas.get(0).getDuracaoTeste() -tarefas.get(0).getTempoTeste()));
if (tarefas.get(0).getDuracaoTeste() >= tarefas.get(0).getTempoTeste()) {
Random r = new Random();
if (!r.nextBoolean()) {
System.out.println("Testador "+nome+" validou a tarefa "+tarefas.get(0).getId()+" mas havia erros pendentes");
tarefas.get(0).setStatus(TarefaStatus.EM_DESENVOLVIMENTO);
tarefas.get(0).setTempoGasto(0);
// Retornando tarefa para programador
ACLMessage tarefaMsg = new ACLMessage(ACLMessage.INFORM);
tarefaMsg.addReceiver(tarefas.get(0).getProgramador().getAID());
tarefaMsg.setLanguage("Português");
tarefaMsg.setOntology("Aviso");
tarefaMsg.setContent("Nova Tarefa");
try {
tarefaMsg.setContentObject(tarefas.get(0));
} catch (IOException e) {
e.printStackTrace();
}
send(tarefaMsg);
}else{
System.out.println("Testador "+nome+" validou a tarefa "+tarefas.get(0).getId()+ " e ela foi finalizada");
}
tarefas.remove(0);
}
}
}
});
ListaFuncionarios.cadastraTestador(this);
}
protected int getTempoTotalTarefas() {
AtomicInteger duracao = new AtomicInteger();
for (Tarefa tarefa : tarefas) {
duracao.addAndGet(tarefa.getDuracaoTeste() - tarefa.getTempoGasto());
}
return duracao.get();
}
}
| 41.75 | 205 | 0.510659 |
ceb09ea795d60842f453c849817a14ccff681a9d | 1,225 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.diemexplorer.explorer.Repositories;
import com.diemexplorer.explorer.Entities.Transactiondetails;
import java.util.List;
import com.diemexplorer.explorer.Entities.Transactiondetails;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author Msi
*/
@Repository
public interface TransactiondetailsRepository extends CrudRepository<Transactiondetails, Long>{
List<Transactiondetails> findAll();
List<Transactiondetails>findTransactiondetailsByVersion(long version);
@Query(value = "SELECT * FROM Transactiondetails td WHERE td.type='move_abort' ORDER BY td.version Desc LIMIT 10", nativeQuery = true)
List<Transactiondetails> FindLastTenSmartContracts();
@Query (value = "SELECT AVG(td.gas_unit_price) from Transactiondetails td where td.version >=:versionFrom AND td.version <=:versionTo")
float getAverageGasUnitPriceFromTo(long versionFrom, long versionTo);
}
| 36.029412 | 139 | 0.786122 |
71acfdbfc77560c4dd2b87a9ee7ad785d42e5aca | 1,374 | /*
* Copyright (C) 2018 Machine Learning and Data Analytics Lab, Friedrich-Alexander-Universität Erlangen-Nürnberg (FAU).
* <p>
* This file 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. If you reuse
* this code you have to keep or cite this comment.
*/
package de.fau.sensorlib.dataframe;
import de.fau.sensorlib.sensors.AbstractSensor;
/**
* A simple implementation of the SensorDataFrame that contains an int identifier and a double value.
*/
public class SimpleDataFrame extends SensorDataFrame {
int mIdentifier;
double mValue;
/**
* Creates a sensor data frame.
*
* @param fromSensor the sensor from which this data frame originated.
* @param timestamp the timestamp in milliseconds when this data frame was generated on the sensor.
*/
public SimpleDataFrame(AbstractSensor fromSensor, double timestamp, int identifier, double value) {
super(fromSensor, timestamp);
mIdentifier = identifier;
mValue = value;
}
public int getIdentifier() {
return mIdentifier;
}
public double getValue() {
return mValue;
}
@Override
public String toString() {
return "SimpleDataFrame(" + mIdentifier + "; " + mValue + ")";
}
}
| 30.533333 | 119 | 0.694323 |
dc3f630c89f7e8bfa43bad7f9fae32e87e4aa2d2 | 757 | package com.github.sylphlike.framework.security;
/**
* 加解密签名与验密方式
* <p> time 17:56 2010/10/29 星期五 </p>
* <p> email 15923508369@163.com </P>
* @author Gopal.pan
* @version 1.0.0
*/
public enum SecurityTypeEnums {
MD5("MD5"),
AES("AES"),
RSA("RSA"),
SM2("SM2"),
;
SecurityTypeEnums(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static SecurityTypeEnums getByCode(String code) {
for (SecurityTypeEnums securityTypeEnums : SecurityTypeEnums.values()) {
if (securityTypeEnums.getCode().equals(code)) {
return securityTypeEnums;
}
}
return null;
}
}
| 18.925 | 80 | 0.579921 |
78aeed4e0b94597377f767f5b13cfcba1fdf2ae9 | 8,779 | /*
* Copyright 2006-2012 Amazon Technologies, Inc. or its affiliates.
* Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
* of Amazon Technologies, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazon.carbonado.repo.indexed;
import java.util.NoSuchElementException;
import org.apache.commons.logging.LogFactory;
import com.amazon.carbonado.CorruptEncodingException;
import com.amazon.carbonado.Cursor;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.RepositoryException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.Storage;
import com.amazon.carbonado.Transaction;
import com.amazon.carbonado.cursor.AbstractCursor;
import com.amazon.carbonado.cursor.FetchAheadCursor;
import com.amazon.carbonado.spi.RepairExecutor;
import com.amazon.carbonado.synthetic.SyntheticStorableReferenceAccess;
/**
* Wraps another cursor which contains index entries and extracts master
* objects from them.
*
* @author Brian S O'Neill
*/
class IndexedCursor<S extends Storable> extends AbstractCursor<S> {
private static final int FETCH_AHEAD;
static {
String prefix = IndexedCursor.class.getName() + '.';
FETCH_AHEAD = Integer.getInteger(prefix + "fetchAhead", 0);
}
private final Cursor<? extends Storable> mCursor;
private final IndexedStorage<S> mStorage;
private final SyntheticStorableReferenceAccess<S> mAccessor;
private S mNext;
IndexedCursor(Cursor<? extends Storable> indexEntryCursor,
IndexedStorage<S> storage,
SyntheticStorableReferenceAccess<S> indexAccessor)
{
if (FETCH_AHEAD > 0) {
indexEntryCursor = new FetchAheadCursor(indexEntryCursor, FETCH_AHEAD);
}
mCursor = indexEntryCursor;
mStorage = storage;
mAccessor = indexAccessor;
}
public void close() throws FetchException {
mCursor.close();
}
public boolean hasNext() throws FetchException {
if (mNext != null) {
return true;
}
try {
while (mCursor.hasNext()) {
final Storable indexEntry = mCursor.next();
S master = mStorage.mMasterStorage.prepare();
mAccessor.copyToMasterPrimaryKey(indexEntry, master);
try {
if (!master.tryLoad()) {
LogFactory.getLog(getClass()).warn
("Master is missing for index entry: " + indexEntry);
continue;
}
} catch (CorruptEncodingException e) {
LogFactory.getLog(getClass()).error
("Master record for index entry is corrupt: " + indexEntry, e);
continue;
}
if (mAccessor.isConsistent(indexEntry, master)) {
mNext = master;
return true;
}
// This index entry is stale. Repair is needed.
// Insert a correct index entry, just to be sure.
try {
final IndexedRepository repo = mStorage.mRepository;
final Storage<?> indexEntryStorage =
repo.getIndexEntryStorageFor(mAccessor.getReferenceClass());
Storable newIndexEntry = indexEntryStorage.prepare();
mAccessor.copyFromMaster(newIndexEntry, master);
if (newIndexEntry.tryLoad()) {
// Good, the correct index entry exists. We'll see
// the master record eventually, so skip.
} else {
// We have no choice but to return the master, at
// the risk of seeing it multiple times. This is
// better than seeing it never.
LogFactory.getLog(getClass()).warn
("Inconsistent index entry: " + indexEntry + ", " + master);
mNext = master;
}
// Repair the stale index entry.
RepairExecutor.execute(new Runnable() {
public void run() {
Transaction txn = repo.enterTransaction();
try {
// Reload master and verify inconsistency.
S master = mStorage.mMasterStorage.prepare();
mAccessor.copyToMasterPrimaryKey(indexEntry, master);
if (master.tryLoad()) {
Storable newIndexEntry = indexEntryStorage.prepare();
mAccessor.copyFromMaster(newIndexEntry, master);
newIndexEntry.tryInsert();
indexEntry.tryDelete();
txn.commit();
}
} catch (FetchException fe) {
LogFactory.getLog(IndexedCursor.class).warn
("Unable to check if repair required for " +
"inconsistent index entry " +
indexEntry, fe);
} catch (PersistException pe) {
LogFactory.getLog(IndexedCursor.class).error
("Unable to repair inconsistent index entry " +
indexEntry, pe);
} finally {
try {
txn.exit();
} catch (PersistException pe) {
LogFactory.getLog(IndexedCursor.class).error
("Unable to repair inconsistent index entry " +
indexEntry, pe);
}
}
}
});
} catch (Exception re) {
LogFactory.getLog(getClass()).error
("Unable to inspect inconsistent index entry " +
indexEntry, re);
}
if (mNext != null) {
return true;
}
}
} catch (NoSuchElementException e) {
} catch (FetchException e) {
try {
close();
} catch (Exception e2) {
// Don't care.
}
throw e;
}
return false;
}
public S next() throws FetchException {
try {
if (hasNext()) {
S next = mNext;
mNext = null;
return next;
}
} catch (FetchException e) {
try {
close();
} catch (Exception e2) {
// Don't care.
}
throw e;
}
throw new NoSuchElementException();
}
@Override
public int skipNext(int amount) throws FetchException {
try {
if (mNext == null) {
return mCursor.skipNext(amount);
}
if (amount <= 0) {
if (amount < 0) {
throw new IllegalArgumentException("Cannot skip negative amount: " + amount);
}
return 0;
}
mNext = null;
return 1 + mCursor.skipNext(amount - 1);
} catch (FetchException e) {
try {
close();
} catch (Exception e2) {
// Don't care.
}
throw e;
}
}
}
| 38.004329 | 98 | 0.490603 |
2ec7e0c2de1944274b2b36e1dfaa11d9e4236448 | 7,153 | package com.zdj.miaoshaproject.controller;
import com.google.common.util.concurrent.RateLimiter;
import com.zdj.miaoshaproject.controller.viewobject.OrderVO;
import com.zdj.miaoshaproject.mq.MqProducer;
import com.zdj.miaoshaproject.service.ItemService;
import com.zdj.miaoshaproject.service.OrderService;
import com.zdj.miaoshaproject.error.BusinessException;
import com.zdj.miaoshaproject.error.EmBusinessError;
import com.zdj.miaoshaproject.response.CommonReturnType;
import com.zdj.miaoshaproject.service.PromoService;
import com.zdj.miaoshaproject.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.*;
@Controller("order")
@RequestMapping("/order")
@CrossOrigin(origins = {"*"},allowCredentials = "true")
public class OrderController extends BaseController {
@Autowired
private OrderService orderService;
@Autowired
private HttpServletRequest httpServletRequest;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private MqProducer mqProducer;
@Autowired
private ItemService itemService;
@Autowired
private PromoService promoService;
private ExecutorService executorService;
private RateLimiter orderCreateRateLimiter;
@PostConstruct
public void init(){
executorService = Executors.newFixedThreadPool(20);
orderCreateRateLimiter = RateLimiter.create(300);
}
// //生成验证码
// @RequestMapping(value = "/generateverifycode",method = {RequestMethod.GET,RequestMethod.POST})
// @ResponseBody
// public void generateverifycode(HttpServletResponse response) throws BusinessException, IOException {
// String token = httpServletRequest.getParameterMap().get("token")[0];
// if(StringUtils.isEmpty(token)){
// throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能生成验证码");
// }
// UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
// if(userModel == null){
// throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能生成验证码");
// }
//
// Map<String,Object> map = CodeUtil.generateCodeAndPic();
//
// redisTemplate.opsForValue().set("verify_code_"+userModel.getId(),map.get("code"));
// redisTemplate.expire("verify_code_"+userModel.getId(),10,TimeUnit.MINUTES);
//
// ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", response.getOutputStream());
//
//
// }
//生成秒杀令牌
@RequestMapping(value = "/generatetoken",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
@ResponseBody
public CommonReturnType generatetoken(@RequestParam(name="itemId")Integer itemId,
@RequestParam(name="promoId")Integer promoId,
@RequestParam(name="token")String token) throws BusinessException {
//根据token获取用户信息
//获取用户的登陆信息
UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
if(userModel == null){
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能下单");
}
if (promoId != null) {
//获取秒杀访问令牌
String promoToken = promoService.generateSecondKillToken(promoId,itemId,userModel.getId());
if(promoToken == null){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"生成令牌失败");
}
//返回对应的结果
return CommonReturnType.create(promoToken);
}
return CommonReturnType.create(11);
}
//封装下单请求
@RequestMapping(value = "/createorder",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
@ResponseBody
public CommonReturnType createOrder(@RequestParam(name="itemId")Integer itemId,
@RequestParam(name="amount")Integer amount,
@RequestParam(name="promoId",required = false)Integer promoId,
@RequestParam(name="promoToken",required = false)String promoToken) throws BusinessException {
if(!orderCreateRateLimiter.tryAcquire()){
throw new BusinessException(EmBusinessError.RATELIMIT);
}
String token = httpServletRequest.getParameterMap().get("token")[0];
if(StringUtils.isEmpty(token)){
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能下单");
}
//获取用户的登陆信息
UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
if(userModel == null){
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能下单");
}
//校验秒杀令牌是否正确
if(promoId != null && promoToken != "11"){
String inRedisPromoToken = (String) redisTemplate.opsForValue().get("promo_token_"+promoId+"_userid_"+userModel.getId()+"_itemid_"+itemId);
if(inRedisPromoToken == null){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"秒杀令牌校验失败");
}
if(!org.apache.commons.lang3.StringUtils.equals(promoToken,inRedisPromoToken)){
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"秒杀令牌校验失败");
}
}
//同步调用线程池的submit方法
//拥塞窗口为20的等待队列,用来队列化泄洪
Future<Object> future = executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
//加入库存流水init状态
String stockLogId = itemService.initStockLog(itemId,amount);
//再去完成对应的下单事务型消息机制
if(!mqProducer.transactionAsyncReduceStock(userModel.getId(),itemId,promoId,amount,stockLogId)){
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"下单失败");
}
return null;
}
});
try {
future.get();
} catch (InterruptedException e) {
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
} catch (ExecutionException e) {
throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
}
return CommonReturnType.create(null);
}
//商品列表页面浏览
@RequestMapping(value = "/getOrders",method = {RequestMethod.GET})
@ResponseBody
public CommonReturnType listOrders(@RequestParam("token") String token) throws BusinessException {
UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
if(userModel == null){
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登陆,不能下单");
}
List<OrderVO> orders = orderService.getOrder(userModel.getId());
return CommonReturnType.create(orders);
}
}
| 39.519337 | 151 | 0.672305 |
2b13a2ebfc9a95b00a417f909d386a2e75c07dc5 | 10,483 | package com.javafee.mainform;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Comparator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import com.javafee.common.Constans.Context;
import com.javafee.common.Params;
import com.javafee.common.SystemProperties;
import com.javafee.common.Utils;
import com.javafee.common.Validator;
import com.javafee.exception.LogGuiException;
import com.javafee.exception.RefusedRegistrationException;
import com.javafee.hibernate.dao.HibernateDao;
import com.javafee.hibernate.dao.HibernateUtil;
import com.javafee.hibernate.dto.association.City;
import com.javafee.hibernate.dto.common.Address;
import com.javafee.hibernate.dto.common.User;
import com.javafee.hibernate.dto.eeatery.Worker;
import com.javafee.mainform.frames.WorkerAddFrame;
import com.javafee.model.WorkerTableModel;
import com.javafee.startform.LogInEvent;
import com.javafee.startform.RegistrationEvent;
public class WorkerAddEvent {
private WorkerAddFrame workerAddModFrame;
private RegistrationEvent registrationEvent;
private WorkerTableModel workerTableModel;
public void control(Context context, WorkerTableModel workerTableModel) {
this.workerTableModel = workerTableModel;
openWorkerAddModFrame(context);
workerAddModFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
Params.getInstance().remove("selectedRowIndex");
Params.getInstance().remove("selectedWorker");
}
});
workerAddModFrame.getCockpitConfirmationPanel().getBtnAccept()
.addActionListener(e -> onClickBtnAccept(context));
}
private void onClickBtnAccept(Context context) {
if (context == Context.ADDITION) {
if (validateRegistration())
registerNow();
} else if (context == Context.MODIFICATION) {
modificateClient();
}
}
private void modificateClient() {
Worker workerShallowClone = (Worker) Params.getInstance().get("selectedWorker");
workerShallowClone.setName(workerAddModFrame.getWorkerDataPanel().getTextFieldName().getText());
workerShallowClone.setSurname(workerAddModFrame.getWorkerDataPanel().getTextFieldSurname().getText());
Address address = new Address();
address.setCity((City) workerAddModFrame.getWorkerDataPanel().getComboBoxCity().getSelectedItem());
address.setStreet(workerAddModFrame.getWorkerDataPanel().getTextFieldAddress().getText());
workerShallowClone.setAddress(address);
workerShallowClone.setEMail(workerAddModFrame.getWorkerDataPanel().getTextFieldEMail().getText());
workerShallowClone.setLogin(workerAddModFrame.getWorkerDataPanel().getTextFieldLogin().getText());
if (Validator.validateClientUpdate(workerShallowClone)) {
HibernateUtil.beginTransaction();
HibernateUtil.getSession()
.evict(workerTableModel.getWorker((Integer) Params.getInstance().get("selectedRowIndex")));
HibernateUtil.getSession().update(Worker.class.getName(), workerShallowClone);
HibernateUtil.commitTransaction();
workerTableModel.setWorker((Integer) Params.getInstance().get("selectedRowIndex"), workerShallowClone);
workerTableModel.fireTableDataChanged();
Utils.displayOptionPane(
SystemProperties.getInstance().getResourceBundle()
.getString("workerAddModEvent.updatingWorkerSuccess"),
SystemProperties.getInstance().getResourceBundle().getString(
"workerAddModEvent.updatingWorkerSuccessTitle"),
JOptionPane.INFORMATION_MESSAGE);
Params.getInstance().remove("selectedWorker");
Params.getInstance().remove("selectedRowIndex");
workerAddModFrame.dispose();
} else {
Utils.displayOptionPane(
SystemProperties.getInstance().getResourceBundle()
.getString("clientAddModEvent.updatingClientError"),
SystemProperties.getInstance().getResourceBundle()
.getString("clientAddModEvent.updatingClientErrorTitle"),
JOptionPane.ERROR_MESSAGE);
}
}
private void openWorkerAddModFrame(Context context) {
if (workerAddModFrame == null || (workerAddModFrame != null && !workerAddModFrame.isDisplayable())) {
workerAddModFrame = new WorkerAddFrame();
if (context == Context.MODIFICATION) {
workerAddModFrame.getWorkerDataPanel().getLblPassword().setVisible(false);
workerAddModFrame.getWorkerDataPanel().getPasswordField().setVisible(false);
reloadRegistrationPanel();
}
reloadComboBoxCity();
workerAddModFrame.setVisible(true);
} else {
workerAddModFrame.toFront();
}
}
private void reloadRegistrationPanel() {
reloadComboBoxCity();
fillRegistrationPanel();
}
private void reloadComboBoxCity() {
DefaultComboBoxModel<City> comboBoxCityModel = new DefaultComboBoxModel<City>();
HibernateDao<City, Integer> city = new HibernateDao<City, Integer>(City.class);
List<City> cityListToSort = city.findAll();
cityListToSort.sort(Comparator.comparing(City::getName, Comparator.nullsFirst(Comparator.naturalOrder())));
cityListToSort.forEach(c -> comboBoxCityModel.addElement(c));
workerAddModFrame.getWorkerDataPanel().getComboBoxCity().setModel(comboBoxCityModel);
}
private void fillRegistrationPanel() {
workerAddModFrame.getWorkerDataPanel().getTextFieldLogin()
.setText(((Worker) Params.getInstance().get("selectedWorker")).getLogin() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getLogin().toString()
: "");
workerAddModFrame.getWorkerDataPanel().getTextFieldEMail()
.setText(((Worker) Params.getInstance().get("selectedWorker")).getEMail() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getEMail().toString()
: "");
workerAddModFrame.getWorkerDataPanel().getTextFieldName()
.setText(((Worker) Params.getInstance().get("selectedWorker")).getName() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getName().toString()
: "");
workerAddModFrame.getWorkerDataPanel().getTextFieldSurname()
.setText(((Worker) Params.getInstance().get("selectedWorker")).getSurname() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getSurname().toString()
: "");
workerAddModFrame.getWorkerDataPanel().getTextFieldAddress()
.setText(((Worker) Params.getInstance().get("selectedWorker")).getAddress() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getAddress().getStreet().toString()
: "");
workerAddModFrame.getWorkerDataPanel().getComboBoxCity().getModel()
.setSelectedItem(((Worker) Params.getInstance().get("selectedWorker")).getAddress().getCity() != null
? ((Worker) Params.getInstance().get("selectedWorker")).getAddress().getCity()
: null);
}
@SuppressWarnings("unchecked")
private void registerNow() {
try {
RegistrationEvent.forceClearRegistrationEvenet();
boolean result = true;
List<User> ud = HibernateUtil.getSession().createQuery("from User").list();
for (User u : ud) {
if (u.getLogin() != null
&& u.getLogin().equals(workerAddModFrame.getWorkerDataPanel().getTextFieldLogin().getText()))
result = false;
}
if (result) {
registrationEvent = RegistrationEvent.getInstance(
workerAddModFrame.getWorkerDataPanel().getTextFieldName().getText(),
workerAddModFrame.getWorkerDataPanel().getTextFieldSurname().getText(),
workerAddModFrame.getWorkerDataPanel().getTextFieldAddress().getText(),
(City) workerAddModFrame.getWorkerDataPanel().getComboBoxCity().getSelectedItem(),
workerAddModFrame.getWorkerDataPanel().getTextFieldLogin().getText(),
workerAddModFrame.getWorkerDataPanel().getTextFieldEMail().getText(),
String.valueOf(workerAddModFrame.getWorkerDataPanel().getPasswordField().getPassword()),
LogInEvent.getRole());
workerTableModel.add((Worker) RegistrationEvent.user);
workerAddModFrame.dispose();
} else {
Utils.displayOptionPane(
SystemProperties.getInstance().getResourceBundle().getString("workerAddModEvent.existingLogin"),
SystemProperties.getInstance().getResourceBundle()
.getString("workerAddModEvent.existingLoginTitle"),
JOptionPane.ERROR_MESSAGE);
}
} catch (RefusedRegistrationException e) {
StringBuilder errorBuilder = new StringBuilder();
if (Params.getInstance().get("ALREADY_REGISTERED") != null) {
errorBuilder.append(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationError5"));
Params.getInstance().remove("ALREADY_REGISTERED");
}
if (Params.getInstance().get("PARAMETERS_ERROR") != null) {
errorBuilder.append(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationError6"));
}
if (Params.getInstance().get("WEAK_PASSWORD") != null) {
errorBuilder.append(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationError7"));
}
if (Params.getInstance().get("INCORRECT_BIRTH_DATE") != null) {
errorBuilder.append(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationError9"));
}
LogGuiException.logError(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationErrorTitle"),
errorBuilder.toString(), e);
clearRegistrationFailsInParams();
}
if (registrationEvent != null)
Utils.displayOptionPane(
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationSuccess2"),
SystemProperties.getInstance().getResourceBundle().getString("startForm.registrationSuccess2Title"),
JOptionPane.INFORMATION_MESSAGE);
}
private void clearRegistrationFailsInParams() {
Params.getInstance().remove("ALREADY_REGISTERED");
Params.getInstance().remove("PARAMETERS_ERROR");
Params.getInstance().remove("WEAK_PASSWORD");
Params.getInstance().remove("INCORRECT_BIRTH_DATE");
}
private boolean validateRegistration() {
boolean result = false;
if (workerAddModFrame.getWorkerDataPanel().getTextFieldLogin().getText().isEmpty()
|| workerAddModFrame.getWorkerDataPanel().getPasswordField().getPassword().length == 0)
JOptionPane.showMessageDialog(workerAddModFrame,
SystemProperties.getInstance().getResourceBundle()
.getString("startForm.validateRegistrationError8"),
SystemProperties.getInstance().getResourceBundle()
.getString("startForm.validateRegistrationError8Title"),
JOptionPane.ERROR_MESSAGE);
else
result = true;
return result;
}
} | 40.789883 | 109 | 0.757512 |
eff14d43e95a0be52dd809e071bbf45cada767a0 | 2,238 | package graphing.model.settings;
import java.awt.*;
public class MarkerSettings extends GraphicalSettings {
private int size;
private boolean filled;
private LineSettings border;
private ShapeType shapeType;
private boolean unique;
public MarkerSettings() {
this(true);
unique = false;
}
public MarkerSettings(boolean show) {
this(Color.BLACK, new LineSettings(), 5, true, ShapeType.SQUARE, false);
}
public MarkerSettings(Color fillColour) {
this(fillColour, new LineSettings(false));
}
public MarkerSettings(Color fillColour, LineSettings border) {
this(fillColour, border, 5, true);
}
public MarkerSettings(Color fillColour, int size, ShapeType shape) {
this(fillColour, new LineSettings(), size, true, shape, true);
}
public MarkerSettings(Color fillColour, LineSettings border, int size, boolean filled) {
this(fillColour, border, size, filled, ShapeType.CIRCLE, true);
}
public MarkerSettings(Color fillColour, LineSettings border, int size, boolean filled, ShapeType shape, boolean show) {
super(fillColour, show);
this.filled = filled;
this.border = border;
this.shapeType = shape;
this.size = size;
unique = true;
}
public Color getFillColour() {
return getColour();
}
public void setFillColour(Color fillColour) {
setColour(fillColour);
unique = true;
}
public LineSettings getBorder() {
return border;
}
public void setBorder(LineSettings border) {
this.border = border;
unique = true;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
unique = true;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
unique = true;
}
public ShapeType getShapeType() {
return shapeType;
}
public void setShapeType(ShapeType shapeType) {
this.shapeType = shapeType;
unique = true;
}
public boolean isUnique() {
return unique;
}
}
| 23.557895 | 123 | 0.623771 |
213a49267ebd42ff561f77c9dbc5a3eecd964d26 | 2,347 | package com.koi.ring.mvp.fragment;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.koi.ring.R;
import com.koi.ring.base.BaseFragment;
import com.koi.ring.mvp.adapter.HomeSearchMerchantAdapter;
import com.koi.ring.mvp.contract.HomeMerchantContract;
import com.koi.ring.mvp.model.HomeMerchantModel;
import com.koi.ring.mvp.presenter.HomeMerchantPresenter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import butterknife.BindView;
/**
* @Author PoQiao
* 邮箱:116
* 创建时间: 2019/9/26
*/
public class HomeMerchantFragment extends BaseFragment<HomeMerchantPresenter> implements HomeMerchantContract.IView {
@BindView(R.id.rab_amount)
RadioButton rabAmount;
@BindView(R.id.rab_score)
RadioButton rabScore;
@BindView(R.id.rab_distance)
RadioButton rabDistance;
@BindView(R.id.rag_choose)
RadioGroup ragChoose;
@BindView(R.id.rv_data)
RecyclerView rvData;
@BindView(R.id.ll_no)
LinearLayout llNo;
@BindView(R.id.nested_view)
NestedScrollView nestedView;
private HomeSearchMerchantAdapter mAdapter;
@Override
protected HomeMerchantPresenter initPresenter() {
return new HomeMerchantPresenter(this, new HomeMerchantModel(this));
}
@Override
protected int setLayoutId() {
return R.layout.fragment_home_merchant;
}
@Override
public void doMore(Bundle savedInstanceState) {
List<String> list = new ArrayList<>();
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
list.add("AA");
mAdapter = new HomeSearchMerchantAdapter(list);
rvData.setLayoutManager(new LinearLayoutManager(getContext()));
rvData.setAdapter(mAdapter);
}
@Override
public void showDialog() {
}
@Override
public void dismissDialog() {
}
}
| 25.791209 | 117 | 0.692373 |
a2abb48d449dcc1fe5b0cba1fb13a25003a83c3f | 17,346 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.coeus.propdev.impl.auth;
import org.kuali.coeus.propdev.impl.auth.task.ProposalTask;
import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocument;
import org.kuali.coeus.propdev.impl.state.ProposalState;
import org.kuali.coeus.sys.framework.auth.KcTransactionalDocumentAuthorizerBase;
import org.kuali.coeus.sys.framework.auth.task.ApplicationTask;
import org.kuali.coeus.sys.framework.auth.task.TaskAuthorizationService;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.coeus.common.budget.framework.core.BudgetParentDocument;
import org.kuali.coeus.common.budget.framework.version.BudgetDocumentVersion;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.coeus.propdev.impl.attachment.Narrative;
import org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kns.authorization.AuthorizationConstants;
import org.kuali.rice.krad.document.Document;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* The Proposal Development Document Authorizer. Primarily responsible for determining if
* a user has permission to create/modify/view proposals.
*
* @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
*/
public class ProposalDevelopmentDocumentAuthorizer extends KcTransactionalDocumentAuthorizerBase {
private TaskAuthorizationService taskAuthenticationService;
protected TaskAuthorizationService getTaskAuthenticationService (){
if (taskAuthenticationService == null)
taskAuthenticationService = KcServiceLocator.getService(TaskAuthorizationService.class);
return taskAuthenticationService;
}
public Set<String> getEditModes(Document document, Person user, Set<String> currentEditModes) {
Set<String> editModes = new HashSet<String>();
ProposalDevelopmentDocument proposalDoc = (ProposalDevelopmentDocument) document;
String proposalNbr = proposalDoc.getDevelopmentProposal().getProposalNumber();
// The getEditMode() method is invoked when a proposal is accessed for creation and when it
// is accessed for modification. New proposals under creation don't have a proposal number.
// For a new proposal, we have to know if the user has the permission to create a proposal.
// For a current proposal, we have to know if the user the permission to modify or view the proposal.
String userId = user.getPrincipalId();
if (proposalNbr == null) {
if (canCreateProposal(user)) {
editModes.add(AuthorizationConstants.EditMode.FULL_ENTRY);
setPermissions(userId, proposalDoc, editModes);
}
else {
editModes.add(AuthorizationConstants.EditMode.UNVIEWABLE);
}
}
else {
if (canEdit(document, user)) {
editModes.add(AuthorizationConstants.EditMode.FULL_ENTRY);
setPermissions(userId, proposalDoc, editModes);
}
else if (canExecuteProposalTask(userId, proposalDoc, TaskName.VIEW_PROPOSAL)) {
editModes.add(AuthorizationConstants.EditMode.VIEW_ONLY);
setPermissions(userId, proposalDoc, editModes);
}
else {
editModes.add(AuthorizationConstants.EditMode.UNVIEWABLE);
}
if (isBudgetComplete(proposalDoc)) {
if (editModes.contains("addBudget")) {
editModes.add("modifyCompletedBudgets");
}
editModes.remove("modifyProposalBudget");
editModes.remove("addBudget");
}
}
return editModes;
}
/**
* Set the permissions to be used during the creation of the web pages.
* The JSP files can access the editModeMap (editingMode) to determine what
* to display to the user. For example, a JSP file may contain the following:
*
* <kra:section permission="modifyProposal">
* .
* .
* .
* </kra:section>
*
* In the above example, the contents are only rendered if the user is allowed
* to modify the proposal. Note that permissions are always signified as
* either TRUE or FALSE.
*
* @param userId the user's unique username
* @param doc the Proposal Development Document
* @param editModes the edit mode map
*/
private void setPermissions(String userId, ProposalDevelopmentDocument doc, Set<String> editModes) {
if (editModes.contains(AuthorizationConstants.EditMode.FULL_ENTRY)) {
editModes.add("modifyProposal");
}
if (canExecuteTask(userId, doc, TaskName.ADD_BUDGET)) {
editModes.add("addBudget");
}
if (canExecuteTask(userId, doc, TaskName.OPEN_BUDGETS)) {
editModes.add("openBudgets");
}
if (canExecuteTask(userId, doc, TaskName.MODIFY_BUDGET)) {
editModes.add("modifyProposalBudget");
}
if (canExecuteTask(userId, doc, TaskName.MODIFY_PROPOSAL_ROLES)) {
editModes.add("modifyPermissions");
}
if (canExecuteTask(userId, doc, TaskName.ADD_NARRATIVE)) {
editModes.add("addNarratives");
}
if (canExecuteTask(userId, doc, TaskName.CERTIFY)) {
editModes.add("certify");
}
if (canExecuteTask(userId, doc, TaskName.MODIFY_NARRATIVE_STATUS)) {
editModes.add("modifyNarrativeStatus");
}
if (canExecuteTask(userId, doc, TaskName.PRINT_PROPOSAL)) {
editModes.add("printProposal");
}
if (canExecuteTask(userId, doc, TaskName.ALTER_PROPOSAL_DATA)) {
editModes.add("alterProposalData");
}
if (canExecuteTask(userId, doc, TaskName.SHOW_ALTER_PROPOSAL_DATA)) {
editModes.add("showAlterProposalData");
}
if (canExecuteTask(userId, doc, TaskName.SUBMIT_TO_SPONSOR)) {
editModes.add("submitToSponsor");
}
if (canExecuteTask(userId, doc, TaskName.MAINTAIN_PROPOSAL_HIERARCHY)) {
editModes.add("maintainProposalHierarchy");
}
if (canExecuteTask(userId, doc, TaskName.REJECT_PROPOSAL)) {
editModes.add(TaskName.REJECT_PROPOSAL);
}
setNarrativePermissions(userId, doc, editModes);
}
private void setNarrativePermissions(String userId, ProposalDevelopmentDocument doc, Set<String> editModes) {
List<Narrative> narratives = doc.getDevelopmentProposal().getNarratives();
for (Narrative narrative : narratives) {
String prefix = "proposalAttachment." + narrative.getModuleNumber() + ".";
if (narrative.getDownloadAttachment(userId)) {
editModes.add(prefix + "download");
}
if (narrative.getReplaceAttachment(userId)) {
editModes.add(prefix + "replace");
}
if (narrative.getDeleteAttachment(userId)) {
editModes.add(prefix + "delete");
}
if (narrative.getModifyAttachmentStatus(userId)) {
editModes.add(prefix + "modifyStatus");
}
if (narrative.getModifyNarrativeRights(userId)) {
editModes.add(prefix + "modifyRights");
}
}
narratives = doc.getDevelopmentProposal().getInstituteAttachments();
for (Narrative narrative : narratives) {
String prefix = "instituteAttachment." + narrative.getModuleNumber() + ".";
if (narrative.getDownloadAttachment(userId)) {
editModes.add(prefix + "download");
}
if (narrative.getReplaceAttachment(userId) ) {
editModes.add(prefix + "replace");
}
if (narrative.getDeleteAttachment(userId)) {
editModes.add(prefix + "delete");
}
if (narrative.getModifyNarrativeRights(userId)) {
editModes.add(prefix + "modifyRights");
}
}
int i = 0;
boolean canReplace = getTaskAuthorizationService().isAuthorized(userId, new ProposalTask(TaskName.REPLACE_PERSONNEL_ATTACHMENT, doc));
for (ProposalPersonBiography ppb : doc.getDevelopmentProposal().getPropPersonBios()) {
ppb.setPositionNumber(i);
String prefix = "biographyAttachments." + ppb.getPositionNumber() + ".";
if (canReplace) {
editModes.add(prefix + "replace");
}
i++;
}
}
/**
* Can the user execute the given task?
* @param userId the user's username
* @param doc the proposal development document
* @param taskName the name of the task
* @return "TRUE" if has permission; otherwise "FALSE"
*/
private boolean canExecuteTask(String userId, ProposalDevelopmentDocument doc, String taskName) {
return canExecuteProposalTask(userId, doc, taskName);
}
/**
* Does the user have the given permission for the given proposal?
* @param userId the user's username
* @param doc the proposal development document
* @param taskName the name of the task
* @return true if has permission; otherwise false
*/
private boolean canExecuteProposalTask(String userId, ProposalDevelopmentDocument doc, String taskName) {
ProposalTask task = new ProposalTask(taskName, doc);
TaskAuthorizationService taskAuthenticationService = getTaskAuthenticationService();
return taskAuthenticationService.isAuthorized(userId, task);
}
public boolean canInitiate(String documentTypeName, Person user) {
return canCreateProposal(user);
}
public boolean canOpen(Document document, Person user) {
ProposalDevelopmentDocument proposalDocument = (ProposalDevelopmentDocument) document;
if (proposalDocument.getDevelopmentProposal().getProposalNumber() == null) {
return canCreateProposal(user);
}
return canExecuteProposalTask(user.getPrincipalId(), proposalDocument, TaskName.VIEW_PROPOSAL);
}
/**
* Does the user have permission to create a proposal. Use the Unit Authorization Service to determine
* if the user has the CREATE_PROPOSAL permission in any unit.
* @param user the user
* @return true if the user has the CREATE_PROPOSAL permission in at least one unit; otherwise false
*/
private boolean canCreateProposal(Person user) {
ApplicationTask task = new ApplicationTask(TaskName.CREATE_PROPOSAL);
TaskAuthorizationService taskAuthenticationService = getTaskAuthenticationService();
return taskAuthenticationService.isAuthorized(user.getPrincipalId(), task);
}
@Override
public boolean canEdit(Document document, Person user) {
ProposalDevelopmentDocument proposalDocument = (ProposalDevelopmentDocument) document;
String proposalStateTypeCode = "";
if (proposalDocument.getDevelopmentProposal().getProposalState() != null){
proposalStateTypeCode = proposalDocument.getDevelopmentProposal().getProposalState().getCode();
}
if(proposalStateTypeCode.equalsIgnoreCase(ProposalState.CANCELED) || proposalStateTypeCode.equalsIgnoreCase(ProposalState.DISAPPROVED)){
return false;
}
return canExecuteProposalTask(user.getPrincipalId(), (ProposalDevelopmentDocument) document, TaskName.MODIFY_PROPOSAL);
}
@Override
public boolean canSave(Document document, Person user) {
return canEdit(document, user);
}
@Override
public boolean canCancel(Document document, Person user) {
return canEdit(document, user) && super.canCancel(document, user);
}
@Override
public boolean canReload(Document document, Person user) {
WorkflowDocument workflow = document.getDocumentHeader().getWorkflowDocument();
return canEdit(document, user) && !workflow.isInitiated() || workflow.isCanceled();
}
@Override
public boolean canRoute(Document document, Person user) {
return canExecuteProposalTask(user.getPrincipalId(), (ProposalDevelopmentDocument) document, TaskName.SUBMIT_TO_WORKFLOW) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canAnnotate(Document document, Person user) {
return canRoute(document, user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canCopy(Document document, Person user) {
return false;
}
@Override
public boolean canApprove( Document document, Person user ) {
return super.canApprove(document,user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canDisapprove( Document document, Person user ) {
return super.canDisapprove(document, user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canBlanketApprove( Document document, Person user ) {
WorkflowDocument workflowDocument = document.getDocumentHeader().getWorkflowDocument();
return workflowDocument.isEnroute() && super.canBlanketApprove(document, user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canAcknowledge( Document document, Person user ) {
return super.canAcknowledge(document, user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_ACKNOWLEDGE_ACTION);
}
protected boolean isBudgetComplete(BudgetParentDocument parentDocument) {
if (!parentDocument.isComplete()) {
return false;
}
for (BudgetDocumentVersion budgetVersion: parentDocument.getBudgetDocumentVersions()) {
if (budgetVersion.getBudgetVersionOverview().isFinalVersionFlag()) {
return true;
}
}
return false;
}
@Override
public boolean canAddNoteAttachment(Document document, String attachmentTypeCode, Person user) {
return canExecuteProposalTask(user.getPrincipalId(), (ProposalDevelopmentDocument) document, TaskName.PROPOSAL_ADD_NOTE_ATTACHMENT);
}
@Override
public boolean canDeleteNoteAttachment(Document document, String attachmentTypeCode, String createdBySelfOnly, Person user) {
boolean retVal = false;
Boolean allowNotesDeletion = getParameterService().getParameterValueAsBoolean(ProposalDevelopmentDocument.class, KeyConstants.ALLOW_PROPOSAL_DEVELOPMENT_NOTES_DELETION);
if(allowNotesDeletion != null && allowNotesDeletion) {
retVal = super.canDeleteNoteAttachment(document, attachmentTypeCode, createdBySelfOnly, user);
}
return retVal;
}
@Override
public boolean canViewNoteAttachment(Document document, String attachmentTypeCode, Person user) {
return canExecuteProposalTask(user.getPrincipalId(), (ProposalDevelopmentDocument) document, TaskName.VIEW_PROPOSAL);
}
@Override
public boolean canFyi( Document document, Person user ) {
return super.canFyi(document, user) && canExecuteProposalTask( user.getPrincipalName(), (ProposalDevelopmentDocument)document, TaskName.PROPOSAL_HIERARCHY_CHILD_WORKFLOW_ACTION);
}
@Override
public boolean canSendNoteFyi(Document document, Person user) {
return false;
}
@Override
public boolean canRecall(Document document, Person user) {
return canExecuteProposalTask(user.getPrincipalId(), (ProposalDevelopmentDocument)document, TaskName.RECALL_PROPOSAL);
}
}
| 44.25 | 272 | 0.678312 |
f702083f49eaa60e1307a8b5ca37f28899cb04af | 4,016 | package io.onedev.server.web.page.project.blob.render.renderers.folder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.AbstractResource;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.onedev.server.OneDev;
import io.onedev.server.model.Project;
import io.onedev.server.persistence.dao.Dao;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.util.DateUtils;
import io.onedev.server.web.avatar.AvatarManager;
import io.onedev.server.web.page.project.commits.CommitDetailPage;
import io.onedev.server.web.util.ReferenceTransformer;
/**
* Loading commits of children may take some time, and we do this via resource loading to avoid blocking
* other Wicket based ajax requests.
*
* @author robin
*
*/
class LastCommitsResource extends AbstractResource {
private static final long serialVersionUID = 1L;
private static final String PARAM_REPO = "repo";
private static final String PARAM_REVISION = "revision";
private static final String PARAM_PATH = "path";
@Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
PageParameters params = attributes.getParameters();
final Long projectId = params.get(PARAM_REPO).toLong();
final String revision = params.get(PARAM_REVISION).toString();
final String path = params.get(PARAM_PATH).toOptionalString();
ResourceResponse response = new ResourceResponse();
response.setContentType("application/json");
response.setWriteCallback(new WriteCallback() {
@Override
public void writeData(Attributes attributes) throws IOException {
Project project = OneDev.getInstance(Dao.class).load(Project.class, projectId);
if (!SecurityUtils.canReadCode(project))
throw new UnauthorizedException();
LastCommitsOfChildren lastCommits = project.getLastCommitsOfChildren(revision, path);
AvatarManager avatarManager = OneDev.getInstance(AvatarManager.class);
Map<String, LastCommitInfo> map = new HashMap<>();
for (Map.Entry<String, LastCommitsOfChildren.Value> entry: lastCommits.entrySet()) {
LastCommitInfo info = new LastCommitInfo();
LastCommitsOfChildren.Value value = entry.getValue();
PageParameters params = CommitDetailPage.paramsOf(project, value.getId().name());
String url = RequestCycle.get().urlFor(CommitDetailPage.class, params).toString();
ReferenceTransformer transformer = new ReferenceTransformer(project, url);
info.html = transformer.apply(value.getSummary());
info.when = DateUtils.formatAge(value.getCommitDate());
PersonIdent author = value.getAuthor();
info.authorName = author.getName();
info.authorEmailAddress = author.getEmailAddress();
info.authorAvatarUrl = avatarManager.getAvatarUrl(author);
map.put(entry.getKey(), info);
}
String json;
try {
json = OneDev.getInstance(ObjectMapper.class).writeValueAsString(map);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
attributes.getResponse().write(json);
}
});
return response;
}
public static PageParameters paramsOf(Project project, String revision, @Nullable String path) {
PageParameters params = new PageParameters();
params.set(PARAM_REPO, project.getId());
params.set(PARAM_REVISION, revision);
if (path != null)
params.set(PARAM_PATH, path);
return params;
}
@SuppressWarnings("unused")
private static class LastCommitInfo {
String html;
String when;
String authorAvatarUrl;
String authorName;
String authorEmailAddress;
}
}
| 32.650407 | 105 | 0.756723 |
0f21c1ea849eb01f4c97a337938abaff9b6cbe2e | 5,194 | package com.ip2.myapp.ui.view.login;
import com.ip2.myapp.backend.entity.User;
import com.ip2.myapp.backend.repository.UserRepository;
import com.ip2.myapp.backend.service.UserService;
import com.ip2.myapp.ui.view.list.ListView;
import com.ip2.myapp.ui.view.list.UserView;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.dom.Element;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouterLink;
@Route(value = "login")
@PageTitle("Login")
@NpmPackage(value = "@polymer/iron-form", version = "3.0.1")
@JsModule("@polymer/iron-form/iron-form.js")
public class LoginView extends VerticalLayout {
private final RegisterForm registerForm;
private UserService userService;
public static User curentUser;
TextField userNameTextField = new TextField();
PasswordField passwordField = new PasswordField();
UserRepository userRepository;
Button addAnswerButton = new Button("Register an account", click -> addUser());
Text text = new Text("Error, incorrect username or password please try again");
public LoginView(UserService userService) {
this.userService = userService;
registerForm = new RegisterForm(userService.findAll());
registerForm.addListener(RegisterForm.SaveEvent.class, this::saveUser);
registerForm.addListener(RegisterForm.CloseEvent.class, e -> closeEditor());
registerForm.setVisible(false);
Div content = new Div(registerForm);
add(content);
generateLogin();
}
public void generateLogin() {
userNameTextField.getElement().setAttribute("name", "username");
userNameTextField.setId("username");
passwordField.getElement().setAttribute("name", "password");
Button submitButton = new Button("Login");
submitButton.setId("submitbutton");
submitButton.addClickListener(buttonClickEvent -> System.out.println(userNameTextField.getValue()));
submitButton.addClickListener(buttonClickEvent -> checkUserDetails());
//UI.getCurrent().getPage().executeJs("document.getElementById('submitbutton').addEventListener('click', () => document.getElementById('ironform').submit());");
FormLayout formLayout = new FormLayout();
formLayout.add(userNameTextField, passwordField, submitButton, addAnswerButton);
Element formElement = new Element("form");
formElement.setAttribute("method", "post");
formElement.setAttribute("action", "login");
formElement.appendChild(formLayout.getElement());
Element ironForm = new Element("iron-form");
ironForm.setAttribute("id", "ironform");
ironForm.setAttribute("allow-redirect", true);
ironForm.appendChild(formElement);
getElement().appendChild(ironForm);
setClassName("login-view");
}
private void checkPassword(int i) {
if (passwordField.getValue().equals(userService.findAll().get(i).getPassword())) {
getHomePage();
} else {
printErrorMsg();
}
}
private void saveUser(RegisterForm.SaveEvent evt) {
userService.save(evt.getUser());
closeEditor();
}
private void addUser() {
editUser(new User());
}
private void editUser(User user) {
registerForm.setUser(user);
registerForm.setVisible(true);
addClassName("editing");
}
private void closeEditor() {
registerForm.setUser(null);
registerForm.setVisible(false);
removeClassName("editing");
}
private void checkUserDetails() {
for (int i = 0; i < userService.findAll().size(); i++) {
if (userNameTextField.getValue().equals(userService.findAll().get(i).getUserName())) {
setUserInfo(i);
checkPassword(i);
break;
} else if ((i + 1) == userService.findAll().size()) {
printErrorMsg();
}
}
}
private void setUserInfo(int i){
curentUser = userService.findAll().get(i);
System.out.println(curentUser.getUserName());
}
public static User getUserInfo(){
return curentUser;
}
private void printErrorMsg() {
add(text);
}
private void getHomePage() {
if(curentUser.getUserName().equals("admin")){
RouterLink listLink = new RouterLink("Successfully Logged in, go to application", ListView.class);
removeAll();
add(listLink);
} else {
RouterLink listLink = new RouterLink("Successfully Logged in, go to application", UserView.class);
removeAll();
add(listLink);
}
}
}
| 31.478788 | 168 | 0.667501 |
85ddf2fe8041bc150d998e6889d78822ad9bd068 | 1,707 | package org.ohdsi.circe.check;
import org.ohdsi.circe.check.checkers.*;
import org.ohdsi.circe.cohortdefinition.CohortExpression;
import java.util.ArrayList;
import java.util.List;
public class Checker implements Check {
private List<Check> getChecks() {
List<Check> checks = new ArrayList<>();
checks.add(new UnusedConceptsCheck());
checks.add(new ExitCriteriaCheck());
checks.add(new ExitCriteriaDaysOffsetCheck());
checks.add(new RangeCheck());
checks.add(new ConceptCheck());
checks.add(new AttributeCheck());
checks.add(new TextCheck());
checks.add(new IncompleteRuleCheck());
checks.add(new InitialEventCheck());
checks.add(new NoExitCriteriaCheck());
checks.add(new ConceptSetCriteriaCheck());
checks.add(new DrugEraCheck());
checks.add(new OcurrenceCheck());
checks.add(new DuplicatesCriteriaCheck());
checks.add(new DuplicatesConceptSetCheck());
checks.add(new TreatmentLineCheck());
checks.add(new DrugDomainCheck());
checks.add(new EmptyConceptSetCheck());
checks.add(new EventsProgressionCheck());
checks.add(new TimeWindowCheck());
checks.add(new TimePatternCheck());
checks.add(new DomainTypeCheck());
checks.add(new CriteriaContradictionsCheck());
checks.add(new DeathTimeWindowCheck());
return checks;
}
@Override
public List<Warning> check(final CohortExpression expression) {
List<Warning> result = new ArrayList<>();
for(Check check : getChecks()) {
result.addAll(check.check(expression));
}
return result;
}
} | 34.836735 | 67 | 0.65495 |
23cebb6c5955ce14ef689b6a5cc787a2a876ba38 | 1,121 | package br.com.triadworks.issuetracker.controller.dashboard;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;
import br.com.triadworks.issuetracker.controller.UsuarioWeb;
import br.com.triadworks.issuetracker.dao.IssueDao;
import br.com.triadworks.issuetracker.model.Issue;
import br.com.triadworks.issuetracker.qualifier.UsuarioLogado;
@Named
@ViewAccessScoped
public class DashboardBean implements Serializable{
private List<Issue> issues = new ArrayList<Issue>();
private IssueDao issueDao;
private UsuarioWeb usuarioWeb;
public DashboardBean() {
}
@Inject
public DashboardBean(IssueDao issueDao, UsuarioWeb usuarioWeb) {
this.issueDao = issueDao;
this.usuarioWeb = usuarioWeb;
}
@PostConstruct
public void preload() {
Long id = usuarioWeb.getUsuario().getId();
issues = issueDao.getIssuesDoUsuario(id);
}
public List<Issue> getIssues() {
return issues;
}
}
| 22.42 | 86 | 0.783229 |
73a804664261641d0f4efe87688c8b899fb27a11 | 513 | package eco.data.m3.routing.simulations;
import java.io.IOException;
import eco.data.m3.routing.JKademliaNode;
import eco.data.m3.routing.node.KademliaId;
public class SimReceiverTest {
public static void main(String[] args)
{
try
{
System.out.println("Init done");
JKademliaNode kad2 = new JKademliaNode("Crystal", new KademliaId("12345678901234567891"), 7572);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| 22.304348 | 108 | 0.625731 |
16501e7d2ab483920cbc516d40f1b059afd05849 | 436 | package project.ece301.mantracker.CreateAccount;
import project.ece301.mantracker.User.CareProvider;
import project.ece301.mantracker.User.Patient;
public interface CreateAccountView {
void showUsernameNotUniqueError();
void showUsernameInvalidError();
void showEmailError();
void showPhoneError();
void navigateToPatientHome(Patient patient);
void navigateToCareProviderHome(CareProvider careProvider);
}
| 24.222222 | 63 | 0.795872 |
0160432cc6032d42e59df264f1de44168aa54f5c | 3,121 | package edu.cmu.minorthird.util;
/**
* String utilities.
*
*/
public class StringUtil
{
/** Line-wrap a string */
static public String lineWrap(String s,int lineLength)
{
StringBuffer buf = new StringBuffer("");
int lastLF = 0;
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if (Character.isWhitespace(ch) && (i-lastLF >= lineLength)) {
buf.append('\n');
lastLF = i;
} else {
buf.append(ch);
}
}
return buf.toString();
}
/** Indent a string */
static public String indent(int tabs,String s)
{
StringBuffer tabbuf = new StringBuffer();
for (int i=0; i<tabs; i++) tabbuf.append("| ");
String tab = tabbuf.toString();
return tab+s.replaceAll("\\n","\n"+tab);
}
/** Convert an array to a string. */
static public String toString(Object[] x)
{
return toString(x,"[","]",",");
}
/** Convert an array to a string. */
static public String toString(double[] x)
{
return toString(x,"[","]",",");
}
/** Convert an array to a string. */
static public String toString(int[] x)
{
return toString(x,"[","]",",");
}
static public String toString(Object[] x,String prefix,String suffix,String sep)
{
StringBuffer buf = new StringBuffer("");
buf.append(prefix);
for (int i=0; i<x.length; i++) {
if (i>0) buf.append(sep);
if (x[i]==null) buf.append("null");
else buf.append(x[i].toString());
}
buf.append(suffix);
return buf.toString();
}
/** Convert an array of doubles to a string. */
static public String toString(double[] x,String prefix,String suffix,String sep)
{
StringBuffer buf = new StringBuffer("");
buf.append(prefix);
for (int i=0; i<x.length; i++) {
if (i>0) buf.append(sep);
buf.append(Double.toString(x[i]));
}
buf.append(suffix);
return buf.toString();
}
/** Convert an array of ints to a string. */
static public String toString(int[] x,String prefix,String suffix,String sep)
{
StringBuffer buf = new StringBuffer("");
buf.append(prefix);
for (int i=0; i<x.length; i++) {
if (i>0) buf.append(sep);
buf.append(Integer.toString(x[i]));
}
buf.append(suffix);
return buf.toString();
}
/** Convert a string to an integer. Throws an IllegalArgumentException
* if the string is not a legal integer. */
static public int atoi(String intName)
{
try {
return Integer.parseInt(intName);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("illegal integer '"+intName+"'");
}
}
/** Convert a string to a double. Throws an IllegalArgumentException
* if the string is not a legal double. */
static public double atof(String doubleName)
{
try {
return Double.parseDouble(doubleName);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("illegal double '"+doubleName+"'");
}
}
/** Truncate a string to fixed length. */
static public String truncate(int len,String s)
{
if (len>=s.length()) return s;
else return s.substring(0,len)+"...";
}
static public void main(String[] args)
{
System.out.println(lineWrap(args[0], atoi(args[1])));
}
}
| 24.574803 | 81 | 0.634732 |
6c65623cf814ab4f6c758c9320688e6e908b0355 | 11,413 | package com.game.sdk.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.game.sdk.Constants;
import com.game.sdk.GameSDK;
import com.game.sdk.ResultCode;
import com.game.sdk.service.HttpService;
import com.game.sdk.util.DBHelper;
import com.game.sdk.util.KnLog;
import com.game.sdk.util.LoadingDialog;
import com.game.sdk.util.Md5Util;
import com.game.sdk.util.Util;
import com.game.sdk_project.SelecteLoginActivity;
import com.game.sdkproxy.R;
/**
* 游客升级成萌创账号
*/
public class AccounterBindActivity extends Activity implements OnClickListener {
private Activity m_activity = null ;
private String m_username = null ;
private String m_password = null ;
private EditText userNameEt;
private EditText passWordEt;
private EditText updatePassword;
private CheckBox m_zc_cb;
private Button m_bind_bt;
public static String m_userName ;
public static String m_passWord ;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
m_activity = this ;
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if(GameSDK.getInstance().ismScreenSensor()){
}else{
setRequestedOrientation(GameSDK.getInstance().getmOrientation());
}
setContentView(R.layout.mc_visitor_account_bind);
initView();
userNameEt.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v ) {
// TODO Auto-generated method stub
userNameEt.setCursorVisible(true);
}
} );
userNameEt.setOnEditorActionListener( new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v , int actionId, KeyEvent event ) {
// TODO Auto-generated method stub
if(EditorInfo.IME_ACTION_DONE==actionId){
userNameEt.clearFocus();
passWordEt.requestFocus();
userNameEt.setCursorVisible(false);
}
return false;
}
} );
passWordEt.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
passWordEt.setCursorVisible(true);
}
} );
passWordEt.setOnEditorActionListener( new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v , int actionId , KeyEvent event ) {
// TODO Auto-generated method stub
if(EditorInfo.IME_ACTION_DONE==actionId){
passWordEt.clearFocus();
userNameEt.clearFocus();
passWordEt.requestFocus();
passWordEt.setCursorVisible(false);
Util.hideEditTextWindow(m_activity, passWordEt);
Util.hideEditTextWindow(m_activity, userNameEt);
}
return false;
}
} );
//协议
m_zc_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//选择了
m_bind_bt.setEnabled(true);
m_bind_bt.setBackgroundColor(getResources().getColor(R.color.mc_Kn_Username));
}else {
m_bind_bt.setEnabled(false);
m_bind_bt.setBackgroundColor(getResources().getColor(R.color.mc_kn_text));
}
}
});
}
private void initView() {
userNameEt = (EditText) findViewById(R.id.account__et);
passWordEt = (EditText) findViewById(R.id.password__et);
m_zc_cb = (CheckBox) findViewById(R.id.zc_cb);
m_bind_bt= (Button) findViewById(R.id.account_bind_bt);// 确定
findViewById(R.id.account_bind_back).setOnClickListener(this);
m_bind_bt.setOnClickListener(this);
}
@Override
public void onClick(View v ) {
// TODO Auto-generated method stub
int id = v.getId();
if(id==R.id.account_bind_back){ //返回
Intent intent = null;
intent = new Intent(m_activity.getApplicationContext(),SelecteLoginActivity.class);
if( null == intent ){
return ;
}
m_activity.startActivity(intent);
m_activity.finish();
m_activity = null ;
}else if(id==R.id.account_bind_bt){ //注册账号
KnLog.log("绑定+++");
Util.hideEditTextWindow(this, passWordEt);
Util.hideEditTextWindow(this, userNameEt);
checkAccountBindParams(m_activity, userNameEt, passWordEt);
KnLog.log("绑定+++END");
}
}
@Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(GameSDK.getInstance().getGameInfo().getOrientation() == Constants.LANDSCAPE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
private void checkAccountBindParams(Activity context, EditText mUsername, EditText mPassword) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
if(TextUtils.isEmpty(username)){
Util.ShowTips(m_activity,getResources().getString(R.string.mc_tips_100));
return ;
}
KnLog.log("判断是否手机号2:"+ismobile(context, username));
if (ismobile(context, username)) return;
if(Util.isMobileNO(username)) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_58) );
}
if (TextUtils.isEmpty(username)) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_2) );
return;
}
if (!username.matches("^.{6,25}$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_4) );
return;
}
if (TextUtils.isEmpty(password)) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_8) );
return;
}
if (!username.matches("^[A-Za-z0-9_-]+$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_3) );
return;
}
if (!password.matches("^.{6,20}$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_5) );
return;
}
password = Md5Util.getMd5(password);
m_username = username ;
m_password = password ;
if(!Util.isNetWorkAvailable(getApplicationContext())){
Util.ShowTips(getApplicationContext(),getResources().getString(R.string.mc_tips_34).toString());
return ;
}
LoadingDialog.show(context, "绑定中...",true);
//查询账号是否存在
HttpService.getUsername(m_activity.getApplicationContext(), handler,username);
//游客绑定账号
//HttpService.visitorBindAccount(getApplicationContext(), handler, username, password);
}
private boolean ismobile(Activity context, String username) {
if(!Util.isMobileNO(username)) { //如果不是手机号
if(TextUtils.isEmpty(username)){
Util.ShowTips(m_activity,getResources().getString(R.string.mc_tips_100));
return true;
}
if (!username.matches("^[a-z|A-Z]{1}.{0,}$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_1));
return true;
}
if (!username.matches("^[A-Za-z0-9_-]+$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_3) );
return true;
}
if (!username.matches("^.{6,25}$")) {
Util.ShowTips(context, getResources().getString(R.string.mc_tips_4) );
return true;
}
}
return false;
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
LoadingDialog.dismiss();
switch (msg.what) {
case ResultCode.GET_USER_SUCCRESS: //账号已经被注册过了
if(msg.obj!=null) {
if (GameSDK.getInstance().getmLoginListener() != null) {
GameSDK.getInstance().getmLoginListener().onSuccess(msg.obj.toString());
Util.ShowTips(m_activity,"账号已经被注册了,请重新输入!");
KnLog.log("账号已经被注册过了,返回的信息:"+msg.obj.toString());
}
}
break;
case ResultCode.GET_USER_NoEXIStTENT: //账号没有被注册过
if(msg.obj!=null) {
if (GameSDK.getInstance().getmLoginListener() != null) {
GameSDK.getInstance().getmLoginListener().onSuccess(msg.obj.toString());
KnLog.log("账号没有被注册过,返回的信息:"+msg.obj.toString());
String username= userNameEt.getText().toString().trim(); //账号
String password=passWordEt.getText().toString().trim(); //密码
String ps = Md5Util.getMd5(password);
KnLog.log("判断是否是手机:"+ismobile(m_activity, username));
if (Util.isMobileNO(username)){ //
KnLog.log("是手机号:"+username+" 密码="+ps);
//跳转发送验证码注册
Intent intent1 =new Intent(AccounterBindActivity.this,TourtistRegActivity.class);
intent1.putExtra("phone",username);
intent1.putExtra("password",ps);
startActivity(intent1);
KnLog.log("跳转页面:");
}else {
KnLog.log("不是手机号:");
String pd = Md5Util.getMd5(password);
m_userName = username ;
m_passWord = pd ;
LoadingDialog.show(m_activity, "绑定中...",true);
//游客绑定账号
HttpService.visitorBindAccount(getApplicationContext(), handler, username, pd );
//直接用户名与密码,注册账号
// HttpService.doRegister(getApplicationContext(), handler, username, pd);
}
}
}
break;
case ResultCode.GET_USER_FAIL: //查询账号返回错误
if(msg.obj!=null) {
if (GameSDK.getInstance().getmLoginListener() != null) {
GameSDK.getInstance().getmLoginListener().onFail(msg.obj.toString());
Util.ShowTips(m_activity,"查询账号失败!");
}
}
break;
case ResultCode.VISITOR_BIND_SUCCESS: //游客绑定账号成功
if(msg.obj!=null) {
if (GameSDK.getInstance().getmLoginListener() != null) {
GameSDK.getInstance().getmLoginListener().onSuccess(msg.obj.toString());
String result= msg.obj.toString();
KnLog.log("游客绑定账号成功:"+result);
//保存用户名与密码
DBHelper.getInstance().insertOrUpdateUser( m_userName , m_passWord );
Util.ShowTips(AccounterBindActivity.this, getResources().getString(R.string.mc_tips_15) );
GameSDK.instance.login(AccounterBindActivity.this); //跳转到免密码登录
}
}
break;
case ResultCode.VISITOR_BIND_FAIL: //游客绑定账号失败
if(msg.obj!=null) {
if (GameSDK.getInstance().getmLoginListener() != null) {
GameSDK.getInstance().getmLoginListener().onFail(msg.obj.toString());
String result1= msg.obj.toString();
KnLog.log("游客绑定账号失败:"+result1);
Util.ShowTips(AccounterBindActivity.this,"绑定账号失败:"+result1 );
}
}
break;
default:
break;
}
}
};
}
| 24.596983 | 99 | 0.695698 |
d8f8698513af38fe6a0b14b46036c73ef0bf2afc | 2,505 | /*******************************************************************************
* Copyright 2013 Mojave Innovations GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Mojave Innovations GmbH - initial API and implementation
******************************************************************************/
package org.entirej.applicationframework.tmt.table;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.entirej.applicationframework.tmt.table.EJTMTTableSortSelectionListener.InvertableSorter;
public abstract class EJTMTAbstractTableSorter extends InvertableSorter
{
private final InvertableSorter _inverse = new InvertableSorter()
{
@Override
public int compare(Viewer viewer, Object e1, Object e2)
{
return -1 * EJTMTAbstractTableSorter.this.compare(viewer, e1, e2);
}
@Override
InvertableSorter getInverseSorter()
{
return EJTMTAbstractTableSorter.this;
}
@Override
public int getSortDirection()
{
return SWT.DOWN;
}
};
@Override
InvertableSorter getInverseSorter()
{
return _inverse;
}
@Override
public int getSortDirection()
{
return SWT.UP;
}
}
| 41.75 | 118 | 0.457086 |
9ede0c07bfb1964a093a3ed7a2b5f5da023996f8 | 1,445 | package com.mitocode.document;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.format.annotation.DateTimeFormat;
@Document(collection = "matriculas")
public class Matricula {
@Id
private String id;
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss")
private LocalDateTime fechamatricula;
@DBRef
private Estudiante estudiante;
private List<MatriculaItem> items;
@NotNull
private boolean estado;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Estudiante getEstudiante() {
return estudiante;
}
public void setEstudiante(Estudiante estudiante) {
this.estudiante = estudiante;
}
public LocalDateTime getFechamatricula() {
return fechamatricula;
}
public void setFechamatricula(LocalDateTime fechamatricula) {
this.fechamatricula = fechamatricula;
}
public boolean isEstado() {
return estado;
}
public void setEstado(boolean estado) {
this.estado = estado;
}
public List<MatriculaItem> getItems() {
return items;
}
public void setItems(List<MatriculaItem> items) {
this.items = items;
}
}
| 18.766234 | 62 | 0.760554 |
fc8ae4355e4b4635836dcb8629235bb93276b691 | 321 | package com.rchab.jaxws.endpoint;
import javax.xml.ws.Endpoint;
import com.rchab.jaxws.ws.HelloWorldImpl;
public class Publisher {
public static final String ADDRESS = "http://localhost:9999/ws/hello";
public static void main(String[] args) {
Endpoint.publish(ADDRESS, new HelloWorldImpl());
}
}
| 21.4 | 74 | 0.716511 |
6d2fd65a7dcebcef3ddce34b854ef1d34026b2cb | 2,383 | package ru.pavlenov.bio.chapter.rosalind.string_algoritm;
import net.sf.jfasta.impl.FASTAFileReaderImpl;
import ru.pavlenov.bio.amino.InvalidAlphabetException;
import ru.pavlenov.bio.amino.LocalAlignment;
import ru.pavlenov.bio.utils.Convert;
import ru.pavlenov.bio.utils.Dump;
import ru.pavlenov.bio.utils.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
/**
* ⓭ + 16
* Какой сам? by Pavlenov Semen 02.07.14.
*
* Finding a Shared Spliced Motif
* http://rosalind.info/problems/lcsq/
*
* Given: Two DNA strings s and t (each having length at most 1 kbp) in FASTA format.
* Return: A longest common subsequence of s and t. (If more than one solution exists, you may return any one.)
*
*/
public class Lcsq {
public static void start() throws IOException, InvalidAlphabetException {
FASTAFileReaderImpl fasta = File.readFasta(Lcsq.class);
List<String> list = Convert.from(fasta).toStringList();
char[] text1 = list.get(0).toCharArray();
char[] text2 = list.get(1).toCharArray();
LocalAlignment lalign = new LocalAlignment(list.get(0), list.get(1));
// lalign.setMatch(1).setPenalty(0);
lalign.make();
lalign.track(lalign.getStartI()-1, lalign.getStartJ()-1);
ArrayList<Character> r1 = lalign.getResult1();
ArrayList<Character> r2 = lalign.getResult2();
// Dump.println(lalign.getResult1());
// Dump.println(lalign.getResult2());
for (int i = 0; i < r1.size(); i++) {
if (r1.get(i) == r2.get(i)) Dump.print(r1.get(i));
}
Dump.ln();
// Integer[][] m = new Integer[text1.length+1][text2.length+1];
//
// for (int i = 0; i < text1.length+1; i++) {
// m[i][0] = 0;
// }
// for (int j = 0; j < text2.length+1; j++) {
// m[0][j] = 0;
// }
//
// for (int i = 0; i < text1.length; i++) {
//
// for (int j = 0; j < text2.length; j++) {
//
// if (text1[i] == text2[j]) m[i+1][j+1] = m[i][j]+1;
// else m[i+1][j+1] = Math.max(m[i+1][j], m[i][j+1]);
//
// }
//
// }
//
// int i = text1.length;
// int j = text2.length;
// String sub = "";
// while (i*j > 0) {
//
//
//
// }
// Dump.println(m);
}
} | 26.477778 | 111 | 0.570709 |
372cc210565c4b8cc42284864812fd85d000aa6b | 855 | //Write a user defined exception class to authenticate the user name and password.
package CO4Q3;
import java.util.Scanner;
public class authentication {
public static void main(String[] args) {
String username = "Himmler";
String password = "U-boat";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Username");
String u1 = sc.nextLine();
System.out.println("Enter the Password");
String u2 = sc.nextLine();
try {
if ((u1.equals(username)) && (u2.equals(password))) {
System.out.println("Acess Granted");
}
else {
throw new credentialexception("Invalid Credentials");
}
}
catch (credentialexception e){
System.out.println(e.getMessage());
}
}}
| 27.580645 | 82 | 0.57076 |
a2eee5e5dee346e0aacd2f09712a406460ec9bc4 | 4,969 | package utils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import java.awt.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CharacterBlurb
{
ResultSet rs;
ResultSet rs2;
Member member;
String character;
String nation;
String race;
String gender;
Color color;
String thumbnail;
EmbedBuilder embed;
int nationRank;
public CharacterBlurb(ResultSet rs, ResultSet rs2, Member member) throws SQLException
{
this.rs = rs;
this.rs2 = rs2;
this.member = member;
character = rs.getString("charname");
nation = rs.getString("chars.nation");
embed = new EmbedBuilder();
}
public EmbedBuilder[] getCharacter() throws SQLException
{
assert member != null;
embed.setAuthor(member.getEffectiveName(), null, member.getUser().getAvatarUrl());
embed.setFooter("This character is owned by Discord user " + member.getEffectiveName());
switch (nation)
{
case "0": // San d'Oria
embed.setColor(Color.decode("#ec5a5a"));
color = Color.decode("#ec5a5a");
nationRank = rs.getInt("rank_sandoria");
embed.setThumbnail("https://vignette.wikia.nocookie.net/ffxi/images/2/2f/Ffxi_flg_03l.jpg");
thumbnail = "https://vignette.wikia.nocookie.net/ffxi/images/2/2f/Ffxi_flg_03l.jpg";
break;
case "1": // Bastok
embed.setColor(Color.decode("#5b80e9"));
color = Color.decode("#5b80e9");
nationRank = rs.getInt("rank_bastok");
embed.setThumbnail("https://vignette.wikia.nocookie.net/ffxi/images/0/07/Ffxi_flg_01l.jpg");
thumbnail = "https://vignette.wikia.nocookie.net/ffxi/images/0/07/Ffxi_flg_01l.jpg";
break;
case "2": // Windurst
embed.setColor(Color.decode("#b5f75d"));
color = Color.decode("#b5f75d");
nationRank = rs.getInt("rank_windurst");
embed.setThumbnail("https://vignette.wikia.nocookie.net/ffxi/images/b/bf/Ffxi_flg_04l.jpg");
thumbnail = "https://vignette.wikia.nocookie.net/ffxi/images/b/bf/Ffxi_flg_04l.jpg";
break;
default:
break;
}
try {
switch (rs.getInt("race"))
{
case 1:
race = "Hume";
gender = "male ";
break;
case 2:
race = "Hume";
gender = "female ";
break;
case 3:
race = "Elvaan";
gender = "male ";
break;
case 4:
race = "Elvaan";
gender = "female ";
break;
case 5:
race = "Tarutaru";
gender = "male ";
break;
case 6:
race = "Tarutaru";
gender = "female ";
break;
case 7:
race = "Mithra";
gender = "";
break;
case 8:
race = "Galka";
gender = "";
break;
default:
throw new IllegalStateException("Unexpected value: " + rs.getInt("race"));
}
final String[] jobs = {"WAR", "MNK", "WHM", "BLM", "RDM", "THF", "PLD", "DRK", "BST", "BRD", "RNG", "SAM", "NIN", "DRG", "SMN", "BLU", "COR", "PUP", "DNC", "SCH"};
for (String job : jobs)
{
if (!rs.getString(job.toLowerCase()).equals("0"))
embed.addField(job, rs.getString(job.toLowerCase()), true);
}
embed.setTitle(character + " the " + gender + race + "\nNation Rank " + nationRank + "\n__**Jobs**__");
} catch (SQLException e)
{
e.printStackTrace();
}
EmbedBuilder embed2 = new EmbedBuilder();
embed2.setAuthor(member.getEffectiveName(), null, member.getUser().getAvatarUrl());
embed2.setFooter("This character is owned by Discord user " + member.getEffectiveName());
embed2.setTitle(rs.getString("chars.charname") + " the " + gender + race + "\n__**Crafts**__");
embed2.setColor(color);
embed2.setThumbnail(thumbnail);
while(rs2.next())
embed2.addField(capitalize(rs2.getString("Skill")), String.valueOf(rs2.getInt("Value")), true);
return new EmbedBuilder[]{embed, embed2};
}
public static String capitalize(String str)
{
if(str == null) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
}
| 36.807407 | 175 | 0.505534 |
3650ebab44677a2c5262c00963ccc070dfb9d543 | 7,267 | /*
* Copyright 2018, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opencensus.examples.grpc.helloworld;
import static io.opencensus.examples.grpc.helloworld.HelloWorldUtils.getPortOrDefaultFromArgs;
import static io.opencensus.examples.grpc.helloworld.HelloWorldUtils.getStringOrDefaultFromArgs;
import com.google.common.collect.ImmutableMap;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import io.opencensus.common.Duration;
import io.opencensus.common.Scope;
import io.opencensus.contrib.grpc.metrics.RpcViews;
import io.opencensus.contrib.zpages.ZPageHandlers;
import io.opencensus.exporter.stats.prometheus.PrometheusStatsCollector;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsConfiguration;
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.exporter.trace.logging.LoggingTraceExporter;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Span;
import io.opencensus.trace.SpanBuilder;
import io.opencensus.trace.Status;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.config.TraceConfig;
import io.opencensus.trace.samplers.Samplers;
import io.prometheus.client.exporter.HTTPServer;
import java.io.IOException;
import java.util.logging.Logger;
/** Server that manages startup/shutdown of a {@code Greeter} server. */
public class HelloWorldServer {
private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
private static final Tracer tracer = Tracing.getTracer();
private final int serverPort;
private Server server;
private HelloWorldServer(int serverPort) {
this.serverPort = serverPort;
}
// A helper function that performs some work in its own Span.
private static void performWork(Span parent) {
SpanBuilder spanBuilder =
tracer.spanBuilderWithExplicitParent("internal_work", parent).setRecordEvents(true);
try (Scope scope = spanBuilder.startScopedSpan()) {
Span span = tracer.getCurrentSpan();
span.putAttribute("my_attribute", AttributeValue.stringAttributeValue("blue"));
span.addAnnotation("Performing work.");
sleepFor(20); // Working hard here.
span.addAnnotation("Done work.");
}
}
private static void sleepFor(int milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Span span = tracer.getCurrentSpan();
span.addAnnotation("Exception thrown when performing work " + e.getMessage());
span.setStatus(Status.UNKNOWN);
}
}
private void start() throws IOException {
server = ServerBuilder.forPort(serverPort).addService(new GreeterImpl()).build().start();
logger.info("Server started, listening on " + serverPort);
Runtime.getRuntime()
.addShutdownHook(
new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
/** Await termination on the main thread since the grpc library uses daemon threads. */
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/** Main launches the server from the command line. */
public static void main(String[] args) throws IOException, InterruptedException {
// Add final keyword to pass checkStyle.
final int serverPort = getPortOrDefaultFromArgs(args, 0, 50051);
final String cloudProjectId = getStringOrDefaultFromArgs(args, 1, null);
final int zPagePort = getPortOrDefaultFromArgs(args, 2, 3000);
final int prometheusPort = getPortOrDefaultFromArgs(args, 3, 9090);
// For demo purposes, always sample
TraceConfig traceConfig = Tracing.getTraceConfig();
traceConfig.updateActiveTraceParams(
traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());
// Registers all RPC views. For demonstration all views are registered. You may want to
// start with registering basic views and register other views as needed for your application.
RpcViews.registerAllViews();
// Registers logging trace exporter.
LoggingTraceExporter.register();
// Starts a HTTP server and registers all Zpages to it.
ZPageHandlers.startHttpServerAndRegisterAll(zPagePort);
logger.info("ZPages server starts at localhost:" + zPagePort);
// Registers Stackdriver exporters.
if (cloudProjectId != null) {
StackdriverTraceExporter.createAndRegister(
StackdriverTraceConfiguration.builder().setProjectId(cloudProjectId).build());
StackdriverStatsExporter.createAndRegister(
StackdriverStatsConfiguration.builder()
.setProjectId(cloudProjectId)
.setExportInterval(Duration.create(5, 0))
.build());
}
// Register Prometheus exporters and export metrics to a Prometheus HTTPServer.
PrometheusStatsCollector.createAndRegister();
HTTPServer prometheusServer = new HTTPServer(prometheusPort, true);
// Start the RPC server. You shouldn't see any output from gRPC before this.
logger.info("gRPC starting.");
final HelloWorldServer server = new HelloWorldServer(serverPort);
server.start();
server.blockUntilShutdown();
}
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
Span span = tracer.getCurrentSpan();
span.putAttribute("my_attribute", AttributeValue.stringAttributeValue("red"));
span.addAnnotation(
"Constructing greeting.",
ImmutableMap.of(
"name", AttributeValue.stringAttributeValue(req.getName()),
"name length", AttributeValue.longAttributeValue(req.getName().length())));
sleepFor(10);
performWork(span);
span.addAnnotation("Sleeping.");
sleepFor(30);
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
logger.info("SayHello RPC handled.");
}
}
}
| 40.149171 | 100 | 0.727673 |
dd356244d51bcfff2f761555275c7e899a74559c | 2,738 | /*
* Copyright (C) 2014 desrever <desrever at nubits.com>
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.nubits.nubot.notifications;
/**
*
* @author desrever <desrever at nubits.com>
*/
import com.nubits.nubot.global.Global;
import com.nubits.nubot.global.Passwords;
import com.nubits.nubot.notifications.jhipchat.HipChat;
import com.nubits.nubot.notifications.jhipchat.Room;
import com.nubits.nubot.notifications.jhipchat.UserId;
import com.nubits.nubot.notifications.jhipchat.messages.Message.Color;
import java.util.logging.Logger;
public class HipChatNotifications {
private static final Logger LOG = Logger.getLogger(HipChatNotifications.class.getName());
private static String BOT_NAME = "Custodian Bot";
private static HipChat hipchat = new HipChat(Passwords.HIPCHAT_KEY);
private static UserId hipchatUser = UserId.create("idbot", BOT_NAME);
private static Room notificationRoom = Room.create(Passwords.HIPCHAT_NOTIFICATIONS_ROOM_ID, hipchat);
private static Room criticalNotificationRoom = Room.create(Passwords.HIPCHAT_CRITICAL_ROOM_ID, hipchat);
public static void sendMessage(String message, Color color) {
String publicAddress = "";
boolean send = true; // default send
boolean notify = false; //default notify
if (Global.options != null) {
publicAddress = Global.options.getNubitsAddress();
send = Global.options.isSendHipchat();
notify = false;
}
String toSend = message + " (" + publicAddress + ")";
if (color == Color.RED) {
notify = true;
}
if (send) {
try {
if (notify) {
criticalNotificationRoom.sendMessage(toSend, hipchatUser, notify, color);
} else {
notificationRoom.sendMessage(toSend, hipchatUser, notify, color);
}
} catch (Exception e) {
LOG.severe("Not sending hipchat notification. Network problem");
}
}
}
}
| 38.56338 | 108 | 0.681885 |
493999c5316cc55040733f8ba497a0b2bac7a83e | 5,097 | /*
* Copyright 2013 Masato Nagai
*
* 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 gprof;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaClassRegistry;
import org.codehaus.groovy.reflection.ClassInfo;
import java.beans.IntrospectionException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.Callable;
public class Profiler extends MetaClassRegistry.MetaClassCreationHandle {
private static Map defaultOptions;
static {
defaultOptions = new HashMap();
defaultOptions.put("includeMethods", Collections.emptyList());
// I believe grabbing phase must be excluded. Is there anyone wants to profile it?
defaultOptions.put("excludeMethods", Arrays.asList("groovy.grape.*"));
defaultOptions.put("includeThreads", Collections.emptyList());
defaultOptions.put("excludeThreads", Collections.emptyList());
}
private List<ProfileMetaClass> proxyMetaClasses = new ArrayList();
private MetaClassRegistry.MetaClassCreationHandle originalMetaClassCreationHandle;
private List<MetaClass> originalMetaClasses = new ArrayList();
private ProfileInterceptor interceptor;
public Profile run(Callable profiled) {
return run(Collections.<String, Object>emptyMap(), profiled);
}
public Profile run(Map<String, Object> options, Callable profiled) {
Map<String, Object> opts = new HashMap(defaultOptions);
opts.putAll(options);
ProfileMethodFilter methodFilter = new ProfileMethodFilter();
methodFilter.addIncludes((List) opts.get("includeMethods"));
methodFilter.addExcludes((List) opts.get("excludeMethods"));
ProfileThreadFilter threadFilter = new ProfileThreadFilter();
threadFilter.addIncludes((List) opts.get("includeThreads"));
threadFilter.addExcludes((List) opts.get("excludeThreads"));
this.interceptor = new ProfileInterceptor(methodFilter, threadFilter);
start();
try {
profiled.call();
} catch (Exception e) {
e.printStackTrace();
}
end();
return new Profile(interceptor.getTree());
}
private void start() {
MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
originalMetaClassCreationHandle = registry.getMetaClassCreationHandler();
registry.setMetaClassCreationHandle(this);
/*
for (ClassInfo classInfo : ClassInfo.getAllClassInfo()) {
Class theClass = classInfo.get();
originalMetaClasses.add(registry.getMetaClass(theClass));
registry.removeMetaClass(theClass);
}
*/
// This is a hack.
try {
Field classSetField = ClassInfo.class.getDeclaredField("globalClassSet");
classSetField.setAccessible(true);
ClassInfo.ClassInfoSet classSet = (ClassInfo.ClassInfoSet) classSetField.get(ClassInfo.class);
for (ClassInfo classInfo : (Collection<ClassInfo>) classSet.values()) {
Class theClass = classInfo.get();
originalMetaClasses.add(registry.getMetaClass(theClass));
registry.removeMetaClass(theClass);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void end() {
MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
registry.setMetaClassCreationHandle(originalMetaClassCreationHandle);
for (ProfileMetaClass metaClass : proxyMetaClasses) {
// clean registry and delegate creating normal meta class for original handle
registry.removeMetaClass(metaClass.getTheClass());
}
for (MetaClass metaClass : originalMetaClasses) {
registry.setMetaClass(metaClass.getTheClass(), metaClass);
}
}
@Override
protected MetaClass createNormalMetaClass(Class theClass, MetaClassRegistry registry) {
if (theClass != ProfileMetaClass.class) {
try {
ProfileMetaClass proxyMetaClass =
new ProfileMetaClass(registry, theClass, new MetaClassImpl(registry, theClass));
proxyMetaClass.setInterceptor(interceptor);
proxyMetaClasses.add(proxyMetaClass);
return proxyMetaClass;
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
return super.createNormalMetaClass(theClass, registry);
}
}
| 40.133858 | 106 | 0.678046 |
5a6425104d3bcde809a8e0c9cd6981b05c88f732 | 5,722 | package org.skunion.BunceGateVPN.GUI.vrouter;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.github.Mealf.BounceGateVPN.Router.VirtualRouter;
import com.github.smallru8.Secure2.config.Config;
import com.github.smallru8.util.Pair;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
public class RoutingTableSetting extends JFrame {
private JPanel contentPane;
private JFrame RTS = this;
private JTable routingTable;
private Pair<Config,VirtualRouter> roPair = null;
private Vector<Vector> rowData = new Vector<Vector>();
private Vector<String> routingTable_column = new Vector<String>();
/**
* Launch the application.
*/
/*
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RoutingTableSetting frame = new RoutingTableSetting();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
*/
/**
* Create the frame.
*/
public RoutingTableSetting(Pair<Config,VirtualRouter>...roPairLs) {
if(roPairLs.length==1)
roPair = roPairLs[0];
routingTable_column.addElement("DesIP");
routingTable_column.addElement("Mask");
routingTable_column.addElement("Gateway");
routingTable_column.addElement("Interface/switch");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 534, 395);
setTitle("Routing table");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
routingTable = new JTable(rowData,routingTable_column);
routingTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
}
});
JScrollPane scrollPane = new JScrollPane(routingTable);
scrollPane.setBounds(10, 10, 498, 297);
contentPane.add(scrollPane);
JButton closeButton = new JButton("Close");
closeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
RTS.dispose();
}
});
closeButton.setBounds(421, 317, 87, 23);
contentPane.add(closeButton);
JButton editButton = new JButton("Edit");
editButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int row = routingTable.getSelectedRow();
if(row!=-1) {
RoutingTableDataSetting dialog = new RoutingTableDataSetting(rowData.get(row),roPair);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
});
editButton.setBounds(10, 317, 87, 23);
contentPane.add(editButton);
JButton addRowButton = new JButton("Add");
addRowButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {//Add a empty row
RoutingTableDataSetting dialog = new RoutingTableDataSetting(null,roPair);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
});
addRowButton.setBounds(107, 317, 87, 23);
contentPane.add(addRowButton);
JButton delRowButton = new JButton("Remove");
delRowButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {//delete row
int row = routingTable.getSelectedRow();
if(row!=-1) {
String[] routingData = new String[3];
for(int i=0;i<3;i++)
routingData[i] = (String)routingTable.getValueAt(row, i);
roPair.second.delRoutingTable(routingData[0], routingData[1], routingData[2]);//從router移除
ArrayList<String> routingTable_raw = new ArrayList<String>();
routingTable_raw.addAll(Arrays.asList(roPair.first.routingTable.split(";")));
for(int i=0;i<routingTable_raw.size();i++) {//刪cfg data
String[] routingDataTmp = routingTable_raw.get(i).split(",");
if(routingDataTmp[0].equals(routingData[0])&&routingDataTmp[1].equals(routingData[1])&&routingDataTmp[2].equals(routingData[2])) {
routingTable_raw.remove(i);
}
}
String routingTable_str = "";
for(int i=0;i<routingTable_raw.size();i++)
routingTable_str+=routingTable_raw.get(i)+";";
roPair.first.pro.setProperty("routingTable", routingTable_str);//存回cfg
roPair.first.saveConf();
routingTable.repaint();
}
}
});
delRowButton.setBounds(204, 317, 87, 23);
contentPane.add(delRowButton);
JButton btnNewButton = new JButton("Refresh");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
rowData.clear();
loadData();
}
});
btnNewButton.setBounds(324, 317, 87, 23);
contentPane.add(btnNewButton);
loadData();
}
private void loadData() {
if(roPair!=null) {
String[] routingTable_RawData = roPair.first.routingTable.split(";");
if(routingTable_RawData.length>0) {
for(int i=0;i<routingTable_RawData.length;i++) {
routingTable_RawData[i].replace(" ", "");//過濾空白
String[] routingData = routingTable_RawData[i].split(",");
if(routingData.length!=4)//資料有問題
continue;
Vector<String> routingData_v = new Vector<String>();
routingData_v.addAll(Arrays.asList(routingData));
rowData.addElement(routingData_v);
}
routingTable.repaint();
}
}
}
}
| 30.275132 | 136 | 0.71094 |
9d65418c22665d9e420e1fc703d27ecf4587a177 | 10,962 | package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.*;
import com.ctre.phoenix.motorcontrol.can.*;
import edu.wpi.first.wpilibj.Solenoid;
import frc.robot.*;
//intake has to go double the speed the shooter goes
public class PowerCell{
private OperatorInterface oi;
public enum State {
Spin, Wait
}
private State state = State.Spin;
// pid values
private final int TIMEOUT = 0;
private final double cLR = 0.1;
private double intake_kP = 5;// 5e-5
private double intake_kD = 0;
private double intake_kI = 0.00000;// 1e-6
private double intake_kF = 0;
private double shooter_kF = 0;
private double shooter_kP = 5;
private double shooter_kD = 0;
private double shooter_kI = 0.00000;// 1e-6
private double storage_kP = 5;
private double storage_kD = 0;
private double storage_kI = 0;
private double storage_kF = 0;
private double feederP_kP = 5;// 5e-5
private double feederP_kD = 0;
private double feederP_kI = 0;// 1e-6
private double feederP_kF = 0;
//current limits
private SupplyCurrentLimitConfiguration shooterLimit = new SupplyCurrentLimitConfiguration(true, 100, 20, 1000);
private SupplyCurrentLimitConfiguration feederLimit = new SupplyCurrentLimitConfiguration(true, 40, 20, 1000);
private boolean feederButton = false;
private boolean disableAll = false;
//motors
private TalonSRX storageMotorL;
private TalonSRX storageMotorH;
private TalonFX shooter;
private TalonSRX intakeMotor;
private TalonFX feederMotor;
//solinoids
private Solenoid gatherer;
private double shooterRpms = 98;
private double intakeRpms = 0.5;
private double storageRpms = 0.6; //%output for now
private double feederRpms = 0.2;
private double feederPosition = 0.0;
private double waitSetPoint = 15;
private double spinSetPoint = 12;
private double spinTimer = 1;
private double waitTimer = 1;
public void init(OperatorInterface operatorinterface){
// Constructors
shooter = new TalonFX(Wiring.shooterMotor);
intakeMotor = new TalonSRX(Wiring.intakeMotor);
storageMotorH = new TalonSRX(Wiring.storageMotorH);
storageMotorL = new TalonSRX(Wiring.storageMotorL);
feederMotor = new TalonFX(Wiring.feederMotor);
gatherer = new Solenoid(2);
oi = operatorinterface;
// Intake Motor Config
intakeMotor.set(ControlMode.PercentOutput, 0);
intakeMotor.configClosedloopRamp(cLR, TIMEOUT);
intakeMotor.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder);
intakeMotor.config_kF(0, intake_kF);
intakeMotor.config_kP(0, intake_kP);
intakeMotor.config_kD(0, intake_kD);
intakeMotor.config_kI(0, intake_kI);
intakeMotor.configNominalOutputForward(0, TIMEOUT);
intakeMotor.configNominalOutputReverse(0, TIMEOUT);
intakeMotor.configPeakOutputForward(+1, TIMEOUT);
intakeMotor.configPeakOutputReverse(-1, TIMEOUT);
intakeMotor.enableCurrentLimit(true);
intakeMotor.configPeakCurrentLimit(75, TIMEOUT);
intakeMotor.configContinuousCurrentLimit(20, TIMEOUT);
intakeMotor.configPeakCurrentDuration(1800, TIMEOUT);
intakeMotor.setNeutralMode(NeutralMode.Coast);
// Shooter Motor Config
shooter.set(TalonFXControlMode.Velocity, 0);
shooter.configClosedloopRamp(cLR, TIMEOUT);
shooter.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder); //shooter.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor);
shooter.config_kF(0, shooter_kF);
shooter.config_kP(0, shooter_kP);
shooter.config_kD(0, shooter_kD);
shooter.config_kI(0, shooter_kI);
shooter.configNominalOutputForward(0, TIMEOUT);
shooter.configNominalOutputReverse(0, TIMEOUT);
shooter.configPeakOutputForward(+1, TIMEOUT);
shooter.configPeakOutputReverse(-1, TIMEOUT);
shooter.setNeutralMode(NeutralMode.Coast);
shooter.configSupplyCurrentLimit(shooterLimit);
// Feeder motor config
feederMotor.set(ControlMode.PercentOutput, 0);
feederMotor.configClosedloopRamp(cLR, TIMEOUT);
feederMotor.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder);//feederMotor.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor);
feederMotor.config_kF(0, feederP_kF);
feederMotor.config_kP(0, feederP_kP);
feederMotor.config_kD(0, feederP_kD);
feederMotor.config_kI(0, feederP_kI);
feederMotor.configNominalOutputForward(0, TIMEOUT);
feederMotor.configNominalOutputReverse(0, TIMEOUT);
feederMotor.configPeakOutputForward(+1, TIMEOUT);
feederMotor.configPeakOutputReverse(-1, TIMEOUT);
feederMotor.setNeutralMode(NeutralMode.Brake);
feederMotor.configSupplyCurrentLimit(feederLimit);
// Storage Motor Config
storageMotorH.set(ControlMode.PercentOutput, 0);
storageMotorH.configClosedloopRamp(cLR, TIMEOUT);
storageMotorH.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder);
storageMotorH.config_kF(0, storage_kF);
storageMotorH.config_kP(0, storage_kP);
storageMotorH.config_kD(0, storage_kD);
storageMotorH.config_kI(0, storage_kI);
storageMotorH.configNominalOutputForward(0, TIMEOUT);
storageMotorH.configNominalOutputReverse(0, TIMEOUT);
storageMotorH.configPeakOutputForward(+1, TIMEOUT);
storageMotorH.configPeakOutputReverse(-1, TIMEOUT);
storageMotorH.enableCurrentLimit(true);
storageMotorH.configPeakCurrentLimit(10, TIMEOUT);
storageMotorH.configContinuousCurrentLimit(10, TIMEOUT);
storageMotorH.configPeakCurrentDuration(1800, TIMEOUT);
storageMotorH.setNeutralMode(NeutralMode.Brake);
storageMotorL.set(ControlMode.PercentOutput, 0);
storageMotorL.configClosedloopRamp(cLR, TIMEOUT);
storageMotorL.configSelectedFeedbackSensor(FeedbackDevice.QuadEncoder);
storageMotorL.config_kF(0, storage_kF);
storageMotorL.config_kP(0, storage_kP);
storageMotorL.config_kD(0, storage_kD);
storageMotorL.config_kI(0, storage_kI);
storageMotorL.configNominalOutputForward(0, TIMEOUT);
storageMotorL.configNominalOutputReverse(0, TIMEOUT);
storageMotorL.configPeakOutputForward(+1, TIMEOUT);
storageMotorL.configPeakOutputReverse(-1, TIMEOUT);
storageMotorL.enableCurrentLimit(true);
storageMotorL.configPeakCurrentLimit(10, TIMEOUT);
storageMotorL.configContinuousCurrentLimit(10, TIMEOUT);
storageMotorL.configPeakCurrentDuration(1800, TIMEOUT);
storageMotorL.setNeutralMode(NeutralMode.Brake);
stopfeeder();
}
public void stopfeeder(){
feederPosition = feederMotor.getSelectedSensorPosition();
feederMotor.set(ControlMode.Position, feederPosition);
}
public void stopStorage(){
storageMotorH.set(ControlMode.PercentOutput, 0);
storageMotorL.set(ControlMode.PercentOutput, 0);
}
public void stopIntake(){
intakeMotor.set(ControlMode.PercentOutput, 0);
}
public void stopShooter(){
shooter.set(TalonFXControlMode.PercentOutput, 0);
}
public void reverseStorage(){
storageMotorH.set(ControlMode.PercentOutput, -storageRpms);
storageMotorL.set(ControlMode.PercentOutput, storageRpms);
}
public void startStorage(){
storageMotorH.set(ControlMode.PercentOutput, storageRpms);
storageMotorL.set(ControlMode.PercentOutput, -storageRpms);
}
public void startFeeder(){
feederMotor.set(ControlMode.PercentOutput, -feederRpms);
}
public void startShooter(){
shooter.set(ControlMode.Velocity, -shooterRpms);
// shooter.set(ControlMode.PercentOutput, -1);
}
public void lowerGatherer(){
gatherer.set(true);
}
public void raiseGatherer(){
gatherer.set(false);
}
public void feeder(){
if (oi.pilot.getRawButton(Buttons.A)) {
if (!feederButton) {
startFeeder();
feederButton = true;
}
}
else {
if (feederButton) {
stopfeeder();
feederButton = false;
}
}
}
public void store(){
startStorage();
switch (state){
case Wait:
// System.out.println("Stopped");
spinTimer = spinSetPoint;
stopStorage();
waitTimer --;
if(waitTimer <= 0 ){
state = State.Spin;
}
break;
case Spin:
waitTimer = waitSetPoint;
spinTimer--;
startStorage();
if(spinTimer <= 0){
state = State.Wait;
}
//System.out.println("Spinning");
}
}
public void storage(){
if (disableAll) {
stopStorage();
}
else if(oi.copilot.getRawButton(Buttons.right_Bumper))
{
reverseStorage();
}
else {
if(oi.pilot.getRawButton(Buttons.A)){
startStorage();
}
else{
store();
}
}
}
public void startIntake(){
intakeMotor.set(ControlMode.PercentOutput, -intakeRpms);
}
public void intake() {
if (disableAll || oi.pilot.getRawButton(Buttons.A)) {
stopIntake();
}
else if (oi.copilot.getRawButton(Buttons.left_Bumper) || oi.copilot.getRawButton(Buttons.right_Bumper)) {
intakeMotor.set(ControlMode.PercentOutput, intakeRpms);
}
else {
intakeMotor.set(ControlMode.PercentOutput, -intakeRpms);// Will need to be velocity
}
}
public void shoot() {
if (disableAll) {
stopShooter();
}
else {
startShooter();
}
}
public void go(){
if(oi.copilot.getRawButton(Buttons.Y)){
disableAll = false;
}
else{
disableAll = true;
}
if(oi.pilot.getRawButton(Buttons.left_Bumper)){
lowerGatherer();
}
else{
raiseGatherer();
}
intake();
shoot();
storage();
feeder();
}
public void startWithoutButton(){
startStorage();
startFeeder();
startShooter();
startIntake();
}
public void stopWithoutButton(){
stopfeeder();
stopShooter();
stopStorage();
stopIntake();
}
} | 34.580442 | 153 | 0.639756 |
ac70f74bb09b66491f6c24a94f83a43a7452b0a8 | 7,486 | package com.Tai;
import spos.lab1.demo.Conjunction;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
public class Manager {
private InetSocketAddress address;
private int maxConnection;
private List<Process> clientProcesses;
private boolean promptEnabled;
private boolean calculationsEnabled;
private int connections = 0;
private Selector selector;
private ServerSocketChannel serverSocket;
private int fCase;
private String type;
private String path;
private static final long delta = 1000;
private Scanner sc;
private long lastPromptTime;
private long startTime;
private HashMap<String, Double> results;
private HashMap<String, Long> time;
NonblockingBufferedReader reader;
Manager(String bindAddress, int bindPort, int connectionNumber, int fCase, String type, boolean promptEnabled) {
address = new InetSocketAddress(bindAddress, bindPort);
maxConnection = connectionNumber;
this.promptEnabled = promptEnabled;
calculationsEnabled = true;
clientProcesses = new ArrayList<>();
this.fCase = fCase;
this.type = type;
String classPath = System.getProperty("java.class.path");
String[] classpathEntries = classPath.split(";");
path = classpathEntries[0];
sc = new Scanner(System.in);
lastPromptTime = System.currentTimeMillis();
startTime = System.currentTimeMillis();
results = new HashMap<>();
time = new HashMap<>();
reader = new NonblockingBufferedReader(new BufferedReader(new InputStreamReader(System.in)));
}
void start() throws IOException {
selector = Selector.open();
serverSocket = ServerSocketChannel.open().bind(address);
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
compute("f");
compute("g");
//keep server running
while (calculationsEnabled) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey key : selectedKeys) {
if (key.isAcceptable()) {
register(serverSocket, selector);
} else if (key.isReadable()) {
SocketChannel clientSocket = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(256);
clientSocket.read(buffer);
String result = new String(buffer.array()).trim();
addResult(result);
//clientSocket.close();
}
}
if (connections <= 0)
calculationsEnabled = false;
prompt();
}
}
private void register(ServerSocketChannel serverSocket, Selector selector) throws IOException {
SocketChannel client = serverSocket.accept();
if (client != null) {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
connections++;
}
}
void stop() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void compute(String function) {
ProcessBuilder clientBuilder =
new ProcessBuilder("java", "-jar", "C:\\Users\\Taya\\Documents\\Projects\\3course\\SystemProgramming\\Lab\\out\\production\\Lab" + "\\" + "Lab1-Client.jar",
address.getHostString(),
Integer.toString(address.getPort()),
type,
function,
Integer.toString(fCase));
try {
clientProcesses.add(clientBuilder.start());
} catch (IOException e) {
e.printStackTrace();
}
}
private void prompt() {
promptA();
promptB();
}
private void promptA() {
if (!calculationsEnabled)
return;
try {
String line = reader.readLine();
if (line != null) {
if (line.equals("a") || line.equals("b") || line.equals("c"))
return;
if (line.equals("q"))
calculationsEnabled = false;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void promptB() {
if (promptEnabled && (System.currentTimeMillis() - lastPromptTime) > delta) {
System.out.println("Computation taking too long. Would you like to:");
System.out.println("(a) continue");
System.out.println("(b) continue without prompt");
System.out.println("(c) cancel");
boolean correct = false;
while (!correct) {
String line = String.valueOf(sc.next().charAt(0));
line = line.toLowerCase();
correct = true;
lastPromptTime = System.currentTimeMillis();
switch (line) {
case "a": {
lastPromptTime = System.currentTimeMillis();
System.out.println("Continue");
break;
}
case "b": {
promptEnabled = false;
System.out.println("Prompt disabled");
break;
}
case "c":
case "q": {
calculationsEnabled = false;
System.out.println("Canceled");
break;
}
default: {
correct = false;
System.out.println("Incorrect response: " + line);
}
}
}
}
}
private void killClientProcesses() {
for (Process i : clientProcesses) {
i.destroy();
}
}
public void quit() {
killClientProcesses();
stop();
reader.close();
System.out.flush();
}
private void addResult(String result) {
String[] args = result.split(" ");
if (args.length < 2)
return;
connections--;
String name = args[0];
double value = Double.parseDouble(args[1]);
System.out.println(name);
System.out.println(value);
results.put(name, value);
Long t = System.currentTimeMillis() - startTime;
time.put(name, t);
if (value == 0.0)
calculationsEnabled = false;
}
HashMap<String, Double> getResults() {
return results;
}
HashMap<String, Long> getTime() {
return time;
}
Double getConjunction() {
if (results.getOrDefault("f", 1.0) == 0.0 || results.getOrDefault("g", 1.0) == 0.0)
return 0.0;
else if (results.getOrDefault("f", 1.0) == 1.0 || results.getOrDefault("g", 1.0) == 1.0)
return null;
return results.get("f") * results.get("g");
}
}
| 30.555102 | 172 | 0.541277 |
0fcca2e462283ee6511afa8eb08f2e424f44d44a | 6,929 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/channel/v1/common.proto
package com.google.cloud.channel.v1;
public final class CommonProto {
private CommonProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_channel_v1_EduData_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_channel_v1_EduData_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_channel_v1_CloudIdentityInfo_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_channel_v1_CloudIdentityInfo_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_channel_v1_Value_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_channel_v1_Value_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_channel_v1_AdminUser_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_channel_v1_AdminUser_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n$google/cloud/channel/v1/common.proto\022\027" +
"google.cloud.channel.v1\032\037google/api/fiel" +
"d_behavior.proto\032\031google/protobuf/any.pr" +
"oto\032\034google/api/annotations.proto\"\260\003\n\007Ed" +
"uData\022F\n\016institute_type\030\001 \001(\0162..google.c" +
"loud.channel.v1.EduData.InstituteType\022F\n" +
"\016institute_size\030\002 \001(\0162..google.cloud.cha" +
"nnel.v1.EduData.InstituteSize\022\017\n\007website" +
"\030\003 \001(\t\"H\n\rInstituteType\022\036\n\032INSTITUTE_TYP" +
"E_UNSPECIFIED\020\000\022\007\n\003K12\020\001\022\016\n\nUNIVERSITY\020\002" +
"\"\271\001\n\rInstituteSize\022\036\n\032INSTITUTE_SIZE_UNS" +
"PECIFIED\020\000\022\016\n\nSIZE_1_100\020\001\022\020\n\014SIZE_101_5" +
"00\020\002\022\021\n\rSIZE_501_1000\020\003\022\022\n\016SIZE_1001_200" +
"0\020\004\022\022\n\016SIZE_2001_5000\020\005\022\023\n\017SIZE_5001_100" +
"00\020\006\022\026\n\022SIZE_10001_OR_MORE\020\007\"\200\003\n\021CloudId" +
"entityInfo\022N\n\rcustomer_type\030\001 \001(\01627.goog" +
"le.cloud.channel.v1.CloudIdentityInfo.Cu" +
"stomerType\022\033\n\016primary_domain\030\t \001(\tB\003\340A\003\022" +
"\037\n\022is_domain_verified\030\004 \001(\010B\003\340A\003\022\027\n\017alte" +
"rnate_email\030\006 \001(\t\022\024\n\014phone_number\030\007 \001(\t\022" +
"\025\n\rlanguage_code\030\010 \001(\t\022\036\n\021admin_console_" +
"uri\030\n \001(\tB\003\340A\003\0222\n\010edu_data\030\026 \001(\0132 .googl" +
"e.cloud.channel.v1.EduData\"C\n\014CustomerTy" +
"pe\022\035\n\031CUSTOMER_TYPE_UNSPECIFIED\020\000\022\n\n\006DOM" +
"AIN\020\001\022\010\n\004TEAM\020\002\"\231\001\n\005Value\022\025\n\013int64_value" +
"\030\001 \001(\003H\000\022\026\n\014string_value\030\002 \001(\tH\000\022\026\n\014doub" +
"le_value\030\003 \001(\001H\000\022+\n\013proto_value\030\004 \001(\0132\024." +
"google.protobuf.AnyH\000\022\024\n\nbool_value\030\005 \001(" +
"\010H\000B\006\n\004kind\"C\n\tAdminUser\022\r\n\005email\030\001 \001(\t\022" +
"\022\n\ngiven_name\030\002 \001(\t\022\023\n\013family_name\030\003 \001(\t" +
"Bl\n\033com.google.cloud.channel.v1B\013CommonP" +
"rotoP\001Z>google.golang.org/genproto/googl" +
"eapis/cloud/channel/v1;channelb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.protobuf.AnyProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_cloud_channel_v1_EduData_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_channel_v1_EduData_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_channel_v1_EduData_descriptor,
new java.lang.String[] { "InstituteType", "InstituteSize", "Website", });
internal_static_google_cloud_channel_v1_CloudIdentityInfo_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_channel_v1_CloudIdentityInfo_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_channel_v1_CloudIdentityInfo_descriptor,
new java.lang.String[] { "CustomerType", "PrimaryDomain", "IsDomainVerified", "AlternateEmail", "PhoneNumber", "LanguageCode", "AdminConsoleUri", "EduData", });
internal_static_google_cloud_channel_v1_Value_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_channel_v1_Value_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_channel_v1_Value_descriptor,
new java.lang.String[] { "Int64Value", "StringValue", "DoubleValue", "ProtoValue", "BoolValue", "Kind", });
internal_static_google_cloud_channel_v1_AdminUser_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_channel_v1_AdminUser_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_channel_v1_AdminUser_descriptor,
new java.lang.String[] { "Email", "GivenName", "FamilyName", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.protobuf.AnyProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 56.333333 | 168 | 0.754366 |
b0926d37f3409ed5107b9e3c1163aed9487ccf1b | 17,111 | package lantern;
/*
* Copyright (C) 2010 Michael Ronald Adams.
* All rights reserved.
*
* 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 code 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.
*/
import java.util.Random;
import java.awt.*;
import java.awt.Window.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JDialog;
import java.io.*;
import java.net.*;
import java.lang.Thread.*;
import java.applet.*;
import javax.swing.GroupLayout.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import java.lang.Integer;
import javax.swing.text.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.Timer;
import java.util.TimerTask;
/*
public class connectFour extends JApplet
{
//public static void main(String[] args)
//{
public void init()
{
fourFrame frame = new fourFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(500,500);
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setTitle("Connect Four");
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
}// end main class
}// end main class
*/
class connectFour extends JInternalFrame implements ActionListener
{
int[] xtops;
int maxX;
int maxY;
int xhit, yhit;
int [] myboard;
int gridXpoint;
int gridYpoint;
int gridWidth;
int gridHeight;
int myX;
int myY;
fourclass fourgame;
int turntype;
myparameters parm;
JMenuItem newgame;
JCheckBoxMenuItem diff1;
JCheckBoxMenuItem diff2;
JCheckBoxMenuItem diff3;
JCheckBoxMenuItem diff4;
class myparameters
{
public int turn;
public int noDraw;
public int gameover;
public int lastx;
public int lasty;
public myparameters()
{
turn=0;
noDraw=1;
gameover=0;
lastx=-1;
lasty=-1;
}
}
connectFour()
{
super("Connect Four",
true, //resizable
true, //closable
true, //maximizable
true);//iconifiable
setSize(500,500);
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Connect Four");
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
parm = new myparameters();
maxX=7;
maxY=6;
parm.turn=0;
turntype=0;
myX=0;
myY=0;
gridXpoint = 80;
gridYpoint = 50;
gridWidth = 40;
gridHeight = 40;
parm.noDraw=1;
myboard = new int[64];// able to handle 8 by 8 and 7 by 6
for( int b=0; b< maxX * maxY; b++)
myboard[b] =0;
xtops = new int[8];
for(int a = 0; a < maxX; a++)
xtops[a]=0;
fourgame = new fourclass();
fourPanel panel = new fourPanel();
add(panel);
/************ Menu *************/
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
newgame = new JMenuItem("New Game");
file.add(newgame);
newgame.addActionListener(this);
menu.add(file);
JMenu diff = new JMenu("Difficulty");
diff1 = new JCheckBoxMenuItem("Normal");
diff.add(diff1);
diff1.addActionListener(this);
diff2 = new JCheckBoxMenuItem("Moderate");
diff.add(diff2);
diff2.addActionListener(this);
diff3 = new JCheckBoxMenuItem("Hard");
diff.add(diff3);
diff3.addActionListener(this);
diff4 = new JCheckBoxMenuItem("Difficult");
diff.add(diff4);
diff4.addActionListener(this);
menu.add(diff);
setJMenuBar(menu);
diff1.setSelected(true);
}// end constructor
public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand().equals("New Game"))
{
// newgame
if(parm.noDraw == 1)
{
maxX=7;
maxY=6;
parm.turn=0;
for(int a =0; a< 8; a++)
xtops[a]=0;
for(int a=0; a< 64; a++)
myboard[a]=0;
parm.gameover=0;
parm.lastx=-1;
parm.lasty=-1;
repaint();
fourgame.reset();
fourgame.type=0;
// now toggle side to move
if(turntype == 0)
{
turntype = 1;
// we feed them maxX instead of a move so the move is off the playable board
mythreadobject runthis= new mythreadobject( maxX, maxY, xtops, parm, fourgame, myboard, xhit, gridXpoint, gridYpoint, gridHeight, gridWidth);
Thread t1 = new Thread(runthis);
t1.start();
}
else
{
turntype=0;
}
}
}// end if new game
if(event.getActionCommand().equals("Normal"))
{
setDifficultyCheck(0);
}// end normal
if(event.getActionCommand().equals("Moderate"))
{
setDifficultyCheck(1);
}
if(event.getActionCommand().equals("Hard"))
{
setDifficultyCheck(2);
}
if(event.getActionCommand().equals("Difficult"))
{
setDifficultyCheck(3);
}
}
// end action performed method
void setDifficultyCheck(int n)
{
if(n == 0)
{
fourgame.level=1;
diff1.setSelected(true);
diff2.setSelected(false);
diff3.setSelected(false);
diff4.setSelected(false);
}
if(n == 1)
{
fourgame.level=2;
diff1.setSelected(false);
diff2.setSelected(true);
diff3.setSelected(false);
diff4.setSelected(false);
}
if(n == 2)
{
fourgame.level=3;
diff1.setSelected(false);
diff2.setSelected(false);
diff3.setSelected(true);
diff4.setSelected(false);
}
if(n == 3)
{
fourgame.level=4;
diff1.setSelected(false);
diff2.setSelected(false);
diff3.setSelected(false);
diff4.setSelected(true);
}
}
class fourPanel extends JPanel implements MouseMotionListener, MouseListener
{
int myX;
int myY;
int oldmx;
int oldmy;
fourPanel()
{
addMouseMotionListener(this);
addMouseListener(this);
}
public void paintComponent(Graphics g2)
{ super.paintComponent(g2);
Color backColor, red, green, blue, orange, yellow, purple, white, black, colorEmpty;
backColor = new Color(255,255,255);
red = new Color(255,0,0);
green = new Color(0,255,0);
blue = new Color(0,0,255);
yellow = new Color(0,255,255);
purple = new Color(255, 255, 0);
orange = new Color(250, 250, 100);
white = new Color(255, 255, 255);
black = new Color(0, 0, 0);
setBackground(backColor);
colorEmpty = new Color(200,200,200);
Graphics2D g = (Graphics2D) g2;
g.setColor(blue);
// draw grid
for(int a=0; a<maxY + 1; a++)
g.fill(new Rectangle2D.Double((double)(gridXpoint), (double)(gridYpoint + a * gridHeight), (double)(maxX * gridWidth),(double) 2));
for(int a=0; a<maxX + 1; a++)
g.fill(new Rectangle2D.Double((double)(gridXpoint + a * gridWidth),(double)( gridYpoint), 2,(double)( maxY * gridHeight)));
// draw filled squares
g.setColor(white);
for(int a=0; a<maxX; a++)
for( int b=0; b<maxY; b++)
{
if(myboard[b * maxX + a] == 1)
{ g.setColor(red);
g2.fillOval((int)(gridXpoint + 2 + a * gridWidth),(int)( gridYpoint + 2 + b * gridHeight),(int)( gridWidth - 2), (int)(gridHeight - 2));
}
if(myboard[b * maxX + a] == 2)
{g.setColor(blue);
g2.fillOval((int)(gridXpoint + 2 + a * gridWidth),(int)( gridYpoint + 2 + b * gridHeight),(int)( gridWidth - 2),(int)( gridHeight - 2));
}
if(parm.lastx == a && parm.lasty == b)
{ g2.setColor(black);
g.fill(new Rectangle2D.Double((double)(gridXpoint + ((int) (gridWidth/2)-3) + a * gridWidth),(double)( gridYpoint + ((int) (gridHeight/2)-3) + b * gridHeight), 6, 6));
}
}
//g.DrawString(parm.turn + " Mouse " + myY,this.Font, mybrush1, 200, 400);
g.drawString("Max Depth Reached: " + fourgame.levelreached, 80,(int)( maxY * gridHeight + 80));
if(parm.gameover == 1)
g.drawString("Game Over, You Win", 270,(int)( maxY * gridHeight + 80));
if(parm.gameover == 2)
g.drawString("Game Over, Computer Wins", 270,(int)( maxY * gridHeight + 80));
if(parm.gameover == 3)
g.drawString("Game Over, Draw", 270,(int)( maxY * gridHeight + 80));
}
int findFour(int x, int token)
{
// our rows go 0-6 then 7-13 so we add 1 for the mod checks
//token is 1 or 2
int win=0;
int max=4;
//if(type==2)
// max=5;
// diagonal down
int count;
count=1;
int a;
for(a=1; a<max; a++) // up +11 down -9
if(x + (maxX+1) * a < maxX * maxY && (x+1 + (maxX +1) * a)%maxX !=1)
{
if(myboard[x + (maxX+1)*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x - (maxX+1) * a >= 0 && (x+1 - (maxX +1) * a)%maxX !=0)
{
if(myboard[x - (maxX+1)*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x - (maxX-1) * a >= 0 && (x+1 - (maxX - 1) * a) % maxX !=1)
{
if(myboard[x - (maxX-1)*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x + (maxX-1) * a < maxX * maxY && (x +1 + (maxX - 1) * a)%maxX !=0)
{
if(myboard[x + (maxX-1)*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x + maxX * a < maxX * maxY)
{
if(myboard[x + maxX*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x -maxX * a >= 0)
{
if(myboard[x - maxX*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x -1 * a >=0 && (x + 1 - a) % maxX != 0)
{
if(myboard[x - 1*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x + a < maxX * maxY && (x + 1 + a) % maxX != 1)
{
if(myboard[x + 1*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
return win;
}
/***************************** mouse events *****************************************/
void eventOutput(String eventDescription, MouseEvent e) {
/* oldmx=mx;
oldmy=my;
mx=e.getX();
my=e.getY();
*/
}
public void mouseMoved(MouseEvent e) {
eventOutput("Mouse moved", e);
}
public void mouseDragged(MouseEvent e) {
eventOutput("Mouse dragged", e);
}
public void mousePressed(MouseEvent e) {
if(parm.gameover >0)
return;
myX = e.getX();
myY = e.getY();
int squareX=0;
int squareY=0;
int aHit=0;
xhit=0;
yhit=0;
int a=0, b=0;
for(a=0; a<maxX; a++)
for(b=0; b<maxY; b++)
{
squareX=gridXpoint + 2 + a * gridWidth;
squareY=gridYpoint + 2 + b * gridHeight;
if(myX > squareX && myX < squareX + gridWidth)
if(myY > squareY && myY < squareY + 40)
{
aHit=1;
xhit=a;
yhit=b;
break;
}
}
if(aHit == 1 && xtops[xhit] < maxY && parm.turn %2== turntype)
{
yhit=maxY - (xtops[xhit]) -1; // we no longer require they hit the y square just that there is an available square in that column
myboard[maxX * yhit + xhit] =2;
xtops[xhit]++;
parm.turn ++;
parm.gameover=findFour(yhit*maxX + xhit, 2);
if(parm.turn == maxX * maxY && parm.gameover == 0)
parm.gameover=3;
myX=xhit;
myY=yhit;
repaint();
/* if(parm.gameover == 0)
{
// set new game to disable
//menuItem2.Enabled = false;
thread1.Start();
}
*/
if(parm.gameover == 0)
{
mythreadobject runthis= new mythreadobject( maxX, maxY, xtops, parm, fourgame, myboard, xhit, gridXpoint, gridYpoint, gridHeight, gridWidth);
Thread t1 = new Thread(runthis);
t1.start();
}// end if game not over
}
}
public void mouseEntered (MouseEvent me) {
}
public void mouseReleased (MouseEvent me) {
}
public void mouseExited (MouseEvent me) {
}
public void mouseClicked (MouseEvent me) {
}
}// end class fourpanel
/********************************* end mouse events **************************************/
class mythreadobject implements Runnable
{
int maxX, maxY, xhit, gridXpoint, gridYpoint, gridHeight, gridWidth;
myparameters parm;
int [] myboard;
int [] xtops;
fourclass fourgame;
public mythreadobject(int maxX1, int maxY1, int [] xtops1, myparameters parm1, fourclass fourgame1, int [] myboard1, int xhit1, int gridXpoint1, int gridYpoint1, int gridWidth1, int gridHeight1)
{
maxX=maxX1;
maxY=maxY1;
xhit=xhit1;
xtops = xtops1;
myboard = myboard1;
fourgame=fourgame1;
gridXpoint=gridXpoint1;
gridYpoint=gridYpoint1;
gridHeight=gridHeight1;
gridWidth=gridWidth1;
parm=parm1;
//Form1 myform1=new FormatException(myform);
}
public void run()
{
parm.noDraw=0;
// Thread current = Thread.CurrentThread;
int finalmove=fourgame.makemove(xhit);
int reversey=((maxY-xtops[finalmove]-1)*maxX);
if(reversey + finalmove >=0)
{
myboard[reversey+ finalmove]=1;
parm.gameover=findFour(reversey + finalmove, 1);
if(parm.gameover == 1)
parm.gameover=2;// 2 is computer wins
parm.lastx=finalmove;
parm.lasty=maxY-xtops[finalmove]-1;
parm.turn++;
if(parm.turn == maxX * maxY && parm.gameover == 0)
parm.gameover=3;
}
else
{
//myX=reversey + finalmove;
//myY=-1;
}
xtops[finalmove]++;
parm.noDraw=1;
//super.Invalidate();
repaint();
}
int findFour(int x, int token)
{
// our rows go 0-6 then 7-13 so we add 1 for the mod checks
//token is 1 or 2
int win=0;
int max=4;
//if(type==2)
// max=5;
// diagonal down
int count;
count=1;
int a;
for(a=1; a<max; a++) // up +11 down -9
if(x + (maxX+1) * a < maxX * maxY && (x+1 + (maxX +1) * a)%maxX !=1)
{
if(myboard[x + (maxX+1)*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x - (maxX+1) * a >= 0 && (x+1 - (maxX +1) * a)%maxX !=0)
{
if(myboard[x - (maxX+1)*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x - (maxX-1) * a >= 0 && (x+1 - (maxX - 1) * a) % maxX !=1)
{
if(myboard[x - (maxX-1)*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x + (maxX-1) * a < maxX * maxY && (x +1 + (maxX - 1) * a)%maxX !=0)
{
if(myboard[x + (maxX-1)*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x + maxX * a < maxX * maxY)
{
if(myboard[x + maxX*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x -maxX * a >= 0)
{
if(myboard[x - maxX*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
count=1;
for(a=1; a<max; a++) // up +11 down -9
if(x -1 * a >=0 && (x + 1 - a) % maxX != 0)
{
if(myboard[x - 1*a]==token)
count++;
else
a=max;
}
else
break;
for(a=1; a<max; a++) // up +11 down -9
if(x + a < maxX * maxY && (x + 1 + a) % maxX != 1)
{
if(myboard[x + 1*a]==token)
count++;
else
a=max;
}
else
break;
if(count >= max)
win=1;
return win;
} // end method
} // end class
}// end class fourframe
| 20.969363 | 202 | 0.536906 |
0bd9092d54ddd8dd0799f345d00547514b754fd5 | 5,440 | package com.automatedtest.sample.problem1;
import java.text.NumberFormat;
import java.util.Locale;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import com.automatedtest.sample.basepage.BasePage;
public class Problem1Page extends BasePage{
private static final String HOME_PAGE_URL = "https://www.exercise1.com/";
Problem1Page() {
PageFactory.initElements(driver, this);
}
void goToproblem1Page(String country){
driver.get(HOME_PAGE_URL + country);
wait.forLoading(5);
}
String getTitle() {
return driver.getTitle();
}
public void setValue1(String value)
{
driver.findElement(By.id("lb1_val_1")).sendKeys(value);
}
public void setValue2(String value)
{
driver.findElement(By.id("lb1_val_2")).sendKeys(value);
}
public void setValue3(String value)
{
driver.findElement(By.id("lb1_val_3")).sendKeys(value);
}
public void setValue4(String value)
{
driver.findElement(By.id("lb1_val_4")).sendKeys(value);
}
public void setValue5(String value)
{
driver.findElement(By.id("lb1_val_5")).sendKeys(value);
}
public String getTotalBase()
{
return driver.findElement(By.id("lbl_ttl_val")).getText();
}
public boolean verifyValue1Currency()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = "$"+formatter.format(value1);
if(moneyString.equals(value1_s))
{
return true;
}
else
{
return false;
}
}
public boolean verifyValue2Currency()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = "$"+formatter.format(value1);
if(moneyString.equals(value1_s))
{
return true;
}
else
{
return false;
}
}
public boolean verifyValue3Currency()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = "$"+formatter.format(value1);
if(moneyString.equals(value1_s))
{
return true;
}
else
{
return false;
}
}
public boolean verifyValue4Currency()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = "$"+formatter.format(value1);
if(moneyString.equals(value1_s))
{
return true;
}
else
{
return false;
}
}
public boolean verifyValue5Currency()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = "$"+formatter.format(value1);
if(moneyString.equals(value1_s))
{
return true;
}
else
{
return false;
}
}
public boolean verifyValue1GreaterThan0()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
if(value1>0)
{
return true;
}else
{
return false;
}
}
public boolean verifyValue2GreaterThan0()
{
String value1_s=driver.findElement(By.id("lb1_val_2")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
if(value1>0)
{
return true;
}else
{
return false;
}
}
public boolean verifyValue3GreaterThan0()
{
String value1_s=driver.findElement(By.id("lb1_val_3")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
if(value1>0)
{
return true;
}else
{
return false;
}
}
public boolean verifyValue4GreaterThan0()
{
String value1_s=driver.findElement(By.id("lb1_val_4")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
if(value1>0)
{
return true;
}else
{
return false;
}
}
public boolean verifyValue5GreaterThan0()
{
String value1_s=driver.findElement(By.id("lb1_val_5")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
if(value1>0)
{
return true;
}else
{
return false;
}
}
public int sumValue()
{
String value1_s=driver.findElement(By.id("lb1_val_1")).getText();
String value2_s=driver.findElement(By.id("lb1_val_2")).getText();
String value3_s=driver.findElement(By.id("lb1_val_3")).getText();
String value4_s=driver.findElement(By.id("lb1_val_4")).getText();
String value5_s=driver.findElement(By.id("lb1_val_5")).getText();
int value1 =Integer.parseInt(value1_s.substring(1,value1_s.length()));
int value2 =Integer.parseInt(value2_s.substring(1,value2_s.length()));
int value3 =Integer.parseInt(value3_s.substring(1,value3_s.length()));
int value4 =Integer.parseInt(value4_s.substring(1,value4_s.length()));
int value5 =Integer.parseInt(value5_s.substring(1,value5_s.length()));
int total=value1+value2+value3+value4+value5;
return total;
}
}
| 22.386831 | 84 | 0.706618 |
e057d9adf64d680f16951e74dd4361ba4a7d98f5 | 13,099 | /*
* Copyright (c) 1998 - 2010. University Corporation for Atmospheric Research/Unidata
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package thredds.server.wms;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import thredds.server.dataset.DatasetException;
import thredds.server.dataset.TdsRequestedDataset;
import thredds.server.wms.config.WmsDetailedConfig;
import ucar.nc2.Attribute;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.VariableDS;
import ucar.nc2.dt.GridDataset;
import ucar.nc2.dt.GridDatatype;
import uk.ac.rdg.resc.edal.cdm.CdmUtils;
import uk.ac.rdg.resc.edal.cdm.DataReadingStrategy;
import uk.ac.rdg.resc.edal.coverage.CoverageMetadata;
import uk.ac.rdg.resc.ncwms.controller.RequestParams;
import uk.ac.rdg.resc.ncwms.exceptions.WmsException;
import uk.ac.rdg.resc.ncwms.util.WmsUtils;
import uk.ac.rdg.resc.ncwms.wms.Dataset;
import uk.ac.rdg.resc.ncwms.wms.Layer;
import uk.ac.rdg.resc.ncwms.wms.VectorLayer;
/**
* A {@link uk.ac.rdg.resc.ncwms.wms.Dataset} that provides access to layers read from
* {@link ucar.nc2.dataset.NetcdfDataset} objects.
*
* @author Jon
*/
public class ThreddsDataset implements Dataset {
private static final Logger log = LoggerFactory.getLogger(ThreddsDataset.class);
private final String urlPath;
private final String title;
private final Map<String, ThreddsScalarLayer> scalarLayers = new LinkedHashMap<>();
private final Map<String, ThreddsVectorLayer> vectorLayers = new LinkedHashMap<>();
/**
* Creates a new ThreddsDataset with the given id from the given NetcdfDataset
*/
private ThreddsDataset(String urlPath, GridDataset gridDataset, WmsDetailedConfig wmsConfig) throws IOException {
this.urlPath = urlPath;
this.title = gridDataset.getTitle();
NetcdfDataset ncDataset = (NetcdfDataset) gridDataset.getNetcdfFile();
DataReadingStrategy drStrategy = CdmUtils.getOptimumDataReadingStrategy(ncDataset);
// Now load the scalar layers
Collection<CoverageMetadata> ccm = CdmUtils.readCoverageMetadata(gridDataset);
Iterator<CoverageMetadata> icm = ccm.iterator();
while (icm.hasNext()) {
CoverageMetadata cm = icm.next();
// Get the most appropriate data-reading strategy for this dataset
//PixelMap pxm = new PixelMap(cm.getHorizontalGrid(), null);
//DataReadingStrategy drStrategy = CdmUtils.getOptimumDataReadingStrategy( pxm, ncDataset );
GridDatatype gdt = gridDataset.findGridDatatype(cm.getId());
//GridDatatype gdt = gridDataset.findGridByShortName(cm.getId());
ThreddsScalarLayer tsl = ThreddsScalarLayer.getNewLayer(cm, gdt, drStrategy, this, wmsConfig);
this.scalarLayers.put(tsl.getName(), tsl);
}
//CdmUtils.findAndUpdateLayers( gridDataset, THREDDS_LAYER_BUILDER, this.scalarLayers );
// Find the vector quantities
Collection<VectorLayer> vectorLayersColl = WmsUtils.findVectorLayers(this.scalarLayers.values());
// Add the vector quantities to the map of layers
for (VectorLayer vecLayer : vectorLayersColl) {
// We must wrap these vector layers as ThreddsVectorLayers to ensure that
// the name of each layer matches its id.
ThreddsVectorLayer tdsVecLayer = new ThreddsVectorLayer(vecLayer);
tdsVecLayer.setLayerSettings(wmsConfig.getSettings(tdsVecLayer));
this.vectorLayers.put(vecLayer.getId(), tdsVecLayer);
}
}
/**
* Creates a new ThreddsDataset for one single layer
*/
private ThreddsDataset(String urlPath, GridDataset gd, List<String> layers, WmsDetailedConfig wmsConfig) {
this.urlPath = urlPath;
this.title = gd.getTitle();
NetcdfDataset ncDataset = (NetcdfDataset) gd.getNetcdfFile();
DataReadingStrategy drStrategy = CdmUtils.getOptimumDataReadingStrategy(ncDataset);
for (String layer : layers) {
//GridDatatype gdt = gd.findGridByShortName(layer);
GridDatatype gdt = gd.findGridDatatype(layer);
CoverageMetadata cm = CdmUtils.readCoverageMetadata(gdt);
ThreddsScalarLayer tsl = ThreddsScalarLayer.getNewLayer(cm, gdt, drStrategy, this, wmsConfig);
this.scalarLayers.put(tsl.getName(), tsl);
}
// Find the vector quantities
Collection<VectorLayer> vectorLayersColl = WmsUtils.findVectorLayers(this.scalarLayers.values());
// Add the vector quantities to the map of layers
for (VectorLayer vecLayer : vectorLayersColl) {
// We must wrap these vector layers as ThreddsVectorLayers to ensure that
// the name of each layer matches its id.
ThreddsVectorLayer tdsVecLayer = new ThreddsVectorLayer(vecLayer);
tdsVecLayer.setLayerSettings(wmsConfig.getSettings(tdsVecLayer));
this.vectorLayers.put(vecLayer.getId(), tdsVecLayer);
}
}
/**
* Uses the {@link #getDatasetPath() url path} as the unique id.
*/
@Override
public String getId() {
return this.urlPath;
}
@Override
public String getTitle() {
return this.title;
}
/**
* Gets the path that was specified on the incoming URL
*/
public String getDatasetPath() {
return this.urlPath;
}
/**
* Returns the current time, since datasets could change at any time without
* our knowledge.
*
* @see ThreddsServerConfig#getLastUpdateTime()
*/
@Override
public DateTime getLastUpdateTime() {
return new DateTime();
}
/**
* Gets the {@link uk.ac.rdg.resc.ncwms.wms.Layer} with the given {@link uk.ac.rdg.resc.ncwms.wms.Layer#getId() id}. The id
* is unique within the dataset, not necessarily on the whole server.
*
* @return The layer with the given id, or null if there is no layer with
* the given id.
* @todo repetitive of code in ncwms.config.Dataset: any way to refactor?
*/
@Override
public ThreddsLayer getLayerById(String layerId) {
ThreddsLayer layer = this.scalarLayers.get(layerId);
if (layer == null)
layer = this.vectorLayers.get(layerId);
return layer;
}
/**
* @todo repetitive of code in ncwms.config.Dataset: any way to refactor?
*/
@Override
public Set<Layer> getLayers() {
Set<Layer> layerSet = new LinkedHashSet<>();
layerSet.addAll(this.scalarLayers.values());
layerSet.addAll(this.vectorLayers.values());
return layerSet;
}
/**
* Returns an empty string
*/
@Override
public String getCopyrightStatement() {
return "";
}
/**
* Returns an empty string
*/
@Override
public String getMoreInfoUrl() {
return "";
}
@Override
public boolean isReady() {
return true;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isError() {
return false;
}
@Override
public Exception getException() {
return null;
}
@Override
public boolean isDisabled() {
return false;
}
/**
* Builds a ThreddsDataset specific for each WMS requests that contains only the layers needed by the requests.
*
* @return ThreddsDataset
* @throws IOException
* @throws DatasetException
* @throws WmsException
*/
static ThreddsDataset getThreddsDatasetForRequest(String request, GridDataset gridDataset, TdsRequestedDataset reqDataset, WmsDetailedConfig wmsConfig, RequestParams params) throws IOException, DatasetException, WmsException {
ThreddsDataset tdsds = null;
//GetLegendGraphic may not even need to create a ThreddsDataset (if no text is required)
if (request.equals("GetLegendGraphic") && params.getString("LAYER") == null) return null;
if (params.getString("LAYERS") == null && params.getString("LAYER") == null && params.getString("LAYERNAME") == null) {
tdsds = new ThreddsDataset(reqDataset.getPath(), gridDataset, wmsConfig);
} else {
//Only one layer for each request. Need two components for vector layers!
String layers = params.getString("LAYERS");
if (layers == null)
layers = params.getString("LAYER");
if (layers == null)
layers = params.getString("LAYERNAME");
List<String> requestedLayers = getLayerComponents(gridDataset, layers);
tdsds = new ThreddsDataset(reqDataset.getPath(), gridDataset, requestedLayers, wmsConfig);
}
return tdsds;
}
/**
* Here we have to revert what was done in WMSUtils methods for creating the virtual datasets
*/
private static List<String> getLayerComponents(GridDataset gd, String layer) {
List<String> layers = new ArrayList<>();
//Layer name is grid.getFullName() --> vs.getFullName()
GridDatatype grid = gd.findGridDatatype(layer); //Actually searches by vs.getFullName()
if (grid == null) {
List<GridDatatype> grids = gd.getGrids();
Iterator<GridDatatype> gridsIt = grids.iterator();
while (gridsIt.hasNext() && layers.size() < 2) {
GridDatatype g = gridsIt.next();
//Search the components by standard_name, long_name and fullname
VariableDS var = g.getVariable();
Attribute stdName = var.findAttributeIgnoreCase("standard_name");
if (stdName != null) {
if (isComponent(layer, stdName.getStringValue()))
layers.add(var.getFullName());
} else {
Attribute longName = var.findAttributeIgnoreCase("long_name");
if (longName != null) {
if (isComponent(layer, longName.getStringValue()))
layers.add(var.getFullName());
} else {//full name
if (isComponent(layer, var.getFullName()))
layers.add(var.getFullName());
}
}
}
} else {
layers.add(layer);
}
return layers;
}
/**
* Returns true if the layerName contains some of the standard components prefixes for CF-1.0 or
* Grib convention
*/
static boolean isComponent(String layerName, String varAtt) {
if (varAtt.contains("eastward_") || varAtt.contains("northward_")) {
//CF-Conventions
String[] tokens = layerName.split("_");
StringBuilder sb = new StringBuilder();
if (tokens.length == 1) {
sb.append(tokens[0]).append("\\b");
} else {
sb.append(tokens[0]).append("\\B");
for (int i = 1; i < tokens.length - 1; i++) {
sb.append(".*\\B").append(tokens[i]).append("\\B");
}
sb.append(".*\\B").append(tokens[tokens.length - 1]).append("\\b");
}
Pattern pattern = Pattern.compile(sb.toString());
Matcher matcher = pattern.matcher(varAtt);
return matcher.find();
}
return varAtt.contains("u-component of " + layerName) || varAtt.contains("v-component of " + layerName);
}
} | 35.986264 | 229 | 0.687839 |
112e0a4a4fbbfe5aae114a52f250762de829e08e | 875 | package net.jsunit;
import junit.framework.TestCase;
import net.jsunit.model.Browser;
public class BrowserLaunchSpecificationTest extends TestCase {
public void testNoOverride() {
BrowserLaunchSpecification spec = new BrowserLaunchSpecification(new Browser("mybrowser.exe", 0));
assertFalse(spec.hasOverrideUrl());
assertNull(spec.getOverrideUrl());
spec = new BrowserLaunchSpecification(new Browser("mybrowser.exe", 0), " ");
assertFalse(spec.hasOverrideUrl());
}
public void testOverride() {
BrowserLaunchSpecification spec = new BrowserLaunchSpecification(
new Browser("mybrowser.exe", 0),
"http://www.example.com"
);
assertTrue(spec.hasOverrideUrl());
assertEquals("http://www.example.com", spec.getOverrideUrl());
}
}
| 32.407407 | 107 | 0.652571 |
8fd7a75e523e3146c100a88fe045d0c486ee4947 | 6,948 | package com.remswork.project.alice.web.service;
import java.util.List;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.remswork.project.alice.exception.ScheduleException;
import com.remswork.project.alice.model.Schedule;
import com.remswork.project.alice.model.support.Message;
import com.remswork.project.alice.service.ScheduleService;
import com.remswork.project.alice.web.bean.TargetPropertiesBean;
import com.remswork.project.alice.web.service.exception.ScheduleServiceException;
@Service
public class ScheduleServiceImpl implements ScheduleService {
@Autowired
private TargetPropertiesBean targetProperties;
private final String payload = "schedule";
@Override
public Schedule getScheduleById(long id) throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
uri.append("/");
uri.append(id);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Response response = target.request().get();
if(response.getStatus() == 200) {
return (Schedule) response.readEntity(Schedule.class);
}else if(response.getStatus() == 404){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
@Override
public List<Schedule> getScheduleList() throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Response response = target.request().get();
if(response.getStatus() == 200) {
return (List<Schedule>) response.readEntity(new GenericType<List<Schedule>>() {});
}else if(response.getStatus() == 404){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
@Override
public Set<Schedule> getScheduleListByTeacherId(long teacherId) throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Response response = target.queryParam("teacherId", teacherId).request().get();
if(response.getStatus() == 200) {
return (Set<Schedule>) response.readEntity(new GenericType<Set<Schedule>>() {});
}else if(response.getStatus() == 404){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
@Override
public Schedule addSchedule(Schedule schedule) throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Builder builder = target.request();
builder.accept("application/json");
Response response = builder.post(Entity.json(schedule));
if(response.getStatus() == 201) {
return (Schedule) response.readEntity(Schedule.class);
}else if(response.getStatus() == 400){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
@Override
public Schedule updateScheduleById(long id, Schedule newSchedule) throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
uri.append("/");
uri.append(id);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Builder builder = target.request();
builder.accept("application/json");
Response response = builder.put(Entity.json(newSchedule));
if(response.getStatus() == 200) {
return (Schedule) response.readEntity(Schedule.class);
}else if(response.getStatus() == 400){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
@Override
public Schedule deleteScheduleById(long id) throws ScheduleException {
try {
StringBuilder uri = new StringBuilder();
uri.append(targetProperties.getDomain());
uri.append("/");
uri.append(targetProperties.getBaseUri());
uri.append("/");
uri.append(payload);
uri.append("/");
uri.append(id);
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uri.toString());
Builder builder = target.request();
builder.accept("application/json");
Response response = builder.delete();
if(response.getStatus() == 200) {
return (Schedule) response.readEntity(Schedule.class);
}else if(response.getStatus() == 400){
Message message = (Message) response.readEntity(Message.class);
throw new ScheduleServiceException(message.getMessage());
}else
throw new ScheduleServiceException("The request might invalid or server is down");
}catch(ScheduleServiceException e) {
throw new ScheduleException(e.getMessage());
}
}
}
| 34.914573 | 93 | 0.726684 |
a02f0a6c04362561162a9cec378647117a39ab57 | 1,908 | package leetcode.mide;
/**
* @Author wyc1856
* @Date 2018/11/15 19:36
* @Description https://leetcode-cn.com/problems/add-two-numbers
**/
public class AddTwoNumber {
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
ListNode l2 = new ListNode(4);
ListNode l3 = new ListNode(3);
l1.next = l2;
l2.next = l3;
ListNode r1 = new ListNode(5);
ListNode r2 = new ListNode(6);
ListNode r3 = new ListNode(4);
r1.next = r2;
r2.next = r3;
System.out.println(compute(l1, r1));
}
public static ListNode compute(ListNode l, ListNode r){
//假表头
ListNode dummyHead = new ListNode(0);
ListNode current = dummyHead;
//进位标识
int carry = 0;
while (l != null || r != null){
int x = l == null ? 0 : l.val;
int y = r == null ? 0 : r.val;
int eachSum = x + y + carry;
carry = eachSum / 10;
current.next = new ListNode(eachSum % 10);
current = current.next;
if (l != null) {
l = l.next;
}
if (r != null) {
r = r.next;
}
}
//最高位之和存在进位
if (carry > 0){
current.next = new ListNode(carry);
}
return dummyHead.next;
}
static class ListNode{
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(val);
while (next != null){
stringBuilder.append("->");
stringBuilder.append(next.val);
next = next.next;
}
return stringBuilder.toString();
}
}
}
| 25.44 | 64 | 0.484277 |
9046f073cc9537f8152e90f0da7f07379e3174ed | 1,886 | package com.example.weburlshortener.controller.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.example.weburlshortener.model.Url;
import com.example.weburlshortener.service.UrlServiceImpl;
@Controller
public class IndexController {
@Value("${app.homeUrlPath}")
protected String homeUrlPath;
@Autowired
protected UrlServiceImpl urlService;
@GetMapping("/{key}")
public ResponseEntity<?> redirect(@PathVariable String key)
{
HttpHeaders responseHeaders = new HttpHeaders();
HttpStatus status = HttpStatus.MOVED_PERMANENTLY;
Url url = this.urlService.getUrlByShortKeyAndIncrementTopHits(key);
// Redirect to homepage if url was not found
if (url == null) {
responseHeaders.set("Location", this.homeUrlPath);
status = HttpStatus.MOVED_PERMANENTLY;
}
else {
responseHeaders.set("Location", url.getAddress());
status = url.getRedirectType() == 302 ? HttpStatus.MOVED_TEMPORARILY : HttpStatus.MOVED_PERMANENTLY;
}
return ResponseEntity.status(status)
.headers(responseHeaders)
.build();
}
@RequestMapping("/")
public ModelAndView index()
{
ModelAndView mv = new ModelAndView("index");
String name = "Vedran";
mv.addObject("name", name);
return mv;
}
@RequestMapping("/help")
public ModelAndView help()
{
ModelAndView mv = new ModelAndView("help");
return mv;
}
}
| 26.194444 | 103 | 0.758749 |
4c642b1c8f43e41bbec8ff87e4d8fa858039a72f | 888 | package zone.nora.slothpixel.example.java;
import zone.nora.slothpixel.Slothpixel;
import zone.nora.slothpixel.player.Player;
import zone.nora.slothpixel.player.stats.tkr.Tkr;
public class GetPlayerExampleJava {
public static void main(String[] args) {
// Make an instance of the Slothpixel API.
Slothpixel slothpixel = new Slothpixel();
// Save a request as a local variable.
Player player = slothpixel.getPlayer("Aerondight");
System.out.println("UUID: " + player.getUuid());
System.out.println("Karma: " + player.getKarma());
System.out.println("Discord: " + player.getLinks().getDiscord());
// Save a specific game's stats.
Tkr tkr = player.getStats().getTkr();
System.out.println("Coins: " + tkr.getCoins());
System.out.println("Gold Trophies: " + tkr.getTrophies().getGold());
}
}
| 35.52 | 76 | 0.661036 |
e04eb0f51bd301ff2152f5646733add08e093543 | 1,691 | package de.codecentric.reedelk.admin.console;
import de.codecentric.reedelk.runtime.api.annotation.ModuleComponent;
import de.codecentric.reedelk.runtime.api.component.ProcessorSync;
import de.codecentric.reedelk.runtime.api.flow.FlowContext;
import de.codecentric.reedelk.runtime.api.message.Message;
import de.codecentric.reedelk.runtime.api.message.MessageBuilder;
import de.codecentric.reedelk.runtime.rest.api.InternalAPI;
import de.codecentric.reedelk.runtime.rest.api.module.v1.ModulePUTReq;
import de.codecentric.reedelk.runtime.rest.api.module.v1.ModulePUTRes;
import de.codecentric.reedelk.runtime.system.api.ModuleService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import static org.osgi.service.component.annotations.ServiceScope.PROTOTYPE;
@ModuleComponent("Update module")
@Component(service = ModuleUpdate.class, scope = PROTOTYPE)
public class ModuleUpdate implements ProcessorSync {
@Reference
private ModuleService moduleService;
@Override
public Message apply(FlowContext flowContext, Message message) {
String payload = message.payload();
String resultJson = update(payload);
return MessageBuilder.get(ModuleUpdate.class)
.withJson(resultJson)
.build();
}
private String update(String json) {
ModulePUTReq putRequest = InternalAPI.Module.V1.PUT.Req.deserialize(json);
long moduleId = moduleService.update(putRequest.getModuleFilePath());
ModulePUTRes dto = new ModulePUTRes();
dto.setModuleId(moduleId);
return InternalAPI.Module.V1.PUT.Res.serialize(dto);
}
}
| 34.510204 | 82 | 0.765228 |
7db204a60f949219bcc65d36ca219ee10b376ca5 | 3,445 | package com.test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.domain.Department;
import com.domain.Employee;
public class Many2One {
public static void main(String[] args) {
// add();
// get();
// Employee employ = query(1);
// System.out.println("deaprt name �� " + employ.getDepart().getName() );
Department depart = add();
queryDepart(depart.getId());
}
//add
static Department add() {
Session session = null;
Transaction tx = null;
try {
Department depart = new Department();
depart.setName("depart1");
// Employee employ = new Employee();
// employ.setDepart(depart);
// employ.setName("employname");
Employee employ1 = new Employee();
employ1.setDepart(depart);
employ1.setName("employname1");
Employee employ2 = new Employee();
employ2.setDepart(depart);
employ2.setName("employname2");
session = HibernateUtil.getSession();
tx = session.beginTransaction();
session.save(depart);
session.save(employ1);
session.save(employ2);
tx.commit();
return depart;
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
if (session != null)
session.close();
}
}
//get
static Employee get() {
Session session = null;
Employee employ = null;
try {
session = HibernateUtil.getSession();
employ = (Employee) session.get(Employee.class, 1);
return employ;
} catch (HibernateException e) {
throw e;
} finally {
if (session != null)
session.close();
}
}
static Department queryDepart(int departId) {
Session session = null;
Department depart = null;
try {
session = HibernateUtil.getSession();
depart = (Department) session.get(Department.class, departId);
System.out.println("" + depart.getEmps().size());
System.out.println(depart.getEmps());
Set<Employee> set = new HashSet<Employee>();
set = depart.getEmps();
Iterator it = set.iterator();
while (it.hasNext()) {
Employee em = new Employee();
em = (Employee) it.next();
System.out.println(em.getName());
}
return depart;
} catch (HibernateException e) {
throw e;
} finally {
if (session != null)
session.close();
}
}
//query
static Employee query(int empId) {
Session session = null;
Employee employ = null;
try {
session = HibernateUtil.getSession();
employ = (Employee) session.get(Employee.class, empId);
System.out.println(" " + employ.getDepart().getName());
return employ;
} catch (HibernateException e) {
throw e;
} finally {
if (session != null)
session.close();
}
}
}
| 25.708955 | 74 | 0.531205 |
1877eb38dca61b09aba0efd7860ca3b40107c903 | 208 | package org.sofwerx.sqan.manet.bt.helper;
import java.io.IOException;
/**
* Interface for BTSocket write listeners
*/
public interface WriteListener {
void onSuccess();
void onError(IOException e);
}
| 16 | 42 | 0.745192 |
bc8d2b4ac970d0d4fac5e173c153484a7ae08bb5 | 2,365 | package wong.spance.html;
/*
* Copyright 2010-2011 Spance Wong.
*
* 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.
*/
import wong.spance.html.element.Table;
import wong.spance.html.element.TableMeta;
import wong.spance.html.render.Modifier;
import wong.spance.html.render.ModifierProvider;
import wong.spance.html.span.CellSpan;
import wong.spance.html.stat.Statistics;
import wong.spance.html.store.DataStore;
import java.util.Map;
/**
* Created by spance on 14/4/4.
*/
public interface TableGroup {
/**
* 提供DataStore的实现为指定的数据源,简单情况下用SimpleDataStore
*
* @param data
*/
void apply(DataStore data);
TableMeta getMeta();
Table getTable();
/**
* 要执行单元格合并或者统计计算,则需要进行分组
* 分组规则CellSpan,已实现RowSpan来提供Y方向分组
* RowSpan提供链式语法,实现三种情况的分组
* on(index) 基于index列字面值的分组
* by(index1) - on(index2) 基于index1的字面值在index2上进行分组
* cascade(index1) - by(index2) - on(index3) 限制在index1的分组下,基于index2的字面值在index3上进行分组
*
* @param cellSpans
*/
void group(CellSpan... cellSpans);
/**
* 在分组后,可执行抽取简单的统计计算结果
* 统计规则由Statistics的链式语法提供,在Statistics.Rule中承载
* 若统计规则的选择面上出现非数字,那必然要异常
*
* @param rules
* @return 返回统计结果的字典,键=分组点的值,值=分组选择面上的按rule计算的结果
*/
Map<String, Number> statistics(Statistics.Rule... rules);
/**
* 对表格组件进行渲染输出
*
* @return
*/
String render();
/**
* 由更易用的 DefaultModifiers 提供Modifier供渲染期使用
*
* @param provider
* @return
*/
String render(ModifierProvider provider);
/**
* 手动提供Modifier的实现,需要实现handler方法
* Modifier定义为每个Element的渲染周期点进行修改调节
* 提供三类抽象实现
* BeforeRenderModifier 前置渲染调节器
* AfterRenderModifier 后置渲染调节器
* TextRenderModifier 文本内容渲染调节器
*
* @param modifiers
* @return
*/
String render(Modifier... modifiers);
}
| 24.894737 | 87 | 0.677801 |
5743c74e2b0a6df308f2255f2a7d7c1d77c45fda | 739 | package xyz.myhelper.sduthelper.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* @author dream
* Created by dream on 15-11-17.
* 版本检查
* @version 1.0
*/
public class VersionCheck {
// 获取当前版本号
public static String getVersionName(Context context) {
PackageManager packageManager = context.getPackageManager(); // 获取PackageManager的版本号
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return "error";
}
}
| 26.392857 | 97 | 0.668471 |
b9af25420db246b0bffac977ba2925a3115c8f41 | 314 | package com.lframework.xingyun.sc.mappers;
import com.lframework.starter.mybatis.mapper.BaseMapper;
import com.lframework.xingyun.sc.entity.TakeStockSheetDetail;
/**
* <p>
* 盘点单详情 Mapper 接口
* </p>
*
* @author zmj
*/
public interface TakeStockSheetDetailMapper extends BaseMapper<TakeStockSheetDetail> {
}
| 19.625 | 86 | 0.767516 |
d801cd1f7df769ee87fa76a0fe50668a559e50b5 | 263 | package com.evil.inc.taskrssosaml.service;
import com.evil.inc.taskrssosaml.domain.Task;
import java.util.List;
public interface TaskService {
Task addTask(Task task);
List<Task> getTasksByUsername(String username);
void deleteTaskById(long id);
}
| 21.916667 | 51 | 0.764259 |
0e85442ce6c3f4f7aae6b925085d483336cf6b18 | 3,712 | /*
* Copyright (c) 2016-2020, MiLaboratory LLC
* All Rights Reserved
*
* Permission to use, copy, modify and distribute any part of this program for
* educational, research and non-profit purposes, by non-profit institutions
* only, without fee, and without a written agreement is hereby granted,
* provided that the above copyright notice, this paragraph and the following
* three paragraphs appear in all copies.
*
* Those desiring to incorporate this work into commercial products or use for
* commercial purposes should contact MiLaboratory LLC, which owns exclusive
* rights for distribution of this program for commercial purposes, using the
* following email address: licensing@milaboratory.com.
*
* IN NO EVENT SHALL THE INVENTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
* SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE INVENTORS HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE INVENTORS HAS
* NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
* MODIFICATIONS. THE INVENTORS MAKES NO REPRESENTATIONS AND EXTENDS NO
* WARRANTIES OF ANY KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
* PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY
* PATENT, TRADEMARK OR OTHER RIGHTS.
*/
package com.milaboratory.minnn.util;
import cc.redberry.pipe.OutputPort;
import com.milaboratory.minnn.pattern.MatchIntermediate;
import java.util.ArrayList;
final class SpecificOutputPort implements OutputPort<MatchIntermediate> {
private final OutputPort<MatchIntermediate> port;
private final ArrayList<MatchIntermediate> cachedMatches = new ArrayList<>();
private final int operandIndex;
private final int from;
private final int to;
private final int portLimit;
private boolean finished = false;
SpecificOutputPort(OutputPort<MatchIntermediate> port, int operandIndex, int from, int to, int portLimit) {
this.port = port;
this.operandIndex = operandIndex;
this.from = from;
this.to = to;
this.portLimit = portLimit;
}
@Override
public MatchIntermediate take() {
if (finished)
return null;
MatchIntermediate match = port.take();
if (match == null)
finished = true;
else {
cachedMatches.add(match);
if (cachedMatches.size() == portLimit)
finished = true;
}
return match;
}
ArrayList<MatchIntermediate> takeAll(boolean nullMatchesAllowed) {
ArrayList<MatchIntermediate> allMatches = new ArrayList<>();
MatchIntermediate currentMatch;
int index = 0;
do {
currentMatch = get(index);
if ((currentMatch != null) || (nullMatchesAllowed && (index == 0)))
allMatches.add(currentMatch);
index++;
} while (currentMatch != null);
return allMatches;
}
MatchIntermediate get(int index) {
if (index < cachedMatches.size())
return cachedMatches.get(index);
else if (index == cachedMatches.size())
return take();
else
throw new IndexOutOfBoundsException("index: " + index + ", cachedMatches size: " + cachedMatches.size());
}
boolean paramsEqualTo(int operandIndex, int from, int to) {
return (operandIndex == this.operandIndex) && (from == this.from) && (to == this.to);
}
boolean isFinished() {
return finished;
}
}
| 37.494949 | 117 | 0.681573 |
7fb5e6d1c20442120b5f07dd7dcd8523256ac78c | 2,620 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.support;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.InterruptibleBatchPreparedStatementSetter;
/**
* Abstract implementation of the {@link InterruptibleBatchPreparedStatementSetter}
* interface, combining the check for available values and setting of those
* into a single callback method {@link #setValuesIfAvailable}.
*
* @author Juergen Hoeller
* @since 2.0
* @see #setValuesIfAvailable
*/
public abstract class AbstractInterruptibleBatchPreparedStatementSetter
implements InterruptibleBatchPreparedStatementSetter {
private boolean exhausted;
/**
* This implementation calls {@link #setValuesIfAvailable}
* and sets this instance's exhaustion flag accordingly.
*/
@Override
public final void setValues(PreparedStatement ps, int i) throws SQLException {
this.exhausted = !setValuesIfAvailable(ps, i);
}
/**
* This implementation return this instance's current exhaustion flag.
*/
@Override
public final boolean isBatchExhausted(int i) {
return this.exhausted;
}
/**
* This implementation returns {@code Integer.MAX_VALUE}.
* Can be overridden in subclasses to lower the maximum batch size.
*/
@Override
public int getBatchSize() {
return Integer.MAX_VALUE;
}
/**
* Check for available values and set them on the given PreparedStatement.
* If no values are available anymore, return {@code false}.
* @param ps PreparedStatement we'll invoke setter methods on
* @param i index of the statement we're issuing in the batch, starting from 0
* @return whether there were values to apply (that is, whether the applied
* parameters should be added to the batch and this method should be called
* for a further iteration)
* @throws SQLException if a SQLException is encountered
* (i.e. there is no need to catch SQLException)
*/
protected abstract boolean setValuesIfAvailable(PreparedStatement ps, int i) throws SQLException;
}
| 32.75 | 98 | 0.75916 |
7d1a471d16f4b794df4327b1048a122c3e2a4dbf | 294 | package pattpack.token_3;
/**
* Representation of multiplication tokens.
*/
public class Mul extends Token {
/**
* Return a printable representation of this token.
* @return A printable representation of this token.
*/
public String toString () { return "Mul"; }
}
| 22.615385 | 57 | 0.663265 |
e8790a5a40390fca027e8d06d14bbe1d9be97e6b | 38,609 | /*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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 im.turms.gateway.domain.session.service;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import im.turms.gateway.access.client.common.UserSession;
import im.turms.gateway.domain.observation.service.MetricsService;
import im.turms.gateway.domain.session.bo.UserLoginInfo;
import im.turms.gateway.domain.session.manager.HeartbeatManager;
import im.turms.gateway.domain.session.manager.UserSessionsManager;
import im.turms.gateway.infra.plugin.extension.UserAuthenticator;
import im.turms.gateway.infra.plugin.extension.UserOnlineStatusChangeHandler;
import im.turms.server.common.access.client.dto.constant.DeviceType;
import im.turms.server.common.access.client.dto.constant.UserStatus;
import im.turms.server.common.access.common.ResponseStatusCode;
import im.turms.server.common.domain.admin.constant.AdminConst;
import im.turms.server.common.domain.common.util.DeviceTypeUtil;
import im.turms.server.common.domain.location.bo.Location;
import im.turms.server.common.domain.session.bo.CloseReason;
import im.turms.server.common.domain.session.bo.SessionCloseStatus;
import im.turms.server.common.domain.session.bo.UserSessionInfo;
import im.turms.server.common.domain.session.bo.UserSessionsInfo;
import im.turms.server.common.domain.session.bo.UserSessionsStatus;
import im.turms.server.common.domain.session.rpc.SetUserOfflineRequest;
import im.turms.server.common.domain.session.service.ISessionService;
import im.turms.server.common.domain.session.service.SessionLocationService;
import im.turms.server.common.domain.session.service.UserStatusService;
import im.turms.server.common.infra.cluster.node.Node;
import im.turms.server.common.infra.cluster.service.rpc.exception.ConnectionNotFound;
import im.turms.server.common.infra.collection.MapUtil;
import im.turms.server.common.infra.context.JobShutdownOrder;
import im.turms.server.common.infra.context.TurmsApplicationContext;
import im.turms.server.common.infra.exception.ResponseException;
import im.turms.server.common.infra.lang.ByteArrayWrapper;
import im.turms.server.common.infra.logging.core.logger.Logger;
import im.turms.server.common.infra.logging.core.logger.LoggerFactory;
import im.turms.server.common.infra.plugin.PluginManager;
import im.turms.server.common.infra.plugin.SequentialExtensionPointInvoker;
import im.turms.server.common.infra.property.TurmsProperties;
import im.turms.server.common.infra.property.TurmsPropertiesManager;
import im.turms.server.common.infra.property.env.gateway.SessionProperties;
import im.turms.server.common.infra.reactor.PublisherPool;
import im.turms.server.common.infra.reactor.PublisherUtil;
import im.turms.server.common.infra.validation.ValidDeviceType;
import im.turms.server.common.infra.validation.Validator;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import javax.annotation.Nullable;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Consumer;
import static im.turms.gateway.infra.metrics.MetricNameConst.LOGGED_IN_USERS_COUNTER;
import static im.turms.gateway.infra.metrics.MetricNameConst.ONLINE_USERS_GAUGE;
/**
* @author James Chen
*/
@Service
public class SessionService implements ISessionService {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionService.class);
private final Node node;
private final TurmsPropertiesManager propertiesManager;
private final HeartbeatManager heartbeatManager;
private final PluginManager pluginManager;
private final SessionLocationService sessionLocationService;
private final UserService userService;
private final UserStatusService userStatusService;
private final UserSimultaneousLoginService userSimultaneousLoginService;
private final ConcurrentHashMap<Long, UserSessionsManager> userIdToSessionsManager;
/**
* We don't use "NonBlockingHashMapLong" because
* we need to support IPv6 addresses which takes 16 bytes per address.
* So we can only eliminate unnecessary objects after Valhalla publish value objects.
*/
private final ConcurrentHashMap<ByteArrayWrapper, ConcurrentLinkedQueue<UserSession>> ipToSessions;
private final List<Consumer<UserSession>> onSessionClosedListeners = new LinkedList<>();
private final Counter loggedInUsersCounter;
private int closeIdleSessionAfterSeconds;
private boolean enableAuthentication;
private boolean notifyClientsOfSessionInfoAfterConnected;
private String serverId;
public SessionService(
Node node,
TurmsApplicationContext context,
TurmsPropertiesManager propertiesManager,
PluginManager pluginManager,
SessionLocationService sessionLocationService,
UserService userService,
UserStatusService userStatusService,
UserSimultaneousLoginService userSimultaneousLoginService,
MetricsService metricsService) {
this.node = node;
this.sessionLocationService = sessionLocationService;
this.propertiesManager = propertiesManager;
this.pluginManager = pluginManager;
this.userService = userService;
this.userStatusService = userStatusService;
this.userSimultaneousLoginService = userSimultaneousLoginService;
userIdToSessionsManager = new ConcurrentHashMap<>(4096);
ipToSessions = new ConcurrentHashMap<>(4096);
updateGlobalProperties(propertiesManager.getGlobalProperties());
updateLocalProperties(propertiesManager.getLocalProperties());
SessionProperties sessionProperties = propertiesManager.getGlobalProperties().getGateway().getSession();
heartbeatManager = new HeartbeatManager(this,
userStatusService,
userIdToSessionsManager,
sessionProperties.getClientHeartbeatIntervalSeconds(),
closeIdleSessionAfterSeconds,
sessionProperties.getMinHeartbeatIntervalSeconds(),
sessionProperties.getSwitchProtocolAfterSeconds());
propertiesManager.addGlobalPropertiesChangeListener(newProperties -> {
updateGlobalProperties(newProperties);
SessionProperties newSessionProperties = newProperties.getGateway().getSession();
heartbeatManager.setClientHeartbeatIntervalSeconds(newSessionProperties.getClientHeartbeatIntervalSeconds());
heartbeatManager.setCloseIdleSessionAfterSeconds(newSessionProperties.getCloseIdleSessionAfterSeconds());
heartbeatManager.setMinHeartbeatIntervalMillis(newSessionProperties.getMinHeartbeatIntervalSeconds() * 1000);
heartbeatManager.setSwitchProtocolAfterMillis(newSessionProperties.getSwitchProtocolAfterSeconds() * 1000);
});
propertiesManager.addLocalPropertiesChangeListener(this::updateLocalProperties);
MeterRegistry registry = metricsService.getRegistry();
loggedInUsersCounter = registry.counter(LOGGED_IN_USERS_COUNTER);
registry.gaugeMapSize(ONLINE_USERS_GAUGE, Tags.empty(), userIdToSessionsManager);
context.addShutdownHook(JobShutdownOrder.CLOSE_SESSIONS, this::destroy);
}
private void updateGlobalProperties(TurmsProperties properties) {
SessionProperties sessionProperties = properties.getGateway().getSession();
closeIdleSessionAfterSeconds = sessionProperties.getCloseIdleSessionAfterSeconds();
enableAuthentication = sessionProperties.isEnableAuthentication();
notifyClientsOfSessionInfoAfterConnected = sessionProperties.isNotifyClientsOfSessionInfoAfterConnected();
}
private void updateLocalProperties(TurmsProperties properties) {
serverId = properties.getGateway().getServiceDiscovery().getIdentity();
}
public Mono<Void> destroy(long timeoutMillis) {
heartbeatManager.destroy(timeoutMillis);
CloseReason closeReason = CloseReason.get(SessionCloseStatus.SERVER_CLOSED);
return clearAllLocalSessions(closeReason)
.onErrorMap(t -> new IllegalStateException("Caught an error while clearing local sessions", t));
}
public void handleHeartbeatUpdateRequest(UserSession session) {
updateHeartbeatTimestamp(session);
}
public Mono<UserSession> handleLoginRequest(
int version,
@NotNull ByteArrayWrapper ip,
@NotNull Long userId,
@Nullable String password,
@NotNull DeviceType deviceType,
@Nullable Map<String, String> deviceDetails,
@Nullable UserStatus userStatus,
@Nullable Location location,
@Nullable String ipStr) {
if (version != 1) {
return Mono.error(ResponseException.get(ResponseStatusCode.UNSUPPORTED_CLIENT_VERSION, "The supported versions are: 1"));
}
if (userSimultaneousLoginService.isForbiddenDeviceType(deviceType)) {
return Mono.error(ResponseException.get(ResponseStatusCode.LOGIN_FROM_FORBIDDEN_DEVICE_TYPE));
}
return authenticate(version, userId, password, deviceType, deviceDetails, userStatus, location, ipStr)
.flatMap(statusCode -> statusCode == ResponseStatusCode.OK
? tryRegisterOnlineUser(version, ip, userId, deviceType, deviceDetails, userStatus, location)
: Mono.error(ResponseException.get(statusCode)));
}
/**
* @return OK, LOGIN_AUTHENTICATION_FAILED, LOGGING_IN_USER_NOT_ACTIVE
*/
private Mono<ResponseStatusCode> authenticate(
int version,
@NotNull Long userId,
@Nullable String password,
@NotNull DeviceType deviceType,
@Nullable Map<String, String> deviceDetails,
@Nullable UserStatus userStatus,
@Nullable Location location,
@Nullable String ip) {
if (userId.equals(AdminConst.ADMIN_REQUESTER_ID)) {
return Mono.just(ResponseStatusCode.LOGIN_AUTHENTICATION_FAILED);
}
if (!enableAuthentication) {
return Mono.just(ResponseStatusCode.OK);
}
if (pluginManager.hasRunningExtensions(UserAuthenticator.class)) {
UserLoginInfo userLoginInfo = new UserLoginInfo(
version,
userId,
password,
deviceType,
deviceDetails,
userStatus,
location,
ip);
Mono<ResponseStatusCode> authenticate = pluginManager.invokeExtensionPointsSequentially(
UserAuthenticator.class,
"authenticate",
(SequentialExtensionPointInvoker<UserAuthenticator, Boolean>)
(authenticator, pre) -> pre.switchIfEmpty(Mono.defer(() -> authenticator.authenticate(userLoginInfo))))
.map(authenticated -> authenticated ? ResponseStatusCode.OK : ResponseStatusCode.LOGIN_AUTHENTICATION_FAILED);
return authenticate
.switchIfEmpty(authenticate0(userId, password));
}
return authenticate0(userId, password);
}
/**
* @return OK, AUTHENTICATION_FAILED, LOGGING_IN_USER_NOT_ACTIVE
*/
private Mono<ResponseStatusCode> authenticate0(
@NotNull Long userId,
@Nullable String password) {
return userService.isActiveAndNotDeleted(userId)
.flatMap(isActiveAndNotDeleted -> isActiveAndNotDeleted
? userService.authenticate(userId, password)
.map(authenticated -> authenticated ? ResponseStatusCode.OK : ResponseStatusCode.LOGIN_AUTHENTICATION_FAILED)
: Mono.just(ResponseStatusCode.LOGGING_IN_USER_NOT_ACTIVE));
}
/**
* @return true if the user was online
*/
@Override
public Mono<Boolean> setLocalSessionsOffline(
@NotNull byte[] ip,
@NotNull CloseReason closeReason) {
try {
Validator.notNull(ip, "ip");
} catch (ResponseException e) {
return Mono.error(e);
}
Queue<UserSession> sessions = ipToSessions.get(new ByteArrayWrapper(ip));
Iterator<UserSession> iterator = sessions.iterator();
if (!iterator.hasNext()) {
return PublisherPool.FALSE;
}
Mono<Boolean> first = setLocalSessionOffline(iterator.next().getUserId(),
DeviceTypeUtil.ALL_AVAILABLE_DEVICE_TYPES_SET,
closeReason);
// Fast path
if (!iterator.hasNext()) {
return first;
}
// Slow path
// Use ArrayList instead of LinkedList because it's really heavy
List<Mono<Boolean>> list = new ArrayList<>(4);
list.add(first);
list.add(setLocalSessionOffline(iterator.next().getUserId(),
DeviceTypeUtil.ALL_AVAILABLE_DEVICE_TYPES_SET,
closeReason));
while (iterator.hasNext()) {
list.add(setLocalSessionOffline(iterator.next().getUserId(),
DeviceTypeUtil.ALL_AVAILABLE_DEVICE_TYPES_SET,
closeReason));
}
return PublisherUtil.atLeastOneTrue(list);
}
/**
* @return true if the user was online
*/
public Mono<Boolean> setLocalSessionOffline(
@NotNull Long userId,
@NotNull @ValidDeviceType DeviceType deviceType,
@NotNull SessionCloseStatus closeStatus) {
try {
Validator.notNull(deviceType, "deviceType");
} catch (ResponseException e) {
return Mono.error(e);
}
return setLocalSessionOffline(userId, Collections.singleton(deviceType), CloseReason.get(closeStatus));
}
/**
* @return true if the user was online
*/
public Mono<Boolean> setLocalSessionOffline(
@NotNull Long userId,
@NotNull @ValidDeviceType DeviceType deviceType,
@NotNull CloseReason closeReason) {
try {
Validator.notNull(deviceType, "deviceType");
} catch (ResponseException e) {
return Mono.error(e);
}
return setLocalSessionOffline(userId, Collections.singleton(deviceType), closeReason);
}
/**
* @return true if the user was online
*/
@Override
public Mono<Boolean> setLocalSessionOffline(
@NotNull Long userId,
@NotEmpty Set<@ValidDeviceType DeviceType> deviceTypes,
@NotNull CloseReason closeReason) {
try {
Validator.notNull(userId, "userId");
} catch (ResponseException e) {
return Mono.error(e);
}
UserSessionsManager manager = getUserSessionsManager(userId);
if (manager == null) {
return PublisherPool.FALSE;
}
return setLocalSessionOfflineByUserIdAndDeviceTypes0(userId, deviceTypes, closeReason, manager);
}
public Mono<Boolean> authAndSetLocalSessionOffline(@NotNull Long userId,
@NotNull DeviceType deviceType,
@NotNull CloseReason closeReason,
int sessionId) {
try {
Validator.notNull(userId, "userId");
Validator.notNull(deviceType, "deviceType");
Validator.notNull(closeReason, "closeReason");
} catch (ResponseException e) {
return Mono.error(e);
}
UserSessionsManager manager = getUserSessionsManager(userId);
if (manager == null) {
return PublisherPool.FALSE;
}
UserSession session = manager.getSession(deviceType);
if (session.getId() == sessionId) {
return setLocalSessionOfflineByUserIdAndDeviceTypes0(userId, Collections.singleton(deviceType), closeReason, manager);
}
return PublisherPool.FALSE;
}
/**
* @implNote The method will be called definitely when a session is closed
* no matter it's closed by the client or the server.
* And the method will clean up sessions in both local and Redis
*/
private Mono<Boolean> setLocalSessionOfflineByUserIdAndDeviceTypes0(
@NotNull Long userId,
@NotEmpty Set<@ValidDeviceType DeviceType> deviceTypes,
@NotNull CloseReason closeReason,
@NotNull UserSessionsManager manager) {
try {
Validator.notNull(closeReason, "closeReason");
Validator.notNull(manager, "manager");
} catch (ResponseException e) {
return Mono.error(e);
}
// Don't close the session (connection) first and then remove the session status in Redis
// because it will make trouble if a client logins again while the session status in Redis hasn't been removed
return userStatusService.removeStatusByUserIdAndDeviceTypes(userId, deviceTypes)
.doOnSuccess(ignored -> {
for (DeviceType deviceType : deviceTypes) {
UserSession session = manager.getSession(deviceType);
if (session == null) {
continue;
}
manager.setDeviceOffline(session.getDeviceType(), closeReason);
ByteArrayWrapper ip = session.getIp();
if (ip != null) {
ipToSessions.computeIfPresent(ip, (key, sessions) -> sessions.remove(session)
? (sessions.isEmpty() ? null : sessions)
: sessions);
}
triggerOnSessionClosedListeners(session);
if (sessionLocationService.isLocationEnabled()) {
sessionLocationService.removeUserLocation(session.getUserId(), session.getDeviceType())
.subscribe(null, t -> LOGGER.error("Failed to remove the user [{}:{}] location",
session.getUserId(), session.getDeviceType(), t));
}
}
removeSessionsManagerIfEmpty(closeReason, manager, userId);
});
}
public Mono<Void> clearAllLocalSessions(@NotNull CloseReason closeReason) {
try {
Validator.notNull(closeReason, "closeReason");
} catch (ResponseException e) {
return Mono.error(e);
}
Set<Map.Entry<Long, UserSessionsManager>> entries = userIdToSessionsManager.entrySet();
List<Mono<Boolean>> monos = new ArrayList<>(entries.size());
for (Map.Entry<Long, UserSessionsManager> entry : entries) {
Long userId = entry.getKey();
Set<DeviceType> loggedInDeviceTypes = entry.getValue().getLoggedInDeviceTypes();
Mono<Boolean> mono = setLocalSessionOffline(userId, loggedInDeviceTypes, closeReason);
monos.add(mono);
}
return Mono.whenDelayError(monos);
}
@Override
public Mono<Boolean> setLocalUserOffline(Long userId, CloseReason closeReason) {
return setLocalSessionOffline(userId, DeviceTypeUtil.ALL_AVAILABLE_DEVICE_TYPES_SET, closeReason);
}
@Override
public List<UserSessionsInfo> getUserSessions(Set<Long> userIds) {
List<UserSessionsInfo> sessions = new ArrayList<>(userIds.size());
for (Long userId : userIds) {
sessions.add(getUserSessions(userId));
}
return sessions;
}
private UserSessionsInfo getUserSessions(Long userId) {
UserSessionsManager manager = userIdToSessionsManager.get(userId);
if (manager == null) {
return new UserSessionsInfo(userId, UserStatus.OFFLINE, Collections.emptyList());
}
Collection<UserSession> sessions = manager.getDeviceTypeToSession().values();
int size = sessions.size();
if (size == 0) {
return new UserSessionsInfo(userId, UserStatus.OFFLINE, Collections.emptyList());
}
ArrayList<UserSessionInfo> sessionInfos = new ArrayList<>(size);
for (UserSession session : sessions) {
ByteArrayWrapper ip = session.getIp();
sessionInfos.add(new UserSessionInfo(
session.getId(),
session.getVersion(),
session.getDeviceType(),
session.getDeviceDetails(),
session.getLoginDate(),
session.getLoginLocation(),
new Date(session.getLastHeartbeatRequestTimestampMillis()),
new Date(session.getLastRequestTimestampMillis()),
session.isSessionOpen(),
ip == null ? null : ip.getBytes(),
null
));
}
return new UserSessionsInfo(userId, manager.getUserStatus(), sessionInfos);
}
public void updateHeartbeatTimestamp(UserSession session) {
session.setLastHeartbeatRequestTimestampMillis(System.currentTimeMillis());
}
public UserSession authAndUpdateHeartbeatTimestamp(long userId, @NotNull @ValidDeviceType DeviceType deviceType, int sessionId) {
Validator.notNull(deviceType, "deviceType");
DeviceTypeUtil.validDeviceType(deviceType);
UserSessionsManager userSessionsManager = getUserSessionsManager(userId);
if (userSessionsManager != null) {
UserSession session = userSessionsManager.getSession(deviceType);
if (session != null && session.getId() == sessionId && !session.getConnection().isConnectionRecovering()) {
session.setLastHeartbeatRequestTimestampMillis(System.currentTimeMillis());
return session;
}
}
return null;
}
/**
* For the case that the client recovers from UDP to TCP/WebSocket:
* Return the local session if the client connects to the machine that owns the existing session;
* Return a new session and disconnect the remote session if the existing session is on a different machine.
*/
public Mono<UserSession> tryRegisterOnlineUser(
int version,
@NotNull ByteArrayWrapper ip,
@NotNull Long userId,
@NotNull DeviceType deviceType,
@Nullable Map<String, String> deviceDetails,
@Nullable UserStatus userStatus,
@Nullable Location location) {
try {
Validator.notNull(ip, "ip");
Validator.notNull(deviceType, "deviceType");
DeviceTypeUtil.validDeviceType(deviceType);
Validator.notEquals(userStatus, UserStatus.UNRECOGNIZED, "The user status must not be UNRECOGNIZED");
Validator.notEquals(userStatus, UserStatus.OFFLINE, "The user status must not be OFFLINE");
if (location != null) {
Validator.inRange(location.longitude(), "longitude", Location.LONGITUDE_MIN, Location.LONGITUDE_MAX);
Validator.inRange(location.latitude(), "latitude", Location.LATITUDE_MIN, Location.LATITUDE_MAX);
}
} catch (ResponseException e) {
return Mono.error(e);
}
// Must fetch the latest status instead of the status in the cache
return userStatusService.fetchUserSessionsStatus(userId)
.flatMap(sessionsStatus -> {
// getSessionStatusFromSharedAndLocalInfo() is used to handle the following edge
// cases to avoid bugs when the session info in local node is inconsistent with the one in Redis.
// Cases: The session exists in the local node, but:
// 1. Though the local node works well, Redis crashes and restart,
// so all session info was lost in Redis, but sessions still exist indeed.
// 2. The local node lost the connection to Redis, which causes
// the local node failed to refresh the heartbeat info of users in Redis.
sessionsStatus = getSessionStatusFromSharedAndLocalInfo(userId, sessionsStatus);
// Check the current sessions status
UserStatus existingUserStatus = sessionsStatus.userStatus();
if (existingUserStatus == UserStatus.OFFLINE) {
return addOnlineDeviceIfAbsent(version, ip, userId, deviceType, deviceDetails, userStatus, location);
}
boolean conflicts = sessionsStatus.getLoggedInDeviceTypes().contains(deviceType);
if (conflicts) {
UserSession session = getLocalUserSession(userId, deviceType);
boolean isDisconnectedSessionOnLocal = session != null
&& session.getConnection() != null
&& !session.getConnection().isConnected();
if (isDisconnectedSessionOnLocal) {
// Note that the downstream should replace the disconnected connection
// with the connected TCP/WebSocket connection
Mono<Void> updateSessionInfoMono = userStatus == null || existingUserStatus == userStatus
? Mono.empty()
: userStatusService.updateOnlineUserStatusIfPresent(userId, userStatus)
.then()
.onErrorResume(t -> {
LOGGER.error("Failed to update the online status of the user " + userId, t);
return Mono.empty();
});
if (location != null) {
updateSessionInfoMono = updateSessionInfoMono
.flatMap(unused -> sessionLocationService
.upsertUserLocation(userId, deviceType, new Date(), location.longitude(), location.latitude())
.onErrorResume(t -> {
LOGGER.error("Failed to upsert the location of the user " + userId, t);
return Mono.empty();
}));
}
return updateSessionInfoMono.thenReturn(session);
} else if (userSimultaneousLoginService.shouldDisconnectLoggingInDeviceIfConflicts()) {
return Mono.error(ResponseException.get(ResponseStatusCode.SESSION_SIMULTANEOUS_CONFLICTS_DECLINE));
}
}
return disconnectConflictedDeviceTypes(userId, deviceType, sessionsStatus)
.flatMap(wasSuccessful -> wasSuccessful
? addOnlineDeviceIfAbsent(version, ip, userId, deviceType, deviceDetails, userStatus, location)
: Mono.error(ResponseException.get(ResponseStatusCode.SESSION_SIMULTANEOUS_CONFLICTS_DECLINE)));
});
}
@Nullable
public UserSessionsManager getUserSessionsManager(@NotNull Long userId) {
Validator.notNull(userId, "userId");
return userIdToSessionsManager.get(userId);
}
@Nullable
public UserSession getLocalUserSession(@NotNull Long userId, @NotNull DeviceType deviceType) {
Validator.notNull(userId, "userId");
Validator.notNull(deviceType, "deviceType");
UserSessionsManager userSessionsManager = userIdToSessionsManager.get(userId);
return userSessionsManager == null ? null : userSessionsManager.getSession(deviceType);
}
@Nullable
public Queue<UserSession> getLocalUserSession(ByteArrayWrapper ip) {
return ipToSessions.get(ip);
}
public int countLocalOnlineUsers() {
return userIdToSessionsManager.size();
}
private Mono<Boolean> disconnectConflictedDeviceTypes(@NotNull Long userId,
@NotNull @ValidDeviceType DeviceType deviceType,
@NotNull UserSessionsStatus sessionsStatus) {
try {
Validator.notNull(userId, "userId");
Validator.notNull(deviceType, "deviceType");
DeviceTypeUtil.validDeviceType(deviceType);
Validator.notNull(sessionsStatus, "sessionsStatus");
} catch (ResponseException e) {
return Mono.error(e);
}
Set<DeviceType> conflictedDeviceTypes = userSimultaneousLoginService.getConflictedDeviceTypes(deviceType);
HashMultimap<String, DeviceType> nodeIdToDeviceTypes = null;
for (DeviceType conflictedDeviceType : conflictedDeviceTypes) {
String nodeId = sessionsStatus.getNodeIdByDeviceType(conflictedDeviceType);
if (nodeId != null) {
if (nodeIdToDeviceTypes == null) {
nodeIdToDeviceTypes = HashMultimap.create(3, 3);
}
nodeIdToDeviceTypes.put(nodeId, deviceType);
}
}
if (nodeIdToDeviceTypes == null) {
return PublisherPool.TRUE;
}
Set<String> nodeIds = nodeIdToDeviceTypes.keySet();
List<Mono<Boolean>> disconnectionRequests = new ArrayList<>(nodeIds.size());
for (String nodeId : nodeIds) {
Set<DeviceType> deviceTypes = nodeIdToDeviceTypes.get(nodeId);
SetUserOfflineRequest request = new SetUserOfflineRequest(userId, deviceTypes, SessionCloseStatus.DISCONNECTED_BY_CLIENT);
disconnectionRequests.add(node.getRpcService().requestResponse(nodeId, request)
.onErrorResume(ConnectionNotFound.class, t -> {
// The connection may not exist because there is a network problem between the local node
// and the target node, or the target node is dead (if it's an unknown node)
// without clearing its user sessions in Redis.
// For the first case (network problem) or we are not sure whether the target node is really dead,
// we keep returning the expected INTERNAL_SERVER_ERROR to client until its TTL expires.
if (node.getDiscoveryService().isKnownMember(nodeId)) {
return Mono.error(t);
}
// For the second case (dead target node), we consider the user sessions already offline,
// so we return true for the logging in client to log in for better user experience.
return PublisherPool.TRUE;
}));
}
return PublisherUtil.areAllTrue(disconnectionRequests);
}
public void onSessionEstablished(@NotNull UserSessionsManager userSessionsManager,
@NotNull @ValidDeviceType DeviceType deviceType) {
loggedInUsersCounter.increment();
if (notifyClientsOfSessionInfoAfterConnected) {
userSessionsManager.pushSessionNotification(deviceType, serverId);
}
}
private Mono<UserSession> addOnlineDeviceIfAbsent(
int version,
@NotNull ByteArrayWrapper ip,
@NotNull Long userId,
@NotNull DeviceType deviceType,
@Nullable Map<String, String> deviceDetails,
@Nullable UserStatus userStatus,
@Nullable Location location) {
// Try to update the global user status
return userStatusService.addOnlineDeviceIfAbsent(userId, deviceType, userStatus, closeIdleSessionAfterSeconds)
.flatMap(wasSuccessful -> {
if (!wasSuccessful) {
return Mono.error(ResponseException.get(ResponseStatusCode.SESSION_SIMULTANEOUS_CONFLICTS_DECLINE));
}
UserStatus finalUserStatus = null == userStatus ? UserStatus.AVAILABLE : userStatus;
UserSessionsManager manager = userIdToSessionsManager
.computeIfAbsent(userId, key -> new UserSessionsManager(key, finalUserStatus));
UserSession session = manager.addSessionIfAbsent(version, deviceType, deviceDetails, location);
// This should never happen
if (null == session) {
manager.setDeviceOffline(deviceType, CloseReason.get(SessionCloseStatus.DISCONNECTED_BY_OTHER_DEVICE));
ipToSessions.computeIfPresent(ip, (key, sessions) -> {
boolean removed = sessions.removeIf(userSession ->
userSession.getUserId().equals(userId)
&& userSession.getDeviceType().equals(deviceType));
return removed
? (sessions.isEmpty() ? null : sessions)
: sessions;
});
session = manager.addSessionIfAbsent(version, deviceType, deviceDetails, location);
if (null == session) {
return Mono.error(ResponseException.get(ResponseStatusCode.SERVER_INTERNAL_ERROR));
}
}
UserSession finalSession = session;
ipToSessions.compute(ip, (key, sessions) -> {
if (sessions == null) {
sessions = new ConcurrentLinkedQueue<>();
}
sessions.add(finalSession);
return sessions;
});
Date now = new Date();
if (null != location && sessionLocationService.isLocationEnabled()) {
return sessionLocationService.upsertUserLocation(userId,
deviceType,
now,
location.longitude(),
location.latitude())
.thenReturn(session);
}
return Mono.just(session);
});
}
private void removeSessionsManagerIfEmpty(@NotNull CloseReason closeReason,
@NotNull UserSessionsManager manager,
@NotNull Long userId) {
if (manager.countSessions() == 0) {
userIdToSessionsManager.remove(userId);
}
pluginManager.invokeExtensionPoints(UserOnlineStatusChangeHandler.class, "goOffline",
handler -> handler.goOffline(manager, closeReason))
.subscribe(null, LOGGER::error);
}
private UserSessionsStatus getSessionStatusFromSharedAndLocalInfo(@NotNull Long userId,
@NotNull UserSessionsStatus sharedSessionsStatus) {
UserSessionsManager manager = userIdToSessionsManager.get(userId);
if (manager == null) {
return sharedSessionsStatus;
}
Map<DeviceType, String> sharedOnlineDeviceTypeToNodeId = sharedSessionsStatus.deviceTypeToNodeId();
for (DeviceType deviceType : manager.getDeviceTypeToSession().keySet()) {
// Don't just merge two maps for convenience to avoiding creating a new map
if (!sharedOnlineDeviceTypeToNodeId.containsKey(deviceType)) {
Map<DeviceType, String> onlineDeviceTypeToNodeId = MapUtil.merge(sharedOnlineDeviceTypeToNodeId,
Maps.transformValues(manager.getDeviceTypeToSession(), ignored -> Node.getNodeId()));
return new UserSessionsStatus(userId, manager.getUserStatus(), onlineDeviceTypeToNodeId);
}
}
return sharedSessionsStatus;
}
// Listener
public void addOnSessionClosedListeners(Consumer<UserSession> onSessionClosed) {
onSessionClosedListeners.add(onSessionClosed);
}
private void triggerOnSessionClosedListeners(UserSession session) {
for (Consumer<UserSession> onSessionClosedListener : onSessionClosedListeners) {
try {
onSessionClosedListener.accept(session);
} catch (Exception e) {
LOGGER.error("Caught an error while triggering a onSessionClosed listener", e);
}
}
}
// Plugin
public Mono<Void> triggerGoOnlinePlugins(@NotNull UserSessionsManager userSessionsManager, @NotNull UserSession userSession) {
return pluginManager.invokeExtensionPoints(UserOnlineStatusChangeHandler.class, "goOnline",
handler -> handler.goOnline(userSessionsManager, userSession));
}
} | 50.206762 | 142 | 0.634722 |
2da06813345fabcc51c82589d97d5b1f03ebc63a | 485 | package org.hibernate.test.hqlfetchscroll;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.testing.RequiresDialect;
@RequiresDialect( value = { Oracle8iDialect.class },
comment = "Oracle does not support the identity column used in the HQLScrollFetchTest mapping." )
public class NoIdentityHQLScrollFetchTest extends HQLScrollFetchTest {
@Override
public String[] getMappings() {
return new String[] { "hqlfetchscroll/NoIdentityParentChild.hbm.xml" };
}
}
| 32.333333 | 99 | 0.795876 |
4295d75f59b1674bf2eef447ac4131e7d6efbb9c | 2,971 | /*
* Copyright 2021 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.xds;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.grpc.xds.FilterChainMatchingProtocolNegotiators.FilterChainMatchingHandler.FilterChainSelector;
import java.util.Comparator;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.GuardedBy;
/**
* Maintains the current xDS selector and any resources using that selector. When the selector
* changes, old resources are closed to avoid old config usages.
*/
final class FilterChainSelectorManager {
private static final AtomicLong closerId = new AtomicLong();
private final Object lock = new Object();
@GuardedBy("lock")
private FilterChainSelector selector;
// Avoid HashSet since it does not decrease in size, forming a high water mark.
@GuardedBy("lock")
private TreeSet<Closer> closers = new TreeSet<Closer>(new CloserComparator());
public FilterChainSelector register(Closer closer) {
synchronized (lock) {
Preconditions.checkState(closers.add(closer), "closer already registered");
return selector;
}
}
public void deregister(Closer closer) {
synchronized (lock) {
closers.remove(closer);
}
}
/** Only safe to be called by code that is responsible for updating the selector. */
public FilterChainSelector getSelectorToUpdateSelector() {
synchronized (lock) {
return selector;
}
}
public void updateSelector(FilterChainSelector newSelector) {
TreeSet<Closer> oldClosers;
synchronized (lock) {
oldClosers = closers;
closers = new TreeSet<Closer>(closers.comparator());
selector = newSelector;
}
for (Closer closer : oldClosers) {
closer.closer.run();
}
}
@VisibleForTesting
int getRegisterCount() {
synchronized (lock) {
return closers.size();
}
}
public static final class Closer {
private final long id = closerId.getAndIncrement();
private final Runnable closer;
/** {@code closer} may be run multiple times. */
public Closer(Runnable closer) {
this.closer = Preconditions.checkNotNull(closer, "closer");
}
}
private static class CloserComparator implements Comparator<Closer> {
@Override public int compare(Closer c1, Closer c2) {
return Long.compare(c1.id, c2.id);
}
}
}
| 30.947917 | 105 | 0.722316 |
3b8c0387d95835ece2071b8f19882cfbd012eca9 | 4,486 | package com.snowalker.shield.match.disruptor;
import com.alibaba.fastjson.JSON;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import net.openhft.affinity.AffinityStrategies;
import net.openhft.affinity.AffinityThreadFactory;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.*;
/**
* @author snowalker
* @version 1.0
* @date 2022/2/2 22:43
* @className
* @desc
*/
public class DisruptorEngine {
private Disruptor disruptor;
public void init() {
disruptor = new Disruptor(
// event Factory
new EventWrapperFactory(),
// ringbuffer size
1024 *1024,
// 线程池
new AffinityThreadFactory("Aft-Core", AffinityStrategies.SAME_CORE),
ProducerType.MULTI,
new BlockingWaitStrategy()
);
// 全局异常处理类
GlobalExceptionHandler<EventWrapper> exceptionHandler = new GlobalExceptionHandler<>(
"disruptorEngine",
(t, seq) -> {
System.err.println("exception thrown on seq:" + seq);
t.printStackTrace();
}
);
disruptor.setDefaultExceptionHandler(exceptionHandler);
disruptor.handleEventsWith(new ConsumerA()).then(new ConsumerB());
disruptor.start();
// 生产者
new Timer().schedule(new ProducerTask(), 2000, 1000);
}
private ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
private class ProducerTask extends TimerTask {
@Override
public void run() {
disruptor.getRingBuffer().publishEvent(
(EventTranslatorOneArg<EventWrapper<String>, String>) (event, sequence, arg0) -> {
event.setT(arg0);
event.setId(threadLocalRandom.nextInt());
}, "SnoWalker-" + UUID.randomUUID().toString());
}
}
private class ConsumerA implements EventHandler<EventWrapper> {
@Override
public void onEvent(EventWrapper event, long sequence, boolean endOfBatch) throws Exception {
System.out.println("Thread-ConsumerA-"+ Thread.currentThread().getName() + " recv event: " + JSON.toJSONString(event));
if (event.getId() % 2 == 0) {
event.setAHandled(true);
} else {
event.setAHandled(false);
}
}
}
private class ConsumerB implements EventHandler<EventWrapper> {
@Override
public void onEvent(EventWrapper event, long sequence, boolean endOfBatch) throws Exception {
System.out.println("Thread-ConsumerB" + " recv event: " + JSON.toJSONString(event));
if (event.isAHandled) {
event.setBHandled(true);
System.out.println("Thread-ConsumerB-" + Thread.currentThread().getName() + " recv event: [A消费者处理-完成] 幂等处理" + JSON.toJSONString(event));
} else {
event.setBHandled(false);
System.out.println("Thread-ConsumerB-" + Thread.currentThread().getName() + " recv event: [A消费者处理-失败] 幂等处理" + JSON.toJSONString(event));
}
}
}
private final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
public void put(String msg) {
queue.offer(msg);
}
public String poll() throws InterruptedException {
return queue.poll(1000, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) throws InterruptedException {
DisruptorEngine disruptorEngine = new DisruptorEngine();
disruptorEngine.init();
for (int i = 0; i < 1000; i++) {
disruptorEngine.put("SnoWalker-MSG-" + i);
}
new Thread(() -> {
boolean flag = true;
while (flag) {
try {
String poll = disruptorEngine.poll();
System.out.println("poll MSG:" + poll);
if (poll == null || poll == "") {
flag = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
| 29.906667 | 152 | 0.578912 |
5e1a89779611e0aea8d917ed147ed82457482805 | 5,834 | package com.bitlab.constant;
import com.bitlab.util.ByteUtils;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
public enum CommandMap {
VERSION("version"),
VERACK("verack"),
PING("ping"),
PONG("pong"),
GETADDR("getaddr"),
ADDR("addr"),
INV("inv"),
ALERT("alert"),
GETUTXOS("getutxos"),
UTXOS("utxos"),
TX("tx"),
GETDATA("getdata"),
REJECT("reject"),
BLOCK("block");
private final String command;
public final int length;
CommandMap (String command) {
this.command = command;
this.length = ByteUtils.stringToBytes(command).length;
}
@Override
public String toString () {
return command;
}
public byte[] toByteArray() {
byte[] bytes = new byte[12];
System.arraycopy(ByteUtils.stringToBytes(command), 0, bytes, 0, length);
return bytes;
}
public static String info(CommandMap name) {
String response;
switch (name){
case VERSION:
response = "version\n" +
"When a node creates an outgoing connection, it will immediately advertise its version. The remote node will respond with its version. No further communication is possible until both peers have exchanged their version.";
break;
case VERACK:
response = "verack\n" +
"The verack message is sent in reply to version. This message consists of only a message header with the command string \"verack\".";
break;
case PING:
response = "ping\n" +
"The ping message is sent primarily to confirm that the TCP/IP connection is still valid. An error in transmission is presumed to be a closed connection and the address is removed as a current peer.\n" +
"\n";
break;
case PONG:
response = "pong\n" +
"The pong message is sent in response to a ping message. In modern protocol versions, a pong response is generated using a nonce included in the ping.";
break;
case GETADDR:
response = "getaddr\n" +
"The getaddr message sends a request to a node asking for information about known active peers to help with finding potential nodes in the network. The response to receiving this message is to transmit one or more addr messages with one or more peers from a database of known active peers. The typical presumption is that a node is likely to be active if it has been sending a message within the last three hours.\n" +
"\n" +
"No additional data is transmitted with this message.";
break;
case ADDR:
response = "addr\n" +
"Provide information on known nodes of the network. Non-advertised nodes should be forgotten after typically 3 hours";
break;
case INV:
response = "inv\n" +
"Allows a node to advertise its knowledge of one or more objects. It can be received unsolicited, or in reply to getblocks.";
break;
case ALERT:
response = "alert\n" +
"Note: Support for alert messages has been removed from bitcoin core in March 2016. Read more here\n" +
"\n" +
"\n" +
"An alert is sent between nodes to send a general notification message throughout the network. If the alert can be confirmed with the signature as having come from the core development group of the Bitcoin software, the message is suggested to be displayed for end-users. Attempts to perform transactions, particularly automated transactions through the client, are suggested to be halted. The text in the Message string should be relayed to log files and any user interfaces.";
break;
case GETUTXOS:
response = "non";
break;
case UTXOS:
response = "null";
break;
case TX:
response = "tx\n" +
"tx describes a bitcoin transaction, in reply to getdata. When a bloom filter is applied tx objects are sent automatically for matching transactions following the merkleblock.";
break;
case GETDATA:
response = "getdata\n" +
"getdata is used in response to inv, to retrieve the content of a specific object, and is usually sent after receiving an inv packet, after filtering known elements. It can be used to retrieve transactions, but only if they are in the memory pool or relay set - arbitrary access to transactions in the chain is not allowed to avoid having clients start to depend on nodes having full transaction indexes (which modern nodes do not).";
break;
case REJECT:
response = "reject\n" +
"The reject message is sent when messages are rejected.";
break;
case BLOCK:
response = "block\n" +
"The block message is sent in response to a getdata message which requests transaction information from a block hash.";
break;
default:
response = "ERROR";
}
return response;
}
// public static String info(String name) {
// var c = Arrays.stream(CommandMap.values())
// .filter(v -> v.name().equals(name))
// .findFirst();
// return c.map(CommandMap::info).orElse(null);
// }
}
| 47.048387 | 502 | 0.587761 |
41ac0e3e21e5b1e4167e5c9ee340865e826de6c5 | 2,087 | package com.wonderfulenchantments;
import com.wonderfulenchantments.renderers.HorseRendererReplacement;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemModelsProperties;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.Map;
@OnlyIn( Dist.CLIENT )
public class RegistryHandlerClient {
public static void setup() {
EntityRendererManager rendererManager = Minecraft.getInstance()
.getRenderManager();
rendererManager.register( EntityType.HORSE, new HorseRendererReplacement( rendererManager ) );
if( Instances.CLIENT_EFFECTS.isEnchantedBookTextureReplacementEnabled() )
ItemModelsProperties.registerProperty( Items.ENCHANTED_BOOK, new ResourceLocation( "book_type" ),
RegistryHandlerClient::enchantmentBookPredicate
);
}
/** Checks whether given item stack has enchantments from Wonderful Enchantments mod. */
private static float enchantmentBookPredicate( ItemStack itemStack, ClientWorld clientWorld, LivingEntity entity ) {
Map< Enchantment, Integer > enchantments = EnchantmentHelper.getEnchantments( itemStack );
boolean hasWonderfulEnchantment = false;
for( Map.Entry< Enchantment, Integer > enchantmentPair : enchantments.entrySet() ) {
Enchantment enchantment = enchantmentPair.getKey();
ResourceLocation enchantmentLocation = enchantment.getRegistryName();
if( enchantmentLocation == null )
continue;
String enchantmentName = enchantmentLocation.getNamespace();
if( enchantmentName.contains( "wonderful_enchantments" ) ) {
hasWonderfulEnchantment = true;
break;
}
}
return hasWonderfulEnchantment ? 1.0f : 0.0f;
}
}
| 38.648148 | 117 | 0.804504 |
4cb3f5dca58a782340c9224b3996480326fc4d97 | 1,698 | package com.learn.mall.product.service.impl;
import com.learn.mall.product.entity.vo.front.SkuItemVo;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.common.utils.PageUtils;
import com.learn.common.utils.Query;
import com.learn.mall.product.dao.SkuSaleAttrValueDao;
import com.learn.mall.product.entity.SkuSaleAttrValueEntity;
import com.learn.mall.product.service.SkuSaleAttrValueService;
@Service("skuSaleAttrValueService")
public class SkuSaleAttrValueServiceImpl extends ServiceImpl<SkuSaleAttrValueDao, SkuSaleAttrValueEntity> implements SkuSaleAttrValueService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SkuSaleAttrValueEntity> page = this.page(
new Query<SkuSaleAttrValueEntity>().getPage(params),
new QueryWrapper<SkuSaleAttrValueEntity>()
);
return new PageUtils(page);
}
/**
* 根据商品(spuID)获取这个商品所有的销售属性和每个销售属性对应的所有的属性值
* 和每个属性值对应的所有具体销售商品(sku)的ID
*/
@Override
public List<SkuItemVo.SkuItemSaleAttrVo> getSaleAttrsBySpuId(Long spuId) {
List<SkuItemVo.SkuItemSaleAttrVo> saleAttrVos = baseMapper.getSaleAttrsBySpuId(spuId);
return saleAttrVos;
}
/**
* 根据skuId 返回这个sku对应的销售属性的名字和属性的值
* 比如: 颜色:蓝色 版本: 8GB+128GB
*/
@Override
public List<String> getSkuSaleAttrValuesAsString(Long skuId) {
return baseMapper.getSkuSaleAttrValuesAsString(skuId);
}
} | 32.653846 | 142 | 0.751472 |
c2afcb75c971ab22b5a7a8700d4e95a7c2f97d36 | 251 | /**
*
*/
package type;
/**
* @author kudo
* @since 2006/06/03(Sat.)
*
*/
public class TypeException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public TypeException(String msg){
super(msg);
}
}
| 10.913043 | 49 | 0.609562 |
cb7e49d1ab70e9275f22b4efa0c86970450ad44e | 683 | package org.janiskirsteins.accounts.api.model_base;
import org.janiskirsteins.accounts.api.v1.DataStoreConcurrencyScheduler;
import spark.Response;
/**
* POST requests are deserialized to child classes of this abstract class.
*
* Then ApiResponse can use this interface to perform resource creation in a unified
* manner.
*
* @see org.janiskirsteins.accounts.api.v1.ApiResponse#responseFromCreateRequestInTransaction(DataStoreConcurrencyScheduler, Response, GenericCreateRequest)
* @param <T> the type of resource that will be created
*/
public interface GenericCreateRequest<T extends BaseModel>
{
T validateAndCreateWithinTransaction() throws InvalidRequestException;
}
| 35.947368 | 156 | 0.818448 |
295b334348f06d76d9035c4c149089d6925c53d7 | 76 | package com.black.blog.jfinal.common;
public class JFinalCommon {
}
| 12.666667 | 38 | 0.710526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.