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
46ffc34723bbcc2407cb6b7843c085f10ef0f1bf
6,573
package cn.shield.checkin.view.parallax; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Size; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.FrameLayout; import cn.shield.checkin.R; public class ParallaxLayerLayout extends FrameLayout { private static final int DEFAULT_BASE_OFFSET_DP = 10; private static final int DEFAULT_OFFSET_INCREMENT_DP = 5; private Interpolator interpolator = new DecelerateInterpolator(); private int offsetIncrementPx; private int baseOffsetPx; private float scaleX = 1.0f; private float scaleY = 1.0f; private TranslationUpdater translationUpdater; public ParallaxLayerLayout(Context context) { super(context); } public ParallaxLayerLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ParallaxLayerLayout); try { baseOffsetPx = a.getDimensionPixelSize(R.styleable.ParallaxLayerLayout_parallaxOffsetBase, -1); if (baseOffsetPx == -1) { baseOffsetPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_BASE_OFFSET_DP, getResources().getDisplayMetrics()); } offsetIncrementPx = a.getDimensionPixelSize(R.styleable.ParallaxLayerLayout_parallaxOffsetIncrement, -1); if (offsetIncrementPx == -1) { offsetIncrementPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_OFFSET_INCREMENT_DP, getResources().getDisplayMetrics()); } scaleX = a.getFloat(R.styleable.ParallaxLayerLayout_parallaxScaleHorizontal, 1.0f); scaleY = a.getFloat(R.styleable.ParallaxLayerLayout_parallaxScaleVertical, 1.0f); if (scaleX > 1.0f || scaleX < 0.0f || scaleY > 1.0f || scaleY < 0.0f) { throw new IllegalArgumentException("Parallax scale must be a value between -1.0 and 1.0"); } } finally { a.recycle(); } } @Override protected void onFinishInflate() { super.onFinishInflate(); computeOffsets(); if (isInEditMode()) { updateTranslations(new float[]{1.0f, 1.0f}); } } private void computeOffsets() { final int childCount = getChildCount(); for (int i = childCount - 1; i >= 0; i--) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); int index; if (lp.customIndex == -1) { index = childCount - 1 - i; } else { index = lp.customIndex; } lp.offsetPx = offsetPxForIndex(index, lp.incrementMultiplier); } } private float offsetPxForIndex(int index, float incrementMultiplier) { return incrementMultiplier * baseOffsetPx + index * offsetIncrementPx; } public void updateTranslations(@Size(2) float[] translations) { if (Math.abs(translations[0]) > 1 || Math.abs(translations[1]) > 1) { throw new IllegalArgumentException("Translation values must be between 1.0 and -1.0"); } final int childCount = getChildCount(); for (int i = childCount - 1; i >= 0; i--) { View child = getChildAt(i); float[] translationsPx = calculateFinalTranslationPx(child, translations); child.setTranslationX(translationsPx[0]); child.setTranslationY(translationsPx[1]); } } public void setTranslationUpdater(TranslationUpdater translationUpdater) { if (this.translationUpdater != null) { this.translationUpdater.unSubscribe(); } this.translationUpdater = translationUpdater; this.translationUpdater.subscribe(this); } @Size(2) private float[] calculateFinalTranslationPx(View child, @Size(2) float[] translations) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); int xSign = translations[0] > 0 ? 1 : -1; int ySign = translations[1] > 0 ? 1 : -1; float translationX = xSign * lp.offsetPx * interpolator.getInterpolation(Math.abs(translations[0])) * scaleX; float translationY = ySign * lp.offsetPx * interpolator.getInterpolation(Math.abs(translations[1])) * scaleY; return new float[]{translationX, translationY}; } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof LayoutParams; } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p.width, p.height); } public interface TranslationUpdater { void subscribe(ParallaxLayerLayout parallaxLayerLayout); void unSubscribe(); } public static class LayoutParams extends FrameLayout.LayoutParams { private float offsetPx; private int customIndex = -1; private float incrementMultiplier = 1.0f; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); gravity = Gravity.CENTER; TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ParallaxLayerLayout_LayoutParams); try { customIndex = a.getInt(R.styleable.ParallaxLayerLayout_LayoutParams_layout_parallaxZIndex, -1); incrementMultiplier = a.getFloat( R.styleable.ParallaxLayerLayout_LayoutParams_layout_parallaxIncrementMultiplier, 1.0f); } finally { a.recycle(); } } public LayoutParams(int width, int height) { super(width, height); gravity = Gravity.CENTER; } } }
35.918033
111
0.639434
10bf66b37631ca6cf057b5e0b775a83aa4127d4a
1,011
package algs.example.gui.canvas; import java.awt.Graphics; import algs.model.ICircle; /** * Displays to the screen a set of ILineSegment objects. * * <p> * Note that this object deals with Cartesian points and properly displays them * using the java.awt.Canvas coordinates that uses the upper left corner as (0,0). * * @author George Heineman * @version 1.0, 6/15/08 * @since 1.0 */ public class CircleCanvas extends ElementCanvas<ICircle> { /** * Generated Serializable ID. Keep Eclipse happy. */ private static final long serialVersionUID = 7452400024011623672L; public CircleCanvas(int width, int height) { super(); this.setSize(width, height); } /** * Provide concrete realization for drawing each element line segment. */ public void drawElement(Graphics sc, ICircle ic) { // Convert to Cartesian coordinates double y = ic.getY(); sc.drawOval((int)(ic.getX()-ic.getRadius()),(int)(y-ic.getRadius()),(int)(ic.getRadius()*2),(int)(ic.getRadius()*2)); } }
24.658537
119
0.699308
beea30fc7eaa5baef93b661f08089b7c5a41d9e1
2,609
package controllers.account.settings; import static play.data.Form.form; import java.net.MalformedURLException; import models.Token; import models.User; import play.Logger; import play.data.Form; import play.data.validation.Constraints; import play.i18n.Messages; import play.mvc.Result; import play.mvc.Security; import controllers.BaseApiController; import controllers.Secured; /** * Settings -> Email page. * @author samir */ @Security.Authenticated(Secured.class) public class Email extends BaseApiController { public static class AskForm { @Constraints.Required public String email; public AskForm() { } AskForm(String email) { this.email = email; } } /** * Password Page. Ask the user to change his password. * * @return index settings */ public static Result index() { User user = User.findByEmail(request().username()); Form<AskForm> askForm = form(AskForm.class); askForm = askForm.fill(new AskForm(user.email)); return jsonResponse("success"); } /** * Send a mail to confirm. * * @return email page with flash error or success */ public static Result runEmail() { Form<AskForm> askForm = form(AskForm.class).bindFromRequest(); User user = User.findByEmail(request().username()); if (askForm.hasErrors()) { flash("error", Messages.get("signup.valid.email")); return badRequest("failure"); } try { String mail = askForm.get().email; Token.sendMailChangeMail(user, mail); flash("success", Messages.get("changemail.mailsent")); return jsonResponse("success"); } catch (MalformedURLException e) { Logger.error("Cannot validate URL", e); flash("error", Messages.get("error.technical")); } return badRequest("failure"); } /** * Validate a email. * * @return email page with flash error or success */ public static Result validateEmail(String token) { User user = User.findByEmail(request().username()); if (token == null) { flash("error", Messages.get("error.technical")); return badRequest("failure"); } Token resetToken = Token.findByTokenAndType(token, Token.TypeToken.email); if (resetToken == null) { flash("error", Messages.get("error.technical")); return badRequest("failure"); } if (resetToken.isExpired()) { resetToken.delete(resetToken); flash("error", Messages.get("error.expiredmaillink")); return badRequest("failure"); } user.email = resetToken.email; user.update(user); session("email", resetToken.email); flash("success", Messages.get("account.settings.email.successful", user.email)); return ok("Success"); } }
23.294643
67
0.696052
b57c1443ea157bc3a29a0063c6581285cc937621
3,585
/* * 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.stackleader.camel.quickstart.jms; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.CamelContext; import org.apache.camel.RoutesBuilder; import org.apache.camel.core.osgi.OsgiDefaultCamelContext; import org.apache.camel.spi.ComponentResolver; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.component.annotations.ReferencePolicyOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author jeckste */ @Component(immediate = true) public class CamelRunner { private static final Logger LOG = LoggerFactory.getLogger(CamelRunner.class); private CamelContext context; private List<RoutesBuilder> routesBuilders; private ReentrantLock lock; public CamelRunner() { routesBuilders = Collections.synchronizedList(Lists.newArrayList()); lock = new ReentrantLock(); } @Activate public void activate(BundleContext bundleContext) throws Exception { try { lock.lock(); context = new OsgiDefaultCamelContext(bundleContext); context.start(); synchronized (routesBuilders) { routesBuilders.forEach(rb -> { try { context.addRoutes(rb); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); } }); } } finally { lock.unlock(); } } @Deactivate public void deactivate() throws Exception { context.stop(); } @Reference(name = "camelComponent", service = ComponentResolver.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, unbind = "unbindCamelComponent") public void gotCamelComponent(ServiceReference serviceReference) { //TODO: handle this if after context start LOG.info("got comp: {}", serviceReference.getBundle().getSymbolicName()); } @Reference(service = RoutesBuilder.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, unbind = "unbindRouteBuilder") public void getRouteBuilder(org.apache.camel.RoutesBuilder routesBuilder) { if (context != null) { try { lock.lock(); context.addRoutes(routesBuilder); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); } finally { lock.unlock(); } } routesBuilders.add(routesBuilder); } //TODO: handle this public void unbindRouteBuilder(RoutesBuilder routesBuilder) { } public void unbindCamelComponent(ServiceReference serviceReference) { } }
32.889908
94
0.670293
0bf5086a3719f92fcc55d34982c662ea3e275be3
4,117
/** * Copyright 2019 MobiledgeX, Inc. All rights and licenses reserved. * MobiledgeX, Inc. 156 2nd Street #408, San Francisco, CA 94105 * * 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.mobiledgex.workshopskeleton; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.view.WindowManager; import android.util.Log; import com.mobiledgex.matchingengine.AppConnectionManager; import com.mobiledgex.matchingengine.MatchingEngine; import java.io.IOException; import java.net.Socket; import java.util.HashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import distributed_match_engine.AppClient; import distributed_match_engine.Appcommon; public class FaceProcessorActivity extends AppCompatActivity { private FaceProcessorFragment mFaceProcessorFragment; private static final String TAG = "FaceProcessorFragment"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_face_processor); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (null == savedInstanceState) { exampleDeveloperWorkflowBackground(); } } @Override public void onAttachFragment(Fragment fragment) { // Rotating the device creates a new instance of the fragment. Update reference here. if (fragment instanceof FaceProcessorFragment) mFaceProcessorFragment = (FaceProcessorFragment) fragment; } @Override public void finish() { Intent resultIntent = new Intent(); String stats = mFaceProcessorFragment.getStatsText(); resultIntent.putExtra("STATS", stats); setResult(RESULT_OK, resultIntent); super.finish(); } public Socket exampleDeveloperWorkflow() { //////////////////////////////////////////////////////////////////////////////////////////// // TODO: Copy/paste the code to follow example developer workflow and get FaceDetection started. return null; //////////////////////////////////////////////////////////////////////////////////////////// } private void exampleDeveloperWorkflowBackground() { // Creates new BackgroundRequest object which will call exampleDeveloperWorkflow new ExampleDeveloperWorkflowBackgroundRequest().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public class ExampleDeveloperWorkflowBackgroundRequest extends AsyncTask<Object, Void, Socket> { @Override protected Socket doInBackground(Object... params) { return exampleDeveloperWorkflow(); } @Override protected void onPostExecute(Socket socket) { if (socket != null) { mFaceProcessorFragment = FaceProcessorFragment.newInstance(); mFaceProcessorFragment.mHost = socket.getInetAddress().getHostName(); mFaceProcessorFragment.mPort = socket.getPort(); getSupportFragmentManager().beginTransaction() .replace(R.id.container, mFaceProcessorFragment) .commit(); try { socket.close(); } catch (IOException ioe) { Log.e(TAG, "Unable to close socket. IOException: " + ioe.getMessage()); } } } } }
36.758929
106
0.666262
4aa022cfe787bdeb8fb09d5097cbfa07c65bb36d
553
package com.github.javaparser.ast.nodeTypes.modifiers; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.nodeTypes.NodeWithModifiers; import static com.github.javaparser.ast.Modifier.*; /** * A node that can be private. */ public interface NodeWithPrivateModifier<N extends Node> extends NodeWithModifiers<N> { default boolean isPrivate() { return getModifiers().contains(PRIVATE); } @SuppressWarnings("unchecked") default N setPrivate(boolean set) { return setModifier(PRIVATE, set); } }
26.333333
87
0.735986
aa9d79bb4be77d50dfed1f7a88eea50fc2b8780a
4,559
package org.ovirt.engine.core.common.businessentities.comparators; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class LexoNumericComparatorTest { private LexoNumericComparator comparator; private String left; private String right; private int expectedResult; public LexoNumericComparatorTest(boolean caseSensitive, String left, String right, int expectedResult) { comparator = new LexoNumericComparator(caseSensitive); this.left = left; this.right = right; this.expectedResult = expectedResult; } private void verifyResult(String left, String right, int expectedResult) { assertEquals(String.format("Expected %1$s to be %3$s %2$s, but it wasn't.", left, right, expectedResult == -1 ? "less than" : expectedResult == 1 ? "greater than" : "equal to"), expectedResult, comparator.compare(left, right)); } @Test public void runTest() { verifyResult(left, right, expectedResult); verifyResult(right, left, -expectedResult); } @Parameterized.Parameters public static Object[][] comparisonParameters() { return new Object[][] { { false, null, null, 0 }, { false, null, "", -1 }, { false, "", "", 0 }, { false, "", "123", -1 }, { false, "123", "123", 0 }, { false, "123", "456", -1 }, { false, "12", "123", -1 }, { false, "012", "12", -1 }, { false, "2", "10", -1 }, { false, "123abc", "123abc", 0 }, { true, "123abc", "123abc", 0 }, { false, "123Abc", "123abc", -1 }, { true, "123Abc", "123abc", -1 }, { false, "123abc", "456abc", -1 }, { false, "12abc", "123abc", -1 }, { false, "012abc", "12abc", -1 }, { false, "2abc", "10abc", -1 }, { false, "123", "abc", -1 }, { false, "abc", "abc", 0 }, { true, "abc", "abc", 0 }, { false, "Abc", "abc", -1 }, { true, "Abc", "abc", -1 }, { false, "abc", "def", -1 }, { false, "ab", "abc", -1 }, { false, "123abc", "123def", -1 }, { false, "123ab", "123abc", -1 }, { false, "abc123", "abc123", 0 }, { true, "abc123", "abc123", 0 }, { false, "Abc123", "abc123", -1 }, { true, "Abc123", "abc123", -1 }, { false, "Abc234", "abc123", 1 }, { true, "Abc234", "abc123", -1 }, { false, "Abc1234", "abc123", 1 }, { true, "Abc1234", "abc123", -1 }, { false, "abc123", "def123", -1 }, { false, "ab123", "abc123", -1 }, { false, "abc123", "abc456", -1 }, { false, "abc12", "abc123", -1 }, { false, "abc012", "abc12", -1 }, { false, "abc2", "abc10", -1 }, { false, "abc123def", "abc123def", 0 }, { true, "abc123def", "abc123def", 0 }, { false, "Abc123def", "abc123def", -1 }, { true, "Abc123def", "abc123def", -1 }, { false, "Abc234def", "abc123def", 1 }, { true, "Abc234def", "abc123def", -1 }, { false, "Abc1234def", "abc123def", 1 }, { true, "Abc1234def", "abc123def", -1 }, { false, "abc123def", "abc123ghi", -1 }, { false, "abc123de", "abc123def", -1 }, { false, "abc123456789123de", "abc123456789123de", 0 }, { true, "abc123456789123de", "abc123456789123de", 0 }, { false, "Abc123456789123de", "abc123456789123de", -1 }, { true, "Abc123456789123de", "abc123456789123de", -1 }, { false, "Abc123456789234de", "abc123456789123de", 1 }, { true, "Abc123456789234de", "abc123456789123de", -1 }, { false, "Abc1234567891234de", "abc123456789123de", 1 }, { true, "Abc1234567891234de", "abc123456789123de", -1 }, { false, "abc123456789123de", "abc123456789123fg", -1 }, { false, "abc123456789123de", "abc123456789123def", -1 } }; } }
43.009434
108
0.469182
4cf35e2b676bfe3a1e4eba810028356c9a36eb51
513
package com.github.cwdtom.hermes; import com.github.cwdtom.hermes.annotation.EnableHermes; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 测试启动类 * * @author chenweidong * @since 1.0.0 */ @SpringBootApplication @EnableHermes public class ApplicationMain { /** * main方法 * * @param args 启动参数 */ public static void main(String[] args) { SpringApplication.run(ApplicationMain.class, args); } }
21.375
68
0.71345
c7dc87a8e9f958a0cb2ead33e5c282f5471bf1cb
1,663
package me.gosimple.nbvcxz; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import com.restfb.DefaultFacebookClient; import com.restfb.FacebookClient; import com.restfb.types.User; public class FacebookScribeAuthenticator { public static void openBrowser(SubGUIProgram subgui) { // String accessToken = "EAACEdEose0cBAHcXy6AXNHAW71L6bOs1ktJntO6CVJdT2ckha6xFdW20UK9F0ZBVDZBON6KlpAGL19JoqCJExsBLNzQc7GoSK3k0DJBNSOhdMK4ZAAf0ZAlf1an9ucwEoj48OYiV6rOTegBb4it2HOfjicYvTbMdxQVDhyQdG94ZANeUeYAZAwpXHIYwPOuK0wU7FHHzeuZCDDn3HdkNbL3"; // // @SuppressWarnings("deprecation") // FacebookClient fbClient = new DefaultFacebookClient(accessToken); // // User me = fbClient.fetchObject("me", User.class); // // System.out.println(me.getName()); String domain = "http://www.google.com"; String appId = "216948179046382"; String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain;//+"&scope=user_about_me"; System.out.println(authUrl); System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get(authUrl); String accessToken; while(true) { if(!driver.getCurrentUrl().contains("facebook.com")) { String url = driver.getCurrentUrl(); accessToken = url.replaceAll(".*#access_token=(.+)&.*", "$1"); driver.quit(); FacebookClient fbClient = new DefaultFacebookClient(accessToken); User user = fbClient.fetchObject("me", User.class); } } } }
33.26
246
0.704149
c3d89985ddc1ad4ad76132fe2fe91d08e123c3a8
1,104
package services.sms; public class SendResult { private String group_id; private String result_code; private String result_message; private String errorString; private String errorCount; private String successCount; public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public String getResult_code() { return result_code; } public void setResult_code(String result_code) { this.result_code = result_code; } public String getResult_message() { return result_message; } public void setResult_message(String result_message) { this.result_message = result_message; } public String getErrorString() { return errorString; } public void setErrorString(String errorString) { this.errorString = errorString; } public String getErrorCount() { return errorCount; } public void setErrorCount(String errorCount) { this.errorCount = errorCount; } public String getSuccessCount() { return successCount; } public void setSuccessCount(String successCount) { this.successCount = successCount; } }
23
55
0.763587
31de0a73b97fc75b3e114ae320382f57b8a4882f
1,885
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.purchase.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.service.CrudService; import com.thinkgem.jeesite.modules.purchase.entity.TsPurchase; import com.thinkgem.jeesite.modules.purchase.dao.TsPurchaseDao; /** * 征订信息维护Service * @author suntao * @version 2018-01-23 */ @Service @Transactional(readOnly = true) public class TsPurchaseService extends CrudService<TsPurchaseDao, TsPurchase> { @Autowired private TsPurchaseDao tsResourceBusDao; public TsPurchase get(String id) { return super.get(id); } public List<TsPurchase> findList(TsPurchase tsPurchase) { return super.findList(tsPurchase); } public List<TsPurchase> getTsPurchaseByOrder(TsPurchase tsPurchase) { return tsResourceBusDao.getTsPurchaseByOrder(tsPurchase); } public Page<TsPurchase> findPage(Page<TsPurchase> page, TsPurchase tsPurchase) { return super.findPage(page, tsPurchase); } @Transactional(readOnly = false) public void save(TsPurchase tsPurchase) { super.save(tsPurchase); } @Transactional(readOnly = false) public void saveTsPurchaseOrder(List<TsPurchase> list , String orderId) { for (TsPurchase tsPurchase : list) { if (tsPurchase.getIsList().equals("1")) { tsPurchase = super.get(tsPurchase.getId()) ; tsPurchase.setOrderId(orderId); super.save(tsPurchase); } } } @Transactional(readOnly = false) public void delete(TsPurchase tsPurchase) { super.delete(tsPurchase); } }
27.318841
108
0.743236
7587185c5c7742700af8f0c7656c06489f28e56c
6,964
/* * Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es) * * 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 es.bsc.compss.invokers; import es.bsc.compss.execution.types.InvocationResources; import es.bsc.compss.types.execution.Invocation; import es.bsc.compss.types.execution.InvocationContext; import es.bsc.compss.types.execution.InvocationParam; import es.bsc.compss.types.execution.exceptions.JobExecutionException; import es.bsc.compss.util.TraceEvent; import es.bsc.compss.util.Tracer; import java.io.File; import java.util.List; import java.util.concurrent.Semaphore; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.bytecode.Descriptor; import storage.CallbackEvent; import storage.CallbackHandler; import storage.StorageException; import storage.StorageItf; import storage.StubItf; public class StorageInvoker extends JavaInvoker { private static final String ERROR_CLASS_NOT_FOUND = "ERROR: Target object class not found"; private static final String ERROR_EXTERNAL_NO_PSCO = "ERROR: External ExecuteTask can only be used with target PSCOs"; private static final String ERROR_STORAGE_CALL = "ERROR: External executeTask call failed"; private static final String ERROR_CALLBACK_INTERRUPTED = "ERROR: External callback interrupted"; private static final String ERROR_EXTERNAL_EXECUTION = "ERROR: External Task Execution failed"; private static final String WARN_RET_VALUE_EXCEPTION = "WARN: Exception on externalExecution return value"; public StorageInvoker(InvocationContext context, Invocation invocation, File taskSandboxWorkingDir, InvocationResources assignedResources) throws JobExecutionException { super(context, invocation, taskSandboxWorkingDir, assignedResources); } @Override public Object runMethod() throws JobExecutionException { // Invoke the requested method from the external platform // WARN: ExternalExecution is only supported for methods with PSCO as target object int n = method.getParameterAnnotations().length; ClassPool pool = ClassPool.getDefault(); Class<?>[] cParams = method.getParameterTypes(); CtClass[] ctParams = new CtClass[n]; for (int i = 0; i < n; i++) { try { ctParams[i] = pool.getCtClass(((Class<?>) cParams[i]).getName()); } catch (NotFoundException e) { throw new JobExecutionException(ERROR_CLASS_NOT_FOUND + " " + cParams[i].getName(), e); } } String descriptor; try { descriptor = method.getName() + Descriptor.ofMethod(pool.getCtClass(method.getReturnType().getName()), ctParams); } catch (NotFoundException e) { throw new JobExecutionException(ERROR_CLASS_NOT_FOUND + " " + method.getReturnType().getName(), e); } // Check and retrieve target PSCO Id String id = null; try { id = ((StubItf) this.invocation.getTarget().getValue()).getID(); } catch (Exception e) { throw new JobExecutionException(ERROR_EXTERNAL_NO_PSCO, e); } if (id == null) { throw new JobExecutionException(ERROR_EXTERNAL_NO_PSCO); } // Call Storage executeTask if (LOGGER.isDebugEnabled()) { LOGGER.info("External ExecuteTask " + method.getName() + " with target PSCO Id " + id + " in " + context.getHostName()); } else { LOGGER.info("External ExecuteTask " + method.getName()); } if (Tracer.extraeEnabled()) { Tracer.emitEvent(TraceEvent.STORAGE_EXECUTETASK.getId(), TraceEvent.STORAGE_EXECUTETASK.getType()); } List<? extends InvocationParam> params = invocation.getParams(); Object[] values = new Object[params.size()]; int paramIdx = 0; for (InvocationParam param : params) { values[paramIdx++] = param.getValue(); } CallbackHandlerPSCO callback = new CallbackHandlerPSCO(); try { String callResult = StorageItf.executeTask(id, descriptor, values, context.getHostName(), callback); LOGGER.debug(callResult); // Wait for execution callback.waitForCompletion(); } catch (StorageException e) { throw new JobExecutionException(ERROR_STORAGE_CALL, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new JobExecutionException(ERROR_CALLBACK_INTERRUPTED, e); } finally { if (Tracer.extraeEnabled()) { Tracer.emitEvent(Tracer.EVENT_END, TraceEvent.STORAGE_EXECUTETASK.getType()); } } // Process the return status CallbackEvent.EventType callStatus = callback.getStatus(); if (!callStatus.equals(CallbackEvent.EventType.SUCCESS)) { throw new JobExecutionException(ERROR_EXTERNAL_EXECUTION); } // Process return value Object retValue = null; if (method.getReturnType().getName().compareTo(void.class.getName()) != 0) { try { retValue = callback.getResult(); } catch (StorageException e) { LOGGER.warn(WARN_RET_VALUE_EXCEPTION, e); retValue = null; } } return retValue; } /** * Class to get the Storage Callback. */ private class CallbackHandlerPSCO extends CallbackHandler { private CallbackEvent event; private Semaphore sem; public CallbackHandlerPSCO() { this.sem = new Semaphore(0); } @Override protected void eventListener(CallbackEvent e) { this.event = e; LOGGER.debug("Received event task finished with callback id " + event.getRequestID()); synchronized (this) { this.notifyAll(); } this.sem.release(); } public void waitForCompletion() throws InterruptedException { this.sem.acquire(); } public CallbackEvent.EventType getStatus() { return this.event.getType(); } public Object getResult() throws StorageException { return StorageItf.getResult(event); } } }
35.896907
116
0.651493
c28c4695c5fb247356f8aaee9bff8768b7b29193
2,216
package com.benny.traveladvisor.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.net.UnknownHostException; /** * Description: This is the Redis configuration class * @author benny.li * Date: 2020/5/18 */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(redisConnectionFactory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 解决jackson2无法反序列化LocalDateTime的问题 mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.registerModule(new JavaTimeModule()); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); serializer.setObjectMapper(mapper); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.setValueSerializer(serializer); template.afterPropertiesSet(); return template; } }
43.45098
131
0.797383
3f4658941090df33827cb423d69a80346c7cc1ed
28,077
package org.mockserver.collections.multimap.nottablematcher; import org.junit.Test; import org.mockserver.collections.CaseInsensitiveRegexMultiMap; import org.mockserver.model.NottableString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockserver.collections.CaseInsensitiveRegexMultiMap.multiMap; import static org.mockserver.model.NottableOptionalString.optionalString; import static org.mockserver.model.NottableString.not; import static org.mockserver.model.NottableString.string; /** * @author jamesdbloom */ public class CaseInsensitiveRegexMultiMapTestNottableContainsAll { @Test public void shouldContainAllExactMatchSingleKeyAndSingleValueForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyOne"), string("keyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllExactMatchSingleKeyAndSingleValueForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("notKeyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllExactMatchSingleKeyAndSingleValueForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyOne"), string("notKeyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndSingleValueForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyOne"), string("keyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndSingleValueForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("notKeyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndSingleValueForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyOne"), string("notKeyOne_valueOne")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")} )), is(true)); } @Test public void shouldContainAllExactMatchSingleKeyAndMultipleValuesForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllExactMatchSingleKeyAndMultipleValuesForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllExactMatchSingleKeyAndMultipleValuesForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), string("notKeyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndMultipleValuesForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndMultipleValuesForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetSingleKeyAndMultipleValuesForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllExactMatchMultipleKeyAndMultipleValuesForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllExactMatchMultipleKeyAndMultipleValuesForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllExactMatchMultipleKeyAndMultipleValuesForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetMultipleKeyAndMultipleValuesForNottedKey() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetMultipleKeyAndMultipleValuesForNottedValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllSubSetMultipleKeyAndMultipleValuesForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("keyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("notKeyTwo"), string("notKeyTwo_valueOne"), string("notKeyTwo_valueTwo")} )), is(true)); // and then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")} )), is(true)); } @Test public void shouldContainAllEmptySubSetMultipleKeyAndMultipleValuesForNottedKeyAndValue() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOneValue")}, new NottableString[]{not("keyTwo"), not("keyTwoValue")}, new NottableString[]{string("keyThree"), string("keyThreeValue"), string("keyThree_valueTwo")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{} )), is(true)); } @Test public void shouldContainAllSubSetMultipleKeyForEmptyMap() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( false, new NottableString[]{} ); // then assertThat(multiMap.containsAll(multiMap( false, new NottableString[]{not("keyOne"), string("keyOneValue")}, new NottableString[]{not("keyTwo"), string("keyTwoValue")} )), is(true)); } @Test public void shouldNotContainAllNotMatchSingleKeySingleEntry() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchSingleValueSingleEntry() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchSingleKeyAndValueSingleEntry() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchSingleKeyMultipleEntries() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchSingleValueMultipleEntries() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchSingleKeyAndValueMultipleEntries() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), not("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")} )), is(false)); } @Test public void shouldNotContainAllNotMatchMultipleKeysMultipleEntries() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{not("keyOne"), string("keyOne_valueOne")}, new NottableString[]{not("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(false)); } @Test public void shouldNotContainAllNotMatchMultipleValuesMultipleEntries() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), not("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), not("keyTwo_valueOne"), not("keyTwo_valueTwo")}, new NottableString[]{string("keyThree"), string("keyThree_valueOne"), string("keyThree_valueTwo"), string("keyThree_valueThree")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOne_valueOne")}, new NottableString[]{string("keyTwo"), string("keyTwo_valueOne"), string("keyTwo_valueTwo")} )), is(false)); assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyTwo"), string("keyTwo.*")} )), is(false)); } @Test public void shouldNotContainAllNotMatchMultipleValuesMultipleEntriesContradiction() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{string("keyOne"), string("keyOneValue")} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{string("keyOne"), string("keyOneValue")}, new NottableString[]{not("keyOne"), not("keyOneValue")} )), is(false)); } @Test public void shouldNotContainAllSubSetMultipleKeyForEmptyMap() { // given CaseInsensitiveRegexMultiMap multiMap = multiMap( true, new NottableString[]{} ); // then assertThat(multiMap.containsAll(multiMap( true, new NottableString[]{not("keyOne"), string("keyOneValue")}, new NottableString[]{string("keyTwo"), string("keyTwoValue")} )), is(false)); } }
45.139871
141
0.643053
4facd7d61f03a2fb5d2595c8877809d02f91d045
2,893
package frontend.labels; import backend.entities.OilRig; import javax.swing.*; import java.awt.*; import java.util.ArrayList; /** Custom JLabel that represents an oil rig * @author Louis Wendler * @since 1.0 * @version 1.0 */ public class OilRigLabel extends NodeLabel { private OilRig oilRig; private int x; private int y; private int radius; /** * Create a OilRigLabel * @param oilRig Oil rig node the OilRigLabel represents * @param icon Image of oil rig icon * @param frame Frame the Popup will be added to * @param x Coordinate of the ImageIcon * @param y Coordinate of the ImageIcon * @param radius Radius of the circle that surrounds the OilRigLabel */ public OilRigLabel(OilRig oilRig, ImageIcon icon, JFrame frame, int x, int y, int radius) { super(oilRig.getAttributes().get("name").toString(), icon, frame, x, y); this.oilRig = oilRig; this.x = x; this.y = y; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.CYAN); g.fillOval(x, y, radius, radius); } @Override public OilRig getNode() { return oilRig; } /** * See NodeLabel.showHoverPopup() * @param point Position of the Popup */ @Override public void showHoverPopup(Point point) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); ArrayList<String> texts = new ArrayList<>(); texts.add(String.format( "Number of workers: %s / %s", oilRig.getNumberWorkers().toString(), oilRig.getMaxWorkers().toString() )); texts.add(String.format( "Number of small ships: %s / %s", oilRig.getNumberSmallShips().toString(), oilRig.getMaxNumberSmallShips() )); texts.add(String.format( "Number of big ships: %s / %s", oilRig.getNumberBigShips().toString(), oilRig.getMaxNumberBigShips() )); texts.add(String.format( "Number of ships: %s / %s", oilRig.getNumberShips().toString(), oilRig.getMaxShips().toString() )); for (String text : texts) { JLabel label = new JLabel(text); panel.add(label); } panel.setOpaque(true); panel.setBackground(new Color(211, 224, 235)); panel.setBorder(BorderFactory.createLineBorder(new Color(46, 53, 59, 100), 2, true)); hoverPopup = popupFactory.getPopup(frame, panel, point.x, point.y); hoverPopup.show(); } }
28.087379
96
0.554096
523ec53639e6afeb66852503415f874db2fd9824
903
/* * Latke - 一款以 JSON 为主的 Java Web 框架 * Copyright (c) 2009-present, b3log.org * * Latke is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.b3log.latke.http; import org.b3log.latke.ioc.Singleton; /** * Processor for testing. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.0.0.3, Feb 9, 2020 * @since 3.2.4 */ @Singleton public class TestProcessor { public void a(final RequestContext context) { context.attr("a", "a"); } }
30.1
204
0.694352
b36ebaececc89071815fd63ea9582245ad2988bd
956
package com.home.commonBase.constlist.generate; /** 场景实例类型(generated by shine) */ public class SceneInstanceType { /** 单例场景(主城) */ public static final int SingleInstance=1; /** 单人副本(可随时出,与player绑定,mmo多用) */ public static final int SinglePlayerBattle=2; /** 多人副本(可随时出,与player绑定,mmo多用) */ public static final int MultiPlayerBattle=3; /** 副本预进入场景(限定进入,与player绑定,moba准备场景用) */ public static final int PreBattle=4; /** 限定多人副本(不可随时出,不与player绑定) */ public static final int FiniteBattle=5; /** 限定多人副本(不可随时出,不与player绑定,帧同步) */ public static final int FiniteBattleWithFrameSync=6; /** 分线单例场景(主城) */ public static final int LinedSingleInstance=7; /** 客户端驱动的单人副本 */ public static final int ClientDriveSinglePlayerBattle=8; /** 自动分线的单例场景(主城类) */ public static final int AutoLinedScene=9; /** 玩家群独立场景 */ public static final int RoleGroupScene=10; /** 长度 */ public static int size=11; }
23.9
58
0.687238
0f121355f72afbaccfbb80a5abd04715b93172fc
396
package cn.blackme.leetcode; public class LeetCode53 { public int maxSubArray(int[] nums) { int dp[] = new int[nums.length]; dp[0] = nums[0]; int max = nums[0]; for (int i = 1; i < nums.length; i++) { dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]); if (max < dp[i]) max = dp[i]; } return max; } }
22
59
0.45202
756cf7af4a78530fb85bd01a6fd767bc67065468
560
package cz.drabek.feedreader.util; import android.support.annotation.Nullable; public class Preconditions { public static <T> T checkNotNull(T reference) { if(reference == null) { throw new NullPointerException(); } else { return reference; } } public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { if(reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } else { return reference; } } }
23.333333
82
0.603571
faef747640f8ff933b28f3714fccd11e1edde8fc
541
package softuni._001accountsystem.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import softuni._001accountsystem.models.entities.Account; import java.math.BigDecimal; /** * Created by IntelliJ IDEA. * User: LAPD * Date: 30.3.2018 г. * Time: 17:49 ч. */ @Repository public interface AccountRepository extends CrudRepository<Account, Long> { Account getByUserUsername(String username); Account getByBalanceLessThan(BigDecimal ballance); }
22.541667
58
0.778189
b21a2e21dd95eec22c77d0a4435d35eac64b351d
474
package egovframework.mybatis.vo; import lombok.Builder; import lombok.Getter; @Getter public class JobResultVO { public static final String OK = "OK"; public static final String FAIL = "FAIL"; public static final String SUCCESS_MESSAGE = "success"; private final String result; private final String message; @Builder public JobResultVO(String result, String message) { this.result = result; this.message = message; } }
20.608696
59
0.694093
48ef14c3f5a65301bad6653e13bc187f9ecc54df
11,069
package br.eti.hmagalhaes.rh.controller; import br.eti.hmagalhaes.rh.TestUtils; import br.eti.hmagalhaes.rh.model.dto.ColaboradorFormDTO; import br.eti.hmagalhaes.rh.model.entity.*; import br.eti.hmagalhaes.rh.model.service.*; import java.util.*; import org.easymock.EasyMock; import org.junit.Before; import org.springframework.validation.BindingResult; import static org.easymock.EasyMock.*; import org.junit.Test; import static org.junit.Assert.*; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.core.convert.ConversionService; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; /** * * @author Hudson P. Magalhães <[email protected]> * @since 27-Feb-2014 */ public class ColaboradorControllerTest { private final ColaboradorController controller = new ColaboradorController(); private ColaboradorService colaboradorServiceMock; private DepartamentoService deptoServiceMock; private ConversionService conversionServiceMock; private BindingResult bindingResultMock; private Model model; public ColaboradorControllerTest() { // Mock de mensagens. // O conteúdo final das mensagens não fará diferença nos testes, portanto, // o mock será único e retornará "ok" para qualquer mensagem. final ResourceBundleMessageSource msg = new ResourceBundleMessageSource(); msg.setParentMessageSource(TestUtils.createMessageSourceNiceMock("ok")); controller.setMsgBundle(msg); // I18nService // Por enquanto este serviço não é tão importante, portanto iremos // usar um só mock (instance). final I18nService i18n = EasyMock.createMock(I18nService.class); expect(i18n.getLocalesSuportados()).andReturn( Arrays.asList(Locale.ENGLISH, new Locale("pt")) ).anyTimes(); expect(i18n.getLocaleAtual()).andReturn(new Locale("pt")).anyTimes(); replay(i18n); controller.setI18nService(i18n); } @Before public void setup() { colaboradorServiceMock = createMock(ColaboradorService.class); deptoServiceMock = createMock(DepartamentoService.class); conversionServiceMock = createMock(ConversionService.class); controller.setColaboradorService(colaboradorServiceMock); controller.setDepartamentoService(deptoServiceMock); controller.setConversionService(conversionServiceMock); bindingResultMock = createNiceMock(BindingResult.class); model = new ExtendedModelMap(); } @Test public void test_listar_ok() { expect(colaboradorServiceMock.buscar()).andReturn(TestUtils.Colab.lista(2)); replay(colaboradorServiceMock); // String view = controller.listar(model, null); // assertEquals("colaborador/listar", view); assertTrue(model.asMap().get("lista") instanceof Collection); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_listar_comMensagem() { expect(colaboradorServiceMock.buscar()).andReturn(TestUtils.Colab.lista(2)); replay(colaboradorServiceMock); // String view = controller.listar(model, "Teste"); // assertEquals("colaborador/listar", view); assertEquals("Teste", model.asMap().get("msg")); assertTrue(model.asMap().get("lista") instanceof Collection); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_listar_colabServiceError() { expect(colaboradorServiceMock.buscar()).andThrow(new RuntimeException()); replay(colaboradorServiceMock); // String view = controller.listar(model, null); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_formEditar_ok() { Colaborador colab = new Colaborador(); colab.setId(10L); ColaboradorFormDTO form = new ColaboradorFormDTO(); form.setId(10l); expect(colaboradorServiceMock.buscar(10l)).andReturn(colab); replay(colaboradorServiceMock); expect(conversionServiceMock.convert(colab, ColaboradorFormDTO.class)). andReturn(form); replay(conversionServiceMock); expect(deptoServiceMock.buscar()).andReturn(TestUtils.Depto.lista(3)); replay(deptoServiceMock); // String view = controller.formEditar(model, 10l); // form = (ColaboradorFormDTO) model.asMap().get("formEditarColaborador"); assertEquals("colaborador/editar", view); assertNotNull(form); assertEquals(new Long(10), form.getId()); assertTrue(model.asMap().get("departamentos") instanceof Collection); verify_localeData(); verify(colaboradorServiceMock, conversionServiceMock, deptoServiceMock); } @Test public void test_formEditar_colabServiceError() { expect(colaboradorServiceMock.buscar(10L)).andThrow(new RuntimeException()); replay(colaboradorServiceMock); // String view = controller.formEditar(model, 10L); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_formEditar_deptoServiceError() { Colaborador colab = new Colaborador(); colab.setId(10L); ColaboradorFormDTO form = new ColaboradorFormDTO(); form.setId(10l); expect(colaboradorServiceMock.buscar(10l)).andReturn(colab); replay(colaboradorServiceMock); expect(conversionServiceMock.convert(colab, ColaboradorFormDTO.class)). andReturn(form); replay(conversionServiceMock); expect(deptoServiceMock.buscar()).andThrow(new RuntimeException()); replay(deptoServiceMock); // String view = controller.formEditar(model, 10l); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock, conversionServiceMock, deptoServiceMock); } @Test public void test_formEditar_regInexistente() { expect(colaboradorServiceMock.buscar(10l)).andReturn(null); replay(colaboradorServiceMock); // String view = controller.formEditar(model, 10L); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_formIncluir_ok() { expect(deptoServiceMock.buscar()).andReturn(TestUtils.Depto.lista(3)); replay(deptoServiceMock); // String view = controller.formIncluir(model); // assertEquals("colaborador/incluir", view); assertTrue(model.asMap().get("formIncluirColaborador") instanceof ColaboradorFormDTO); assertTrue(model.asMap().get("departamentos") instanceof Collection); verify_localeData(); verify(deptoServiceMock); } @Test public void test_formIncluir_deptoServiceError() { expect(deptoServiceMock.buscar()).andThrow(new RuntimeException()); replay(deptoServiceMock); // String view = controller.formIncluir(model); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(deptoServiceMock); } @Test public void test_salvarEditar_ok() { ColaboradorFormDTO form = new ColaboradorFormDTO(); expect(colaboradorServiceMock.atualizar(form)).andReturn(new Colaborador()); replay(colaboradorServiceMock); // String view = controller.salvarEditar(model, form, bindingResultMock); // assertEquals("redirect:/colaborador/", view); assertNotNull(model.asMap().get("msg")); verify(colaboradorServiceMock); } @Test public void test_salvarEditar_colabServiceError() { ColaboradorFormDTO form = new ColaboradorFormDTO(); expect(colaboradorServiceMock.atualizar(form)).andThrow(new RuntimeException()); replay(colaboradorServiceMock); // String view = controller.salvarEditar(model, form, bindingResultMock); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_salvarEditar_validacaoFalha() { ColaboradorFormDTO form = new ColaboradorFormDTO(); form.setId(10L); expect(bindingResultMock.hasErrors()).andReturn(true); replay(bindingResultMock); expect(deptoServiceMock.buscar()).andReturn(TestUtils.Depto.lista(3)); replay(deptoServiceMock); // String view = controller.salvarEditar(model, form, bindingResultMock); // form = (ColaboradorFormDTO) model.asMap().get("formEditarColaborador"); assertEquals("colaborador/editar", view); assertNotNull(form); assertEquals(new Long(10), form.getId()); assertTrue(model.asMap().get("departamentos") instanceof Collection); verify_localeData(); verify(bindingResultMock, deptoServiceMock); } @Test public void test_salvarIncluir_ok() { ColaboradorFormDTO form = new ColaboradorFormDTO(); expect(colaboradorServiceMock.inserir(form)).andReturn(new Colaborador()); replay(colaboradorServiceMock); // String view = controller.salvarIncluir(model, form, bindingResultMock); // assertEquals("redirect:/colaborador/", view); assertNotNull(model.asMap().get("msg")); verify(colaboradorServiceMock); } @Test public void test_salvarIncluir_colabServiceError() { ColaboradorFormDTO form = new ColaboradorFormDTO(); expect(colaboradorServiceMock.inserir(form)).andThrow(new RuntimeException()); replay(colaboradorServiceMock); // String view = controller.salvarIncluir(model, form, bindingResultMock); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } @Test public void test_salvarIncluir_validacaoFalha() { expect(bindingResultMock.hasErrors()).andReturn(true); replay(bindingResultMock); expect(deptoServiceMock.buscar()).andReturn(TestUtils.Depto.lista(3)); replay(deptoServiceMock); // String view = controller.salvarIncluir(model, new ColaboradorFormDTO(), bindingResultMock); // assertEquals("colaborador/incluir", view); assertTrue(model.asMap().get("formIncluirColaborador") instanceof ColaboradorFormDTO); assertTrue(model.asMap().get("departamentos") instanceof Collection); verify_localeData(); verify(bindingResultMock, deptoServiceMock); } @Test public void test_remover_ok() { colaboradorServiceMock.remover(10L); expectLastCall(); replay(colaboradorServiceMock); // String view = controller.remover(model, 10L); // assertEquals("redirect:/colaborador/", view); assertNotNull(model.asMap().get("msg")); verify(colaboradorServiceMock); } @Test public void test_remover_colabServiceError() { colaboradorServiceMock.remover(10L); expectLastCall().andThrow(new RuntimeException()); replay(colaboradorServiceMock); // String view = controller.remover(model, 10L); // assertEquals("error", view); assertNotNull(model.asMap().get("error")); verify_localeData(); verify(colaboradorServiceMock); } /** * Verifica se estão no modelo os dados referentes ao form de locale, * presente em todas views. */ private void verify_localeData() { assertTrue(model.asMap().get("locales") instanceof Collection); assertTrue(model.asMap().get("localeAtual") instanceof Locale); } }
28.825521
88
0.747583
3b4cd877d6c4ceeb036ad3bc55a7020e7fad02f5
2,054
/* 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.custom; import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelFunctionTransformer; import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EndsWithFunctionTransformer extends FeelToJuelFunctionTransformer { public static final Pattern ENDS_WITH_PATTERN = Pattern.compile("^ends with\\((.+)\\)$"); public static final String JUEL_ENDS_WITH = "endsWith"; public EndsWithFunctionTransformer() { try { method = EndsWithFunctionTransformer.class.getMethod(JUEL_ENDS_WITH, String.class, String.class); } catch (Exception ex) { ex.printStackTrace(); } } public boolean canTransform(String feelExpression) { Matcher startsWithMatcher = ENDS_WITH_PATTERN.matcher(feelExpression); return startsWithMatcher.matches(); } @Override public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { Matcher startsWithMatcher = ENDS_WITH_PATTERN.matcher(feelExpression); if (startsWithMatcher.matches()) { return JUEL_ENDS_WITH + "(" + inputName + ", " + startsWithMatcher.group(1) + ")"; } else { return feelExpression; } } public static boolean endsWith(final String input, final String match) { if (input != null) { return input.endsWith(match); } return false; } @Override public String getLocalName() { return JUEL_ENDS_WITH; } }
31.121212
104
0.731256
7b9b57a2596b4970ef43743eefab6d76fae719b7
380
package cn.elvea.platform.commons.utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * RegionUtilsTests * * @author elvea * @since 0.0.1 */ public class RegionUtilsTests { @Test public void test() throws Exception { RegionUtils.McaData data = RegionUtils.fetchMcaData(); Assertions.assertNotNull(data); } }
18.095238
62
0.692105
7f368196e8069f646eb4d805a8964be62d1d8457
12,843
package com.avaje.ebeaninternal.server.deploy.id; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.persistence.PersistenceException; import com.avaje.ebeaninternal.api.SpiExpressionRequest; import com.avaje.ebeaninternal.server.core.DefaultSqlUpdate; import com.avaje.ebeaninternal.server.core.InternString; import com.avaje.ebeaninternal.server.deploy.BeanProperty; import com.avaje.ebeaninternal.server.deploy.DbReadContext; import com.avaje.ebeaninternal.server.deploy.DbSqlContext; import com.avaje.ebeaninternal.server.lib.util.MapFromString; import com.avaje.ebeaninternal.server.type.DataBind; /** * Bind an Id that is made up of multiple separate properties. * <p> * The id passed in for binding is expected to be a map with the key being the * String name of the property and the value being that properties bind value. * </p> */ public final class IdBinderMultiple implements IdBinder { private final BeanProperty[] props; private final String idProperties; private final String idInValueSql; public IdBinderMultiple(BeanProperty[] idProps) { this.props = idProps; StringBuilder sb = new StringBuilder(); for (int i = 0; i < idProps.length; i++) { if (i > 0){ sb.append(","); } sb.append(idProps[i].getName()); } idProperties = InternString.intern(sb.toString()); sb = new StringBuilder(); sb.append("("); for (int i = 0; i < props.length; i++) { if (i > 0){ sb.append(","); } sb.append("?"); } sb.append(")"); idInValueSql = sb.toString(); } public void initialise(){ // do nothing } public String getOrderBy(String pathPrefix, boolean ascending){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { if (i > 0) { sb.append(" "); } if (pathPrefix != null){ sb.append(pathPrefix).append("."); } sb.append(props[i].getName()); if (!ascending){ sb.append(" desc"); } } return sb.toString(); } public void createLdapNameById(LdapName name, Object id) throws InvalidNameException { if (id instanceof Map<?,?> == false){ throw new RuntimeException("Expecting a Map for concatinated key"); } Map<?,?> mapId = (Map<?,?>)id; for (int i = 0; i < props.length; i++) { Object v = mapId.get(props[i].getName()); if (v == null){ throw new RuntimeException("No value in Map for key "+props[i].getName()); } Rdn rdn = new Rdn(props[i].getDbColumn(), v); name.add(rdn); } } public void buildSelectExpressionChain(String prefix, List<String> selectChain) { for (int i = 0; i < props.length; i++) { props[i].buildSelectExpressionChain(prefix, selectChain); } } public void createLdapNameByBean(LdapName name, Object bean) throws InvalidNameException { for (int i = 0; i < props.length; i++) { Object v = props[i].getValue(bean); Rdn rdn = new Rdn(props[i].getDbColumn(), v); name.add(rdn); } } public int getPropertyCount() { return props.length; } public String getIdProperty() { return idProperties; } public BeanProperty findBeanProperty(String dbColumnName) { for (int i = 0; i < props.length; i++) { if (dbColumnName.equalsIgnoreCase(props[i].getDbColumn())){ return props[i]; } } return null; } public boolean isComplexId(){ return true; } public String getDefaultOrderBy() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { if (i > 0){ sb.append(","); } sb.append(props[i].getName()); } return sb.toString(); } public BeanProperty[] getProperties() { return props; } public void addIdInBindValue(SpiExpressionRequest request, Object value) { for (int i = 0; i < props.length; i++) { request.addBindValue(props[i].getValue(value)); } } public String getIdInValueExprDelete(int size) { return getIdInValueExpr(size); } public String getIdInValueExpr(int size) { StringBuilder sb = new StringBuilder(); sb.append(" in"); sb.append(" ("); sb.append(idInValueSql); for (int i = 1; i < size; i++) { sb.append(",").append(idInValueSql); } sb.append(") "); return sb.toString(); } public String getBindIdInSql(String baseTableAlias) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 0; i < props.length; i++) { if (i > 0) { sb.append(","); } if (baseTableAlias != null){ sb.append(baseTableAlias); sb.append("."); } sb.append(props[i].getDbColumn()); } sb.append(")"); return sb.toString(); } public Object[] getIdValues(Object bean){ Object[] bindvalues = new Object[props.length]; for (int i = 0; i < props.length; i++) { bindvalues[i] = props[i].getValue(bean); } return bindvalues; } @SuppressWarnings("unchecked") public Object[] getBindValues(Object idValue){ Object[] bindvalues = new Object[props.length]; // concatenated id as a Map try { Map<String, ?> uidMap = (Map<String, ?>) idValue; for (int i = 0; i < props.length; i++) { Object value = uidMap.get(props[i].getName()); bindvalues[i] = value; } return bindvalues; } catch (ClassCastException e) { String msg = "Expecting concatinated idValue to be a Map"; throw new PersistenceException(msg, e); } } public Object readTerm(String idTermValue) { String[] split = idTermValue.split("|"); if (split.length != props.length){ String msg = "Failed to split ["+idTermValue+"] using | for id."; throw new PersistenceException(msg); } Map<String, Object> uidMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < props.length; i++) { Object v = props[i].getScalarType().parse(split[i]); uidMap.put(props[i].getName(), v); } return uidMap; } @SuppressWarnings("unchecked") public String writeTerm(Object idValue) { Map<String, ?> uidMap = (Map<String, ?>) idValue; StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { Object v = uidMap.get(props[i].getName()); String formatValue = props[i].getScalarType().format(v); if (i > 0){ sb.append("|"); } sb.append(formatValue); } return sb.toString(); } public Object readData(DataInput dataInput) throws IOException { LinkedHashMap<String,Object> map = new LinkedHashMap<String, Object>(); boolean notNull = true; for (int i = 0; i < props.length; i++) { Object value = props[i].readData(dataInput); map.put(props[i].getName(), value); if (value == null) { notNull = false; } } if (notNull) { return map; } else { return null; } } @SuppressWarnings("unchecked") public void writeData(DataOutput dataOutput, Object idValue) throws IOException { Map<String,Object> map = (Map<String,Object>)idValue; for (int i = 0; i < props.length; i++) { Object embFieldValue = map.get(props[i].getName()); //Object embFieldValue = props[i].getValue(idValue); props[i].writeData(dataOutput, embFieldValue); } } public void loadIgnore(DbReadContext ctx) { for (int i = 0; i < props.length; i++) { props[i].loadIgnore(ctx); } } public Object readSet(DbReadContext ctx, Object bean) throws SQLException { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); boolean notNull = false; for (int i = 0; i < props.length; i++) { Object value = props[i].readSet(ctx, bean, null); if (value != null){ map.put(props[i].getName(), value); notNull = true; } } if (notNull){ return map; } else { return null; } } public Object read(DbReadContext ctx) throws SQLException { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); boolean notNull = false; for (int i = 0; i < props.length; i++) { Object value = props[i].read(ctx); if (value != null){ map.put(props[i].getName(), value); notNull = true; } } if (notNull){ return map; } else { return null; } } @SuppressWarnings("unchecked") public void bindId(DefaultSqlUpdate sqlUpdate, Object idValue) { // concatenated id as a Map try { Map<String, ?> uidMap = (Map<String, ?>) idValue; for (int i = 0; i < props.length; i++) { Object value = uidMap.get(props[i].getName()); sqlUpdate.addParameter(value); } } catch (ClassCastException e) { String msg = "Expecting concatinated idValue to be a Map"; throw new PersistenceException(msg, e); } } @SuppressWarnings("unchecked") public void bindId(DataBind bind, Object idValue) throws SQLException { // concatenated id as a Map try { Map<String, ?> uidMap = (Map<String, ?>) idValue; for (int i = 0; i < props.length; i++) { Object value = uidMap.get(props[i].getName()); props[i].bind(bind, value); } } catch (ClassCastException e) { String msg = "Expecting concatinated idValue to be a Map"; throw new PersistenceException(msg, e); } } public void appendSelect(DbSqlContext ctx, boolean subQuery) { for (int i = 0; i < props.length; i++) { props[i].appendSelect(ctx, subQuery); } } public String getAssocIdInExpr(String prefix) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 0; i < props.length; i++) { if (i > 0) { sb.append(","); } if (prefix != null) { sb.append(prefix); sb.append("."); } sb.append(props[i].getName()); } sb.append(")"); return sb.toString(); } public String getAssocOneIdExpr(String prefix, String operator){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { if (i > 0) { sb.append(" and "); } if (prefix != null){ sb.append(prefix); sb.append("."); } sb.append(props[i].getName()); sb.append(operator); } return sb.toString(); } public String getBindIdSql(String baseTableAlias) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { if (i > 0) { sb.append(" and "); } if (baseTableAlias != null){ sb.append(baseTableAlias); sb.append("."); } sb.append(props[i].getDbColumn()); sb.append(" = ? "); } return sb.toString(); } public Object convertSetId(Object idValue, Object bean) { // allow Map or String for concatenated id Map<?,?> mapVal = null; if (idValue instanceof Map<?,?>) { mapVal = (Map<?,?>) idValue; } else { mapVal = MapFromString.parse(idValue.toString()); } // Use a new LinkedHashMap to control the order LinkedHashMap<String,Object> newMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < props.length; i++) { BeanProperty prop = props[i]; Object value = mapVal.get(prop.getName()); // Convert the property type if required value = props[i].getScalarType().toBeanType(value); newMap.put(prop.getName(), value); if (bean != null) { // support PropertyChangeSupport prop.setValueIntercept(bean, value); } } return newMap; } }
27.738661
92
0.562563
777b42f0de48e3715338d3278cfe5837f314baea
1,024
package com.pr.sepp.sep.build.model.resp; import com.offbytwo.jenkins.model.BuildResult; import com.pr.sepp.sep.build.model.constants.JenkinsBuildStatus; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Objects; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class JenkinsBuildResp { private Integer buildVersion; private boolean showSelect = false; private JenkinsBuildStatus status; public static JenkinsBuildResp apply(Integer number, BuildResult result) { JenkinsBuildResp jenkinsBuildResp = new JenkinsBuildResp(); jenkinsBuildResp.setBuildVersion(number); jenkinsBuildResp.setShowSelect(false); jenkinsBuildResp.setStatus(Objects.equals(result, null) ? JenkinsBuildStatus.BUILDING : JenkinsBuildStatus.valueOf(result.name())); return jenkinsBuildResp; } public boolean canDeploy() { return this.getStatus() == JenkinsBuildStatus.UNSTABLE || this.getStatus() == JenkinsBuildStatus.SUCCESS; } }
28.444444
89
0.803711
4d85f3d9119873d5e433a6abf7421b2046e4a5f8
10,243
/* * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.identity.authenticator.signedjwt; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.SignedJWT; import org.apache.axiom.util.base64.Base64Utils; import org.apache.axis2.context.MessageContext; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.core.security.AuthenticatorsConfiguration; import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; import org.wso2.carbon.core.services.util.CarbonAuthenticationUtil; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.identity.authenticator.signedjwt.internal.SignedJWTAuthenticatorServiceComponent; import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.AuthenticationObserver; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.servlet.http.HttpServletRequest; import java.security.interfaces.RSAPublicKey; /** * SignedJWTAuthenticator Authenticate a user with a signed JWT. */ public class SignedJWTAuthenticator implements CarbonServerAuthenticator { public static final String SIGNED_JWT_AUTH_USERNAME = "Username"; private static final int DEFAULT_PRIORITY_LEVEL = 20; private static final String AUTHENTICATOR_NAME = "SignedJWTAuthenticator"; private static final String AUTHORIZATION_HEADER_TYPE = "Bearer"; private static final Log log = LogFactory.getLog(SignedJWTAuthenticator.class); @Override public int getPriority() { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.getAuthenticatorConfig(AUTHENTICATOR_NAME); if (authenticatorConfig != null && authenticatorConfig.getPriority() > 0) { return authenticatorConfig.getPriority(); } return DEFAULT_PRIORITY_LEVEL; } @Override public boolean isDisabled() { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.getAuthenticatorConfig(AUTHENTICATOR_NAME); return authenticatorConfig != null && authenticatorConfig.isDisabled(); } @Override public boolean authenticateWithRememberMe(MessageContext msgCxt) { return false; } @Override public String getAuthenticatorName() { return AUTHENTICATOR_NAME; } @Override public boolean isAuthenticated(MessageContext msgCxt) { boolean isAuthenticated = false; HttpServletRequest request = (HttpServletRequest) msgCxt.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); try { //Get the filesystem keystore default primary certificate KeyStoreManager keyStoreManager = KeyStoreManager.getInstance( MultitenantConstants.SUPER_TENANT_ID); keyStoreManager.getDefaultPrimaryCertificate(); String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); String headerData = decodeAuthorizationHeader(authorizationHeader); JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) keyStoreManager.getDefaultPublicKey()); SignedJWT jwsObject = SignedJWT.parse(headerData); if (jwsObject.verify(verifier)) { String userName = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); String tenantDomain = MultitenantUtils.getTenantDomain(userName); userName = MultitenantUtils.getTenantAwareUsername(userName); TenantManager tenantManager = SignedJWTAuthenticatorServiceComponent .getRealmService().getTenantManager(); int tenantId = tenantManager.getTenantId(tenantDomain); if(tenantId == -1){ log.error("tenantDomain is not valid. username : " + userName + ", tenantDomain : " + tenantDomain); return false; } handleAuthenticationStarted(tenantId); UserStoreManager userStore = SignedJWTAuthenticatorServiceComponent .getRealmService().getTenantUserRealm(tenantId).getUserStoreManager(); if (userStore.isExistingUser(userName)) { isAuthenticated = true; } if (isAuthenticated) { CarbonAuthenticationUtil.onSuccessAdminLogin(request.getSession(), userName, tenantId, tenantDomain, "Signed JWT Authentication"); handleAuthenticationCompleted(tenantId, true); return true; } else { log.error("Authentication Request is rejected. User does not exists in UserStore"); CarbonAuthenticationUtil .onFailedAdminLogin(request.getSession(), userName, tenantId, "Signed JWT Authentication", "User does not exists in UserStore"); handleAuthenticationCompleted(tenantId, false); return false; } } } catch (Exception e) { log.error("Error authenticating the user " + e.getMessage(), e); } return isAuthenticated; } @Override public boolean isHandle(MessageContext msgCxt) { HttpServletRequest request = (HttpServletRequest) msgCxt.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); if (log.isDebugEnabled()) { if (authorizationHeader != null) { log.debug("Authorization header is not null"); } } if (authorizationHeader != null) { String authType = getAuthType(authorizationHeader); if (log.isDebugEnabled()) { log.debug("Authorization header type is : " + authType); } if (authType != null && authType.equalsIgnoreCase(AUTHORIZATION_HEADER_TYPE)) { if (log.isDebugEnabled()) { log.debug("Request can be handled using this authenticator, so returning true"); } return true; } } return false; } /** * Gets the authentication type in authorization header. * * @param authorizationHeader The authorization header - Authorization: Bearer QWxhZGRpbjpvcGVuIHNlc2FtZQ==" * @return The authentication type mentioned in authorization header. */ private String getAuthType(String authorizationHeader) { String[] splitValues = null; if (authorizationHeader != null) { splitValues = authorizationHeader.trim().split(" "); } if (splitValues == null || splitValues.length == 0) { return null; } return splitValues[0].trim(); } private String decodeAuthorizationHeader(String authorizationHeader) { String[] splitValues = authorizationHeader.trim().split(" "); byte[] decodedBytes = Base64Utils.decode(splitValues[1].trim()); if (decodedBytes != null) { return new String(decodedBytes); } else { if (log.isDebugEnabled()) { log.debug("Error decoding authorization header. Could not retrieve user name and password."); } return null; } } private void handleAuthenticationStarted(int tenantId) { BundleContext bundleContext = SignedJWTAuthenticatorServiceComponent.getBundleContext(); if (bundleContext != null) { ServiceTracker tracker = new ServiceTracker(bundleContext, AuthenticationObserver.class.getName(), null); tracker.open(); Object[] services = tracker.getServices(); if (services != null) { for (Object service : services) { ((AuthenticationObserver) service).startedAuthentication(tenantId); } } tracker.close(); } } private void handleAuthenticationCompleted(int tenantId, boolean isSuccessful) { BundleContext bundleContext = SignedJWTAuthenticatorServiceComponent.getBundleContext(); if (bundleContext != null) { ServiceTracker tracker = new ServiceTracker(bundleContext, AuthenticationObserver.class.getName(), null); tracker.open(); Object[] services = tracker.getServices(); if (services != null) { for (Object service : services) { ((AuthenticationObserver) service).completedAuthentication( tenantId, isSuccessful); } } tracker.close(); } } }
42.679167
114
0.650591
697cd21965d3e16bd96139a83bdc1583f488877b
562
package com.ysy.tmall.product.dao; import com.ysy.tmall.common.constant.ProductConstant; import com.ysy.tmall.product.entity.SpuInfoEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * spu信息 * * @author SilenceIronMan * @email [email protected] * @date 2020-06-27 21:47:45 */ @Mapper public interface SpuInfoDao extends BaseMapper<SpuInfoEntity> { void updateSpuStatus(@Param("spuId") Long spuId, @Param("publishStatus") Integer spuUp); }
26.761905
92
0.775801
c7b94da0d995eaa66ca266ba437c2f28eafd5c36
1,355
/* * Copyright 2011-2014 Rafael Iñigo * * 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.vikingbrain.nmt.client.modules.impl; import com.vikingbrain.nmt.client.modules.ModuleMetadata; import com.vikingbrain.nmt.operations.TheDavidboxOperationFactory; /** * It allows to create the operations related to the metadata module. * * @author vikingBrain */ public class ModuleMetadataImpl extends AbstractModule implements ModuleMetadata { /** * Constructor. * @param operationFactory the operation factory */ public ModuleMetadataImpl(TheDavidboxOperationFactory operationFactory) { super(operationFactory); } //TODO list_all_metadata //TODO get_metadata //TODO set_metadata //TODO get_reference_file //TODO delete_metadata //TODO delete_all_metadata }
27.653061
83
0.735793
f1bf2713d225d0c69cec471da6fe2b2514db912a
595
TreeNode delete(TreeNode root, int data){ if(root == null){ System.out.println("Error - key: "+data+" not found"); return root; } else if(data > root.data) root.right = delete(root.right, data); else if(data < root.data) root.left = delete(root.left, data); else{ if(root.right == null){ return root.left; } else if(root.left == null){ return root.right; } else{ TreeNode temp = root.right; while(temp != null && temp.left != null) temp = temp.left; root.data = temp.data; root.right = delete(root.right, temp.data); } } return root; }
19.193548
56
0.613445
570dc3b0def0673a83cce01c48f752ae9ed55588
119
package com.imooc.vat.service; public interface Producer { public void sendMessage(String routeKey,Object data); }
17
54
0.781513
60eac8a90b0a792669b2532e10bb3469c4c1d41f
2,787
package io.bootique; import static java.util.Arrays.asList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.Collections; import io.bootique.it.ItestModuleProvider; import org.junit.Test; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import io.bootique.annotation.Args; public class BootiqueIT { private String[] args = new String[] { "a", "b", "c" }; @Test public void testAutoLoadedProviders() { Collection<BQModuleProvider> autoLoaded = Bootique.app(args).autoLoadedProviders(); assertEquals(1, autoLoaded.size()); autoLoaded.forEach(m -> assertTrue(m instanceof ItestModuleProvider)); } @Test public void testCreateInjector() { Injector i = Bootique.app(args).createInjector(); String[] args = i.getInstance(Key.get(String[].class, Args.class)); assertSame(this.args, args); } @Test public void testApp_Collection() { Injector i = Bootique.app(asList(args)).createInjector(); String[] args = i.getInstance(Key.get(String[].class, Args.class)); assertArrayEquals(this.args, args); } @Test public void testCreateInjector_Overrides() { Injector i = Bootique.app(args).override(BQCoreModule.class).with(M0.class).createInjector(); String[] args = i.getInstance(Key.get(String[].class, Args.class)); assertSame(M0.ARGS, args); } @Test public void testCreateInjector_Overrides_Multi_Level() { Injector i = Bootique.app(args).override(BQCoreModule.class).with(M0.class).override(M0.class).with(M1.class) .createInjector(); String[] args = i.getInstance(Key.get(String[].class, Args.class)); assertSame(M1.ARGS, args); } @Test public void testCreateInjector_OverridesWithProvider() { BQModuleProvider provider = new BQModuleProvider() { @Override public Module module() { return new M0(); } @Override public Collection<Class<? extends Module>> overrides() { return Collections.singleton(BQCoreModule.class); } }; Injector i = Bootique.app(args).module(provider).createInjector(); String[] args = i.getInstance(Key.get(String[].class, Args.class)); assertSame(M0.ARGS, args); } static class M0 implements Module { static String[] ARGS = { "1", "2", "3" }; @Override public void configure(Binder binder) { binder.bind(String[].class).annotatedWith(Args.class).toInstance(ARGS); } } static class M1 implements Module { static String[] ARGS = { "x", "y", "z" }; @Override public void configure(Binder binder) { binder.bind(String[].class).annotatedWith(Args.class).toInstance(ARGS); } } }
26.046729
111
0.724794
2937d54f760445e153b4afec9e9c3d24dd45a0ee
524
package edict.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by Manjeet Singh on 7/25/2018. */ @JsonIgnoreProperties(ignoreUnknown = true) public class TokenModel { private String email; private int token; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getToken() { return token; } public void setToken(int token) { this.token = token; } }
17.466667
61
0.641221
c401f8bcedcc6915da53d947fdc79f8cfc91362a
1,823
/* Copyright 2020 The FedLearn Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jdt.fedlearn.coordinator.entity.common; import com.fasterxml.jackson.databind.ObjectMapper; import com.jdt.fedlearn.common.entity.core.Message; import com.jdt.fedlearn.common.exception.SerializeException; import java.io.IOException; import java.util.List; /** * 通用请求,包括taskList和type * taskList指需要查询的task列表 * type指任务状态, TODO 需要改成枚举类 */ public class CommonQuery implements Message { private List<String> taskList; private String type; public CommonQuery() { } public CommonQuery(List<String> taskList, String type) { this.taskList = taskList; this.type = type; } public CommonQuery(String jsonStr) { parseJson(jsonStr); } public List<String> getTaskList() { return taskList; } public String getType() { return type; } public void parseJson(String jsonStr) { ObjectMapper mapper = new ObjectMapper(); CommonQuery p3r = null; try { p3r = mapper.readValue(jsonStr, CommonQuery.class); this.taskList = p3r.taskList; this.type = p3r.type; } catch (IOException e) { throw new SerializeException("predict Phase1 Request to json"); } } }
27.621212
75
0.698848
f5d188104af7130f61ca8bf2146da547272767fa
969
package org.jeecg.modules.dreamlabs.user.service.impl; import org.jeecg.modules.dreamlabs.user.entity.DreamlabsUserParam; import org.jeecg.modules.dreamlabs.user.mapper.DreamlabsUserParamMapper; import org.jeecg.modules.dreamlabs.user.service.IDreamlabsUserParamService; import org.springframework.stereotype.Service; import java.util.List; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; /** * @Description: 用户参数表 * @Author: jeecg-boot * @Date: 2020-07-04 * @Version: V1.0 */ @Service public class DreamlabsUserParamServiceImpl extends ServiceImpl<DreamlabsUserParamMapper, DreamlabsUserParam> implements IDreamlabsUserParamService { @Autowired private DreamlabsUserParamMapper dreamlabsUserParamMapper; @Override public List<DreamlabsUserParam> selectByMainId(String mainId) { return dreamlabsUserParamMapper.selectByMainId(mainId); } }
34.607143
149
0.804954
c79eb2f9c4db6af1504b2d1149f131564d6d11db
5,458
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.etlsolutions.examples.database.hibernate.pojo; import com.etlsolutions.examples.utility.ConstrainableUtilities; import com.etlsolutions.examples.data.api.AuthorBookLink; import com.etlsolutions.examples.data.api.identifiable.IdentifiableAuthorBookLink; import java.io.Serializable; import java.util.Objects; import org.hibernate.proxy.HibernateProxy; /** * The AuthorBookLinkPojo class represents an entry in the AUGHOR_BOOK_LINK * table of the database. * * @author Zhipeng Chang * * @since 1.0.0 * * @version 1.0.0 */ public class AuthorBookLinkPojo implements Serializable, IdentifiableAuthorBookLink { private static final long serialVersionUID = 466493046297379855L; private AuthorPojo authorPojo; private BookPojo bookPojo; public AuthorBookLinkPojo() { } /** * Construct an object using the specified POJOs. * * @param authorPojo * @param bookPojo */ public AuthorBookLinkPojo(AuthorPojo authorPojo, BookPojo bookPojo) { this.authorPojo = authorPojo; this.bookPojo = bookPojo; } @Override public int getAuthorId() { return authorPojo == null ? 0 : authorPojo.getId(); } @Override public int getBookId() { return bookPojo == null ? 0 : bookPojo.getId(); } @Override public AuthorPojo getAuthor() { return authorPojo; } @Override public BookPojo getBook() { return bookPojo; } @Override public boolean hasSameConstraint(AuthorBookLink authorBookLink) { if(this == authorBookLink) { return true; } if(authorBookLink == null) { return false; } if(this instanceof HibernateProxy) { return authorBookLink.hasSameConstraint((AuthorBookLink)((HibernateProxy) this).getHibernateLazyInitializer().getImplementation()); } if(authorBookLink instanceof HibernateProxy) { return hasSameConstraint(((AuthorBookLink)(((HibernateProxy)authorBookLink).getHibernateLazyInitializer().getImplementation()))); } if(!ConstrainableUtilities.hasSameConstraint(authorPojo, authorBookLink.getAuthor())) { return false; } return ConstrainableUtilities.hasSameConstraint(bookPojo, authorBookLink.getBook()); } @Override public boolean hasSameParameters(AuthorBookLink authorBookLink) { if(this == authorBookLink) { return true; } if(authorBookLink == null) { return false; } if(this instanceof HibernateProxy) { return authorBookLink.hasSameParameters((AuthorBookLink)((HibernateProxy) this).getHibernateLazyInitializer().getImplementation()); } if(authorBookLink instanceof HibernateProxy) { return hasSameParameters(((AuthorBookLink)(((HibernateProxy)authorBookLink).getHibernateLazyInitializer().getImplementation()))); } return ConstrainableUtilities.hasSameParameters(authorPojo, authorBookLink.getAuthor()) && ConstrainableUtilities.hasSameParameters(bookPojo, authorBookLink.getBook()); } @Override public int hashCode() { if(this instanceof HibernateProxy) { return ((HibernateProxy) this).getHibernateLazyInitializer().getImplementation().hashCode(); } int hash = 7; hash = 17 * hash + Objects.hashCode(this.authorPojo); hash = 17 * hash + Objects.hashCode(this.bookPojo); return hash; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if (obj == null) { return false; } if(this instanceof HibernateProxy) { return ((HibernateProxy) this).getHibernateLazyInitializer().getImplementation().equals(obj); } if(obj instanceof HibernateProxy) { return equals(((HibernateProxy)obj).getHibernateLazyInitializer().getImplementation()); } if (getClass() != obj.getClass()) { return false; } final AuthorBookLinkPojo other = (AuthorBookLinkPojo) obj; return Objects.equals(this.authorPojo, other.authorPojo) && Objects.equals(this.bookPojo, other.bookPojo); } }
32.488095
177
0.632466
7c07904a6cfdd27e748fcc4dd7ae3aed8ebda691
1,954
package com.google.codeu.data; import java.util.List; public class Table{ private String firstName; private String lastName; private String email; private String phoneNumber; private String restName; private String restAdd; private String restDescrip; private String dateTime; private String maxSize; private String otherNotes; private List<String> members; private double lat; private double lng; public Table(String firstName, String lastName, String email, String phoneNumber, String restName, String restAdd, String restDescrip, String dateTime, String maxSize, String otherNotes, List<String> members, double lat, double lng){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.phoneNumber = phoneNumber; this.restName = restName; this.restAdd = restAdd; this.restDescrip = restDescrip; this.dateTime = dateTime; this.maxSize = maxSize; this.otherNotes = otherNotes; this.members = members; this.lat = lat; this.lng = lng; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public String getEmail(){ return email; } public String getPhoneNumber(){ return phoneNumber; } public String getRestName(){ return restName; } public String getRestAdd(){ return restAdd; } public String getRestDescrip(){ return restDescrip; } public String getDateTime(){ return dateTime; } public String getMaxSize(){ return maxSize; } public String getOtherNotes(){ return otherNotes; } public double getLat(){ return lat; } public double getLng(){ return lng; } public List<String> getMembers(){ return members; } }
25.051282
237
0.632549
78af8950e7b8d644713734f50abc7b134fca42b2
318
package cn.udesk.config; /** * Created by user on 2017/1/4. */ public class UdeskBaseInfo { //相关推送平台注册生成的ID public static String registerId = ""; /** * 控制在线时的消息的通知 在聊天界面的时候 关闭,不在聊天的界面的开启 */ public static boolean isNeedMsgNotice = true; public static String sendMsgTo = ""; }
13.25
49
0.63522
630bb12e8a0d5deee5383538e6a8c960a327db26
5,293
package com.codepath.nytimessearch1.activities; /** * Created by ramyarao on 6/21/16. */ import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.codepath.nytimessearch1.R; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; // ... // ... public class EditNameDialogFragment extends DialogFragment implements TextView.OnEditorActionListener { //private EditText mEditText; //public boolean fashion; //@BindView(R.id.button1) @BindView(R.id.spinner) Spinner spinner; @BindView(R.id.cbFashion) CheckBox cbFashion; @BindView(R.id.cbArts) CheckBox cbArts; @BindView(R.id.cbSports) CheckBox cbSports; boolean fashion; boolean arts; boolean sports; String[] valsOfOrder; String beginDay; String beginMonth; String dateString; private final int REQUEST_CODE = 20; public EditNameDialogFragment() { // Empty constructor is required for DialogFragment // Make sure not to add arguments to the constructor // Use `newInstance` instead as shown below } public interface EditNameDialogListener { void onFinishEditDialog(String inputText, String inputText2, boolean fshn, boolean arts, boolean sports); } public static EditNameDialogFragment newInstance(String title) { EditNameDialogFragment frag = new EditNameDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); return frag; } // this method is only called once for this fragment @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // retain this fragment setRetainInstance(true); } // public void dismiss(View view) { // dialog.dismiss(); // } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_edit_name, container); ButterKnife.bind(this, v); String [] values = {"newest", "oldest",}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values); adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinner.setAdapter(adapter); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Get field from view SearchActivity searchActivity = (SearchActivity) getActivity(); cbFashion.setChecked(searchActivity.fashion); cbArts.setChecked(searchActivity.arts); cbSports.setChecked(searchActivity.sports); ArrayList<String> vals = new ArrayList<>(); vals.add("newest"); vals.add("oldest"); spinner.setSelection ( vals.indexOf(searchActivity.sort)); //mEditText.setOnEditorActionListener(this); // mEditText.setOnEditorActionListener(this); // Fetch arguments from bundle and set title String title = getArguments().getString("title", "Enter Name"); getDialog().setTitle(title); // Show soft keyboard automatically and request focus to field //mEditText.requestFocus(); getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } public void sendData(View view) { // MainActivity.dismiss(); } @Override public void onDismiss(final DialogInterface dialog) { EditNameDialogListener listener = (EditNameDialogListener) getActivity(); fashion = cbFashion.isChecked(); sports = cbSports.isChecked(); arts = cbArts.isChecked(); String text = spinner.getSelectedItem().toString(); // listener.onFinishEditDialog(mEditText.getText().toString(), text, fashion, arts, sports); listener.onFinishEditDialog("sup", text, fashion, arts, sports); super.onDismiss(dialog); } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Toast.makeText(getContext(), "HI", Toast.LENGTH_LONG).show(); if (EditorInfo.IME_ACTION_DONE == actionId) { // Return input text back to activity through the implemented listener EditNameDialogListener listener = (EditNameDialogListener) getActivity(); //listener.onFinishEditDialog(mEditText.getText().toString()); // Close the dialog and return back to the parent activity dismiss(); return true; } return false; } }
30.953216
130
0.681655
696f40b44ba466b34484cd0eefb05877bfb1cf73
1,242
package com.example.a10767.electronic_wardrobe.Main_Fragment; /** * Created by 10767 on 2018/9/9. */ public class Collect { private String picture; private String txt; private String id; private boolean collect; private String heart_txt; public Collect(String picture, String txt, boolean collect, String heart_txt) { super(); this.picture = picture; this.txt = txt; this.collect = collect; this.heart_txt = heart_txt; } public Collect() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getTxt() { return txt; } public void setTxt(String txt) { this.txt = txt; } public boolean isCollect() { return collect; } public void setCollect(boolean collect) { this.collect = collect; } public String getHeart_txt() { return heart_txt; } public void setHeart_txt(String heart_txt) { this.heart_txt = heart_txt; } }
18.818182
83
0.590177
ba2f50a71f909242d9a1e9b3ff62fa04bbe270ec
4,158
/* * Copyright (c) 2017. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad.repository; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.Size; import android.support.v7.content.res.AppCompatResources; import android.view.View; import android.view.ViewTreeObserver; import io.reactivex.Single; /** * Created by akihit on 2017/11/19. */ public class ImageQuery { final Uri uri; final Drawable placeholder; final int width; final int height; final boolean centerCrop; private ImageQuery(Builder builder) { uri = builder.uri; placeholder = builder.placeholder; width = builder.width; height = builder.height; centerCrop = builder.centerCrop; } public static class Builder { private final Uri uri; Drawable placeholder; int width; int height; boolean centerCrop = false; public Builder(String url) { this(url != null ? Uri.parse(url) : null); } public Builder(Uri uri) { this.uri = uri; } public Builder placeholder(Drawable placeholder) { this.placeholder = placeholder; return this; } public Builder placeholder(Context context, @DrawableRes int placeholderRes) { return placeholder(AppCompatResources.getDrawable(context, placeholderRes)); } public Builder width(@Size(min = 1) int width) { this.width = width; return this; } public Builder width(Context context, @DimenRes int widthRes) { return width(context.getResources().getDimensionPixelSize(widthRes)); } public Builder height(@Size(min = 1) int height) { this.height = height; return this; } public Builder height(Context context, @DimenRes int heightRes) { return height(context.getResources().getDimensionPixelSize(heightRes)); } public Builder sizeForSquare(int size) { width(size); height(size); return this; } public Builder sizeForSquare(Context context, @DimenRes int sizeRes) { final int size = context.getResources().getDimensionPixelSize(sizeRes); return sizeForSquare(size); } public Builder centerCrop() { this.centerCrop = true; return this; } public ImageQuery build() { return new ImageQuery(this); } public Single<ImageQuery> build(View view) { if (view.getWidth() > 0 && view.getHeight() > 0) { width(view.getWidth()); height(view.getHeight()); return Single.just(build()); } return observeOnGlobalLayout(view) .map(v -> { this.width(v.getWidth()); this.height(v.getHeight()); return this.build(); }); } } private static Single<View> observeOnGlobalLayout(View target) { return Single.create(e -> target.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (target.getHeight() <= 0 || target.getWidth() <= 0) { return; } e.onSuccess(target); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { target.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { target.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } })); } }
28.675862
110
0.664021
866532c3af348afdd367e6792167928ab2e053bb
10,258
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.trans.steps.abort; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.steps.abort.Abort; import org.pentaho.di.trans.steps.abort.AbortMeta; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.trans.step.BaseStepDialog; public class AbortDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = Abort.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private Label wlRowThreshold; private TextVar wRowThreshold; private FormData fdlRowThreshold, fdRowThreshold; private Label wlMessage; private TextVar wMessage; private FormData fdlMessage, fdMessage; private Label wlAlwaysLogRows; private Button wAlwaysLogRows; private FormData fdlAlwaysLogRows, fdAlwaysLogRows; private AbortMeta input; public AbortDialog(Shell parent, Object in, TransMeta transMeta, String sname) { super(parent, (BaseStepMeta)in, transMeta, sname); input=(AbortMeta)in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); props.setLook(shell); setShellImage(shell, input); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "AbortDialog.Shell.Title")); //$NON-NLS-1$ int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(BaseMessages.getString(PKG, "AbortDialog.Stepname.Label")); //$NON-NLS-1$ props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.right= new FormAttachment(middle, -margin); fdlStepname.top = new FormAttachment(0, margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); // RowThreshold line wlRowThreshold=new Label(shell, SWT.RIGHT); wlRowThreshold.setText(BaseMessages.getString(PKG, "AbortDialog.RowThreshold.Label")); //$NON-NLS-1$ props.setLook(wlRowThreshold); fdlRowThreshold=new FormData(); fdlRowThreshold.left = new FormAttachment(0, 0); fdlRowThreshold.right= new FormAttachment(middle, -margin); fdlRowThreshold.top = new FormAttachment(wStepname, margin); wlRowThreshold.setLayoutData(fdlRowThreshold); wRowThreshold=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wRowThreshold.setText(""); //$NON-NLS-1$ props.setLook(wRowThreshold); wRowThreshold.addModifyListener(lsMod); wRowThreshold.setToolTipText(BaseMessages.getString(PKG, "AbortDialog.RowThreshold.Tooltip")); wRowThreshold.addModifyListener(lsMod); fdRowThreshold=new FormData(); fdRowThreshold.left = new FormAttachment(middle, 0); fdRowThreshold.top = new FormAttachment(wStepname, margin); fdRowThreshold.right= new FormAttachment(100, 0); wRowThreshold.setLayoutData(fdRowThreshold); // Message line wlMessage=new Label(shell, SWT.RIGHT); wlMessage.setText(BaseMessages.getString(PKG, "AbortDialog.AbortMessage.Label")); //$NON-NLS-1$ props.setLook(wlMessage); fdlMessage=new FormData(); fdlMessage.left = new FormAttachment(0, 0); fdlMessage.right= new FormAttachment(middle, -margin); fdlMessage.top = new FormAttachment(wRowThreshold, margin); wlMessage.setLayoutData(fdlMessage); wMessage=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wMessage.setText(""); //$NON-NLS-1$ props.setLook(wMessage); wMessage.addModifyListener(lsMod); wMessage.setToolTipText(BaseMessages.getString(PKG, "AbortDialog.AbortMessage.Tooltip")); wMessage.addModifyListener(lsMod); fdMessage=new FormData(); fdMessage.left = new FormAttachment(middle, 0); fdMessage.top = new FormAttachment(wRowThreshold, margin); fdMessage.right= new FormAttachment(100, 0); wMessage.setLayoutData(fdMessage); wlAlwaysLogRows = new Label(shell, SWT.RIGHT); wlAlwaysLogRows.setText(BaseMessages.getString(PKG, "AbortDialog.AlwaysLogRows.Label")); props.setLook(wlAlwaysLogRows); fdlAlwaysLogRows = new FormData(); fdlAlwaysLogRows.left = new FormAttachment(0, 0); fdlAlwaysLogRows.top = new FormAttachment(wMessage, margin); fdlAlwaysLogRows.right = new FormAttachment(middle, -margin); wlAlwaysLogRows.setLayoutData(fdlAlwaysLogRows); wAlwaysLogRows = new Button(shell, SWT.CHECK); props.setLook(wAlwaysLogRows); wAlwaysLogRows.setToolTipText(BaseMessages.getString(PKG, "AbortDialog.AlwaysLogRows.Tooltip")); fdAlwaysLogRows = new FormData(); fdAlwaysLogRows.left = new FormAttachment(middle, 0); fdAlwaysLogRows.top = new FormAttachment(wMessage, margin); fdAlwaysLogRows.right = new FormAttachment(100, 0); wAlwaysLogRows.setLayoutData(fdAlwaysLogRows); wAlwaysLogRows.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } }); // Some buttons wOK=new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$ wCancel=new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$ setButtonPositions(new Button[] { wOK, wCancel }, margin, wAlwaysLogRows); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wCancel.addListener(SWT.Selection, lsCancel); wOK.addListener (SWT.Selection, lsOK ); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); wRowThreshold.addSelectionListener( lsDef ); wMessage.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if ( input.getRowThreshold() !=null ) wRowThreshold.setText(input.getRowThreshold()); if ( input.getMessage() != null ) wMessage.setText(input.getMessage()); wAlwaysLogRows.setSelection(input.isAlwaysLogRows()); wStepname.selectAll(); } private void getInfo(AbortMeta in) { input.setRowThreshold(wRowThreshold.getText()); input.setMessage(wMessage.getText()); input.setAlwaysLogRows(wAlwaysLogRows.getSelection()); } /** * Cancel the dialog. */ private void cancel() { stepname=null; input.setChanged(changed); dispose(); } private void ok() { if (Const.isEmpty(wStepname.getText())) return; getInfo(input); stepname = wStepname.getText(); // return value dispose(); } }
38.709434
109
0.670014
58875de0b4390c0ea2ce589552fd7fd84b8051a8
2,522
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.envers.test.integration.modifiedflags; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.joined.ChildEntity; import org.hibernate.envers.test.integration.inheritance.joined.ParentEntity; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; /** * @author Adam Warski (adam at warski dot org) * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedChildAuditing extends AbstractModifiedFlagsEntityTest { private Integer id1; @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] {ChildEntity.class, ParentEntity.class}; } @Test @Priority(10) public void initData() { EntityManager em = getEntityManager(); id1 = 1; // Rev 1 em.getTransaction().begin(); ChildEntity ce = new ChildEntity( id1, "x", 1l ); em.persist( ce ); em.getTransaction().commit(); // Rev 2 em.getTransaction().begin(); ce = em.find( ChildEntity.class, id1 ); ce.setData( "y" ); ce.setNumVal( 2l ); em.getTransaction().commit(); } @Test public void testChildHasChanged() throws Exception { List list = queryForPropertyHasChanged( ChildEntity.class, id1, "data" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( ChildEntity.class, id1, "numVal" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( ChildEntity.class, id1, "data" ); assertEquals( 0, list.size() ); list = queryForPropertyHasNotChanged( ChildEntity.class, id1, "numVal" ); assertEquals( 0, list.size() ); } @Test public void testParentHasChanged() throws Exception { List list = queryForPropertyHasChanged( ParentEntity.class, id1, "data" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( ParentEntity.class, id1, "data" ); assertEquals( 0, list.size() ); } }
30.756098
94
0.731562
f8b10985f73c6f79dbaa45f1e16fcf5db4ae709a
945
package uk.co.idv.common.adapter.json.error.internalserver; import org.junit.jupiter.api.Test; import uk.co.idv.common.adapter.json.error.ApiError; import uk.co.idv.common.adapter.json.error.handler.ErrorHandler; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; class InternalServerHandlerTest { private final ErrorHandler handler = new InternalServerHandler(); @Test void shouldReturnInternalServerError() { Throwable throwable = new Throwable(); Optional<ApiError> error = handler.apply(throwable); assertThat(error).containsInstanceOf(InternalServerError.class); } @Test void shouldPopulateMessage() { Throwable throwable = new Throwable("message"); Optional<ApiError> error = handler.apply(throwable); assertThat(error).isPresent(); assertThat(error.get().getMessage()).isEqualTo(throwable.getMessage()); } }
27
79
0.726984
920345e8668bec5850596c8a6ddc12a6c92a5f4b
4,216
/* * 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.prestosql.tests.product.launcher.env; import com.github.dockerjava.api.DockerClient; import com.google.common.base.CaseFormat; import com.google.common.collect.ImmutableMap; import com.google.common.reflect.ClassPath; import io.airlift.log.Logger; import io.prestosql.tests.product.launcher.env.common.TestsEnvironment; import org.testcontainers.DockerClientFactory; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.tests.product.launcher.docker.ContainerUtil.killContainers; import static io.prestosql.tests.product.launcher.docker.ContainerUtil.removeNetworks; import static io.prestosql.tests.product.launcher.env.Environment.PRODUCT_TEST_LAUNCHER_NETWORK; import static io.prestosql.tests.product.launcher.env.Environment.PRODUCT_TEST_LAUNCHER_STARTED_LABEL_NAME; import static io.prestosql.tests.product.launcher.env.Environment.PRODUCT_TEST_LAUNCHER_STARTED_LABEL_VALUE; import static java.lang.reflect.Modifier.isAbstract; public final class Environments { private Environments() {} private static final Logger log = Logger.get(Environments.class); public static void pruneEnvironment() { log.info("Shutting down previous containers"); try (DockerClient dockerClient = DockerClientFactory.lazyClient()) { killContainers( dockerClient, listContainersCmd -> listContainersCmd.withLabelFilter(ImmutableMap.of(PRODUCT_TEST_LAUNCHER_STARTED_LABEL_NAME, PRODUCT_TEST_LAUNCHER_STARTED_LABEL_VALUE))); removeNetworks( dockerClient, listNetworksCmd -> listNetworksCmd.withNameFilter(PRODUCT_TEST_LAUNCHER_NETWORK)); } catch (IOException e) { throw new UncheckedIOException(e); } } public static List<Class<? extends EnvironmentProvider>> findByBasePackage(String packageName) { try { return ClassPath.from(Environments.class.getClassLoader()).getTopLevelClassesRecursive(packageName).stream() .map(ClassPath.ClassInfo::load) .filter(clazz -> clazz.isAnnotationPresent(TestsEnvironment.class)) .map(clazz -> (Class<? extends EnvironmentProvider>) clazz.asSubclass(EnvironmentProvider.class)) .collect(toImmutableList()); } catch (IOException e) { throw new RuntimeException(e); } } public static List<Class<? extends EnvironmentConfig>> findConfigsByBasePackage(String packageName) { try { return ClassPath.from(Environments.class.getClassLoader()).getTopLevelClassesRecursive(packageName).stream() .map(ClassPath.ClassInfo::load) .filter(clazz -> !isAbstract(clazz.getModifiers())) .filter(clazz -> EnvironmentConfig.class.isAssignableFrom(clazz)) .map(clazz -> (Class<? extends EnvironmentConfig>) clazz.asSubclass(EnvironmentConfig.class)) .collect(toImmutableList()); } catch (IOException e) { throw new RuntimeException(e); } } public static String nameForClass(Class<? extends EnvironmentProvider> clazz) { return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, clazz.getSimpleName()); } public static String nameForConfigClass(Class<? extends EnvironmentConfig> clazz) { return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, clazz.getSimpleName()); } }
43.463918
178
0.712287
b9bb8758f56791088bc2798f65767de7386d9887
279
package seedu.hustler.ui; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for Ui class. */ public class UiTest { @Test /** * Dummy test for Ui class. */ public void dummyTest() { } }
13.95
60
0.623656
fc872c8928a0d7e3ab72d1229be03eb161b8e2ec
1,592
package org.springframework.cloud.autoconfigure; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.endpoint.event.RefreshEventListener; import org.springframework.cloud.test.ClassPathExclusions; import org.springframework.cloud.test.ModifiedClassPathRunner; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb */ @RunWith(ModifiedClassPathRunner.class) @ClassPathExclusions({ "spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar" }) public class RefreshAutoConfigurationClassPathTests { private static ConfigurableApplicationContext getApplicationContext( Class<?> configuration, String... properties) { return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE) .properties(properties).run(); } @Test public void refreshEventListenerCreated() { try (ConfigurableApplicationContext context = getApplicationContext( Config.class)) { assertThat(context.getBeansOfType(RefreshEventListener.class)) .as("RefreshEventListeners not created").isNotEmpty(); assertThat(context.containsBean("refreshEndpoint")) .as("refreshEndpoint created").isFalse(); } } @Configuration @EnableAutoConfiguration static class Config { } }
32.489796
81
0.811558
26d155480af6590cb7b6dc017f200808a315b514
1,928
/* * Copyright (c) 2017 Dell Inc., or its subsidiaries. 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 * */ package io.pravega.anomalydetection.event.pipeline; import io.pravega.anomalydetection.event.state.Event; import io.pravega.anomalydetection.event.state.EventStateMachine; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.Collector; import java.time.Instant; public class EventStateMachineMapper extends RichFlatMapFunction<Event, Event.Alert> { private transient ValueState<EventStateMachine.State> state; @Override public void open(Configuration parameters) throws Exception { ValueStateDescriptor<EventStateMachine.State> descriptor = new ValueStateDescriptor<>( "state", // the state name TypeInformation.of(EventStateMachine.State.class)); // type information state = getRuntimeContext().getState(descriptor); } @Override public void flatMap(Event event, Collector<Event.Alert> collector) throws Exception { EventStateMachine.State value = state.value(); if(value == null) { value = EventStateMachine.Transitions.initialState; } EventStateMachine.State nextValue = value.transition(event.getEvent()); if(nextValue instanceof EventStateMachine.InvalidTransition) { Event.Alert alert = new Event.Alert(Instant.now(), event, value); collector.collect(alert); state.update(null); } else if (!nextValue.terminal()){ state.update(nextValue); } else { state.update(null); } } }
35.054545
88
0.770228
a022364662d63cc00e54408cf02c2e3ba4e7b675
5,994
package signpost; import static java.util.Arrays.asList; import org.junit.Test; import static org.junit.Assert.*; import static signpost.Utils.tr; import static signpost.Utils.setUp; import static signpost.PuzzleGenerator.*; import static signpost.ModelTests.checkNumbers; /** Tests of the Model class. * @author P. N. Hilfinger */ public class PuzzleGeneratorTests { /** Check that SOLN is a valid WIDTH x HEIGHT puzzle that has fixed ends * unless ALLOWLOOSE. */ private void checkPuzzle(int[][] soln, int width, int height, boolean allowLoose) { assertTrue("Bad size", soln.length == width && soln[0].length == height); int last = width * height; for (int x0 = 0; x0 < width; x0 += 1) { for (int y0 = 0; y0 < width; y0 += 1) { int v = soln[x0][y0]; if (v == last) { continue; } assertTrue("Value out of range", v >= 1 && v <= last); int c; for (int x1 = c = 0; x1 < width; x1 += 1) { for (int y1 = 0; y1 < height; y1 += 1) { if (soln[x1][y1] == v + 1) { assertTrue("Values not in line", x0 == x1 || y0 == y1 || Math.abs(x0 - x1) == Math.abs(y0 - y1)); c += 1; } } } assertEquals("Duplicate or unconnected values", 1, c); } } if (!allowLoose) { assertTrue("End points incorrect", soln[0][height - 1] == 1 && soln[width - 1][0] == last); } } @Test public void puzzleTest() { PuzzleGenerator puzzler = new PuzzleGenerator(314159); Model model; model = puzzler.getPuzzle(5, 5, false); checkPuzzle(model.solution(), 5, 5, false); model = puzzler.getPuzzle(4, 6, false); checkPuzzle(model.solution(), 4, 6, false); model = puzzler.getPuzzle(5, 5, true); checkPuzzle(model.solution(), 5, 5, true); } @Test public void uniquePuzzleTest() { PuzzleGenerator puzzler = new PuzzleGenerator(314159); Model model; model = puzzler.getPuzzle(1, 2, false); checkPuzzle(model.solution(), 1, 2, false); model = puzzler.getPuzzle(1, 3, false); checkPuzzle(model.solution(), 1, 3, false); } @Test public void uniqueSuccessorTest() { Model M = setUp(tr(SOLN1), SOLN1_NUMBERS, CONNECT1); assertEquals("Unique connection to edge Sq", M.get(2, 6), findUniqueSuccessor(M, M.get(3, 5))); assertEquals("Unique connection through connected Sq", M.get(5, 0), findUniqueSuccessor(M, M.get(3, 2))); assertEquals("Ambiguous connection", null, findUniqueSuccessor(M, M.get(3, 4))); assertEquals("Successive numbered squares", M.get(3, 1), findUniqueSuccessor(M, M.get(2, 0))); assertEquals("Unique connection to numbered Sq", M.get(1, 1), findUniqueSuccessor(M, M.get(3, 3))); assertEquals("Unique connection to numbered Sq", M.get(1, 1), findUniqueSuccessor(M, M.get(3, 3))); assertEquals("Unique connection of numbered to unnumbered Sq", M.get(4, 2), findUniqueSuccessor(M, M.get(6, 4))); } @Test public void uniquePredecessorTest() { Model M = setUp(tr(SOLN2), SOLN2_NUMBERS, CONNECT2); assertEquals("Unique predecessor", M.get(5, 6), findUniquePredecessor(M, M.get(1, 6))); assertEquals("Predecessor not unique", null, findUniquePredecessor(M, M.get(3, 3))); } @Test public void extendSimpleTest1() { Model M = setUp(tr(SOLN3), new int[] { 1, 16 }, new int[] {}); assertTrue("Extend simple on ambiguous puzzle.", extendSimple(M)); checkNumbers(tr(PARTIAL_SOLN3), M, asList(1, 16)); } @Test public void extendSimpleTest2() { Model M = setUp(tr(SOLN3), new int[] { 1, 9, 16 }, new int[] {}); assertTrue("Extend simple on unambiguous puzzle.", extendSimple(M)); checkNumbers(tr(SOLN3), M, asList(1, 9, 16)); } static final int[][] SOLN1 = { { 3, 9, 29, 4, 49, 8, 5 }, { 47, 12, 46, 28, 48, 6, 27 }, { 15, 13, 16, 40, 41, 39, 24 }, { 14, 44, 45, 36, 26, 7, 23 }, { 2, 31, 1, 32, 25, 10, 30 }, { 21, 37, 20, 35, 19, 11, 22 }, { 42, 38, 34, 18, 43, 33, 17 } }; static final int[] SOLN1_NUMBERS = { 9, 49, 27, 15, 40, 24, 44, 1, 30, 37, 35, 34 }; static final int[] CONNECT1 = { 18, 19, 41, 42, 7, 8, 8, 9 }; static final int[][] SOLN2 = { { 23, 48, 46, 18, 19, 47, 45 }, { 42, 49, 4, 32, 8, 35, 36 }, { 21, 6, 33, 11, 7, 15, 34 }, { 5, 20, 9, 28, 1, 39, 38 }, { 22, 10, 27, 41, 29, 30, 26 }, { 43, 44, 16, 17, 13, 14, 12 }, { 24, 2, 3, 31, 25, 40, 37 } }; static final int[] SOLN2_NUMBERS = { 23, 46, 18, 47, 49, 32, 11, 34, 1, 44, 17, 2, 25 }; static final int[] CONNECT2 = { 45, 46 }; /** An ambiguous puzzle. The arrows corresponding to SOLN3, where the * only fixed numbers are 1 and 16 has multiple solutions. */ static final int[][] SOLN3 = { { 1, 4, 13, 2 }, { 8, 5, 3, 14 }, { 6, 7, 12, 11 }, { 9, 15, 10, 16 } }; /** This should be the result of extendSimple on the puzzle SOLN3, * SOLN3_NUMBERS. */ static final int[][] PARTIAL_SOLN3 = { { 1, 4, 0, 2 }, { 0, 5, 3, 0 }, { 6, 0, 0, 0 }, { 0, 0, 0, 16 } }; }
36.108434
79
0.496663
1c0fe045fff51eb4befce1bddad0660096654c08
1,084
package org.noear.solon.core.handle; /** * Session 状态器接口 * * 用于对接http自带 sesssion 或 扩展 sesssion(可相互切换) * * @author noear * @since 1.0 * */ public interface SessionState { /** * 刷新SESSION状态 */ default void sessionRefresh() { } /** * 发布SESSION状态(类似jwt) */ default void sessionPublish() { } /** * 是否可替换 */ default boolean replaceable() { return true; } /** * 获取SESSION_ID */ String sessionId(); /** * 变更SESSION_ID */ String sessionChangeId(); /** * 获取SESSION状态 */ Object sessionGet(String key); /** * 设置SESSION状态 */ void sessionSet(String key, Object val); /** * 移除SESSION状态 */ void sessionRemove(String key); /** * 清除SESSION状态 */ void sessionClear(); /** * 会话重置(清空数据,并变更会话ID) * */ void sessionReset(); /** * 获取会话令牌(如: solon.extend.sessionstate.jwt 插件支持) * */ default String sessionToken() { throw new UnsupportedOperationException(); } }
14.648649
52
0.526753
9bd920f7c59327483fc8bfe0e780d5d16279ba84
1,032
package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class Gpstest extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gpstest); webView=(WebView)findViewById(R.id.webView); WebSettings webSettings= webView.getSettings(); webView.getSettings().setJavaScriptEnabled(true); webSettings.setAppCacheEnabled(false); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url){ view.loadUrl(url); return true; } }); webView.loadUrl(" https://maps.google.com/maps?f=q&q=(37.598288141681266,126.96199236220738)"); } }
34.4
104
0.695736
123c3ef605d2a5fde3f40d79d95a922e1f37abdc
1,901
package net.n2oapp.framework.autotest.impl.component.widget.calendar; import com.codeborne.selenide.Condition; import net.n2oapp.framework.autotest.N2oSelenide; import net.n2oapp.framework.autotest.api.component.button.StandardButton; import net.n2oapp.framework.autotest.api.component.widget.calendar.CalendarToolbar; import net.n2oapp.framework.autotest.impl.component.N2oComponent; import net.n2oapp.framework.autotest.impl.component.widget.calendar.view.CalendarViewType; /** * Панель действий календаря для автотестирования */ public class N2oCalendarToolbar extends N2oComponent implements CalendarToolbar { @Override public StandardButton todayButton() { return button("Сегодня"); } @Override public StandardButton prevButton() { return button("Назад"); } @Override public StandardButton nextButton() { return button("Вперед"); } @Override public void shouldHaveLabel(String label) { element().$(".rbc-toolbar-label").shouldHave(Condition.text(label)); } @Override public StandardButton monthViewButton() { return button("Месяц"); } @Override public StandardButton dayViewButton() { return button("День"); } @Override public StandardButton agendaViewButton() { return button("Повестка дня"); } @Override public StandardButton weekViewButton() { return button("Неделя"); } @Override public StandardButton workWeekButton() { return button("Рабочая неделя"); } @Override public void shouldHaveActiveView(CalendarViewType viewType) { element().$(".rbc-active").shouldHave(Condition.text(viewType.getTitle())); } private StandardButton button(String label) { return N2oSelenide.component(element().$$("button").findBy(Condition.text(label)), StandardButton.class); } }
27.955882
113
0.703314
c5b87cae84695ddd248e0822162da9c13c24daca
86
package Chess.Match.Board; public interface Printable { public String toCLI(); }
14.333333
28
0.732558
c58784afd7b7efa5f86bcc6b14c8aed69a32fca7
1,852
/* * Copyright 2013-2021 consulo.io * * 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 consulo.desktop.swt.ui.impl.image; import consulo.ui.image.Image; import org.eclipse.nebula.cwt.svg.SvgDocument; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import javax.annotation.Nonnull; /** * @author VISTALL * @since 10/07/2021 */ public class DesktopSwtSvgLibraryImageImpl implements Image, DesktopSwtImage { private final int myWidth; private final int myHeight; private final SvgDocument mySvgDocument; public DesktopSwtSvgLibraryImageImpl(int width, int height, SvgDocument svgDocument) { myWidth = width; myHeight = height; mySvgDocument = svgDocument; } public SvgDocument getSvgDocument() { return mySvgDocument; } @Override public int getHeight() { return myHeight; } @Override public int getWidth() { return myWidth; } @Nonnull @Override public org.eclipse.swt.graphics.Image toSWTImage() { org.eclipse.swt.graphics.Image swtImage = new org.eclipse.swt.graphics.Image(null, myWidth, myHeight); GC gc = new GC(swtImage); gc.setBackground(new Color(0, 0, 0, 0)); gc.setAlpha(0); gc.fillRectangle(0, 0, myWidth, myHeight); mySvgDocument.apply(gc, swtImage.getBounds()); gc.dispose(); return swtImage; } }
26.84058
106
0.726242
2c52483e239bf319b4bdceb0910e59ec641c3730
6,878
package org.apache.maven.report.projectinfo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.doxia.sink.Sink; import org.apache.maven.model.CiManagement; import org.apache.maven.model.Model; import org.apache.maven.model.Notifier; import org.apache.maven.plugins.annotations.Mojo; import org.codehaus.plexus.i18n.I18N; import org.codehaus.plexus.util.StringUtils; import java.util.List; import java.util.Locale; /** * Generates the Project Continuous Integration System report. * * @author <a href="mailto:[email protected]">Vincent Siveton </a> * @version $Id$ * @since 2.0 */ @Mojo( name = "cim" ) public class CimReport extends AbstractProjectInfoReport { // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override public void executeReport( Locale locale ) { CimRenderer r = new CimRenderer( getSink(), getProject().getModel(), getI18N( locale ), locale ); r.render(); } /** {@inheritDoc} */ public String getOutputName() { return "integration"; } @Override protected String getI18Nsection() { return "cim"; } // ---------------------------------------------------------------------- // Private // ---------------------------------------------------------------------- /** * Internal renderer class */ private static class CimRenderer extends AbstractProjectInfoRenderer { private Model model; CimRenderer( Sink sink, Model model, I18N i18n, Locale locale ) { super( sink, i18n, locale ); this.model = model; } @Override protected String getI18Nsection() { return "cim"; } @Override public void renderBody() { CiManagement cim = model.getCiManagement(); if ( cim == null ) { startSection( getTitle() ); paragraph( getI18nString( "nocim" ) ); endSection(); return; } String system = cim.getSystem(); String url = cim.getUrl(); List<Notifier> notifiers = cim.getNotifiers(); // Overview startSection( getI18nString( "overview.title" ) ); sink.paragraph(); if ( isCimSystem( system, "anthill" ) ) { linkPatternedText( getI18nString( "anthill.intro" ) ); } else if ( isCimSystem( system, "bamboo" ) ) { linkPatternedText( getI18nString( "bamboo.intro" ) ); } else if ( isCimSystem( system, "buildforge" ) ) { linkPatternedText( getI18nString( "buildforge.intro" ) ); } else if ( isCimSystem( system, "continuum" ) ) { linkPatternedText( getI18nString( "continuum.intro" ) ); } else if ( isCimSystem( system, "cruisecontrol" ) ) { linkPatternedText( getI18nString( "cruisecontrol.intro" ) ); } else if ( isCimSystem( system, "hudson" ) ) { linkPatternedText( getI18nString( "hudson.intro" ) ); } else if ( isCimSystem( system, "jenkins" ) ) { linkPatternedText( getI18nString( "jenkins.intro" ) ); } else if ( isCimSystem( system, "luntbuild" ) ) { linkPatternedText( getI18nString( "luntbuild.intro" ) ); } else { linkPatternedText( getI18nString( "general.intro" ) ); } sink.paragraph_(); endSection(); // Access startSection( getI18nString( "access" ) ); if ( !StringUtils.isEmpty( url ) ) { paragraph( getI18nString( "url" ) ); verbatimLink( url, url ); } else { paragraph( getI18nString( "nourl" ) ); } endSection(); // Notifiers startSection( getI18nString( "notifiers.title" ) ); if ( notifiers == null || notifiers.isEmpty() ) { paragraph( getI18nString( "notifiers.nolist" ) ); } else { sink.paragraph(); sink.text( getI18nString( "notifiers.intro" ) ); sink.paragraph_(); startTable(); String type = getI18nString( "notifiers.column.type" ); String address = getI18nString( "notifiers.column.address" ); String configuration = getI18nString( "notifiers.column.configuration" ); tableHeader( new String[]{type, address, configuration} ); for ( Notifier notifier : notifiers ) { tableRow( new String[]{notifier.getType(), createLinkPatternedText( notifier.getAddress(), notifier.getAddress() ), propertiesToString( notifier.getConfiguration() )} ); } endTable(); } endSection(); } /** * Checks if a CIM system is bugzilla, continuum... * * @param connection * @param cim * @return true if the CIM system is bugzilla, continuum..., false otherwise. */ private boolean isCimSystem( String connection, String cim ) { if ( StringUtils.isEmpty( connection ) ) { return false; } if ( StringUtils.isEmpty( cim ) ) { return false; } return connection.toLowerCase( Locale.ENGLISH ).startsWith( cim.toLowerCase( Locale.ENGLISH ) ); } } }
30.034934
108
0.515121
65c2177779be5a3f07eac823578139f7ffba8569
3,635
package com.api.diy_form.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.api.diy_form.model.FormModel; import com.api.model.DiyFieldData; import com.api.model.DiyForm; import com.api.model.DiyFormField; import com.base.framework.dao.impl.BaseDao; import com.base.framework.dao.impl.SqlParameter; @Repository public class DiyFormDao extends BaseDao{ public List<DiyForm> getForm(DiyForm diyForm) { String sql = "SELECT\n" + " DF.FORM_ID,\n" + " DF.FORM_CODE,\n" + " DF.FORM_VERSION,\n" + " DF.FORM_NAME,\n" + " DF.COMMENTS\n" + "FROM\n" + " DIY_FORM DF\n" + "ORDER BY\n" + " DF.FORM_CODE,\n" + " DF.FORM_VERSION"; List<DiyForm> result = query(sql, DiyForm.class); return result; } public boolean checkFormCode(String formCode) { String sql = "SELECT\n" + " 1\n" + "FROM\n" + " DUAL\n" + "WHERE\n" + " EXISTS (\n" + " SELECT\n" + " 1\n" + " FROM\n" + " DIY_FORM\n" + " WHERE\n" + " FORM_CODE = :FORM_CODE\n" + " )"; String result = queryForString(sql, new SqlParameter().add("FORM_CODE", formCode)); return "1".equals(result); } public List<DiyFormField> getFormField(Integer formId) { String sql = "SELECT\n" + " FF.FIELD_ID,\n" + " FF.FIELD_CODE,\n" + " FF.FIELD_TEXT\n" + "FROM\n" + " DIY_FORM_FIELD FF\n" + "WHERE\n" + " FF.FORM_ID = :FORM_ID\n" + "ORDER BY\n" + " FF.DISPLAY_ORDER"; List<DiyFormField> result = query(sql, new SqlParameter().add("FORM_ID", formId),DiyFormField.class); return result; } public List<DiyFieldData> getFormFieldData(Integer fieldId) { String sql = "SELECT\n" + " FD.DATA_ID,\n" + " FD.FIELD_TEXT,\n" + " FD.FIELD_VALUE\n" + "FROM\n" + " DIY_FIELD_DATA FD\n" + "WHERE\n" + " FD.FIELD_ID = :FIELD_ID\n" + "ORDER BY\n" + " FD.DISPLAY_ORDER"; List<DiyFieldData> result = query(sql, new SqlParameter().add("FIELD_ID", fieldId),DiyFieldData.class); return result; } public void deleteRemovedData(FormModel formModel) { String sql = null; SqlParameter sqlParameter = new SqlParameter(); if (formModel.getRemovedField() != null && formModel.getRemovedField().size()>0) { sql = "DELETE FROM DIY_FORM_FIELD WHERE FIELD_ID IN (:FIELD_ID)"; sqlParameter.add("FIELD_ID", formModel.getRemovedField()); delete(sql, sqlParameter); } if (formModel.getRemovedData() != null && formModel.getRemovedData().size()>0) { sql = "DELETE FROM DIY_FIELD_DATA WHERE DATA_ID IN (:DATA_ID)"; sqlParameter.add("DATA_ID", formModel.getRemovedData()); delete(sql, sqlParameter); } } public void deleteForm(Integer formId) { String sql = "DELETE\n" + "FROM\n" + " DIY_FIELD_DATA\n" + "WHERE\n" + " EXISTS (\n" + " SELECT\n" + " 1\n" + " FROM\n" + " DIY_FORM_FIELD DFF\n" + " WHERE\n" + " DFF.FORM_ID = :FORM_ID\n" + " AND DIY_FIELD_DATA.FIELD_ID = DFF.FIELD_ID\n" + " )"; SqlParameter sqlParameter = new SqlParameter().add("FORM_ID", formId); delete(sql, sqlParameter); sql = "DELETE\n" + "FROM\n" + " DIY_FORM\n" + "WHERE\n" + " FORM_ID = :FORM_ID"; delete(sql, sqlParameter); sql = "DELETE\n" + "FROM\n" + " DIY_FORM_FIELD\n" + "WHERE\n" + " FORM_ID = :FORM_ID"; delete(sql, sqlParameter); } }
28.178295
106
0.579367
2474138ceece7df0a9bdf14d55b3c2cd1569264e
2,177
package edu.washington.cs.detector; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.ibm.wala.ipa.callgraph.CGNode; import edu.washington.cs.detector.util.Globals; //keep track the whole call chain public class CallChainNode { private final CGNode node; private CallChainNode parent = null; public CallChainNode(CGNode node) { //this(node, (CGNode)null); assert node != null; this.node = node; } public CallChainNode(CGNode node, CGNode parent) { //this(node, new CallChainNode(parent)); assert node != null; this.node = node; this.parent = new CallChainNode(parent); } public CallChainNode(CGNode node, CallChainNode parent) { assert node != null; assert parent != null; this.node = node; this.parent = parent; //compute line number //this.lineNum = this.node.getMethod().getLineNumber(0); } public CGNode getNode() { return this.node; } public CallChainNode getParent() { return parent; } public void setParent(CGNode node) { assert this.parent == null; this.parent = new CallChainNode(node); } public List<CGNode> getChainToRoot() { List<CGNode> list = new LinkedList<CGNode>(); list.add(node); CallChainNode parentNode = parent; while(parentNode != null) { list.add(parentNode.node); parentNode = parentNode.getParent(); } //reverse it Collections.reverse(list); return list; } public String getChainToRootAsStr() { StringBuilder sb = new StringBuilder(); int count = 0; for(CGNode node : getChainToRoot()) { if(count != 0) { sb.append(" -> "); } count++; sb.append(node); //print method?, not the node; avoiding context info sb.append(", line: "); sb.append(node.getMethod().getLineNumber(0)); sb.append(Globals.lineSep); } return sb.toString(); } public static Set<CGNode> getUnderlyingCGNodes(Collection<CallChainNode> nodes) { Set<CGNode> cgNodeSet = new LinkedHashSet<CGNode>(); for(CallChainNode node : nodes) { cgNodeSet.add(node.node); } return cgNodeSet; } }
22.677083
82
0.688103
a9146fd4136396c3cb3536c059e160d5c00e367e
385
package com.arrow.dashboard.properties.list; import java.util.List; import com.arrow.dashboard.property.impl.SimplePropertyBuilder; public class StringListPropertyBuilder extends SimplePropertyBuilder<StringListProperty, List<String>, StringListPropertyView>{ public StringListPropertyBuilder() { super(StringListProperty.class); // TODO Auto-generated constructor stub } }
25.666667
127
0.823377
d840eebf3fb33064d150ef2aad33b5799ac55fd9
2,168
// { Driver Code Starts import java.io.*; import java.util.*; import java.lang.*; public class LRUDesign { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine()); while (t-- > 0) { int capacity = Integer.parseInt(read.readLine()); int queries = Integer.parseInt(read.readLine()); LRUCache cache = new LRUCache(capacity); String str[] = read.readLine().trim().split(" "); int len = str.length; int itr = 0; for (int i = 0; (i < queries) && (itr < len); i++) { String queryType = str[itr++]; if (queryType.equals("SET")) { int key = Integer.parseInt(str[itr++]); int value = Integer.parseInt(str[itr++]); cache.set(key, value); } if (queryType.equals("GET")) { int key = Integer.parseInt(str[itr++]); System.out.print(cache.get(key) + " "); } } System.out.println(); } } } // } Driver Code Ends // design the class in the most optimal way class LRUCache { Map<Integer,Integer> map ; int capacity ; public LRUCache(int N) { this.map = new LinkedHashMap<Integer,Integer>(); this.capacity = N; } public int get(int x) { int key = x; if(!map.containsKey(key)) return -1; int value = map.get(key); if(map.size()>1) { map.remove(key); map.put(key,value); } return value; } public void set(int x, int y) { int key = x; int value = y; if(!map.containsKey(key)) { if(map.size()==capacity) { int firstKey = map.keySet().iterator().next(); map.remove(firstKey); } map.put(key,value); } else { map.remove(key); map.put(key,value); } } }
27.1
65
0.482011
dfb82f745caa3cb0a461e6c61e7a9d07bc04c77e
4,145
/* Copyright (c) Royal Holloway, University of London | Contact Claudio Rizzo ([email protected]), Johannes Kinder ([email protected]) or Lorenzo Cavallaro ([email protected]) for details or support | LICENSE.md for license details */ package com.rhul.clod.sootPlugin.javascriptinterface; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.rhul.clod.BabelConfig; import com.rhul.clod.sootPlugin.postAnalysis.PostAnalysisResults.Vulns; public class JavaScriptInterface implements Iterable<JavaScriptMethod> { private List<JavaScriptMethod> exposedMethods; private String type; private BabelConfig config = BabelConfig.getConfigs(); /** * It is the name the developer gave to this interface in order to use it in the * javascript section. */ private List<String> names; /** * Type of the WebView adding this interface */ private List<String> webViewTypes; public JavaScriptInterface(String type) { this.exposedMethods = new ArrayList<JavaScriptMethod>(); this.type = type; this.names = new ArrayList<>(); this.webViewTypes = new ArrayList<>(); } public void addWebViewBind(String webViewType) { if (!webViewTypes.contains(webViewType)) { webViewTypes.add(webViewType); } } public List<String> getWebViewTypesBinded() { List<String> toReturn = new ArrayList<>(webViewTypes); return toReturn; } public JavaScriptInterface(String type, JavaScriptMethod... javaScriptMethods) { this(type); this.exposedMethods = Arrays.asList(javaScriptMethods); } @Override public Iterator<JavaScriptMethod> iterator() { return exposedMethods.iterator(); } public String getType() { return this.type; } public void addMethod(JavaScriptMethod jsMethod) { if (!exposedMethods.contains(jsMethod)) { exposedMethods.add(jsMethod); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JavaScriptInterface other = (JavaScriptInterface) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } public List<String> getNames() { List<String> jsNames = new ArrayList<>(names); return Collections.unmodifiableList(jsNames); } public void addName(String name) { if (!this.names.contains(name)) { this.names.add(name); } } public void toJson(boolean all) { for (JavaScriptMethod jsMethod : exposedMethods) { if (jsMethod.isVulnerable() || all) { jsMethod.toJson(); } } } public void classToFile(int id) { File dir = new File(config.getLibraryFolder() + "/" + config.getApkName()); Map<Vulns, String> vulnerabilities = new HashMap<>(); List<String> intentVulns = new ArrayList<>(); for (JavaScriptMethod jsMethod : exposedMethods) { if (jsMethod.isVulnerable()) { for (Vulns v : jsMethod.vulnTo()) { vulnerabilities.put(v, jsMethod.getsMethod().getSubSignature()); } intentVulns.addAll(jsMethod.getIntentVulns()); } } if (dir.mkdirs()) System.out.println("Created directory: " + dir.getAbsolutePath()); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonObject jobj = new JsonObject(); jobj.add("library", gson.toJsonTree(getType())); jobj.add("vulns", gson.toJsonTree(vulnerabilities)); jobj.add("ivulns", gson.toJsonTree(intentVulns)); String path = dir.getAbsolutePath() + "/" + id + "_" + config.getApkName() + ".libs"; try (FileWriter file = new FileWriter(path)) { file.write(gson.toJson(jobj)); } catch (IOException e) { e.printStackTrace(); } } }
26.741935
263
0.711218
ca813679d7f8ee4ed95d169e8fcd47fcf9764e99
873
package utils; //泛型接口定义 interface ISum<T> { public abstract void sum(T... t); } //从泛型接口继承的具体类型类 class IntSum implements ISum<Integer> { public void sum(Integer... t) { int s = 0; for (int e : t) { s += e; } System.out.println(s); } } class DoubleSum implements ISum<Double> { public void sum(Double... t) { double s = 0.0; for (double e : t) { s += e; } System.out.println(s); } } //使用示例 public class SumMain { public static void main(String[] args) { IntSum intSum = new IntSum(); intSum.sum(1, 2, 3, 4, 5); intSum.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); DoubleSum doubleSum = new DoubleSum(); doubleSum.sum(1.0, 1.5, 2.0, 2.5, 3.0); doubleSum.sum(1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0); } }
20.302326
67
0.498282
10bffee30f3f01386e8ca1966aa1984bafd43496
889
package com.pandect.weatherexample.request.weathertoday; import com.google.auto.value.AutoValue; /** * Created by PROFESSORCORE on 7/23/17. */ @AutoValue public abstract class WeatherObject { //id, main, description, icon public abstract int id(); public abstract String main(); public abstract String description(); public abstract String icon(); static Builder builder() { return new AutoValue_WeatherObject.Builder() .setId(-1) .setMain("") .setDescription("") .setIcon(""); } @AutoValue.Builder abstract static class Builder { abstract Builder setId(int id); abstract Builder setMain(String main); abstract Builder setDescription(String description); abstract Builder setIcon(String icon); abstract WeatherObject build(); } }
26.147059
60
0.63892
ab91d1c070ffff2a2f226977dab5201ee8ec7634
2,175
package com.crazydroid.databindingtest; import android.databinding.DataBindingUtil; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.constraint.solver.widgets.ResolutionDimension; import android.support.v7.widget.RecyclerView; import android.view.View; import com.crazydroid.databindingtest.databinding.LayoutItem2Binding; import com.crazydroid.databindingtest.databinding.LayoutItemBinding; public class MyDecorator extends RecyclerView.ItemDecoration { private Paint mPaint; private int mDividerHeight; public MyDecorator() { mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.parseColor("#F8F8F8")); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); //第一个ItemView以及grid item不需要在上面绘制分割线 if (parent.getChildAdapterPosition(view) != 0 && DataBindingUtil.getBinding(view) instanceof LayoutItemBinding){ //这里直接硬编码为1px mDividerHeight = view.getContext().getResources().getDimensionPixelSize(R.dimen.divide_height); outRect.top = mDividerHeight; } } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); int childCount = parent.getChildCount(); for ( int i = 0; i < childCount; i++ ) { View view = parent.getChildAt(i); int index = parent.getChildAdapterPosition(view); //第一个ItemView、非标题类不需要绘制 if ( index == 0 ||DataBindingUtil.getBinding(view) instanceof LayoutItem2Binding) { continue; } float dividerTop = view.getTop() - mDividerHeight; float dividerLeft = parent.getPaddingLeft(); float dividerBottom = view.getTop(); float dividerRight = parent.getWidth() - parent.getPaddingRight(); c.drawRect(dividerLeft,dividerTop,dividerRight,dividerBottom,mPaint); } } }
34.52381
120
0.691034
82404a015814e906194f0a15d3d6732d4ab38879
2,083
/* * Copyright (C) 2015 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 fathom.shiro; import com.google.inject.Inject; import com.google.inject.Singleton; import fathom.rest.Context; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.pippo.core.route.RouteHandler; /** * A guard that requires an authenticated session and redirects * to a form login url if the session is unauthenticated. * <p> * This is used in conjunction with {@see FormAuthcHandler}. * </p> * * @author James Moger */ @Singleton public class FormAuthcGuard implements RouteHandler<Context> { private final Logger log = LoggerFactory.getLogger(FormAuthcGuard.class); public final static String DESTINATION_ATTRIBUTE = "originalDestination"; protected final String loginUrl; @Inject public FormAuthcGuard(String loginUrl) { this.loginUrl = loginUrl; } @Override public void handle(Context context) { if (!SecurityUtils.getSubject().isAuthenticated()) { // unauthenticated session, save request & redirect to login url String requestUri = context.getRequest().getApplicationUriWithQuery(); context.setSession(DESTINATION_ATTRIBUTE, requestUri); context.redirect(loginUrl); log.info("Unauthenticated request for {}, redirecting to {}", context.getRequestUri(), loginUrl); } else { // session already authenticated context.next(); } } }
31.560606
109
0.709554
e1f6be93a7525b68ca5632340de0abf659373e0e
4,384
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone; import static com.google.common.collect.Multimaps.index; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Ordering; import com.google.errorprone.DocGenTool.Target; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; /** * @author [email protected] (Alex Eagle) */ public class BugPatternIndexWriter { void dump(Collection<BugPatternInstance> patterns, Writer w, Target target) throws IOException { Map<String, List<Map<String, String>>> data = new TreeMap<>(Ordering.natural().reverse()); ListMultimap<String, BugPatternInstance> index = index( patterns, new Function<BugPatternInstance, String>() { @Override public String apply(BugPatternInstance input) { return (input.maturity.description + " : " + input.severity).replace("_", "\\_"); } }); for (Entry<String, Collection<BugPatternInstance>> entry : index.asMap().entrySet()) { data.put( entry.getKey(), FluentIterable.from(entry.getValue()) .transform( new Function<BugPatternInstance, Map<String, String>>() { @Override public Map<String, String> apply(BugPatternInstance input) { return ImmutableMap.of("name", input.name, "summary", input.summary); } }) .toSortedList( new Ordering<Map<String, String>>() { @Override public int compare(Map<String, String> left, Map<String, String> right) { return left.get("name").compareTo(right.get("name")); } })); } Map<String, Object> templateData = new HashMap<>(); List<Map<String, Object>> entryData = new ArrayList<>(); for (Entry<String, List<Map<String, String>>> entry : data.entrySet()) { entryData.add(ImmutableMap.of("category", entry.getKey(), "checks", entry.getValue())); } templateData.put("bugpatterns", entryData); if (target == Target.EXTERNAL) { Map<String, String> frontmatterData = ImmutableMap.<String, String>builder() .put("title", "Bug Patterns") .put("layout", "master") .build(); DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options); Writer yamlWriter = new StringWriter(); yamlWriter.write("---\n"); yaml.dump(frontmatterData, yamlWriter); yamlWriter.write("---\n"); templateData.put("frontmatter", yamlWriter.toString()); MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("com/google/errorprone/resources/bugpatterns_external.mustache"); mustache.execute(w, templateData); } else { MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("com/google/errorprone/resources/bugpatterns_internal.mustache"); mustache.execute(w, templateData); } } }
36.533333
98
0.65625
6e9353a604e884c00b7f6a0e3c2754b7323b4b3d
6,381
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package net.gcolin.di.atinject; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import javax.inject.Inject; import net.gcolin.common.reflect.Reflect; /** * Some utility methods. * * @author Gaël COLIN * @since 1.0 */ public class Reflects { private static final Function<Method, String> METHOD_HASH_ACCEPT = m -> { StringBuilder str = new StringBuilder(); if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())) { String n = m.getDeclaringClass().getName(); str.append(n.substring(0, n.lastIndexOf('.'))).append(":"); } str.append(m.getName()); str.append(m.getReturnType()); Class<?>[] array = m.getParameterTypes(); for (int i = 0, l = array.length; i < l; i++) { str.append(";").append(array[i]); } return str.toString(); }; private static final Predicate<Method> METHOD_HASH_ADD = m -> Modifier.isStatic(m.getModifiers()) || Modifier.isPublic(m.getModifiers()) || Modifier.isProtected(m.getModifiers()); private static final Predicate<Field> FIELD_INJECT_STATIC_ACCEPT = f -> f.isAnnotationPresent(Inject.class) && Modifier.isStatic(f.getModifiers()); private static final Predicate<Method> METHOD_INJECT_STATIC_ACCEPT = m -> m.isAnnotationPresent(Inject.class) && Modifier.isStatic(m.getModifiers()); private static final Predicate<Method> METHOD_POSTCONSTRUCT_ACCEPT = m -> Reflect.hasAnnotation(m.getAnnotations(), "javax.annotation.PostConstruct") && m.getParameterTypes().length == 0; private static final Predicate<Method> METHOD_PREDESTROY_ACCEPT = m -> Reflect.hasAnnotation(m.getAnnotations(), "javax.annotation.PreDestroy") && m.getParameterTypes().length == 0; private Reflects() { } public static Field[][] findStaticFields(Class<?> clazz) { return Reflect.find(clazz, Reflect.FIELD_ITERATOR, FIELD_INJECT_STATIC_ACCEPT, Reflect.array(Field.class)); } public static InjectionPoint[] findInjectPoints(Class<?> clazz, Environment env) { InjectionPointBuilder[] builders = env.getInjectionPointBuilders(); List<InjectionPoint> all = new ArrayList<>(); InjectionPointBuilder builder; if (builders.length == 1) { builder = builders[0]; } else { builder = new InjectionPointBuilder() { @Override public InjectionPoint create(Field field, Environment env) { for (int i = 0; i < builders.length; i++) { InjectionPoint ip = builders[i].create(field, env); if (ip != null) { return ip; } } return null; } @Override public InjectionPoint create(Method method, Environment env) { for (int i = 0; i < builders.length; i++) { InjectionPoint ip = builders[i].create(method, env); if (ip != null) { return ip; } } return null; } }; } Class<?> cl = clazz; Set<String> upper = new HashSet<>(); Set<String> allmethods = new HashSet<>(); while (cl != Object.class && cl != null) { Method[] methods = cl.getDeclaredMethods(); for (int i = methods.length - 1; i >= 0; i--) { Method method = methods[i]; String hash = METHOD_HASH_ACCEPT.apply(method); if (!upper.contains(hash)) { boolean add = METHOD_HASH_ADD.test(method); if (add) { upper.add(hash); } if (!allmethods.contains(hash)) { InjectionPoint ip = builder.create(method, env); if (ip != null) { all.add(ip); } } if (!add) { allmethods.add(hash); } } } Field[] fields = cl.getDeclaredFields(); for (int i = fields.length - 1; i >= 0; i--) { InjectionPoint ip = builder.create(fields[i], env); if (ip != null) { all.add(ip); } } cl = cl.getSuperclass(); } if (all.isEmpty()) { return null; } InjectionPoint[] ips = new InjectionPoint[all.size()]; for (int i = 0, j = ips.length - 1; j >= 0; i++, j--) { ips[i] = all.get(j); } return ips; } public static Method[][] findStaticMethods(Class<?> clazz) { return Reflect.find(clazz, Reflect.METHOD_ITERATOR, METHOD_INJECT_STATIC_ACCEPT, Reflect.array(Method.class)); } public static Method[][] findPredestroyMethods(Class<?> clazz) { return Reflect.find(clazz, Reflect.METHOD_ITERATOR, METHOD_PREDESTROY_ACCEPT, Reflect.array(Method.class)); } public static Method[][] findPostconstructMethods(Class<?> clazz) { return Reflect.find(clazz, Reflect.METHOD_ITERATOR, METHOD_POSTCONSTRUCT_ACCEPT, Reflect.array(Method.class)); } public static Class<?> getInterface(Class<?> c) { if (c.getInterfaces().length > 0) { return c.getInterfaces()[0]; } return c; } public static boolean hasAnnotation(Annotation[] array, Set<Class<? extends Annotation>> possiblities) { for (int i = 0; i < array.length; i++) { if (possiblities.contains(array[i].annotationType())) { return true; } } return false; } @SuppressWarnings("unchecked") public static <T extends Annotation> T getAnnotation(Annotation[] array, Set<Class<? extends Annotation>> possiblities) { for (int i = 0; i < array.length; i++) { if (possiblities.contains(array[i].annotationType())) { return (T) array[i]; } } return null; } }
33.062176
117
0.661182
a4071514577ff8d01e961c58e40bd2a3de6d2554
478
/*package mekanism.common.integration.crafttweaker.gas; import com.blamejared.crafttweaker.api.annotations.ZenRegister; import org.openzen.zencode.java.ZenCodeType; @ZenRegister @ZenCodeType.Name("mekanism.gas.IGasDefinition") public interface IGasDefinition { @ZenCodeType.Operator(ZenCodeType.OperatorType.MUL) IGasStack asStack(int mb); @ZenCodeType.Getter("name") String getName(); @ZenCodeType.Getter("displayName") String getDisplayName(); }*/
26.555556
63
0.771967
019f589b6d951ec7668196a846f9aa2d07e51147
3,556
package com.java110.community.dao.impl; import com.alibaba.fastjson.JSONObject; import com.java110.common.constant.ResponseConstant; import com.java110.common.exception.DAOException; import com.java110.common.util.DateUtil; import com.java110.community.dao.IServiceServiceDao; import com.java110.core.base.dao.BaseServiceDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * 服务服务 与数据库交互 * Created by wuxw on 2017/4/5. */ @Service("serviceServiceDaoImpl") //@Transactional public class ServiceServiceDaoImpl extends BaseServiceDao implements IServiceServiceDao { private static Logger logger = LoggerFactory.getLogger(ServiceServiceDaoImpl.class); /** * 服务信息封装 * * @param businessServiceInfo 服务信息 封装 * @throws DAOException DAO异常 */ @Override public int saveServiceInfo(Map businessServiceInfo) throws DAOException { businessServiceInfo.put("month", DateUtil.getCurrentMonth()); // 查询business_user 数据是否已经存在 logger.debug("保存服务信息 入参 businessServiceInfo : {}", businessServiceInfo); int saveFlag = sqlSessionTemplate.insert("serviceServiceDaoImpl.saveServiceInfo", businessServiceInfo); return saveFlag; } /** * 查询服务信息 * * @param info bId 信息 * @return 服务信息 * @throws DAOException DAO异常 */ @Override public List<Map> getBusinessServiceInfo(Map info) throws DAOException { logger.debug("查询服务信息 入参 info : {}", info); List<Map> businessServiceInfos = sqlSessionTemplate.selectList("serviceServiceDaoImpl.getBusinessServiceInfo", info); return businessServiceInfos; } /** * 保存服务信息 到 instance * * @param info bId 信息 * @throws DAOException DAO异常 */ @Override public void saveServiceInfoInstance(Map info) throws DAOException { logger.debug("保存服务信息Instance 入参 info : {}", info); int saveFlag = sqlSessionTemplate.insert("serviceServiceDaoImpl.saveServiceInfoInstance", info); if (saveFlag < 1) { throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR, "保存服务信息Instance数据失败:" + JSONObject.toJSONString(info)); } } /** * 查询服务信息(instance) * * @param info bId 信息 * @return List<Map> * @throws DAOException DAO异常 */ @Override public List<Map> getServiceInfo(Map info) throws DAOException { logger.debug("查询服务信息 入参 info : {}", info); List<Map> businessServiceInfos = sqlSessionTemplate.selectList("serviceServiceDaoImpl.getServiceInfo", info); return businessServiceInfos; } /** * 修改服务信息 * * @param info 修改信息 * @throws DAOException DAO异常 */ @Override public int updateServiceInfo(Map info) throws DAOException { logger.debug("修改服务信息Instance 入参 info : {}", info); int saveFlag = sqlSessionTemplate.update("serviceServiceDaoImpl.updateServiceInfo", info); return saveFlag; } /** * 查询服务数量 * * @param info 服务信息 * @return 服务数量 */ @Override public int queryServicesCount(Map info) { logger.debug("查询服务数据 入参 info : {}", info); List<Map> businessServiceInfos = sqlSessionTemplate.selectList("serviceServiceDaoImpl.queryServicesCount", info); if (businessServiceInfos.size() < 1) { return 0; } return Integer.parseInt(businessServiceInfos.get(0).get("count").toString()); } }
27.145038
127
0.675197
15fb6450173a385f3eefbe2734d511d263100cf3
5,872
package ru.fizteh.fivt.students.gudkov394.Storable.src; import ru.fizteh.fivt.storage.structured.Storeable; import ru.fizteh.fivt.storage.structured.Table; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by kagudkov on 07.11.14. */ public class MySerialize implements Serializable { interface Read { Object getObject(String string) throws ParseException; } interface Write { String getString(Object object); } private Map<Class, Read> readMap = new HashMap<>(); private Map<Class, Write> writeMap = new HashMap<>(); public MySerialize() { readMap.put(Integer.class, new Read() { @Override public Object getObject(String string) throws ParseException { return Integer.valueOf(string); } }); readMap.put(Long.class, new Read() { @Override public Object getObject(String string) throws ParseException { return Long.valueOf(string); } }); readMap.put(Float.class, new Read() { @Override public Object getObject(String string) throws ParseException { return Float.valueOf(string); } }); readMap.put(Double.class, new Read() { @Override public Object getObject(String string) throws ParseException { return Double.valueOf(string); } }); readMap.put(Byte.class, new Read() { @Override public Object getObject(String string) throws ParseException { return Byte.valueOf(string); } }); readMap.put(Boolean.class, new Read() { @Override public Object getObject(String string) throws ParseException { if (string.trim().toLowerCase().equals("true")) { return true; } else if (string.trim().toLowerCase().equals("false")) { return false; } throw new ParseException("not a valid boolean value", 0); } }); readMap.put(String.class, new Read() { @Override public Object getObject(String string) throws ParseException { if (string.length() > 1 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"') { return string.substring(1, string.length() - 1); } throw new ParseException("not a valid String value", 0); } }); writeMap.put(Integer.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(Long.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(Float.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(Double.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(Byte.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(Boolean.class, new Write() { @Override public String getString(Object object) { return object.toString(); } }); writeMap.put(String.class, new Write() { @Override public String getString(Object object) { return "\"" + object + "\""; } }); } public Storeable deserialize(Table table, String value) throws ParseException { value = value.trim(); if (value.length() < 3 || value.charAt(0) != '[' || value.charAt(value.length() - 1) != ']' || value.charAt(1) == ',' || value.charAt(value.length() - 2) == ',') { throw new ParseException("JSON is invalid, failed with '[' or ','", 0); } String[] tokens = value.substring(1, value.length() - 1).split(","); if (tokens.length != table.getColumnsCount()) { throw new ParseException("wrong number of column", 0); } List<Object> contents = new ArrayList<>(); for (int i = 0; i < table.getColumnsCount(); i++) { try { if (!("null".equals(tokens[i].trim().toLowerCase()))) { contents.add(readMap.get(table.getColumnType(i)).getObject(tokens[i].trim())); } else { contents.add(null); } } catch (NumberFormatException e) { throw new ParseException("not a valid ", 0); } } return new TableContents(contents); } public String serialize(Table table, Storeable value) { int columnsCount = table.getColumnsCount(); StringBuilder stringBuilder = new StringBuilder("["); for (int i = 0; i < columnsCount; i++) { if (value.getColumnAt(i) != null) { stringBuilder.append(writeMap.get(table.getColumnType(i)).getString(value.getColumnAt(i))); } else { stringBuilder.append("null"); } stringBuilder.append(','); } stringBuilder.setCharAt(stringBuilder.length() - 1, ']'); return stringBuilder.toString(); } }
33.175141
114
0.529973
07b70fc8e8ea22fbad572daa145d5c5b9193d7fe
491
package org.apache.bcel.generic; import org.apache.bcel.ExceptionConstants; public class ARRAYLENGTH extends Instruction implements ExceptionThrower, StackProducer { public ARRAYLENGTH() { super((short)190, (short)1); } public Class[] getExceptions() { return new Class[]{ExceptionConstants.NULL_POINTER_EXCEPTION}; } public void accept(Visitor v) { v.visitExceptionThrower(this); v.visitStackProducer(this); v.visitARRAYLENGTH(this); } }
24.55
89
0.714868
746b1ede2d3f5f2480842887797cf4b2ddcdadd1
364
package com.wepay; import com.wepay.net.WePayResource; public class WePay { public static Long clientId; public static String clientSecret; public static void initialize(Long appClientId, String appClientSecret, Boolean useStageEnv) { clientId = appClientId; clientSecret = appClientSecret; WePayResource.initializeWePayResource(useStageEnv); } }
21.411765
95
0.791209
fe5b483dad46357d23bfd29ab38fc82ca734dbb7
2,166
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.rpc.asynchain; import com.alipay.sofa.rpc.context.RpcInvokeContext; import com.alipay.sofa.rpc.core.request.RequestBase; import com.alipay.sofa.rpc.log.Logger; import com.alipay.sofa.rpc.log.LoggerFactory; import com.alipay.sofa.rpc.message.bolt.BoltSendableResponseCallback; import java.util.Random; /** * * * @author <a href="mailto:[email protected]">GengZhang</a> */ public class ServiceBImpl implements ServiceB { private final static Logger LOGGER = LoggerFactory.getLogger(ServiceBImpl.class); private Random random = new Random(); ServiceC serviceC; public ServiceBImpl(ServiceC serviceC) { this.serviceC = serviceC; } @Override public int getInt(int num) { RpcInvokeContext.getContext().setResponseCallback(new BoltSendableResponseCallback() { @Override public void onAppResponse(Object appResponse, String methodName, RequestBase request) { // 此时C-异步返回->B LOGGER.info("b get resp from c :" + appResponse); int respToA = random.nextInt(1000); // 调这个方法B-异步返回->A sendAppResponse(respToA); // 如果A是异步调用,则拿到这个appResponse返回值 } }); String s = serviceC.getStr("xx"); return -1; } }
33.84375
99
0.682825
7efdb442ad9ec711c928dccff348d498d4c4857c
1,555
package com.github.ruediste1.i18n.messageFormat.formatTypeParsers; import static java.util.stream.Collectors.joining; import com.github.ruediste.lambdaPegParser.DefaultParser; import com.github.ruediste.lambdaPegParser.DefaultParsingContext; import com.github.ruediste1.i18n.messageFormat.PatternParser; import com.github.ruediste1.i18n.messageFormat.ast.PatternNode; public abstract class FormatTypeParser extends DefaultParser { public FormatTypeParser(DefaultParsingContext ctx) { super(ctx); } /** * The style part of a placeholder, including the initial comma. * * @param argumentName * name of the argument */ abstract public PatternNode style(String argumentName); public PatternParser patternParser; public void setPatternParser(PatternParser patternParser) { this.patternParser = patternParser; } /** * <pre> * ( "''" | quoted | ./"}' ) + * </pre> */ public String subFormatPattern() { return OneOrMore(() -> FirstOf(() -> Str("''"), () -> quotedSubFormatPattern(), () -> NoneOf("}"))).stream() .collect(joining()); } /** * <pre> * "'" ("''" | ./' )* "'" * </pre> */ public String quotedSubFormatPattern() { return Str("'") + this.<String> ZeroOrMore(() -> FirstOf(() -> Str("''"), () -> NoneOf("'"))).stream() .collect(joining()) + Opt(() -> Str("'")).orElse(""); } public void whiteSpace() { patternParser.whiteSpace(); } }
28.272727
116
0.610289
5b74ce008a6b5b9eb3f47ba39558e8a55e73c1dd
922
package me.kp.moon.moonpvp.kit.listeners; import me.kp.moon.moonpvp.data.PlayerData; import me.kp.moon.moonpvp.data.PlayerDataManager; import me.kp.moon.moonpvp.kit.KitType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; public class VampireListener implements Listener { @EventHandler public void PlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); Player killer = player.getKiller(); if (killer == null) return; PlayerData killerData = PlayerDataManager.getPlayerData(killer); if (killerData == null) return; if (killerData.kitType != KitType.VAMPIRE) return; killer.setMaxHealth(killer.getMaxHealth() + 1.0); killer.sendMessage("§aVocê recebeu meio coração a mais por matar §e" + player.getName() + "§a."); } }
35.461538
105
0.719089
c6c1fd854f682627301678aeb6a38b004d3650a7
3,502
package demo.marketmatch; import com.alibaba.fastjson.JSONObject; import demo.marketmatch.domain.MarketMatchOrder; import demo.marketmatch.domain.MarketMatchOrderBook; import demo.marketmatch.domain.MarketMatchTrade; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Created by helly on 2016/9/30. */ public class MarketMatchViewer { private static final MarketMatchViewer VIEWER = new MarketMatchViewer(); private static final JSONObject EMPTY = new JSONObject(); private static final int MAX_SIZE = 100; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); private Map<String, Map<String, Object>> viewerMap = new HashMap<>(); public static MarketMatchViewer getInstance() { return VIEWER; } private MarketMatchViewer() { } public void pushBook(String pid, MarketMatchOrderBook book) { try { writeLock.lock(); put(pid, "book", book); } finally { writeLock.unlock(); } } private void put(String pid, String name, Object obj) { if (viewerMap.containsKey(pid)) { viewerMap.get(pid).put(name, obj); } else { Map<String, Object> map = new HashMap<>(); map.put(name, obj); viewerMap.put(pid, map); } } public void pushOrder(String pid, MarketMatchOrder order) { try { writeLock.lock(); append(pid, "order", order); } finally { writeLock.unlock(); } } private void append(String pid, String name, Object object) { if (viewerMap.containsKey(pid)) { Map<String, Object> map = viewerMap.get(pid); if (map.containsKey(name)) { List<Object> list = ((List<Object>) map.get(name)); list.add(0, object); while (list.size() > MAX_SIZE) { list.remove(MAX_SIZE); } } else { putList(pid, name, object); } } else { putList(pid, name, object); } } private void putList(String pid, String name, Object object) { List<Object> list = new ArrayList<>(); list.add(object); put(pid, name, list); } public void pushTrade(String pid, List<MarketMatchTrade> trades) { try { writeLock.lock(); appendAll(pid, "trade", trades); } finally { writeLock.unlock(); } } private void appendAll(String pid, String name, List<MarketMatchTrade> list) { for (MarketMatchTrade trade : list) { append(pid, name, trade); } } public String view(String pid) { String json; JSONObject jsonObject; try { readLock.lock(); if (viewerMap.containsKey(pid)) { Map<String, Object> retData = viewerMap.get(pid); jsonObject = new JSONObject(); jsonObject.putAll(retData); } else { jsonObject = EMPTY; } json = jsonObject.toJSONString(); } finally { readLock.unlock(); } return json; } }
29.183333
82
0.575385
2319ef504416bab494aa9f33e5cfaa6447f0297b
5,155
package fi.riista.sql; import com.querydsl.core.types.Path; import com.querydsl.core.types.PathMetadata; import com.querydsl.core.types.dsl.DateTimePath; import com.querydsl.core.types.dsl.NumberPath; import com.querydsl.sql.ColumnMetadata; import com.querydsl.sql.spatial.RelationalPathSpatial; import javax.annotation.Generated; import java.sql.Types; import static com.querydsl.core.types.PathMetadataFactory.forVariable; /** * SQPermitDecisionInvoice is a Querydsl query type for SQPermitDecisionInvoice */ @Generated("com.querydsl.sql.codegen.MetaDataSerializer") public class SQPermitDecisionInvoice extends RelationalPathSpatial<SQPermitDecisionInvoice> { private static final long serialVersionUID = -1455095517; public static final SQPermitDecisionInvoice permitDecisionInvoice = new SQPermitDecisionInvoice("permit_decision_invoice"); public final NumberPath<Long> batchId = createNumber("batchId", Long.class); public final NumberPath<Integer> consistencyVersion = createNumber("consistencyVersion", Integer.class); public final NumberPath<Long> createdByUserId = createNumber("createdByUserId", Long.class); public final DateTimePath<java.sql.Timestamp> creationTime = createDateTime("creationTime", java.sql.Timestamp.class); public final NumberPath<Long> deletedByUserId = createNumber("deletedByUserId", Long.class); public final DateTimePath<java.sql.Timestamp> deletionTime = createDateTime("deletionTime", java.sql.Timestamp.class); public final NumberPath<Long> invoiceId = createNumber("invoiceId", Long.class); public final DateTimePath<java.sql.Timestamp> modificationTime = createDateTime("modificationTime", java.sql.Timestamp.class); public final NumberPath<Long> modifiedByUserId = createNumber("modifiedByUserId", Long.class); public final NumberPath<Long> permitDecisionId = createNumber("permitDecisionId", Long.class); public final NumberPath<Long> permitDecisionInvoiceId = createNumber("permitDecisionInvoiceId", Long.class); public final com.querydsl.sql.PrimaryKey<SQPermitDecisionInvoice> permitDecisionInvoicePkey = createPrimaryKey(permitDecisionInvoiceId); public final com.querydsl.sql.ForeignKey<SQInvoice> permitDecisionInvoiceInvoiceFk = createForeignKey(invoiceId, "invoice_id"); public final com.querydsl.sql.ForeignKey<SQPermitDecision> permitDecisionInvoiceDecisionFk = createForeignKey(permitDecisionId, "permit_decision_id"); public final com.querydsl.sql.ForeignKey<SQPermitDecisionInvoiceBatch> permitDecisionInvoiceBatchFk = createForeignKey(batchId, "permit_decision_invoice_batch_id"); public SQPermitDecisionInvoice(String variable) { super(SQPermitDecisionInvoice.class, forVariable(variable), "public", "permit_decision_invoice"); addMetadata(); } public SQPermitDecisionInvoice(String variable, String schema, String table) { super(SQPermitDecisionInvoice.class, forVariable(variable), schema, table); addMetadata(); } public SQPermitDecisionInvoice(String variable, String schema) { super(SQPermitDecisionInvoice.class, forVariable(variable), schema, "permit_decision_invoice"); addMetadata(); } public SQPermitDecisionInvoice(Path<? extends SQPermitDecisionInvoice> path) { super(path.getType(), path.getMetadata(), "public", "permit_decision_invoice"); addMetadata(); } public SQPermitDecisionInvoice(PathMetadata metadata) { super(SQPermitDecisionInvoice.class, metadata, "public", "permit_decision_invoice"); addMetadata(); } public void addMetadata() { addMetadata(batchId, ColumnMetadata.named("batch_id").withIndex(11).ofType(Types.BIGINT).withSize(19)); addMetadata(consistencyVersion, ColumnMetadata.named("consistency_version").withIndex(2).ofType(Types.INTEGER).withSize(10).notNull()); addMetadata(createdByUserId, ColumnMetadata.named("created_by_user_id").withIndex(3).ofType(Types.BIGINT).withSize(19)); addMetadata(creationTime, ColumnMetadata.named("creation_time").withIndex(6).ofType(Types.TIMESTAMP).withSize(35).withDigits(6).notNull()); addMetadata(deletedByUserId, ColumnMetadata.named("deleted_by_user_id").withIndex(4).ofType(Types.BIGINT).withSize(19)); addMetadata(deletionTime, ColumnMetadata.named("deletion_time").withIndex(8).ofType(Types.TIMESTAMP).withSize(35).withDigits(6)); addMetadata(invoiceId, ColumnMetadata.named("invoice_id").withIndex(10).ofType(Types.BIGINT).withSize(19).notNull()); addMetadata(modificationTime, ColumnMetadata.named("modification_time").withIndex(7).ofType(Types.TIMESTAMP).withSize(35).withDigits(6).notNull()); addMetadata(modifiedByUserId, ColumnMetadata.named("modified_by_user_id").withIndex(5).ofType(Types.BIGINT).withSize(19)); addMetadata(permitDecisionId, ColumnMetadata.named("permit_decision_id").withIndex(9).ofType(Types.BIGINT).withSize(19).notNull()); addMetadata(permitDecisionInvoiceId, ColumnMetadata.named("permit_decision_invoice_id").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull()); } }
53.697917
168
0.778661
526e16275d0789a82e94dcaa8a2759c7474b8dd5
482
package com.smarttable.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by huang on 2017/11/4. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SmartTable { String name() default ""; boolean count() default false; int pageSize() default Integer.MAX_VALUE; int currentPage() default 0; }
24.1
45
0.755187
465644a87cf47897d0b48ecca346cf5f8e3e98f7
5,634
package org.keedio.flume.interceptor.enrichment.interceptor; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; /** * Created by PC on 10/06/2016. */ public class EnrichedEventBodyExtraData { private String topic; private String timestamp; private String sha1Hex; private String filePath; private String fileName; private String lineNumber; private String type; @JsonCreator public EnrichedEventBodyExtraData(@JsonProperty("topic") String topic, @JsonProperty("timestamp") String timestamp, @JsonProperty("sha1Hex") String sha1Hex, @JsonProperty("filePath") String filePath, @JsonProperty("fileName") String fileName, @JsonProperty("lineNumber") String lineNumber, @JsonProperty("type") String type) { this.topic = topic; this.timestamp = timestamp; this.sha1Hex = sha1Hex; this.filePath = filePath; this.fileName = fileName; this.lineNumber = lineNumber; this.type = type; } public EnrichedEventBodyExtraData() {} public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getSha1Hex() { return sha1Hex; } public void setSha1Hex(String sha1Hex) { this.sha1Hex = sha1Hex; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getLineNumber() { return lineNumber; } public void setLineNumber(String lineNumber) { this.lineNumber = lineNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } boolean equals (EnrichedEventBodyExtraData enrichedEventBodyExtraData) { boolean isEquals = true; if (this == null && enrichedEventBodyExtraData != null) { isEquals = false; } else if (this != null && enrichedEventBodyExtraData == null) { isEquals = false; } else if (this == null && enrichedEventBodyExtraData == null) { isEquals = true; } else { if (this.getTopic() == null && enrichedEventBodyExtraData.getTopic() != null) { isEquals = false; } else if (this.getTopic() != null && enrichedEventBodyExtraData.getTopic() == null) { isEquals = false; } else { isEquals = this.getTopic().equals(enrichedEventBodyExtraData.getTopic()); } if (this.getTimestamp() == null && enrichedEventBodyExtraData.getTimestamp() != null) { isEquals = false; } else if (this.getTimestamp() != null && enrichedEventBodyExtraData.getTimestamp() == null) { isEquals = false; } else { isEquals = this.getTimestamp().equals(enrichedEventBodyExtraData.getTimestamp()); } if (this.getSha1Hex() == null && enrichedEventBodyExtraData.getSha1Hex() != null) { isEquals = false; } else if (this.getSha1Hex() != null && enrichedEventBodyExtraData.getSha1Hex() == null) { isEquals = false; } else { isEquals = this.getSha1Hex().equals(enrichedEventBodyExtraData.getSha1Hex()); } if (this.getFilePath() == null && enrichedEventBodyExtraData.getFilePath() != null) { isEquals = false; } else if (this.getFilePath() != null && enrichedEventBodyExtraData.getFilePath() == null) { isEquals = false; } else { isEquals = this.getFilePath().equals(enrichedEventBodyExtraData.getFilePath()); } if (this.getFileName() == null && enrichedEventBodyExtraData.getFileName() != null) { isEquals = false; } else if (this.getFileName() != null && enrichedEventBodyExtraData.getFileName() == null) { isEquals = false; } else { isEquals = this.getFileName().equals(enrichedEventBodyExtraData.getFileName()); } if (this.getLineNumber() == null && enrichedEventBodyExtraData.getLineNumber() != null) { isEquals = false; } else if (this.getLineNumber() != null && enrichedEventBodyExtraData.getLineNumber() == null) { isEquals = false; } else { isEquals = this.getLineNumber().equals(enrichedEventBodyExtraData.getLineNumber()); } if (this.getType() == null && enrichedEventBodyExtraData.getType() != null) { isEquals = false; } else if (this.getType() != null && enrichedEventBodyExtraData.getType() == null) { isEquals = false; } else { isEquals = this.getType().equals(enrichedEventBodyExtraData.getType()); } } return isEquals; } }
31.830508
109
0.566738
8102c668d2e106b81e1d9d4907505e321616a7ad
607
package kornell.core.entity; //TODO: Persist transition-triggering events //TODO: Document states and transitions public enum EnrollmentState { notEnrolled, //??? enrolled, //Enrolled on class, directly by an Institution or by being approved after requesting requested, //Requested participation in a private course denied, //Participation request denied cancelled, //Participation canceled by institution (payment, timeout, ?) deleted //Soft-delete //finished All content seen and all required evaluations either passed or failed //TODO: Abandoned? }
40.466667
102
0.724876
fa9ac46e5acc117225fc310e5e0a11e27cafa886
2,598
package org.sqs; import java.util.Locale; import java.util.ResourceBundle; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.NoSuchMessageException; import org.springframework.context.support.ResourceBundleMessageSource; public class LocaleUtils { private final Logger logger = Logger.getLogger(getClass()); //Resource bundle message source name @Value("${message.source}") private String MESSAGES = "messages"; private Locale locale = Locale.ENGLISH; private ResourceBundle resource = ResourceBundle.getBundle(MESSAGES); private ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); public LocaleUtils(Locale locale) { this.locale = locale; this.resource = ResourceBundle.getBundle(MESSAGES,this.locale); this.messageSource.setBasename(MESSAGES); } /* * Get the translation of input string for the locale */ public String get(String sInput) { return resource.getString(sInput); } /* OLD private ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("locale.xml"); public String get(String sInput) { return get(sInput, new Object[]{}); } */ /* * Get the translation of input string for the locale * and replace '{#}' with the asParameters elements */ public String get(String sInput, Object asParameters[]) { String sOutput = sInput; try { sOutput = messageSource.getMessage(sInput, asParameters, locale); } catch (NoSuchMessageException nsme) { logger.error("Resource bundle " + locale + " not found: " + sInput); try { sOutput = messageSource.getMessage(sInput, asParameters, Locale.ENGLISH); } catch (NoSuchMessageException nsmen) { logger.error("Resource bundle " + Locale.ENGLISH +" not found: " + sInput); } } return sOutput; } /* OLD: public String get(String sInput, Object asParameters[]) { String sOutput = sInput; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("locale.xml"); try { sOutput = context.getMessage(sInput, asParameters, locale); } catch (NoSuchMessageException nsme) { logger.error("Resource bundle " + locale + " not found: " + sInput); try { sOutput = context.getMessage(sInput, asParameters, Locale.ENGLISH); } catch (NoSuchMessageException nsmen) { logger.error("Resource bundle " + Locale.ENGLISH +" not found: " + sInput); } } context.close(); return sOutput; } */ }
29.191011
100
0.700924
1a404d3e8b72debbf16629f7f822613d12130698
1,994
package downfall.patches; import com.evacipated.cardcrawl.modthespire.lib.*; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.rooms.AbstractRoom; import com.megacrit.cardcrawl.screens.CombatRewardScreen; import com.megacrit.cardcrawl.ui.buttons.ProceedButton; import downfall.monsters.FleeingMerchant; import downfall.rooms.HeartShopRoom; import javassist.CtBehavior; import java.util.ArrayList; @SpirePatch( clz = ProceedButton.class, method = "update" ) public class ProceedButtonPatch { @SpireInsertPatch( locator = Locator.class ) public static SpireReturn Insert(ProceedButton __instance) { AbstractRoom r = AbstractDungeon.getCurrRoom(); if (r instanceof HeartShopRoom) { if ((((HeartShopRoom) r).startedCombat && FleeingMerchant.DEAD) || FleeingMerchant.ESCAPED) { AbstractRoom tRoom = new HeartShopRoom(false); tRoom.rewards.clear(); AbstractDungeon.combatRewardScreen.clear(); AbstractDungeon.currMapNode.setRoom(tRoom); AbstractDungeon.getCurrRoom().rewards.clear(); AbstractDungeon.scene.nextRoom(tRoom); CardCrawlGame.fadeIn(1.5F); AbstractDungeon.rs = AbstractDungeon.RenderScene.NORMAL; tRoom.onPlayerEntry(); AbstractDungeon.closeCurrentScreen(); return SpireReturn.Return(null); } } return SpireReturn.Continue(); } private static class Locator extends SpireInsertLocator { @Override public int[] Locate(CtBehavior ctMethodToPatch) throws Exception { Matcher finalMatcher = new Matcher.MethodCallMatcher(AbstractDungeon.class, "closeCurrentScreen"); return new int[]{LineFinder.findAllInOrder(ctMethodToPatch, new ArrayList<>(), finalMatcher)[2]}; } } }
38.346154
110
0.681043
414013304cd52969e5b6ddbb980d9dc88c647aeb
20,821
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gemstone.gemfire.internal.cache.ha; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import com.gemstone.gemfire.cache.AttributesFactory; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheException; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.CacheListener; import com.gemstone.gemfire.cache.DataPolicy; import com.gemstone.gemfire.cache.EntryEvent; import com.gemstone.gemfire.cache.InterestResultPolicy; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.RegionAttributes; import com.gemstone.gemfire.cache.Scope; import com.gemstone.gemfire.cache.client.internal.PoolImpl; import com.gemstone.gemfire.cache.client.internal.QueueStateImpl.SequenceIdAndExpirationObject; import com.gemstone.gemfire.cache.util.CacheListenerAdapter; import com.gemstone.gemfire.cache30.ClientServerTestCase; import com.gemstone.gemfire.cache30.CacheSerializableRunnable; import com.gemstone.gemfire.distributed.DistributedSystem; import com.gemstone.gemfire.internal.AvailablePort; import com.gemstone.gemfire.internal.cache.CacheServerImpl; import com.gemstone.gemfire.internal.cache.EntryEventImpl; import com.gemstone.gemfire.internal.cache.EventID; import dunit.DistributedTestCase; import dunit.Host; import dunit.VM; /** * * Test to verify correct propagation of operations eventID's for put all * * * @author Mitul Bid * @since 5.1 */ public class PutAllDUnitTest extends DistributedTestCase { /** server1 VM **/ VM server1 = null; /** server2 VM **/ VM server2 = null; /** client1 VM **/ VM client1 = null; /** client2 VM **/ VM client2 = null; /** port of server1**/ public static int PORT1; /** port of server2**/ public static int PORT2; /** region name**/ private static final String REGION_NAME = "PutAllDUnitTest_Region"; /** cache **/ private static Cache cache = null; /** server **/ static CacheServerImpl server = null; /** test constructor **/ public PutAllDUnitTest(String name) { super(name); } /** get the hosts and the VMs **/ public void setUp() throws Exception { super.setUp(); final Host host = Host.getHost(0); server1 = host.getVM(0); server2 = host.getVM(1); client1 = host.getVM(2); client2 = host.getVM(3); } /** close the caches**/ public void tearDown2() throws Exception { super.tearDown2(); client1.invoke(PutAllDUnitTest.class, "closeCache"); client2.invoke(PutAllDUnitTest.class, "closeCache"); // close server server1.invoke(PutAllDUnitTest.class, "closeCache"); server2.invoke(PutAllDUnitTest.class, "closeCache"); // close cache in the controller VM (ezoerner) Not doing this was causing CacheExistsExceptions in other dunit tests closeCache(); } /** stops the server **/ private CacheSerializableRunnable stopServer() { CacheSerializableRunnable stopserver = new CacheSerializableRunnable( "stopServer") { public void run2() throws CacheException { server.stop(); } }; return stopserver; } /** function to create a 2 servers and 3 client (1 client will be in the unit controller VM) **/ private void createClientServerConfiguration() { PORT1 = ((Integer)server1.invoke(PutAllDUnitTest.class, "createServerCache")).intValue(); PORT2 = ((Integer)server2.invoke(PutAllDUnitTest.class, "createServerCache")).intValue(); client1.invoke(PutAllDUnitTest.class, "createClientCache1", new Object[] { getServerHostName(server1.getHost()), new Integer(PORT1) }); client2.invoke(PutAllDUnitTest.class, "createClientCache2", new Object[] { getServerHostName(server1.getHost()), new Integer(PORT2) }); try { createClientCache2(getServerHostName(server1.getHost()), new Integer(PORT2)); } catch (Exception e) { fail(" test failed due to "+e); } } /** create the server **/ public static Integer createServerCache() throws Exception { new PutAllDUnitTest("temp").createCache(new Properties()); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); factory.setDataPolicy(DataPolicy.REPLICATE); CacheListener clientListener = new HAEventIdPropagationListenerForClient1(); factory.setCacheListener(clientListener); RegionAttributes attrs = factory.create(); cache.createRegion(REGION_NAME, attrs); server = (CacheServerImpl)cache.addCacheServer(); assertNotNull(server); int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET); server.setPort(port); server.setNotifyBySubscription(true); server.start(); return new Integer(server.getPort()); } /** function to create cache **/ private void createCache(Properties props) throws Exception { DistributedSystem ds = getSystem(props); assertNotNull(ds); ds.disconnect(); ds = getSystem(props); cache = CacheFactory.create(ds); assertNotNull(cache); } private static PoolImpl pool = null; /** function to create client cache with HAEventIdPropagationListenerForClient2 as the listener **/ public static void createClientCache2(String host, Integer port1) throws Exception { PORT1 = port1.intValue(); Properties props = new Properties(); props.setProperty("mcast-port", "0"); props.setProperty("locators", ""); new PutAllDUnitTest("temp").createCache(props); props.setProperty("retryAttempts", "2"); props.setProperty("endpoints", "ep1="+host+":" + PORT1); props.setProperty("redundancyLevel", "-1"); props.setProperty("establishCallbackConnection", "true"); props.setProperty("LBPolicy", "Sticky"); props.setProperty("readTimeout", "2000"); props.setProperty("socketBufferSize", "1000"); props.setProperty("retryInterval", "250"); props.setProperty("connectionsPerServer", "2"); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); PoolImpl p = (PoolImpl)ClientServerTestCase.configureConnectionPool(factory, host, PORT1,-1, true, -1, 2, null); CacheListener clientListener = new HAEventIdPropagationListenerForClient2(); factory.setCacheListener(clientListener); RegionAttributes attrs = factory.create(); cache.createRegion(REGION_NAME, attrs); Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); region.registerInterest("ALL_KEYS", InterestResultPolicy.NONE); pool = p; } /** function to create client cache **/ public static void createClientCache1(String host, Integer port1) throws Exception { PORT1 = port1.intValue(); Properties props = new Properties(); props.setProperty("mcast-port", "0"); props.setProperty("locators", ""); new PutAllDUnitTest("temp").createCache(props); props.setProperty("retryAttempts", "2"); props.setProperty("endpoints", "ep1="+host+":" + PORT1); props.setProperty("redundancyLevel", "-1"); props.setProperty("establishCallbackConnection", "true"); props.setProperty("LBPolicy", "Sticky"); props.setProperty("readTimeout", "2000"); props.setProperty("socketBufferSize", "1000"); props.setProperty("retryInterval", "250"); props.setProperty("connectionsPerServer", "2"); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.DISTRIBUTED_ACK); PoolImpl p = (PoolImpl)ClientServerTestCase.configureConnectionPool(factory, host, PORT1,-1, true, -1, 2, null); CacheListener clientListener = new HAEventIdPropagationListenerForClient1(); factory.setCacheListener(clientListener); RegionAttributes attrs = factory.create(); cache.createRegion(REGION_NAME, attrs); Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); region.registerInterest("ALL_KEYS", InterestResultPolicy.NONE); pool = p; } /** function to close cache **/ public static void closeCache() { if (cache != null && !cache.isClosed()) { try { cache.close(); cache.getDistributedSystem().disconnect(); } catch (RuntimeException e) { //ignore } } } /** function to assert that the ThreadIdtoSequence id Map is not Null but is empty **/ public static void assertThreadIdToSequenceIdMapisNotNullButEmpty() { Map map = pool.getThreadIdToSequenceIdMap(); assertNotNull(map); // I didn't change this method name for merge purposes, but because of the // marker, the map will contain one entry assertTrue(map.size() == 1); } /** function to assert that the ThreadIdtoSequence id Map is not Null and has only one entry **/ public static Object assertThreadIdToSequenceIdMapHasEntryId() { Map map = pool.getThreadIdToSequenceIdMap(); assertNotNull(map); // The map size can now be 1 or 2 because of the server thread putting // the marker in the queue. If it is 2, the first entry is the server // thread; the second is the client thread. If it is 1, the entry is the // client thread. The size changes because of the map.clear call below. assertTrue(map.size() != 0); // Set the entry to the last entry Map.Entry entry = null; for (Iterator threadIdToSequenceIdMapIterator = map.entrySet().iterator(); threadIdToSequenceIdMapIterator.hasNext();) { entry = (Map.Entry)threadIdToSequenceIdMapIterator.next(); } ThreadIdentifier tid = (ThreadIdentifier) entry.getKey(); SequenceIdAndExpirationObject seo = (SequenceIdAndExpirationObject)entry.getValue(); long sequenceId = seo.getSequenceId(); EventID evId = new EventID(tid.getMembershipID(),tid.getThreadID(),sequenceId); synchronized(map) { map.clear(); } return evId; } /** function to assert that the ThreadIdtoSequence id Map is not Null and has only one entry **/ public static Object[] assertThreadIdToSequenceIdMapHasEntryIds() { EventID[] evids = new EventID[5]; Map map = pool.getThreadIdToSequenceIdMap(); assertNotNull(map); evids[0] = putAlleventId1; evids[1] = putAlleventId2; evids[2] = putAlleventId3; evids[3] = putAlleventId4; evids[4] = putAlleventId5; assertNotNull(evids[0]); assertNotNull(evids[1]); assertNotNull(evids[2]); assertNotNull(evids[3]); assertNotNull(evids[4]); return evids; } /** EventId * */ protected static EventID eventId = null; protected volatile static EventID putAlleventId1 = null; protected volatile static EventID putAlleventId2 = null; protected volatile static EventID putAlleventId3 = null; protected volatile static EventID putAlleventId4 = null; protected volatile static EventID putAlleventId5 = null; protected volatile static EntryEvent putAllevent1 = null; protected volatile static EntryEvent putAllevent2 = null; protected volatile static EntryEvent putAllevent3 = null; protected volatile static EntryEvent putAllevent4 = null; protected volatile static EntryEvent putAllevent5 = null; protected final static String PUTALL_KEY1 = "putAllKey1"; protected final static String PUTALL_KEY2 = "putAllKey2"; protected final static String PUTALL_KEY3 = "putAllKey3"; protected final static String PUTALL_KEY4 = "putAllKey4"; protected final static String PUTALL_KEY5 = "putAllKey5"; private static String PUTALL_VALUE1 = "putAllValue1"; private static String PUTALL_VALUE2 = "putAllValue2"; private static String PUTALL_VALUE3 = "putAllValue3"; private static String PUTALL_VALUE4 = "putAllValue4"; private static String PUTALL_VALUE5 = "putAllValue5"; /** * This test: * 1) creates a client server configuration * 2) asserts that the ThreadIdToSequenceIdMap is not null but is empty (on the client) * 3) does a put on the server * 4) Wait till put is received by the server (and also records the eventId in a variable) and returns the eventId generated on the server * 5) asserts that the ThreadIdToSequenceIdMap is not null and has one entry (on the client side) and returns the eventId stored in the map * 6) verifies the equality of the two event ids * * @throws Exception */ public void testPutAll() throws Exception { setReceivedOperationToFalse(); client2.invoke(PutAllDUnitTest.class, "setReceivedOperationToFalse"); createClientServerConfiguration(); EventID[] eventIds1 = (EventID[])client1.invoke(PutAllDUnitTest.class, "putAll"); assertNotNull(eventIds1); // wait for key to propagate till client // assert map not null on client client2.invoke(PutAllDUnitTest.class, "waitTillOperationReceived"); waitTillOperationReceived(); EventID[] eventIds2 = (EventID[])client2.invoke(PutAllDUnitTest.class, "assertThreadIdToSequenceIdMapHasEntryIds"); assertNotNull(eventIds2); server1.invoke(PutAllDUnitTest.class, "assertGotAllValues"); server2.invoke(PutAllDUnitTest.class, "assertGotAllValues"); client1.invoke(PutAllDUnitTest.class, "assertCallbackArgs"); client2.invoke(PutAllDUnitTest.class, "assertGotAllValues"); client2.invoke(PutAllDUnitTest.class, "assertCallbackArgs"); server1.invoke(PutAllDUnitTest.class, "assertCallbackArgs"); server2.invoke(PutAllDUnitTest.class, "assertCallbackArgs"); assertGotAllValues(); assertCallbackArgs(); EventID[] eventIds3 = (EventID[])assertThreadIdToSequenceIdMapHasEntryIds(); for (int i = 0; i < 5; i++) { assertNotNull(eventIds1[i]); assertNotNull(eventIds2[i]); assertEquals(eventIds1[i], eventIds2[i]); } for (int i = 0; i < 5; i++) { assertNotNull(eventIds1[i]); assertNotNull(eventIds3[i]); assertEquals(eventIds1[i], eventIds3[i]); } } public static void setReceivedOperationToFalse(){ receivedOperation = false; } public static void assertGotAllValues() { Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); assertTrue(region.get(PUTALL_KEY1).equals(PUTALL_VALUE1)); assertTrue(region.get(PUTALL_KEY2).equals(PUTALL_VALUE2)); assertTrue(region.get(PUTALL_KEY3).equals(PUTALL_VALUE3)); assertTrue(region.get(PUTALL_KEY4).equals(PUTALL_VALUE4)); assertTrue(region.get(PUTALL_KEY5).equals(PUTALL_VALUE5)); } public static void assertCallbackArgs() { assertEquals("putAllCallbackArg", putAllevent1.getCallbackArgument()); assertEquals("putAllCallbackArg", putAllevent2.getCallbackArgument()); assertEquals("putAllCallbackArg", putAllevent3.getCallbackArgument()); assertEquals("putAllCallbackArg", putAllevent4.getCallbackArgument()); assertEquals("putAllCallbackArg", putAllevent5.getCallbackArgument()); } /** * does an update and return the eventid generated. Eventid is caught in the * listener and stored in a static variable* */ public static Object[] putAll() { Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); try { Map map = new LinkedHashMap(); map.put(PUTALL_KEY1,PUTALL_VALUE1); map.put(PUTALL_KEY2,PUTALL_VALUE2); map.put(PUTALL_KEY3,PUTALL_VALUE3); map.put(PUTALL_KEY4,PUTALL_VALUE4); map.put(PUTALL_KEY5,PUTALL_VALUE5); region.putAll(map, "putAllCallbackArg"); EventID[] evids = new EventID[5]; evids[0] = putAlleventId1; evids[1] = putAlleventId2; evids[2] = putAlleventId3; evids[3] = putAlleventId4; evids[4] = putAlleventId5; assertNotNull(evids[0]); assertNotNull(evids[1]); assertNotNull(evids[2]); assertNotNull(evids[3]); assertNotNull(evids[4]); return evids; } catch (Exception e) { fail("put failed due to " + e); } return null; } /** Object to wait on till create is received **/ protected static Object lockObject = new Object(); /** boolean to signify receipt of create **/ protected static volatile boolean receivedOperation = false; /** wait till create is received. listener will send a notification if create is received**/ public static void waitTillOperationReceived() { synchronized (lockObject) { if (!receivedOperation) { try { lockObject.wait(10000); } catch (InterruptedException e) { fail("interrupted"); } } if (!receivedOperation) { fail(" operation should have been received but it has not been received yet"); } } } /** * Listener which sends a notification after create to waiting threads and also extracts teh event id * storing it in a static variable * */ static class HAEventIdPropagationListenerForClient2 extends CacheListenerAdapter { private int putAllReceivedCount =0; public void afterCreate(EntryEvent event) { boolean shouldNotify = false; Object key = event.getKey(); if (key.equals(PUTALL_KEY1)) { putAllReceivedCount++; putAlleventId1 = (EventID)assertThreadIdToSequenceIdMapHasEntryId(); putAllevent1 = event; } else if (key.equals(PUTALL_KEY2)) { putAllReceivedCount++; putAlleventId2 = (EventID)assertThreadIdToSequenceIdMapHasEntryId(); putAllevent2 = event; } else if (key.equals(PUTALL_KEY3)) { putAllReceivedCount++; putAlleventId3 = (EventID)assertThreadIdToSequenceIdMapHasEntryId(); putAllevent3 = event; } else if (key.equals(PUTALL_KEY4)) { putAllReceivedCount++; putAlleventId4 = (EventID)assertThreadIdToSequenceIdMapHasEntryId(); putAllevent4 = event; } else if (key.equals(PUTALL_KEY5)) { putAllReceivedCount++; putAlleventId5 = (EventID)assertThreadIdToSequenceIdMapHasEntryId(); putAllevent5 = event; } if(putAllReceivedCount==5){ shouldNotify = true; } if(shouldNotify){ synchronized (lockObject) { receivedOperation = true; lockObject.notify(); } } } } /** * Listener which sends a notification after create to waiting threads and also extracts teh event ids * storing them in static variables * */ static class HAEventIdPropagationListenerForClient1 extends CacheListenerAdapter { private int putAllReceivedCount =0; public void afterCreate(EntryEvent event) { getLogWriter().fine(" entered after created with "+event.getKey()); boolean shouldNotify = false; Object key = event.getKey(); if (key.equals(PUTALL_KEY1)) { putAllReceivedCount++; putAlleventId1 = ((EntryEventImpl)event).getEventId(); assertNotNull(putAlleventId1); putAllevent1 = event; } else if (key.equals(PUTALL_KEY2)) { putAllReceivedCount++; putAlleventId2 = ((EntryEventImpl)event).getEventId(); assertNotNull(putAlleventId2); putAllevent2 = event; } else if (key.equals(PUTALL_KEY3)) { putAllReceivedCount++; putAlleventId3 = ((EntryEventImpl)event).getEventId(); assertNotNull(putAlleventId3); putAllevent3 = event; } else if (key.equals(PUTALL_KEY4)) { putAllReceivedCount++; putAlleventId4 = ((EntryEventImpl)event).getEventId(); assertNotNull(putAlleventId4); putAllevent4 = event; } else if (key.equals(PUTALL_KEY5)) { putAllReceivedCount++; putAlleventId5 =((EntryEventImpl)event).getEventId(); assertNotNull(putAlleventId5); putAllevent5 = event; } if(putAllReceivedCount==5){ shouldNotify = true; } if(shouldNotify){ synchronized (lockObject) { receivedOperation = true; lockObject.notify(); } } } } }
34.759599
141
0.702224
c3ad877ebefa4e4a2021e4467662da3fc1f5044d
7,900
/* * VennEuler -- A Venn and Euler Diagram program. * * Copyright 2009 by Leland Wilkinson. * * The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the License. */ package edu.uic.ncdm.venn; public class Eigen { private Eigen() {} public static void eigenSymmetric(double[][] a, double[][] eigenvectors, double[] eigenvalues) { // eigenvalues and eigenvectors for dense system (A-lambda*I)x = 0 // returns eigenvectors in columns double[] e = new double[eigenvalues.length]; Eigen.tred2(a, eigenvectors, eigenvalues, e); Eigen.imtql2(eigenvectors, eigenvalues, e); Eigen.sort(eigenvalues, eigenvectors); } private static void tred2(double[][] a, double[][] z, double[] d, double[] e) { /* Tridiagonalization of symmetric matrix. * This method is a translation of the Algol procedure tred2(), * Wilkinson and Reinsch, Handbook for Auto. Comp., Vol II-Linear Algebra, (1971). * Converted to Java by Leland Wilkinson. */ int i, j, jp1, k, l, n; double f, g, h, hh, scale; n = d.length; for (i = 0; i < n; i++) { for (j = 0; j <= i; j++) z[i][j] = a[i][j]; } if (n > 1) { for (i = n - 1; i > 0; i--) { l = i - 1; h = 0.0; scale = 0.0; if (l > 0) { for (k = 0; k <= l; k++) scale += Math.abs(z[i][k]); } if (scale == 0.0) e[i] = z[i][l]; else { for (k = 0; k <= l; k++) { z[i][k] /= scale; h += z[i][k] * z[i][k]; } f = z[i][l]; g = f < 0.0 ? Math.sqrt(h) : -Math.sqrt(h); e[i] = scale * g; h -= f * g; z[i][l] = f - g; f = 0.0; for (j = 0; j <= l; j++) { z[j][i] = z[i][j] / (scale * h); g = 0.0; for (k = 0; k <= j; k++) g += z[j][k] * z[i][k]; jp1 = j + 1; if (l >= jp1) { for (k = jp1; k <= l; k++) g += z[k][j] * z[i][k]; } e[j] = g / h; f += e[j] * z[i][j]; } hh = f / (h + h); for (j = 0; j <= l; j++) { f = z[i][j]; g = e[j] - hh * f; e[j] = g; for (k = 0; k <= j; k++) z[j][k] = z[j][k] - f * e[k] - g * z[i][k]; } for (k = 0; k <= l; k++) z[i][k] *= scale; } d[i] = h; } } d[0] = 0.0; e[0] = 0.0; for (i = 0; i < n; i++) { l = i - 1; if (d[i] != 0.0) { for (j = 0; j <= l; j++) { g = 0.0; for (k = 0; k <= l; k++) g += z[i][k] * z[k][j]; for (k = 0; k <= l; k++) z[k][j] -= g * z[k][i]; } } d[i] = z[i][i]; z[i][i] = 1.0; if (l >= 0) { for (j = 0; j <= l; j++) { z[i][j] = 0.0; z[j][i] = 0.0; } } } } private static int imtql2(double[][] z, double[] d, double[] e) { /* Implicit QL iterations on tridiagonalized matrix. * This method is a translation of the Algol procedure imtql2(), * Wilkinson and Reinsch, Handbook for Auto. Comp., Vol II-Linear Algebra, (1971). * Converted to Java by Leland Wilkinson. */ int i, ii, ip1, j, k, l, lp1, m, mm, mml, n; double b, c, f, g, p, r, s; double EPSILON = 1.0e-15; n = d.length; if (n == 1) return 0; for (i = 1; i < n; i++) e[i - 1] = e[i]; e[n - 1] = 0.0; mm = 0; for (l = 0; l < n; l++) { lp1 = l + 1; j = 0; for (; ;) { for (m = l; m < n; m++) { mm = m; if (m == n - 1) break; if (Math.abs(e[m]) <= EPSILON * (Math.abs(d[m]) + Math.abs(d[m + 1]))) break; } m = mm; p = d[l]; if (m == l) break; if (j == 30) return l; j++; g = (d[lp1] - p) / (2.0 * e[l]); r = Math.sqrt(g * g + 1.0); g = d[m] - p + e[l] / (g + (g < 0.0 ? -r : r)); s = 1.0; c = 1.0; p = 0.0; mml = m - l; for (ii = 1; ii <= mml; ii++) { i = m - ii; ip1 = i + 1; f = s * e[i]; b = c * e[i]; if (Math.abs(f) >= Math.abs(g)) { c = g / f; r = Math.sqrt(c * c + 1.0); e[ip1] = f * r; s = 1.0 / r; c *= s; } else { s = f / g; r = Math.sqrt(s * s + 1.0); e[ip1] = g * r; c = 1.0 / r; s *= c; } g = d[ip1] - p; r = (d[i] - g) * s + 2.0 * c * b; p = s * r; d[ip1] = g + p; g = c * r - b; for (k = 0; k < n; k++) { f = z[k][ip1]; z[k][ip1] = s * z[k][i] + c * f; z[k][i] = c * z[k][i] - s * f; } } d[l] -= p; e[l] = g; e[m] = 0.0; } } return 0; } private static void sort(double[] d, double[][] z) { int l; int k; int j; int i; int ip1; double p; int ii; int n = d.length; /* Sort by eigenvalues (descending) */ for (l = 1; l <= n; l = 3 * l + 1) ; while (l > 2) { l = l / 3; k = n - l; for (j = 0; j < k; j++) { i = j; while (i >= 0) { ip1 = i + l; if (d[i] < d[ip1] || Double.isNaN(d[i])) { p = d[i]; d[i] = d[ip1]; d[ip1] = p; for (ii = 0; ii < n; ii++) { p = z[ii][i]; z[ii][i] = z[ii][ip1]; z[ii][ip1] = p; } i = i - l; } else break; } } } } }
33.474576
100
0.293924
a436ada4c604cff98e0fd9bcbf487d5515c9fa40
6,875
import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Administrator */ public class MyScheduleTableModel extends AbstractTableModel { int standardColIndex = 3;//기준 칼럼 index=2;{col={subject, protected Object[][] data; private boolean[][] backUpState; protected String[] columnNames; // Class[] titleTypes = new Class[]{ // java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class // }; private boolean[][] state; final int MAX_SUBJECT = 50; private int colNum; private List<Integer> groupTimeList; public MyScheduleTableModel() { super(); colNum = 10; //if(english) // MyScheduleTableModelHelper_Eng helper = new MyScheduleTableModelHelper_Eng(0, colNum); MyScheduleTableModelHelper helper = new MyScheduleTableModelHelper(0, colNum); this.data = helper.getData(); this.columnNames = helper.getColTitleArr(); this.state = helper.getState(); // this.backUpState= state.clone(); // data=helper.getData(); } public int getStandardCalIndex() { return standardColIndex; } public MyScheduleTableModel(String[] title, Object[][] data, boolean[][] state, List<Integer> groupList, int standardColIndex) { this.groupTimeList = groupList; this.columnNames = title; this.standardColIndex = standardColIndex; // if(Rooibos.ENGLISH) setColumnName("Reference", this.standardColIndex); setColumnName("기준", this.standardColIndex); colNum = title.length; this.data = data; this.state = state; backUpState = new boolean[data.length][columnNames.length]; int numRows = getRowCount(); int numCols = getColumnCount(); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { backUpState[i][j] = this.state[i][j]; } } } public void setColumnName(String s, int index) { columnNames[index] = s; fireTableStructureChanged(); } public Class getColumnClass(int c) { // return getValueAt(0, c).getClass(); Class type = String.class; switch (c) { case 0: type = Integer.class; break; case 2: type = Boolean.class; break; } return type; } public String getColumnName(int col) { return columnNames[col]; } @Override public int getRowCount() { if (data == null) { return 0; } for (int i = 0; i < data.length; i++) { if (data[i] == null || data[i].toString().equals("")) { return i; } } return data.length; } @Override public boolean isCellEditable(int row, int col) { boolean canEdit = false; if (col == standardColIndex) { canEdit = true; } else if (col == 2) {//(getColumnName(col).equals("활성화")) { if (data[row][1] != null) {//if data is null means row <start canEdit = true; } } return canEdit; } @Override public int getColumnCount() { return columnNames.length; } @Override public Object getValueAt(int row, int col) { return data[row][col]; } public Object[][] getData() { return data; } public void setValueAt(Object value, int row, int col) { Calendar calendar = Calendar.getInstance(); if (col == 2) { boolean tmp = (boolean) value; if (!tmp) { Arrays.fill(state[row], false); } else { for( int j=0; j<getColumnCount();j++) state[row][j] = backUpState[row][j]; } } if (col == standardColIndex) { // int old=data[row][col] ; Date oldDate = (Date) data[row][col]; Date newDate = (Date) value; calendar.setTime(oldDate); System.out.print("oldDate [" + row + " ][ " + col + "]\t" + calendar.getTime()); long diff = newDate.getTime() - oldDate.getTime(); for (int k = 3; k < getColumnCount(); k++) { if (data[row][k] == null) { break; } else if (k == standardColIndex) { continue; } oldDate = (Date) data[row][k];//선택된 셀: 기준시간 data[row][k] = new Date(oldDate.getTime() + diff); fireTableCellUpdated(row, k); } } data[row][col] = value; if (value instanceof Date) { calendar.setTime((Date) value); System.out.println(" ===New Data [" + row + "][" + col + "]\t" + calendar.getTime()); } fireTableCellUpdated(row, col); // printDebugData(); } private void printDebugData() { int numRows = getRowCount(); int numCols = getColumnCount(); for (int i = 0; i < numRows; i++) { System.out.print(" row " + i + ":"); for (int j = 0; j < numCols; j++) { System.out.print(" " + data[i][j] + "=>" + state[i][j]); } System.out.println(); } System.out.println("--------------------------"); } public Object getStateAt(int row, int col) { return state[row][col]; } public void setStateAt(boolean b, int row, int col) { state[row][col] = b; } public boolean[][] getState() { return this.state; } }
31.392694
800
0.563927
c144387a4d5edc06b5646f3f323648d68e3ae609
1,836
package com.facebook.react.cxxbridge; import android.content.Context; import com.facebook.react.devsupport.DebugServerException; public abstract class JSBundleLoader { public abstract String loadScript(CatalystInstanceImpl catalystInstanceImpl); public static JSBundleLoader createAssetLoader(final Context context, final String assetUrl) { return new JSBundleLoader() { public String loadScript(CatalystInstanceImpl instance) { instance.loadScriptFromAssets(context.getAssets(), assetUrl); return assetUrl; } }; } public static JSBundleLoader createFileLoader(final String fileName) { return new JSBundleLoader() { public String loadScript(CatalystInstanceImpl instance) { instance.loadScriptFromFile(fileName, fileName); return fileName; } }; } public static JSBundleLoader createCachedBundleFromNetworkLoader(final String sourceURL, final String cachedFileLocation) { return new JSBundleLoader() { public String loadScript(CatalystInstanceImpl instance) { try { instance.loadScriptFromFile(cachedFileLocation, sourceURL); return sourceURL; } catch (Exception e) { throw DebugServerException.makeGeneric(e.getMessage(), e); } } }; } public static JSBundleLoader createRemoteDebuggerBundleLoader(final String proxySourceURL, final String realSourceURL) { return new JSBundleLoader() { public String loadScript(CatalystInstanceImpl instance) { instance.setSourceURLs(realSourceURL, proxySourceURL); return realSourceURL; } }; } }
37.469388
127
0.647059
aae77db2cb4e8bfe4af2837b9cc71ed6d8dd4900
467
package base.iface; import java.util.List; import thriftContract.TDDIKeyValueMap; public interface IBaseElement { boolean isSetId(); long getId(); void setId(long id); boolean isSetName(); String getName(); void setName(String name); boolean isSetDescription(); String getDescription(); void setDescription(String name); boolean isSetKeyValueMaps(); List<TDDIKeyValueMap> getKeyValueMaps(); void setKeyValueMaps(List<TDDIKeyValueMap> tKeyValueMaps); }
22.238095
59
0.779443
9c8ea9a820ebe742e5e99c6a51a2703573e42c8c
2,564
// referenced class Solution { private int[][] H; public void findSecretWord(String[] wordlist, Master master) { int n = wordlist.length; H = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int match = 0; for (int k = 0; k < 6; k++) { if (wordlist[i].charAt(k) == wordlist[j].charAt(k)) { match++; } } H[i][j] = match; H[j][i] = match; } } List<Integer> path = new ArrayList(); List<Integer> possible = new ArrayList(); for (int i = 0; i < n; i++) { possible.add(i); } while (!possible.isEmpty()) { int guess = solve(possible, path); int matches = master.guess(wordlist[guess]); if (matches == wordlist[0].length()) { return; } List<Integer> possible2 = new ArrayList(); for (Integer j: possible) { if (H[guess][j] == matches) { possible2.add(j); } } possible = possible2; path.add(guess); } } public int solve(List<Integer> possible, List<Integer> path) { if (possible.size() <= 2) { return possible.get(0); } List<Integer> ansgrp = possible; int ansguess = -1; for (int guess = 0; guess < H.length; guess++) { if (!path.contains(guess)) { ArrayList<Integer>[] groups = new ArrayList[7]; for (int i = 0; i < 7; i++) { groups[i] = new ArrayList<Integer>(); } for (Integer j: possible) { if (j != guess) { groups[H[guess][j]].add(j); } } ArrayList<Integer> maxgroup = groups[0]; for (int i = 0; i < 7; i++) { if (groups[i].size() > maxgroup.size()) { maxgroup = groups[i]; } } if (maxgroup.size() < ansgrp.size()) { ansgrp = maxgroup; ansguess = guess; } } } return ansguess; } }
29.813953
73
0.365055
09195ab03b41c1bdc6e835c9a3fa0a0f40396ac0
180
package org.vatplanner.importer.postgis.status.utils; @FunctionalInterface public interface ExceptionalBiConsumer<T, U> { void accept(T value1, U value2) throws Exception; }
22.5
53
0.788889
0f7add868865761acc6d8efc596a19fb67cdd492
585
package no.nnsn.seisanquakemljpa.models.quakeml.v20.helpers.resourcemetadata; import lombok.Data; import no.nnsn.seisanquakemljpa.models.quakeml.v20.helpers.common.CountryCodeURI; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @Data @Embeddable @XmlAccessorType(XmlAccessType.FIELD) public class PostalAddress { private String streetAddress; private String locality; private String postalCode; @Embedded private CountryCodeURI country; }
26.590909
81
0.817094
f7281c6a0e986db884382642f182f5ae7a07f7a6
1,887
/* * Copyright (c) 2022. Alwin Ibba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ibbaa.keepitup.ui.validation; import android.graphics.Color; import android.widget.EditText; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; import org.junit.Test; import org.junit.runner.RunWith; import net.ibbaa.keepitup.test.mock.TestRegistry; import static org.junit.Assert.assertEquals; @SmallTest @RunWith(AndroidJUnit4.class) public class TextColorValidatingWatcherTest { @Test public void testChangeTextColor() { EditText testEditText = new EditText(TestRegistry.getContext()); TextColorValidatingWatcher watcher = new TextColorValidatingWatcher(testEditText, this::validateTrue, Color.BLACK, Color.RED); watcher.afterTextChanged(null); assertEquals(Color.BLACK, testEditText.getCurrentTextColor()); watcher = new TextColorValidatingWatcher(testEditText, this::validateFalse, Color.BLACK, Color.RED); watcher.afterTextChanged(null); assertEquals(Color.RED, testEditText.getCurrentTextColor()); } @SuppressWarnings({"SameReturnValue"}) private boolean validateTrue(EditText editText) { return true; } @SuppressWarnings({"SameReturnValue"}) private boolean validateFalse(EditText editText) { return false; } }
33.105263
134
0.747218
943fa6ef6134737fedc02f63c7a680b6ab9dd2e1
4,545
package com.hortonworks.streamline.streams.cluster.service.metadata.json; import com.hortonworks.streamline.streams.catalog.Component; import com.hortonworks.streamline.streams.catalog.ServiceConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.Principal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Principals { private static final Logger LOG = LoggerFactory.getLogger(Principals.class); /* * The map Key is the principal's service component . Val is list of principals for this service. * Typically it is one principal per host running this service. */ private Map<String, List<Principal>> principals; public Principals(Map<String, List<Principal>> principals) { this.principals = principals; } /** * Instance built from services configurations in Ambari */ public static Principals fromAmbariConfig(ServiceConfiguration serviceConfig, Map<String, Component> serviceToComponent) throws IOException { return fromAmbariConfig(serviceConfig.getConfigurationMap(), serviceToComponent); } /** * Instance built from map with Ambari configurations */ public static Principals fromAmbariConfig(Map<String, String> config, Map<String, Component> serviceToComponent) throws IOException { final Map<String, List<Principal>> allPrincs = new HashMap<>(); for (Map.Entry<String, Component> stc : serviceToComponent.entrySet()) { // stc - serviceToComponent final String serviceName = stc.getKey(); final Map<String, List<Principal>> princs = config.entrySet() .stream() .filter((e) -> e.getKey().contains("principal") && e.getKey().replace("_principal_name","").equals(serviceName)) .peek((e) -> LOG.debug("Processing Ambari property [{}]=[{}] for service [{}]", e.getKey(), e.getValue(), serviceName)) .collect(Collectors.toMap( (e) -> { // Extracts the principal service component from Ambari property key String key = e.getKey().split("principal")[0]; return key.substring(0, key.length() - 1); // remove _ at the end }, (e) -> stc.getValue().getHosts() // get hosts for service component (e.g nimbus, storm_ui, kafka broker) .stream() .map((host) -> host == null || host.isEmpty() ? UserPrincipal.fromPrincipal(e.getValue()) : ServicePrincipal.forHost(e.getValue(), host)) .collect(Collectors.toList()))); LOG.debug("Processed {}", princs); allPrincs.putAll(princs); } return new Principals(allPrincs); } /** * Instance built from service configuration properties (e.g hive-metastore.xml, hbase-site.xml) */ public static Principals fromServiceProperties(ServiceConfiguration serviceConfig, Component component) throws IOException { return fromServiceProperties(serviceConfig.getConfigurationMap(), component); } /** * Instance built from service configuration properties (e.g hive-metastore.xml, hbase-site.xml) */ public static Principals fromServiceProperties(Map<String, String> props, Component component) throws IOException { final Map<String, List<Principal>> princs = props.entrySet() .stream() .filter((e) -> e.getKey().contains("principal")) .collect(Collectors.toMap( Map.Entry::getKey, (e) -> component.getHosts() // get hosts for service component (e.g HBase master or Hive metastore) .stream() .map((host) -> ServicePrincipal.forHost(e.getValue(), host)) .collect(Collectors.toList()))); return new Principals(princs); } public Map<String, List<Principal>> toMap() { return principals; } @Override public String toString() { return "{" + "Principals=" + principals + '}'; } }
43.285714
139
0.592079
3c4a496c747fcf34692c042f460d3624dc630aa6
3,835
package org.twinone.bleprofile; import android.annotation.TargetApi; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.os.Build; import android.os.ParcelUuid; import android.util.Log; import org.twinone.util.DoubleValueConverter; import java.util.Arrays; import java.util.UUID; /** * Created by johnny on 10/21/15. */ public class TemperatureProfile { private static final String TAG = TemperatureProfile.class.getSimpleName(); /** * See https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.health_thermometer.xml * for details */ private static final UUID TEMPERATURE_SERVICE_UUID = UUID .fromString("00001809-0000-1000-8000-00805f9b34fb"); /** * See https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic * .temperature_measurement.xml * for details */ private static final UUID TEMPERATURE_MEASUREMENT_CHAR_UUID = UUID .fromString("00002A1C-0000-1000-8000-00805f9b34fb"); public static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private static final double INITIAL_TEMPERATURE_MEASUREMENT_VALUE = 98.5f; private BluetoothGattService mTemperatureService; private BluetoothGattCharacteristic mTemperatureMeasurementCharacteristic; @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public TemperatureProfile() { mTemperatureMeasurementCharacteristic = new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_CHAR_UUID, BluetoothGattCharacteristic.PROPERTY_INDICATE, BluetoothGattCharacteristic.PERMISSION_READ); mTemperatureMeasurementCharacteristic.addDescriptor( getClientCharacteristicConfigurationDescriptor()); mTemperatureService = new BluetoothGattService(TEMPERATURE_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); mTemperatureService.addCharacteristic(mTemperatureMeasurementCharacteristic); setInitialValues(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static BluetoothGattDescriptor getClientCharacteristicConfigurationDescriptor() { return new BluetoothGattDescriptor(CCCD, (BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE)); } public void setInitialValues() { setTemperatureMeasurementValue(INITIAL_TEMPERATURE_MEASUREMENT_VALUE); } public BluetoothGattService getBluetoothGattService() { return mTemperatureService; } public ParcelUuid getServiceUUID() { return new ParcelUuid(TEMPERATURE_SERVICE_UUID); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public void setTemperatureMeasurementValue(double temperatureMeasurementValue) { DoubleValueConverter doubleValue = new DoubleValueConverter(); doubleValue.setValue(temperatureMeasurementValue); Log.d(TAG, "mantissa = " + doubleValue.getMantissa() + " exponent = " + doubleValue.getExponent()); mTemperatureMeasurementCharacteristic.setValue(new byte[]{0, 0, 0, 0, 0}); mTemperatureMeasurementCharacteristic.setValue(doubleValue.getMantissa(), doubleValue.getExponent(), BluetoothGattCharacteristic.FORMAT_FLOAT, /* offset */ 1); Log.d(TAG, Arrays.toString(mTemperatureMeasurementCharacteristic.getValue())); } public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) { Log.v(TAG, "writeCharacteristic"); if (offset != 0) { return BluetoothGatt.GATT_INVALID_OFFSET; } if (value.length != 1) { return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH; } return BluetoothGatt.GATT_SUCCESS; } public BluetoothGattCharacteristic getTemperatureMeasurementCharacteristic() { return mTemperatureMeasurementCharacteristic; } }
34.54955
125
0.811473
e6a71a80c1cf944f951f27240014a67cafdeb38b
486
package SimulationTest.one.exam6.exam1.part3; import java.time.LocalDate; /* What will be the result of compiling and executing Test class? */ public class Test69 { public static void main(String[] args) { LocalDate newYear = LocalDate.of(2018, 1, 1); LocalDate christmas = LocalDate.of(2018, 12, 25); boolean flag1 = newYear.isAfter(christmas); boolean flag2 = newYear.isBefore(christmas); System.out.println(flag1 + ":" + flag2); } }
30.375
62
0.67284
b76771aaf44099591a65efab969f9ff06b653db4
646
package entidades; public class Aluno { private int idAluno; private String loginAluno; private String senhaAluno; private String nivel; public String getNivel(){return nivel;} public void setNivel(String nivel){this.nivel = nivel;} public int getIdAluno(){return idAluno;} public void setIdAluno(int idAluno){this.idAluno = idAluno;} public String getLoginAluno(){return loginAluno;} public void setLoginAluno(String loginAluno){this.loginAluno = loginAluno;} public String getSenhaAluno(){return senhaAluno;} public void setSenhaAluno(String senhaAluno){this.senhaAluno = senhaAluno;} }
40.375
87
0.735294
775eeddedcc2e315aa465a124fc635c371efb183
919
package org.nibiru.model.core.impl.bind; import static com.google.common.base.Preconditions.checkNotNull; import org.nibiru.model.core.api.Value; import org.nibiru.model.core.impl.java.JavaType; import org.nibiru.model.core.impl.java.JavaValue; import com.google.common.base.Function; public class Bind<T> { private final Value<T> value; private Bind(Value<T> value) { this.value = value; } public static <X> Bind<X> on(Value<X> value) { checkNotNull(value); return new Bind<>(value); } public <X> Bind<X> map(final Function<T, X> converter) { checkNotNull(converter); final JavaValue<X> targetValue = JavaValue.of(JavaType.ofUnchecked(Object.class)); value.addObserver(() -> { targetValue.set(converter.apply(value.get())); }); return new Bind<>(targetValue); } public void to(final Value<T> target) { checkNotNull(target); value.addObserver(() -> target.set(value.get())); } }
24.837838
84
0.717084
24d57b5442925b78ad107b1447f90be47d1fa78e
3,887
/** */ package roadblock.emf.ibl.Ibl; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>ATGC Arrange</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link roadblock.emf.ibl.Ibl.ATGCArrange#getPartList <em>Part List</em>}</li> * </ul> * * @see roadblock.emf.ibl.Ibl.IblPackage#getATGCArrange() * @model kind="class" * @generated */ public class ATGCArrange extends ATGCDirective { /** * The cached value of the '{@link #getPartList() <em>Part List</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPartList() * @generated * @ordered */ protected EList<MolecularSpecies> partList; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ATGCArrange() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return IblPackage.Literals.ATGC_ARRANGE; } /** * Returns the value of the '<em><b>Part List</b></em>' containment reference list. * The list contents are of type {@link roadblock.emf.ibl.Ibl.MolecularSpecies}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Part List</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Part List</em>' containment reference list. * @see roadblock.emf.ibl.Ibl.IblPackage#getATGCArrange_PartList() * @model containment="true" * @generated */ public List<MolecularSpecies> getPartList() { if (partList == null) { partList = new EObjectContainmentEList<MolecularSpecies>(MolecularSpecies.class, this, IblPackage.ATGC_ARRANGE__PART_LIST); } return partList; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case IblPackage.ATGC_ARRANGE__PART_LIST: return ((InternalEList<?>)getPartList()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case IblPackage.ATGC_ARRANGE__PART_LIST: return getPartList(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case IblPackage.ATGC_ARRANGE__PART_LIST: getPartList().clear(); getPartList().addAll((Collection<? extends MolecularSpecies>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case IblPackage.ATGC_ARRANGE__PART_LIST: getPartList().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case IblPackage.ATGC_ARRANGE__PART_LIST: return partList != null && !partList.isEmpty(); } return super.eIsSet(featureID); } } // ATGCArrange
24.29375
126
0.660149
1cde6bdd5733d649f811d7e80720349e7c0ba3c7
3,428
package com.willlee.leetcode.problems201_300; public class Leetcode221 { public int maximalSquare(char[][] matrix) { int maxSide = 0; if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return maxSide; } int rows = matrix.length, columns = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (matrix[i][j] == '1') { // 遇到一个 1 作为正方形的左上角 maxSide = Math.max(maxSide, 1); // 计算可能的最大正方形边长 int currentMaxSide = Math.min(rows - i, columns - j); for (int k = 1; k < currentMaxSide; k++) { // 判断新增的一行一列是否均为 1 boolean flag = true; if (matrix[i + k][j + k] == '0') { break; } for (int m = 0; m < k; m++) { if (matrix[i + k][j + m] == '0' || matrix[i + m][j + k] == '0') { flag = false; break; } } if (flag) { maxSide = Math.max(maxSide, k + 1); } else { break; } } } } } int maxSquare = maxSide * maxSide; return maxSquare; } public int maximalSquare1(char[][] matrix) { int maxSide = 0; if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return maxSide; } int rows = matrix.length, columns = matrix[0].length; int[][] dp = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (matrix[i][j] == '1') { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; } maxSide = Math.max(maxSide, dp[i][j]); } } } int maxSquare = maxSide * maxSide; return maxSquare; } int m; int n; int res = 0; public int maximalSquare2(char[][] matrix) { m = matrix.length; if (m == 0) return 0; n = matrix[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') { dfs(matrix, 1, i, j); } } } return res; } // 以 x,y为起点 dfs void dfs(char[][] matrix, int len, int x, int y) { if (!judge(matrix, x, y, len)) { return; } res = Math.max(res, len * len); dfs(matrix, len + 1, x, y); } boolean judge(char[][] matrix, int x, int y, int len) { if (x + len > m || y + len > n) { return false; } for (int i = x; i < x + len; i++) { for (int j = y; j < y + len; j++) { if (matrix[i][j] != '1') { return false; } } } return true; } }
30.882883
104
0.348308
43ef5805b5c1fee70f481973013ff2eb8c6f8320
5,026
package io.github.polysmee.settings; import android.content.Context; import android.content.SharedPreferences; import androidx.fragment.app.testing.FragmentScenario; import androidx.preference.PreferenceManager; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import io.github.polysmee.R; import io.github.polysmee.settings.fragments.SettingsAppointmentsReminderFragment; import static com.schibsted.spain.barista.assertion.BaristaVisibilityAssertions.assertDisplayed; import static com.schibsted.spain.barista.interaction.BaristaSleepInteractions.sleep; import static java.util.concurrent.TimeUnit.SECONDS; @RunWith(AndroidJUnit4.class) public class SettingsAppointmentsReminderFragmentTest { private static Context context() { return ApplicationProvider.getApplicationContext(); } private static int getSettingsTimeFromAppointmentValueWithDefault0() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context()); return sharedPreferences.getInt(context().getResources().getString(R.string.preference_key_appointments_reminder_notification_time_from_appointment_minutes), 0); } @Before @After public void resetPreference() { PreferenceManager.getDefaultSharedPreferences(context()).edit().putInt( context().getResources().getString(R.string.preference_key_appointments_reminder_notification_time_from_appointment_minutes), context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min)).commit(); } @Before public void createFragment() { FragmentScenario.launchInContainer(SettingsAppointmentsReminderFragment.class); sleep(1, SECONDS); } //used in tests (this test or any other) to know if the fragment is been displayed public static void checkFragmentIsDisplayed() { PreferenceManager.getDefaultSharedPreferences(context()).edit().putInt( context().getResources().getString(R.string.preference_key_appointments_reminder_notification_time_from_appointment_minutes), context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min)).commit(); sleep(1, SECONDS); assertDisplayed(R.string.title_settings_appointments_reminder_notification_time_from_appointment); assertDisplayed(R.string.summary_settings_appointments_reminder_notification_time_from_appointment); assertDisplayed("" + ApplicationProvider.getApplicationContext().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min)); } @Test public void checkFragmentIsWellDisplayed() { checkFragmentIsDisplayed(); } @Test public void preference_time_from_appointment_default() { int expectedPreferenceValue = context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min); int preference_value_time_from_appointment = getSettingsTimeFromAppointmentValueWithDefault0(); Assert.assertEquals(expectedPreferenceValue, preference_value_time_from_appointment); } /** @Test public void preference_time_from_appointment_change_settings_value_up() { Assert.assertEquals(context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min), getSettingsTimeFromAppointmentValueWithDefault0()); int expectedPreferenceValue = context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min)+1; UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); device.pressKeyCode(KeyEvent.KEYCODE_DPAD_RIGHT); sleep(1, SECONDS); int preference_value_time_from_appointment = getSettingsTimeFromAppointmentValueWithDefault0(); Assert.assertEquals(expectedPreferenceValue, preference_value_time_from_appointment); } @Test public void preference_time_from_appointment_change_settings_value_down() { Assert.assertEquals(context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min), getSettingsTimeFromAppointmentValueWithDefault0()); int expectedPreferenceValue = context().getResources().getInteger(R.integer.default_appointment_reminder_notification__time_from_appointment_min)-1; UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); device.pressKeyCode(KeyEvent.KEYCODE_DPAD_LEFT); sleep(1, SECONDS); int preference_value_time_from_appointment = getSettingsTimeFromAppointmentValueWithDefault0(); Assert.assertEquals(expectedPreferenceValue, preference_value_time_from_appointment); }**/ }
53.468085
193
0.809391
26f7347dc36303ee8d143b16136dc09b4faf2cde
1,369
package site.jsun999.service.impl; import site.jsun999.mapper.BaseMapper; import site.jsun999.mapper.UserMapper; import site.jsun999.model.User; import site.jsun999.service.UserService; import site.jsun999.web.exception.GlobalException; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { @Autowired private UserMapper userMapper; @Override public User findByUsername(String username) throws GlobalException { return this.userMapper.getByUsername(username); } @Override public void updatePwd(String username, String oldpwd, String newpwd) throws GlobalException { User user = this.findByUsername(username); if (user == null) { throw new GlobalException(403,"用户名不存在"); } if(!user.getPassword().equals(DigestUtils.md5Hex(oldpwd))) { throw new GlobalException(403,"旧密码不正确"); } User tmp = new User(); tmp.setId(user.getId()); tmp.setPassword(DigestUtils.md5Hex(newpwd)); this.userMapper.updateByPrimaryKeySelective(tmp); } @Override public BaseMapper<User> getBaseMapper() { return this.userMapper; } }
28.520833
97
0.71366
e6924377bed378585a4edcebf3908b1060232ab2
314
package chapter14; /** * Object类是所有类的基类 */ public class ObjectTest { public static void main(String[] args){ Class clazz = new ObjectTest().getClass(); System.out.println(clazz.getName()); //System.out.println(clazz.toString()); System.out.println(clazz.hashCode()); } }
22.428571
50
0.630573