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
9a84ae0f6cd3d51e8d403f5c7563fbc03fb555b4
630
// Copyright 2020 by PostFinance Ltd - all rights reserved package ch.postfinance.devops.fusion.demo.apptest.runner.validation; public class ValidationException extends Exception { private final String field; private final Object expected; private final Object actual; public ValidationException(String field, Object expected, Object actual) { this.field = field; this.expected = expected; this.actual = actual; } @Override public String getLocalizedMessage() { return "Assert on " + field + " failed: Expected '" + expected + "' but was '" + actual + "'!"; } }
30
103
0.679365
abc9d5a085242cff36395d90e835602302064d2f
3,698
/* * Created on 2012/02/20 * Copyright (c) 2010-2012, Wei-ju Wu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Wei-ju Wu nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.zmpp.glk.sound; import java.util.logging.*; import java.util.List; import java.util.ArrayList; import org.zmpp.iff.*; import org.zmpp.glk.GlkIterateResult; public class GlkSoundSystem { private static Logger logger = Logger.getLogger("glk"); private List<GlkSoundChannel> channels = new ArrayList<GlkSoundChannel>(); private int _nextId = 1; public NativeSoundSystem nativeSoundSystem; private GlkSoundChannel channelWithId(int id) { for (GlkSoundChannel channel: channels) { if (channel.id == id) return channel; } return NullSoundChannel.getInstance(); } public void destroyChannel(int channelId) { GlkSoundChannel channel = channelWithId(channelId); channel.stop(); channels.remove(channel); } public GlkIterateResult iterate(int channelId) { GlkSoundChannel channel = null; if (!channels.isEmpty()) { if (channelId == 0) channel = channels.get(0); else { int i = 0; for (; i < channels.size(); i++) { if (channels.get(i).id == channelId) break; } channel = (i >= channels.size() - 1) ? null : channels.get(i + 1); } } return (channel == null) ? new GlkIterateResult(0, 0) : new GlkIterateResult(channel.id, channel.rock); } public void stopChannel(int channelId) { channelWithId(channelId).stop(); } public int createChannel(int rock) { NativeSoundChannel nativeChannel = nativeSoundSystem.createChannel(); GlkSoundChannel newChannel = new GlkSoundChannel(_nextId++, rock, nativeChannel); channels.add(newChannel); return newChannel.id; } public void setVolume(int channelId, int volume) { channelWithId(channelId).setVolume(volume); } public int play(int channelId, int soundnum, int repeats, int notify) { return channelWithId(channelId).play(soundnum, repeats, notify) ? 1 : 0; } public int getRock(int channelId) { return channelWithId(channelId).rock; } }
40.637363
111
0.693889
79566ffe073aeac67b5cd356337f7df0ad7c143c
1,069
// Generated automatically from android.view.ContentInfo for testing purposes package android.view; import android.content.ClipData; import android.net.Uri; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; public class ContentInfo implements Parcelable { protected ContentInfo() {} public Bundle getExtras(){ return null; } public ClipData getClip(){ return null; } public String toString(){ return null; } public Uri getLinkUri(){ return null; } public int describeContents(){ return 0; } public int getFlags(){ return 0; } public int getSource(){ return 0; } public static Parcelable.Creator<ContentInfo> CREATOR = null; public static int FLAG_CONVERT_TO_PLAIN_TEXT = 0; public static int SOURCE_APP = 0; public static int SOURCE_AUTOFILL = 0; public static int SOURCE_CLIPBOARD = 0; public static int SOURCE_DRAG_AND_DROP = 0; public static int SOURCE_INPUT_METHOD = 0; public static int SOURCE_PROCESS_TEXT = 0; public void writeToParcel(Parcel p0, int p1){} }
34.483871
77
0.735267
af1ce0bafc1c6e687fd55649f1effc2466b68a59
2,264
package com.github.sakaguchi3.jbatch002.vavr; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.function.BiConsumer; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Test; import com.github.sakaguchi3.util.UtilRandom; import com.google.common.base.Stopwatch; import io.vavr.concurrent.Future; import io.vavr.control.Try; public class FutureTest { static final Logger LOGGER = LogManager.getLogger(); BiConsumer<String, Stopwatch> printTime = (s, sw) -> { System.out.printf("%13s time: %s\n", s, sw); sw.reset(); sw.start(); }; @Test public void test01() { Future<Float> intFuture = Future.of(() -> 1.0f * 3 / 2) // .await(); assertEquals(intFuture.isCompleted(), (true)); assertEquals(intFuture.get(), (1.5f)); debug(); } @Test public void test02() { Future<Integer> ret01 = Future.of(() -> longTimeComputing(300)); // 評価されていない debug(); assertEquals(ret01.isCompleted(), (false)); int reti01 = ret01.get(); // 評価される debug(); } @Test public void a20test() { Stopwatch sw = Stopwatch.createStarted(); var time = 50; List<Future<Integer>> futures = List.of( // Future.of(() -> longTimeComputing(time)), // Future.of(() -> longTimeComputing(time)), // Future.of(() -> longTimeComputing(time)), // Future.of(() -> longTimeComputing(time))); printTime.accept("fast,", sw); List<Integer> list = futures.parallelStream() // .flatMap(v -> Try.of(() -> v.get()).toJavaStream()) // .collect(Collectors.toList()); printTime.accept("slow,", sw); for (int i = 0; i < 4; i++) { longTimeComputing(time); } printTime.accept("VerySlow,", sw); } // -------------------------------------------------------------------------------- // method // -------------------------------------------------------------------------------- public int longTimeComputing(int time) { try { Thread.sleep(time); } catch (Exception e) { e.printStackTrace(); } return UtilRandom.randInt(); } void debug() { } }
21.980583
85
0.580389
e32ac4ffca9d37d9de6857f20494b93c31e138d9
5,616
package com.cloudinary.android.sample.app; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.net.Uri; import android.provider.DocumentsContract; import android.support.v4.util.Pair; import android.view.WindowManager; import com.cloudinary.utils.StringUtils; import java.io.IOException; import java.io.InputStream; public class Utils { public static Bitmap decodeBitmapStream(Context context, Uri uri, int reqWidth, int reqHeight) throws IOException { InputStream is = context.getContentResolver().openInputStream(uri); // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); is.close(); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; is = context.getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); is.close(); return bitmap == null ? null : getCroppedBitmap(bitmap); } public static Bitmap getCroppedBitmap(Bitmap bitmap) { int dimension = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight(); Bitmap output = Bitmap.createBitmap(dimension, dimension, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); int horizontalDiff = (bitmap.getWidth() - dimension) / 2; int verticalDiff = (bitmap.getHeight() - dimension) / 2; final Rect rect = new Rect(-horizontalDiff, -verticalDiff, bitmap.getWidth() - horizontalDiff, bitmap.getHeight() - verticalDiff); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawCircle(dimension / 2, dimension / 2, dimension / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight && width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; } public static Uri toUri(Context context, int resourceId) { Resources res = context.getResources(); return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + res.getResourcePackageName(resourceId) + '/' + res.getResourceTypeName(resourceId) + '/' + res.getResourceEntryName(resourceId)); } public static int getScreenWidth(Context context) { WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point point = new Point(); window.getDefaultDisplay().getSize(point); return point.x; } public static Pair<String, String> getResourceNameAndType(Context context, Uri uri) { Cursor cursor = null; String type = null; String name = null; try { cursor = context.getContentResolver().query(uri, new String[]{DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_DISPLAY_NAME}, null, null, null); if (cursor != null && cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)); type = cursor.getString(cursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE)); if (StringUtils.isNotBlank(type)) { type = type.substring(0, type.indexOf('/')); } } } finally { if (cursor != null) { cursor.close(); } } if (StringUtils.isBlank(type)) { type = "image"; } return new Pair<>(name, type); } public static void openMediaChooser(Activity activity, int requestCode) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/jpeg", "image/jpg", "image/png", "video/*"}); intent.setType("(*/*"); activity.startActivityForResult(intent, requestCode); } }
40.402878
186
0.665954
b68867b7959be57ab1a4ced063320b0254c475d9
1,471
package java.lang; import com.dragome.commons.javascript.ScriptHelper; import com.dragome.utils.NamingUtils; /** * This is the common base class of all Java language enumeration types. */ public abstract class Enum<E> { private String desc; private int ordinal; /** * Sole constructor. */ protected Enum(String theDesc, int theOrdinal) { desc= theDesc; ordinal= theOrdinal; } /** * Returns the enum constant of the specified enum type with the specified name. * * Note: This method (signature only) is required by the JDK compiler! */ public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) { String enumDragomeName = NamingUtils.javaToDragomeNotation(enumType); ScriptHelper.put("enumType", enumType, null); ScriptHelper.put("enumDragomeName", enumDragomeName, null); ScriptHelper.put("name", name, null); return (T) ScriptHelper.eval("enumType.$$$nativeClass___java_lang_Object.$$clinit_()[\"$$$\"+name+\"___\"+enumDragomeName]", null); } /** * Returns the ordinal of this enumeration constant. */ public int ordinal() { return ordinal; } /** * Returns the name of this enum constant. */ public String toString() { return desc; } public String name() { //TODO revisar return null; } public final Class<E> getDeclaringClass() { Class<?> clazz= getClass(); Class<?> zuper= clazz.getSuperclass(); return (zuper == Enum.class) ? (Class<E>) clazz : (Class<E>) zuper; } }
21.955224
133
0.694086
55855f8efedd380ab161b358a8f8749e9c0b380e
6,588
/* * Copyright 2009 Hannes Wallnoefer <[email protected]> * * 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.ringojs.jsgi; import org.mozilla.javascript.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.lang.reflect.Method; public class JsgiRequest extends ScriptableObject { Scriptable jsgiObject; HttpServletRequest request; HttpServletResponse response; int readonly = PERMANENT | READONLY; Object httpVersion; /** * Prototype constructor */ public JsgiRequest(Context cx, Scriptable scope) throws NoSuchMethodException { setParentScope(scope); setPrototype(ScriptableObject.getObjectPrototype(scope)); defineProperty("host", null, getMethod("getServerName"), null, readonly); defineProperty("port", null, getMethod("getServerPort"), null, readonly); defineProperty("queryString", null, getMethod("getQueryString"), null, readonly); defineProperty("version", null, getMethod("getHttpVersion"), null, readonly); defineProperty("remoteAddress", null, getMethod("getRemoteHost"), null, readonly); defineProperty("scheme", null, getMethod("getUrlScheme"), null, readonly); // JSGI spec and Jack's lint require env.constructor to be Object defineProperty("constructor", ScriptableObject.getProperty(scope, "Object"), DONTENUM); Scriptable jsgi = jsgiObject = cx.newObject(scope); Scriptable version = cx.newArray(scope, new Object[] {Integer.valueOf(0), Integer.valueOf(3)}); ScriptableObject.defineProperty(jsgi, "version", version, readonly); ScriptableObject.defineProperty(jsgi, "multithread", Boolean.TRUE, readonly); ScriptableObject.defineProperty(jsgi, "multiprocess", Boolean.FALSE, readonly); ScriptableObject.defineProperty(jsgi, "async", Boolean.TRUE, readonly); ScriptableObject.defineProperty(jsgi, "runOnce", Boolean.FALSE, readonly); ScriptableObject.defineProperty(jsgi, "cgi", Boolean.FALSE, readonly); } /** * Instance constructor */ public JsgiRequest(Context cx, HttpServletRequest request, HttpServletResponse response, JsgiRequest prototype, Scriptable scope, JsgiServlet servlet) { this.request = request; this.response = response; setPrototype(prototype); setParentScope(scope); Scriptable jsgi = cx.newObject(scope); jsgi.setPrototype(prototype.jsgiObject); ScriptableObject.defineProperty(this, "jsgi", jsgi, PERMANENT); Scriptable headers = cx.newObject(scope); ScriptableObject.defineProperty(this, "headers", headers, PERMANENT); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); String value = request.getHeader(name); name = name.toLowerCase(); headers.put(name, headers, value); } put("scriptName", this, checkString(request.getContextPath() + request.getServletPath())); String pathInfo = request.getPathInfo(); String uri = request.getRequestURI(); // Workaround for Tomcat returning "/" for pathInfo even if URI doesn't end with "/" put("pathInfo", this, "/".equals(pathInfo) && !uri.endsWith("/") ? "" : checkString(pathInfo)); put("method", this, checkString(request.getMethod())); Scriptable env = cx.newObject(scope); ScriptableObject.defineProperty(this, "env", env, PERMANENT); ScriptableObject.defineProperty(env, "servlet", Context.javaToJS(servlet, this), PERMANENT); ScriptableObject.defineProperty(env, "servletRequest", Context.javaToJS(request, this), PERMANENT); ScriptableObject.defineProperty(env, "servletResponse", Context.javaToJS(response, this), PERMANENT); // JSGI spec and Jack's lint require env.constructor to be Object defineProperty("constructor", scope.get("Object", scope), DONTENUM); } public String getServerName() { return checkString(request.getServerName()); } public String getServerPort() { return checkString(Integer.toString(request.getServerPort())); } public String getQueryString() { return checkString(request.getQueryString()); } public Object getHttpVersion() { if (httpVersion == null) { Context cx = Context.getCurrentContext(); Scriptable scope = getParentScope(); String protocol = request.getProtocol(); if (protocol != null) { int major = protocol.indexOf('/'); int minor = protocol.indexOf('.'); if (major > -1 && minor > major) { major = Integer.parseInt(protocol.substring(major + 1, minor)); minor = Integer.parseInt(protocol.substring(minor + 1)); httpVersion = cx.newArray(scope, new Object[] { Integer.valueOf(major), Integer.valueOf(minor)}); } } if (httpVersion == null) { cx.newArray(scope, new Object[0]); } } return httpVersion; } public String getRemoteHost() { return checkString(request.getRemoteHost()); } public String getUrlScheme() { return request.isSecure() ? "https" : "http"; } public Object getServletRequest() { return Context.javaToJS(request, this); } public Object getServletResponse() { return Context.javaToJS(response, this); } private static Method getMethod(String name) throws NoSuchMethodException { return JsgiRequest.class.getDeclaredMethod(name); } private static String checkString(String str) { return str == null ? "" : str; } /** * Return the name of the class. */ @Override public String getClassName() { return "JsgiRequest"; } }
41.433962
109
0.657256
de6d3691d77e6afc3c7ba56d0513473006b28651
78
/** * Created by pczhangyu on 2017/9/5. */ package com.poseidon.web.service;
19.5
36
0.692308
5bf57dc9f20f1feafabf4e7fd8ea64eaaeb1ee2b
295
package com.showka.repository.i; import org.springframework.data.jpa.repository.JpaRepository; import com.showka.entity.TShohinIdoMeisai; import com.showka.entity.TShohinIdoMeisaiPK; public interface TShohinIdoMeisaiRepository extends JpaRepository<TShohinIdoMeisai, TShohinIdoMeisaiPK> { }
26.818182
105
0.854237
4c5d9c170167aba37808096b1d56a27d3ead67fa
2,129
/** * Licensed to Inspektr under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Inspektr 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.github.inspektr.audit.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * States that this method should be logged for auditing purposes. * * @author Alice Leung * @author Dmitriy Kopylenko * @author Scott Battaglia * @version $Revision$ $Date$ * @since 1.0 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Audit { /** * Identifier for this particular application in the audit trail logs. This attribute should only be used to override the basic application code when you want to differentiate a section of the code. * @return the application code or an empty String if none is set. */ String applicationCode() default ""; /** * The action to write to the log when we audit this method. Value must be defined. * @return the action to write to the logs. */ String action(); /** * Reference name of the resource resolver to use. * * @return the reference to the resource resolver. CANNOT be NULL. */ String resourceResolverName(); /** * Reference name of the action resolver to use. * * @return the reference to the action resolver. CANNOT be NULL. */ String actionResolverName(); }
31.776119
200
0.726163
953b51bf98ebb9250c7aa0fa51b07129a8b63537
2,243
package com.jagex; public class Class199_Sub10 extends Class199 { int anInt9919; String aString9920; int anInt9921; int anInt9922; public void method2859() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)76).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, -1274311805); } public void method2856() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)124).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, -977743074); } public void method2861() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)6).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, 730784041); } public void method2855() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)43).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, 2016568752); } Class199_Sub10(RSByteBuffer var1) { super(var1); this.anInt9919 = var1.readUnsignedShort() * -1051807373; this.aString9920 = var1.readString(-1668799242); this.anInt9921 = var1.readInt() * 1069130959; this.anInt9922 = var1.readUnsignedShort() * -1590904539; } public void method2857() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)103).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, -799497944); } public void method2858() { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)43).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, 1888337088); } public void method2852(byte var1) { Class645.aClass207Array8445[this.anInt9919 * 1974328251].method2913((byte)63).method10780(this.aString9920, this.anInt9921 * -1294671313, 0, this.anInt9922 * 2124069549, -804101659); } static final void method9010(Class681 var0, int var1) { var0.anIntArray8622[(var0.anInt8623 += -1957887669) * -1730576285 - 1] = client.aBool11035?1:0; } }
45.77551
190
0.714668
1c158f1fc14a120165ded59a1116c0333b0396fa
516
// http://codeforces.com/problemset/problem/488/A import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int temp = a; int b = 0; while (b == 0) { boolean isLucky = String.valueOf(temp).contains("8"); if (isLucky) { int difference = Math.abs(a - temp); b = (difference > 0) ? difference : 0; } temp++; } System.out.println(b); // Close scanner read.close(); } }
17.793103
56
0.602713
883fb7555dceaa238c1254b58cd249527038a0b7
654
package be.tarsos.dsp.util.fft; /** * @author joren * See https://mgasior.web.cern.ch/mgasior/pap/FFT_resol_note.pdf */ public class BlackmanHarrisNuttall extends WindowFunction { float c0 = 0.355768f; float c1 = 0.487396f; float c2 = 0.144232f; float c3 = 0.012604f; @Override protected float value(int length, int index) { float sum = 0; sum += c0 * Math.cos((TWO_PI * 0 * index ) / (float) (length)) ; sum += c1 * Math.cos((TWO_PI * 1 * index ) / (float) (length)); sum += c2 * Math.cos((TWO_PI * 2 * index ) / (float) (length)); sum += c3 * Math.cos((TWO_PI * 3 * index ) / (float) (length)); return sum; } }
24.222222
66
0.614679
5d3b069c6d9da560cc426557e276fc4135b9dada
2,670
package com.example.helloHotSpot; import java.lang.reflect.Method; import com.example.hellowifi.R; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { //private Button startWifiButton; //private WifiManager wfManager; //private final String TAG = "test_wifi_log"; //private WifiConfiguration wifiConfiguration = new WifiConfiguration(); private Button startWifiButton; private WifiManager wfManager; private final String TAG ="myLog"; private WifiConfiguration wifiConfiguration =new WifiConfiguration(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startWifiButton = (Button)findViewById(R.id.startWifiButton); wfManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); startWifiButton.setText("Click to start Wifi"); startWifiButton.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub String name="mywifitest",pw="12345678"; createAp(name,pw); } }); } public void createAp(String ssid,String pw) { if (wfManager.isWifiEnabled()) { //如果开启了WIFI,则将它关闭。 wfManager.setWifiEnabled(false); Log.d(TAG, "wifi closed"); } try { wifiConfiguration.SSID = ssid; wifiConfiguration.preSharedKey = pw; Method method1 = wfManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); Log.d(TAG, "Wifi created"); Method method = wfManager.getClass().getMethod("isWifiApEnabled"); method.setAccessible(true); method1.invoke(wfManager, wifiConfiguration,true); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
31.785714
87
0.773408
b6b67f2bd607bd63cfd3fd0f22f4612b99718ac9
172
package de.uni_bonn.cs.tnn.core; public interface Input { double getWeightedValue(); double getUnweightedOutput(); void updateWeight(double weightChange); }
17.2
43
0.738372
73e787bf17c356c9781852ce0fe5f30650845062
1,023
package com.jslsolucoes.nginx.admin.agent.model.response; import java.math.BigDecimal; public class NginxServerInfoResponse implements NginxResponse { private String version; private String address; private Integer pid; private BigDecimal uptime; public NginxServerInfoResponse() { } public NginxServerInfoResponse(String version, String address, Integer pid, BigDecimal uptime) { this.version = version; this.address = address; this.pid = pid; this.uptime = uptime; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public BigDecimal getUptime() { return uptime; } public void setUptime(BigDecimal uptime) { this.uptime = uptime; } }
18.6
98
0.690127
361b1bcbecccd2eb5545ecec973bb68bbb521fd0
2,777
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.versioning.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Item; import com.amdocs.zusammen.datatypes.item.ItemVersion; import org.openecomp.convertor.ElementConvertor; import org.openecomp.sdc.versioning.dao.impl.zusammen.VersionZusammenDaoImpl; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; public class ItemVersionToVersionConvertor extends ElementConvertor { @Override public Object convert(Element element) { return null; } @Override public Object convert(Item item) { return null; } @Override public Object convert(ElementInfo elementInfo) { return null; } @Override public Version convert(ItemVersion itemVersion) { if (itemVersion == null) { return null; } Version version = Version.valueOf(itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL)); version.setStatus(VersionStatus.valueOf(itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); version.setName(itemVersion.getData().getInfo().getName()); version.setDescription(itemVersion.getData().getInfo().getDescription()); version.setId(itemVersion.getId().getValue()); if (itemVersion.getBaseId() != null) { version.setBaseId(itemVersion.getBaseId().getValue()); } version.setCreationTime(itemVersion.getCreationTime()); version.setModificationTime(itemVersion.getModificationTime()); return version; } }
42.075758
142
0.652503
ba2327d499e740942d50deaf7f66653d763b700b
15,721
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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.intellij.openapi.vcs.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Separator; import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.localVcs.UpToDateLineNumberProvider; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.annotate.*; import com.intellij.openapi.vcs.changes.BackgroundFromStartOption; import com.intellij.openapi.vcs.changes.VcsAnnotationLocalChangesListener; import com.intellij.openapi.vcs.history.VcsFileRevision; import com.intellij.openapi.vcs.impl.BackgroundableActionEnabledHandler; import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl; import com.intellij.openapi.vcs.impl.UpToDateLineNumberProviderImpl; import com.intellij.openapi.vcs.impl.VcsBackgroundableActions; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColorUtil; import com.intellij.util.containers.SortedList; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.*; import java.util.List; /** * @author Konstantin Bulenkov * @author: lesya */ public class AnnotateToggleAction extends ToggleAction implements DumbAware, AnnotationColors { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.actions.AnnotateToggleAction"); protected static final Key<Collection<ActiveAnnotationGutter>> KEY_IN_EDITOR = Key.create("Annotations"); public void update(AnActionEvent e) { super.update(e); final boolean enabled = isEnabled(VcsContextFactory.SERVICE.getInstance().createContextOn(e)); e.getPresentation().setEnabled(enabled); } private static boolean isEnabled(final VcsContext context) { VirtualFile[] selectedFiles = context.getSelectedFiles(); if (selectedFiles == null) return false; if (selectedFiles.length != 1) return false; VirtualFile file = selectedFiles[0]; if (file.isDirectory()) return false; Project project = context.getProject(); if (project == null || project.isDisposed()) return false; final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstance(project); final BackgroundableActionEnabledHandler handler = ((ProjectLevelVcsManagerImpl)plVcsManager) .getBackgroundableActionHandler(VcsBackgroundableActions.ANNOTATE); if (handler.isInProgress(file.getPath())) return false; final AbstractVcs vcs = plVcsManager.getVcsFor(file); if (vcs == null) return false; final AnnotationProvider annotationProvider = vcs.getAnnotationProvider(); if (annotationProvider == null) return false; final FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file); if (fileStatus == FileStatus.UNKNOWN || fileStatus == FileStatus.ADDED || fileStatus == FileStatus.IGNORED) { return false; } return hasTextEditor(file); } private static boolean hasTextEditor(@NotNull VirtualFile selectedFile) { return !selectedFile.getFileType().isBinary(); } public boolean isSelected(AnActionEvent e) { VcsContext context = VcsContextFactory.SERVICE.getInstance().createContextOn(e); Editor editor = context.getEditor(); if (editor == null) return false; Collection annotations = editor.getUserData(KEY_IN_EDITOR); return annotations != null && !annotations.isEmpty(); } public void setSelected(AnActionEvent e, boolean selected) { final VcsContext context = VcsContextFactory.SERVICE.getInstance().createContextOn(e); Editor editor = context.getEditor(); if (!selected) { if (editor != null) { editor.getGutter().closeAllAnnotations(); } } else { if (editor == null) { VirtualFile selectedFile = context.getSelectedFile(); FileEditor[] fileEditors = FileEditorManager.getInstance(context.getProject()).openFile(selectedFile, false); for (FileEditor fileEditor : fileEditors) { if (fileEditor instanceof TextEditor) { editor = ((TextEditor)fileEditor).getEditor(); } } } LOG.assertTrue(editor != null); doAnnotate(editor, context.getProject()); } } private static void doAnnotate(final Editor editor, final Project project) { final VirtualFile file = FileDocumentManager.getInstance().getFile(editor.getDocument()); if (project == null) return; final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstance(project); final AbstractVcs vcs = plVcsManager.getVcsFor(file); if (vcs == null) return; final AnnotationProvider annotationProvider = vcs.getCachingAnnotationProvider(); final Ref<FileAnnotation> fileAnnotationRef = new Ref<FileAnnotation>(); final Ref<VcsException> exceptionRef = new Ref<VcsException>(); final BackgroundableActionEnabledHandler handler = ((ProjectLevelVcsManagerImpl)plVcsManager).getBackgroundableActionHandler( VcsBackgroundableActions.ANNOTATE); handler.register(file.getPath()); final Task.Backgroundable annotateTask = new Task.Backgroundable(project, VcsBundle.message("retrieving.annotations"), true, BackgroundFromStartOption.getInstance()) { public void run(final @NotNull ProgressIndicator indicator) { try { fileAnnotationRef.set(annotationProvider.annotate(file)); } catch (VcsException e) { exceptionRef.set(e); } catch (Throwable t) { handler.completed(file.getPath()); } } @Override public void onCancel() { onSuccess(); } @Override public void onSuccess() { handler.completed(file.getPath()); if (!exceptionRef.isNull()) { AbstractVcsHelper.getInstance(project).showErrors(Arrays.asList(exceptionRef.get()), VcsBundle.message("message.title.annotate")); } if (!fileAnnotationRef.isNull()) { doAnnotate(editor, project, file, fileAnnotationRef.get(), vcs, true); } } }; ProgressManager.getInstance().run(annotateTask); } public static void doAnnotate(final Editor editor, final Project project, final VirtualFile file, final FileAnnotation fileAnnotation, final AbstractVcs vcs, final boolean onCurrentRevision) { final UpToDateLineNumberProvider getUpToDateLineNumber = new UpToDateLineNumberProviderImpl(editor.getDocument(), project); editor.getGutter().closeAllAnnotations(); final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(project).getAnnotationLocalChangesListener(); fileAnnotation.setCloser(new Runnable() { @Override public void run() { if (project.isDisposed()) return; UIUtil.invokeLaterIfNeeded(new Runnable() { @Override public void run() { if (project.isDisposed()) return; editor.getGutter().closeAllAnnotations(); } }); } }); if (onCurrentRevision) { listener.registerAnnotation(file, fileAnnotation); } // be careful, not proxies but original items are put there (since only their presence not behaviour is important) Collection<ActiveAnnotationGutter> annotations = editor.getUserData(KEY_IN_EDITOR); if (annotations == null) { annotations = new HashSet<ActiveAnnotationGutter>(); editor.putUserData(KEY_IN_EDITOR, annotations); } final EditorGutterComponentEx editorGutter = (EditorGutterComponentEx)editor.getGutter(); final HighlightAnnotationsActions highlighting = new HighlightAnnotationsActions(project, file, fileAnnotation, editorGutter); final List<AnnotationFieldGutter> gutters = new ArrayList<AnnotationFieldGutter>(); final AnnotationSourceSwitcher switcher = fileAnnotation.getAnnotationSourceSwitcher(); final List<AnAction> additionalActions = new ArrayList<AnAction>(); if (vcs.getCommittedChangesProvider() != null) { additionalActions.add(new ShowDiffFromAnnotation(getUpToDateLineNumber, fileAnnotation, vcs, file)); } additionalActions.add(new CopyRevisionNumberAction(getUpToDateLineNumber, fileAnnotation)); final AnnotationPresentation presentation = new AnnotationPresentation(highlighting, switcher, editorGutter, gutters, additionalActions.toArray(new AnAction[additionalActions.size()])); final Map<String, Color> bgColorMap = Registry.is("vcs.show.colored.annotations") ? computeBgColors(fileAnnotation) : null; final Map<String, Integer> historyIds = Registry.is("vcs.show.history.numbers") ? computeLineNumbers(fileAnnotation) : null; if (switcher != null) { switcher.switchTo(switcher.getDefaultSource()); final LineAnnotationAspect revisionAspect = switcher.getRevisionAspect(); final CurrentRevisionAnnotationFieldGutter currentRevisionGutter = new CurrentRevisionAnnotationFieldGutter(fileAnnotation, editor, revisionAspect, presentation, bgColorMap); final MergeSourceAvailableMarkerGutter mergeSourceGutter = new MergeSourceAvailableMarkerGutter(fileAnnotation, editor, null, presentation, bgColorMap); presentation.addSourceSwitchListener(currentRevisionGutter); presentation.addSourceSwitchListener(mergeSourceGutter); currentRevisionGutter.consume(switcher.getDefaultSource()); mergeSourceGutter.consume(switcher.getDefaultSource()); gutters.add(currentRevisionGutter); gutters.add(mergeSourceGutter); } final LineAnnotationAspect[] aspects = fileAnnotation.getAspects(); for (LineAnnotationAspect aspect : aspects) { final AnnotationFieldGutter gutter = new AnnotationFieldGutter(fileAnnotation, editor, aspect, presentation, bgColorMap); gutter.setAspectValueToBgColorMap(bgColorMap); gutters.add(gutter); } if (historyIds != null) { gutters.add(new HistoryIdColumn(fileAnnotation, editor, presentation, bgColorMap, historyIds)); } gutters.add(new HighlightedAdditionalColumn(fileAnnotation, editor, null, presentation, highlighting, bgColorMap)); final AnnotateActionGroup actionGroup = new AnnotateActionGroup(gutters, editorGutter); presentation.addAction(actionGroup, 1); gutters.add(new ExtraFieldGutter(fileAnnotation, editor, presentation, bgColorMap, actionGroup)); presentation.addAction(new ShowHideAdditionalInfoAction(gutters, editorGutter, actionGroup)); addActionsFromExtensions(presentation, fileAnnotation); for (AnAction action : presentation.getActions()) { if (action instanceof LineNumberListener) { presentation.addLineNumberListener((LineNumberListener)action); } } for (AnnotationFieldGutter gutter : gutters) { final AnnotationGutterLineConvertorProxy proxy = new AnnotationGutterLineConvertorProxy(getUpToDateLineNumber, gutter); if (gutter.isGutterAction()) { editor.getGutter().registerTextAnnotation(proxy, proxy); } else { editor.getGutter().registerTextAnnotation(proxy); } annotations.add(gutter); } } private static void addActionsFromExtensions(@NotNull AnnotationPresentation presentation, @NotNull FileAnnotation fileAnnotation) { AnnotationGutterActionProvider[] extensions = AnnotationGutterActionProvider.EP_NAME.getExtensions(); if (extensions.length > 0) { presentation.addAction(new Separator()); } for (AnnotationGutterActionProvider provider : extensions) { presentation.addAction(provider.createAction(fileAnnotation)); } } @Nullable private static Map<String, Integer> computeLineNumbers(FileAnnotation fileAnnotation) { final SortedList<VcsFileRevision> revisions = new SortedList<VcsFileRevision>(new Comparator<VcsFileRevision>() { @Override public int compare(VcsFileRevision o1, VcsFileRevision o2) { try { final int result = o1.getRevisionDate().compareTo(o2.getRevisionDate()); return result != 0 ? result : o1.getRevisionNumber().compareTo(o2.getRevisionNumber()); } catch (Exception e) { return 0; } } }); final Map<String, Integer> numbers = new HashMap<String, Integer>(); final List<VcsFileRevision> fileRevisionList = fileAnnotation.getRevisions(); if (fileRevisionList != null) { revisions.addAll(fileRevisionList); for (VcsFileRevision revision : fileRevisionList) { final String revNumber = revision.getRevisionNumber().asString(); if (!numbers.containsKey(revNumber)) { final int num = revisions.indexOf(revision); if (num != -1) { numbers.put(revNumber, num + 1); } } } } return numbers.size() < 2 ? null : numbers; } @Nullable private static Map<String, Color> computeBgColors(FileAnnotation fileAnnotation) { final Map<String, Color> bgColors = new HashMap<String, Color>(); final Map<String, Color> revNumbers = new HashMap<String, Color>(); final int length = BG_COLORS.length; final List<VcsFileRevision> fileRevisionList = fileAnnotation.getRevisions(); final boolean darcula = UIUtil.isUnderDarcula(); if (fileRevisionList != null) { for (VcsFileRevision revision : fileRevisionList) { final String author = revision.getAuthor(); final String revNumber = revision.getRevisionNumber().asString(); if (author != null && !bgColors.containsKey(author)) { final int size = bgColors.size(); Color color = BG_COLORS[size < length ? size : size % length]; if (darcula) { color = ColorUtil.shift(color, 0.3); } bgColors.put(author, color); } if (revNumber != null && !revNumbers.containsKey(revNumber)) { revNumbers.put(revNumber, bgColors.get(author)); } } } return bgColors.size() < 2 ? null : revNumbers; } }
43.913408
140
0.715921
5eb914e4792659e020ab61a9c39d35ff06a7855a
3,810
package tk.wlemuel.cotable.cache; import android.content.Context; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * CacheManager * * @author Steve Lemuel * @version 0.1 * @desc CacheManager * @created 2015/05/09 * @updated 2015/05/09 */ public class CacheManager { /** * Save the object * * @param context context * @param ser serializable object * @param file cache file * @throws java.io.IOException IOException */ @SuppressWarnings("JavaDoc") public static boolean saveObject(Context context, Serializable ser, String file) { FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = context.openFileOutput(file, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); oos.writeObject(ser); oos.flush(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (oos != null) oos.close(); } catch (Exception e) { e.printStackTrace(); } try { if (fos != null) fos.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * Read the object * * @param context context * @param file cache file * @return serializable object * @throws java.io.IOException Exception */ @SuppressWarnings("JavaDoc") public static Serializable readObject(Context context, String file) { if (!isExistDataCache(context, file)) return null; FileInputStream fis = null; ObjectInputStream ois = null; try { fis = context.openFileInput(file); ois = new ObjectInputStream(fis); return (Serializable) ois.readObject(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); // Delete the cache file if the deserialization failed. if (e instanceof InvalidClassException) { File data = context.getFileStreamPath(file); //noinspection ResultOfMethodCallIgnored data.delete(); } } finally { try { if (ois != null) ois.close(); } catch (Exception e) { e.printStackTrace(); } try { if (fis != null) fis.close(); } catch (Exception e) { e.printStackTrace(); } } return null; } /** * Judge whether the cache file is readable. * * @param context context * @param cachefile cache file * @return true if the cache file is readable, false otherwise. */ public static boolean isReadDataCache(Context context, String cachefile) { return readObject(context, cachefile) != null; } /** * Juget whether the cache file exists. * * @param context context * @param cachefile cache file * @return true if the cache data exists, false otherwise. */ public static boolean isExistDataCache(Context context, String cachefile) { if (context == null) return false; boolean exist = false; File data = context.getFileStreamPath(cachefile); if (data.exists()) exist = true; return exist; } }
28.432836
79
0.55748
6aec6e41e3d2bb0f3703940c4faf1fb14b6d588e
1,834
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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.simonvt.cathode.settings; import android.support.v4.util.LongSparseArray; import android.text.format.DateUtils; import net.simonvt.cathode.R; public enum NotificationTime { MINUTES_15(R.string.preference_notification_time_minutes_15, 15 * DateUtils.MINUTE_IN_MILLIS), MINUTES_30(R.string.preference_notification_time_minutes_30, 30 * DateUtils.MINUTE_IN_MILLIS), HOURS_1(R.string.preference_notification_time_hours_1, DateUtils.HOUR_IN_MILLIS), HOURS_2(R.string.preference_notification_time_hours_2, 2 * DateUtils.HOUR_IN_MILLIS); private int stringRes; private long notificationTime; NotificationTime(int stringRes, long notificationTime) { this.stringRes = stringRes; this.notificationTime = notificationTime; } public int getStringRes() { return stringRes; } public long getNotificationTime() { return notificationTime; } private static final LongSparseArray<NotificationTime> TIME_MAPPING = new LongSparseArray<>(); static { for (NotificationTime time : NotificationTime.values()) { TIME_MAPPING.put(time.notificationTime, time); } } public static NotificationTime fromValue(long cacheTime) { return TIME_MAPPING.get(cacheTime); } }
32.75
96
0.766085
a016b3ea3c654d17323bc6816ef13253df3dfa3a
9,806
/* * Copyright (C) 2019 Nafundi * * 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.opendatakit.aggregate.format.element; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.TimeZone; import org.junit.Test; import org.opendatakit.aggregate.format.Row; import org.opendatakit.aggregate.submission.SubmissionKey; import org.opendatakit.aggregate.submission.type.GeoPoint; import org.opendatakit.aggregate.submission.type.jr.JRTemporal; import org.opendatakit.common.persistence.WrappedBigDecimal; public class BasicElementFormatterTest { @Test public void formats_UIDs() { assertThat(formatUid(null), is(nullValue())); assertThat(formatUid(""), is("")); assertThat(formatUid("uuid:8030500e-12c6-40f4-badd-c9e32361f928"), is("uuid:8030500e-12c6-40f4-badd-c9e32361f928")); } @Test public void formats_booleans() { assertThat(format((Boolean) null), is(nullValue())); assertThat(format(true), is("true")); assertThat(format(false), is("false")); } @Test public void formats_choices() { assertThat(formatChoices((String[]) null), is("")); assertThat(formatChoices(""), is("")); assertThat(formatChoices("choice1"), is("choice1")); assertThat(formatChoices("choice1", "choice2"), is("choice1 choice2")); } @Test public void formats_dateTimes_from_metadata_and_generated_data() { OffsetDateTime now = OffsetDateTime.parse("2018-01-01T10:20:30.123Z"); assertThat(format((Date) null), is(nullValue())); withOffset("Europe/Madrid", () -> assertThat(format(Date.from(now.toInstant())), is("Jan 1, 2018 11:20:30 AM")) ); } private static void withOffset(String zoneId, Runnable block) { TimeZone backup = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone(zoneId)); block.run(); TimeZone.setDefault(backup); } @Test public void formats_decimals() { assertThat(format((WrappedBigDecimal) null), is(nullValue())); assertThat(format(WrappedBigDecimal.fromDouble(1.234)), is("1.234")); } @Test public void formats_dates_from_user_input() { assertThat(formatJRDate(null), is(nullValue())); assertThat(formatJRDate(JRTemporal.date("2018-01-01")), is("January 1, 2018")); } @Test public void formats_times_from_user_input() { assertThat(formatJRTime(null), is(nullValue())); // Some JVMs can add the AM/PM designation in between assertThat(formatJRTime(JRTemporal.time("10:20:30.123Z")), allOf(startsWith("10:20:30"), endsWith("Z"))); assertThat(formatJRTime(JRTemporal.time("10:20:30.123+01:00")), allOf(startsWith("10:20:30"), endsWith("+01:00"))); } @Test public void formats_dateTimes_from_user_input() { assertThat(formatJRDateTime(null), is(nullValue())); // Some JVMs can add the AM/PM designation in between assertThat(formatJRDateTime(JRTemporal.dateTime("2018-01-01T10:20:30.123Z")), allOf(startsWith("January 1, 2018 10:20:30"), endsWith("Z"))); assertThat(formatJRDateTime(JRTemporal.dateTime("2018-01-01T10:20:30.123+01:00")), allOf(startsWith("January 1, 2018 10:20:30"), endsWith("+01:00"))); } @Test public void formatsgeopoints() { assertThat(format(null, false, false), is(nullValue())); assertThat(format(geopoint(1, 2, null, null), true, true), is("1.0, 2.0")); assertThat(format(geopoint(1, 2, 3, 4), false, false), is("1.0, 2.0")); assertThat(format(geopoint(1, 2, 3, 4), true, false), is("1.0, 2.0, 3.0")); assertThat(format(geopoint(1, 2, 3, 4), false, true), is("1.0, 2.0, 4.0")); // Oopsie, this doesn't make much sense... assertThat(format(geopoint(1, 2, 3, 4), true, true), is("1.0, 2.0, 3.0, 4.0")); assertThat(formatSeparated(null, false, false), contains(nullValue())); assertThat(formatSeparated(geopoint(1, 2, null, null), true, true), contains("1.0", "2.0", null, null)); assertThat(formatSeparated(geopoint(1, 2, 3, 4), false, false), contains("1.0", "2.0")); assertThat(formatSeparated(geopoint(1, 2, 3, 4), true, false), contains("1.0", "2.0", "3.0")); assertThat(formatSeparated(geopoint(1, 2, 3, 4), false, true), contains("1.0", "2.0", "4.0")); // Oopsie, this doesn't make much sense... assertThat(formatSeparated(geopoint(1, 2, 3, 4), true, true), contains("1.0", "2.0", "3.0", "4.0")); } @Test public void formats_longs() { assertThat(format((Long) null), is(nullValue())); assertThat(format(1L), is("1")); } @Test public void formats_strings() { assertThat(format((String) null), is(nullValue())); assertThat(format("some string"), is("some string")); } private GeoPoint geopoint(Number lat, Number lon, Number alt, Number acc) { return new GeoPoint( Optional.ofNullable(lat).map(Number::doubleValue).map(WrappedBigDecimal::fromDouble).orElse(null), Optional.ofNullable(lon).map(Number::doubleValue).map(WrappedBigDecimal::fromDouble).orElse(null), Optional.ofNullable(alt).map(Number::doubleValue).map(WrappedBigDecimal::fromDouble).orElse(null), Optional.ofNullable(acc).map(Number::doubleValue).map(WrappedBigDecimal::fromDouble).orElse(null) ); } private static String formatUid(String uid) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatUid(uid, null, row); return row.getFormattedValues().get(0); } private static String format(Boolean value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatBoolean(value, null, "0", row); return row.getFormattedValues().get(0); } private static String formatChoices(String... choices) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatChoices(choices != null ? Arrays.asList(choices) : null, null, "0", row); return row.getFormattedValues().get(0); } private static String format(Date value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatDateTime(value, null, "0", row); return row.getFormattedValues().get(0); } private static String format(WrappedBigDecimal value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatDecimal(value, null, "0", row); return row.getFormattedValues().get(0); } private static String formatJRDate(JRTemporal value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatJRDate(value, null, "0", row); return row.getFormattedValues().get(0); } private static String formatJRTime(JRTemporal value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatJRTime(value, null, "0", row); return row.getFormattedValues().get(0); } private static String formatJRDateTime(JRTemporal value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatJRDateTime(value, null, "0", row); return row.getFormattedValues().get(0); } private static String format(GeoPoint value, boolean includeAltitude, boolean includeAccuracy) { BasicElementFormatter formatter = new BasicElementFormatter(false, includeAltitude, includeAccuracy); Row row = new Row(new SubmissionKey("submission key")); formatter.formatGeoPoint(value, null, "0", row); return row.getFormattedValues().get(0); } private static List<String> formatSeparated(GeoPoint value, boolean includeAltitude, boolean includeAccuracy) { BasicElementFormatter formatter = new BasicElementFormatter(true, includeAltitude, includeAccuracy); Row row = new Row(new SubmissionKey("submission key")); formatter.formatGeoPoint(value, null, "0", row); return row.getFormattedValues(); } private static String format(Long value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatLong(value, null, "0", row); return row.getFormattedValues().get(0); } private static String format(String value) { BasicElementFormatter formatter = new BasicElementFormatter(false, false, false); Row row = new Row(new SubmissionKey("submission key")); formatter.formatString(value, null, "0", row); return row.getFormattedValues().get(0); } }
42.820961
154
0.714257
dbcc6a55008458adb5737372a14dd8bdded5a8ac
901
package com.jjh.bookshop.main; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse; import org.springframework.boot.actuate.endpoint.web.annotation.EndpointWebExtension; import org.springframework.boot.actuate.info.InfoEndpoint; import org.springframework.stereotype.Component; import java.util.Map; @Component @EndpointWebExtension(endpoint = InfoEndpoint.class) public class InfoWebEndpointExtension { private InfoEndpoint delegate; // standard constructor @ReadOperation public WebEndpointResponse<Map<String, Object>> info() { Map<String, Object> info = this.delegate.info(); Integer status = getStatus(info); return new WebEndpointResponse<>(info, status); } private Integer getStatus(Map<String, Object> info) { return 200; } }
30.033333
85
0.760266
45f85b0efb96cc6cf1084a2034320118454dbc94
331
package com.example.boot.mapper.role; import com.example.boot.model.role.Permissions; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.Set; @Repository public interface PermissionsMapper { Set<Permissions> getPermissionsByRole(@Param("roleId")Integer roleId); }
25.461538
74
0.812689
6519bbd440ba59e75024ed304717b72dafc3183a
825
package com.github.ontio.account; import com.github.ontio.common.ErrorCode; import com.github.ontio.sdk.exception.SDKException; import org.spongycastle.util.Arrays; import java.security.spec.AlgorithmParameterSpec; /** * Parameter spec for SM2 ID parameter */ public class SM2ParameterSpec implements AlgorithmParameterSpec { private byte[] id; /** * Base constructor. * * @param id the ID string associated with this usage of SM2. */ public SM2ParameterSpec(byte[] id) throws SDKException { if (id == null){ throw new SDKException(ErrorCode.ParamError); } this.id = Arrays.clone(id); } /** * Return the ID value. * * @return the ID string. */ public byte[] getID() { return Arrays.clone(id); } }
20.625
65
0.635152
fe02a33753c42ab75f0602e24204703aaa1997f4
361
package icbm.classic.api.data; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumHand; /** * Created by Dark(DarkGuardsman, Robert) on 1/7/19. */ @FunctionalInterface public interface EntityInteractionFunction { boolean onInteraction(Entity entity, EntityPlayer player, EnumHand hand); }
24.066667
77
0.792244
88a7958306b72c15f44573dbfe85a8dfddcd8708
4,817
package mono.com.microsoft.appcenter.channel; public class Channel_ListenerImplementor extends java.lang.Object implements mono.android.IGCUserPeer, com.microsoft.appcenter.channel.Channel.Listener { /** @hide */ public static final String __md_methods; static { __md_methods = "n_onClear:(Ljava/lang/String;)V:GetOnClear_Ljava_lang_String_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onGloballyEnabled:(Z)V:GetOnGloballyEnabled_ZHandler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onGroupAdded:(Ljava/lang/String;Lcom/microsoft/appcenter/channel/Channel$GroupListener;)V:GetOnGroupAdded_Ljava_lang_String_Lcom_microsoft_appcenter_channel_Channel_GroupListener_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onGroupRemoved:(Ljava/lang/String;)V:GetOnGroupRemoved_Ljava_lang_String_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onPaused:(Ljava/lang/String;Ljava/lang/String;)V:GetOnPaused_Ljava_lang_String_Ljava_lang_String_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onPreparedLog:(Lcom/microsoft/appcenter/ingestion/models/Log;Ljava/lang/String;I)V:GetOnPreparedLog_Lcom_microsoft_appcenter_ingestion_models_Log_Ljava_lang_String_IHandler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onPreparingLog:(Lcom/microsoft/appcenter/ingestion/models/Log;Ljava/lang/String;)V:GetOnPreparingLog_Lcom_microsoft_appcenter_ingestion_models_Log_Ljava_lang_String_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_onResumed:(Ljava/lang/String;Ljava/lang/String;)V:GetOnResumed_Ljava_lang_String_Ljava_lang_String_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + "n_shouldFilter:(Lcom/microsoft/appcenter/ingestion/models/Log;)Z:GetShouldFilter_Lcom_microsoft_appcenter_ingestion_models_Log_Handler:Com.Microsoft.Appcenter.Channel.IChannelListenerInvoker, Microsoft.AppCenter.Android.Bindings\n" + ""; mono.android.Runtime.register ("Com.Microsoft.Appcenter.Channel.IChannelListenerImplementor, Microsoft.AppCenter.Android.Bindings", Channel_ListenerImplementor.class, __md_methods); } public Channel_ListenerImplementor () { super (); if (getClass () == Channel_ListenerImplementor.class) mono.android.TypeManager.Activate ("Com.Microsoft.Appcenter.Channel.IChannelListenerImplementor, Microsoft.AppCenter.Android.Bindings", "", this, new java.lang.Object[] { }); } public void onClear (java.lang.String p0) { n_onClear (p0); } private native void n_onClear (java.lang.String p0); public void onGloballyEnabled (boolean p0) { n_onGloballyEnabled (p0); } private native void n_onGloballyEnabled (boolean p0); public void onGroupAdded (java.lang.String p0, com.microsoft.appcenter.channel.Channel.GroupListener p1) { n_onGroupAdded (p0, p1); } private native void n_onGroupAdded (java.lang.String p0, com.microsoft.appcenter.channel.Channel.GroupListener p1); public void onGroupRemoved (java.lang.String p0) { n_onGroupRemoved (p0); } private native void n_onGroupRemoved (java.lang.String p0); public void onPaused (java.lang.String p0, java.lang.String p1) { n_onPaused (p0, p1); } private native void n_onPaused (java.lang.String p0, java.lang.String p1); public void onPreparedLog (com.microsoft.appcenter.ingestion.models.Log p0, java.lang.String p1, int p2) { n_onPreparedLog (p0, p1, p2); } private native void n_onPreparedLog (com.microsoft.appcenter.ingestion.models.Log p0, java.lang.String p1, int p2); public void onPreparingLog (com.microsoft.appcenter.ingestion.models.Log p0, java.lang.String p1) { n_onPreparingLog (p0, p1); } private native void n_onPreparingLog (com.microsoft.appcenter.ingestion.models.Log p0, java.lang.String p1); public void onResumed (java.lang.String p0, java.lang.String p1) { n_onResumed (p0, p1); } private native void n_onResumed (java.lang.String p0, java.lang.String p1); public boolean shouldFilter (com.microsoft.appcenter.ingestion.models.Log p0) { return n_shouldFilter (p0); } private native boolean n_shouldFilter (com.microsoft.appcenter.ingestion.models.Log p0); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
39.809917
291
0.802367
0b82311f6ebd7b9ac74d9b9a5adaa12f0bd1851b
2,434
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("34") class Record_2722 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 2722: FirstName is Rochelle") void FirstNameOfRecord2722() { assertEquals("Rochelle", customers.get(2721).getFirstName()); } @Test @DisplayName("Record 2722: LastName is Muskus") void LastNameOfRecord2722() { assertEquals("Muskus", customers.get(2721).getLastName()); } @Test @DisplayName("Record 2722: Company is Days Inn") void CompanyOfRecord2722() { assertEquals("Days Inn", customers.get(2721).getCompany()); } @Test @DisplayName("Record 2722: Address is 50 W Skippack Pike") void AddressOfRecord2722() { assertEquals("50 W Skippack Pike", customers.get(2721).getAddress()); } @Test @DisplayName("Record 2722: City is Ambler") void CityOfRecord2722() { assertEquals("Ambler", customers.get(2721).getCity()); } @Test @DisplayName("Record 2722: County is Montgomery") void CountyOfRecord2722() { assertEquals("Montgomery", customers.get(2721).getCounty()); } @Test @DisplayName("Record 2722: State is PA") void StateOfRecord2722() { assertEquals("PA", customers.get(2721).getState()); } @Test @DisplayName("Record 2722: ZIP is 19002") void ZIPOfRecord2722() { assertEquals("19002", customers.get(2721).getZIP()); } @Test @DisplayName("Record 2722: Phone is 215-542-0749") void PhoneOfRecord2722() { assertEquals("215-542-0749", customers.get(2721).getPhone()); } @Test @DisplayName("Record 2722: Fax is 215-542-7153") void FaxOfRecord2722() { assertEquals("215-542-7153", customers.get(2721).getFax()); } @Test @DisplayName("Record 2722: Email is [email protected]") void EmailOfRecord2722() { assertEquals("[email protected]", customers.get(2721).getEmail()); } @Test @DisplayName("Record 2722: Web is http://www.rochellemuskus.com") void WebOfRecord2722() { assertEquals("http://www.rochellemuskus.com", customers.get(2721).getWeb()); } }
25.354167
78
0.73295
8c9be6835d98e8c22c418d53e083b4581265c4f4
1,826
package comp5216.sydney.edu.au.findmygym.model; import android.annotation.SuppressLint; import java.io.Serializable; import comp5216.sydney.edu.au.findmygym.R; /** * A class that records a personal trainer reservation. */ public class Reservation implements Serializable { private String rsvId; // null if no trainer reserved private String trainerId; private String gymId; private String userId; private int price; private Timeslot timeslot; public void setRsvId(String rsvId) { this.rsvId = rsvId; } @SuppressLint("DefaultLocale") public Reservation(String rsvId, String userId, String gymId, String trainerId, int price, Timeslot timeslot) { this.userId = userId; this.gymId = gymId; this.trainerId = trainerId; this.timeslot = timeslot; this.price = price; this.rsvId = rsvId; } @Override public String toString() { return "Reservation{" + "rsvId='" + rsvId + '\'' + ", trainerId='" + trainerId + '\'' + ", gymId='" + gymId + '\'' + ", userId='" + userId + '\'' + ", price=" + price + ", timeslot=" + timeslot + '}'; } public int getPrice() { return price; } public String getRsvId() { return rsvId; } public String getGymId() { return gymId; } public String getUserId() { return userId; } /** * @return the personal trainer to reserve */ public String getTrainerId() { return trainerId; } /** * @return the timeslot of this reservation */ public Timeslot getSelectedTimeSlot() { return timeslot; } }
22
94
0.55586
af0f2d07e6b480d737dc8e99fab1c6e90f58a262
8,803
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.android; import com.facebook.buck.android.build_config.BuildConfigFields; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.externalactions.android.AndroidBuildConfigExternalAction; import com.facebook.buck.externalactions.android.AndroidBuildConfigExternalActionArgs; import com.facebook.buck.externalactions.utils.ExternalActionsUtils; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.modern.BuildableWithExternalAction; import com.facebook.buck.rules.modern.ModernBuildRule; import com.facebook.buck.rules.modern.OutputPath; import com.facebook.buck.rules.modern.OutputPathResolver; import com.facebook.buck.rules.modern.model.BuildableCommand; import com.google.common.collect.ImmutableList; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; /** * {@link BuildRule} that can generate a {@code BuildConfig.java} file and compile it so it can be * used as a Java library. * * <p>This rule functions as a {@code java_library} that can be used as a dependency of an {@code * android_library}, but whose implementation may be swapped out by the {@code android_binary} that * transitively includes the {@code android_build_config}. Specifically, its compile-time * implementation will use non-constant-expression (see JLS 15.28), placeholder values (because they * cannot be inlined) for the purposes of compilation that will be swapped out with final, * production values (that can be inlined) when building the final APK. Consider the following * example: * * <pre> * android_build_config( * name = 'build_config', * package = 'com.example.pkg', * ) * * # The .java files in this library may contain references to the boolean * # com.example.pkg.BuildConfig.DEBUG because :build_config is in the deps. * android_library( * name = 'mylib', * srcs = glob(['src/**&#47;*.java']), * deps = [ * ':build_config', * ], * ) * * android_binary( * name = 'debug', * package_type = 'DEBUG', * keystore = '//keystores:debug', * manifest = 'AndroidManifest.xml', * target = 'Google Inc.:Google APIs:19', * deps = [ * ':mylib', * ], * ) * * android_binary( * name = 'release', * package_type = 'RELEASE', * keystore = '//keystores:release', * manifest = 'AndroidManifest.xml', * target = 'Google Inc.:Google APIs:19', * deps = [ * ':mylib', * ], * ) * </pre> * * The {@code :mylib} rule will be compiled against a version of {@code BuildConfig.java} whose * contents are: * * <pre> * package com.example.pkg; * public class BuildConfig { * private BuildConfig() {} * public static final boolean DEBUG = !Boolean.parseBoolean(null); * } * </pre> * * Note that the value is not a constant expression, so it cannot be inlined by {@code javac}. When * building {@code :debug} and {@code :release}, the {@code BuildConfig.class} file that {@code * :mylib} was compiled against will not be included in the APK as the other transitive Java deps of * the {@code android_binary} will. The {@code BuildConfig.class} will be replaced with one that * corresponds to the value of the {@code package_type} argument to the {@code android_binary} rule. * For example, {@code :debug} will include a {@code BuildConfig.class} file that is compiled from: * * <pre> * package com.example.pkg; * public class BuildConfig { * private BuildConfig() {} * public static final boolean DEBUG = true; * } * </pre> * * whereas {@code :release} will include a {@code BuildConfig.class} file that is compiled from: * * <pre> * package com.example.pkg; * public class BuildConfig { * private BuildConfig() {} * public static final boolean DEBUG = false; * } * </pre> * * This swap happens before ProGuard is run as part of building the APK, so it will be able to * exploit the "final-ness" of the {@code DEBUG} constant in any whole-program optimization that it * performs. */ public class AndroidBuildConfig extends ModernBuildRule<AndroidBuildConfig.Impl> { protected AndroidBuildConfig( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, SourcePathRuleFinder sourcePathRuleFinder, String javaPackage, BuildConfigFields defaultValues, Optional<SourcePath> valuesFile, boolean useConstantExpressions, boolean shouldExecuteInSeparateProcess) { super( buildTarget, projectFilesystem, sourcePathRuleFinder, new Impl( buildTarget, javaPackage, defaultValues, valuesFile, useConstantExpressions, new OutputPath("BuildConfig.java"), shouldExecuteInSeparateProcess)); } @Override public SourcePath getSourcePathToOutput() { return getSourcePath(getBuildable().outputPath); } public String getJavaPackage() { return getBuildable().javaPackage; } public boolean isUseConstantExpressions() { return getBuildable().useConstantExpressions; } public BuildConfigFields getBuildConfigFields() { return getBuildable().defaultValues; } static class Impl extends BuildableWithExternalAction { private static final String TEMP_FILE_PREFIX = "android_build_config_"; private static final String TEMP_FILE_SUFFIX = ""; @AddToRuleKey private final BuildTarget buildTarget; @AddToRuleKey private final String javaPackage; @AddToRuleKey(stringify = true) private final BuildConfigFields defaultValues; @AddToRuleKey private final Optional<SourcePath> valuesFile; @AddToRuleKey private final boolean useConstantExpressions; @AddToRuleKey private final OutputPath outputPath; private Impl( BuildTarget buildTarget, String javaPackage, BuildConfigFields defaultValues, Optional<SourcePath> valuesFile, boolean useConstantExpressions, OutputPath outputPath, boolean shouldExecuteInSeparateProcess) { super(shouldExecuteInSeparateProcess); this.buildTarget = buildTarget; this.javaPackage = javaPackage; this.defaultValues = defaultValues; this.valuesFile = valuesFile; this.useConstantExpressions = useConstantExpressions; this.outputPath = outputPath; } @Override public BuildableCommand getBuildableCommand( ProjectFilesystem filesystem, OutputPathResolver outputPathResolver, BuildContext buildContext) { Path jsonFilePath = createTempFile(filesystem); AndroidBuildConfigExternalActionArgs jsonArgs = AndroidBuildConfigExternalActionArgs.of( buildTarget.getUnflavoredBuildTarget().toString(), javaPackage, useConstantExpressions, valuesFile.map( file -> buildContext .getSourcePathResolver() .getRelativePath(filesystem, file) .toString()), defaultValues.getNameToField().values().stream() .map(BuildConfigFields.Field::toString) .collect(ImmutableList.toImmutableList()), outputPathResolver.resolvePath(outputPath).toString()); ExternalActionsUtils.writeJsonArgs(jsonFilePath, jsonArgs); return BuildableCommand.newBuilder() .addExtraFiles(jsonFilePath.toString()) .setExternalActionClass(AndroidBuildConfigExternalAction.class.getName()) .build(); } private Path createTempFile(ProjectFilesystem filesystem) { try { return filesystem.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX); } catch (IOException e) { throw new IllegalStateException( "Failed to create temp file when creating android build config buildable command"); } } } }
36.226337
100
0.704646
38b47e41f3776d3ed2440af32671a0e9c812db91
536
package greedyalgorithm; import java.util.Arrays; public class MarcCakeWalk { private static long marcsCakewalk(int[] calorie) { Arrays.sort(calorie); long min = 0; int i=0; for (int j = calorie.length -1; j >= 0; j--) { min = (long) (min + (Math.pow(2,i) * calorie[j])); i++; } return min; } public static void main(String[] args) { int[] inputArray = new int[]{7, 4, 9, 6}; System.out.println(marcsCakewalk(inputArray)); } }
23.304348
63
0.537313
8cefd25bbed08d31d485a83ce84272162079da44
1,911
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package hmi.animation; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.google.common.collect.ImmutableMap; /** * Helper class to more efficiently obtain parts from a VJoint tree. * @author hvanwelbergen */ public class VJointPartsMap { private Map<String,VJoint> jointMap; public VJointPartsMap(VJoint vjRoot) { Map<String,VJoint> m = new HashMap<String,VJoint>(); m.put(vjRoot.getSid(),vjRoot); for(VJoint vj: vjRoot.getParts()) { if(vj.getSid() != null) { m.put(vj.getSid(),vj); } } jointMap = ImmutableMap.copyOf(m); } public VJoint get(String sid) { return jointMap.get(sid); } public Collection<VJoint>getJoints() { return jointMap.values(); } }
32.389831
91
0.609628
1426cab8fdfd37e1a478f63ea4b45acd3b4df38d
5,935
package org.apache.archiva.metadata.repository; /* * 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.archiva.metadata.model.ArtifactMetadata; import org.apache.archiva.metadata.model.MetadataFacet; import org.apache.archiva.metadata.model.ProjectMetadata; import org.apache.archiva.metadata.model.ProjectVersionMetadata; import org.apache.archiva.metadata.model.ProjectVersionReference; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; public class TestMetadataRepository implements MetadataRepository { public ProjectMetadata getProject( String repoId, String namespace, String projectId ) { return null; } public ProjectVersionMetadata getProjectVersion( String repoId, String namespace, String projectId, String projectVersion ) { return null; } public Collection<String> getArtifactVersions( String repoId, String namespace, String projectId, String projectVersion ) { return null; } public Collection<ProjectVersionReference> getProjectReferences( String repoId, String namespace, String projectId, String projectVersion ) { return null; } public Collection<String> getRootNamespaces( String repoId ) { return null; } public Collection<String> getNamespaces( String repoId, String namespace ) { return null; } public Collection<String> getProjects( String repoId, String namespace ) { return null; } public Collection<String> getProjectVersions( String repoId, String namespace, String projectId ) { return null; } public void updateProject( String repoId, ProjectMetadata project ) { } public void updateArtifact( String repoId, String namespace, String projectId, String projectVersion, ArtifactMetadata artifactMeta ) { } public void updateProjectVersion( String repoId, String namespace, String projectId, ProjectVersionMetadata versionMetadata ) { } public void updateNamespace( String repoId, String namespace ) { } public List<String> getMetadataFacets( String repodId, String facetId ) { return Collections.emptyList(); } public MetadataFacet getMetadataFacet( String repositoryId, String facetId, String name ) { return null; } public void addMetadataFacet( String repositoryId, MetadataFacet metadataFacet ) { } public void removeMetadataFacets( String repositoryId, String facetId ) { } public void removeMetadataFacet( String repoId, String facetId, String name ) { } public List<ArtifactMetadata> getArtifactsByDateRange( String repoId, Date startTime, Date endTime ) { return null; } public Collection<String> getRepositories() { return null; } public List<ArtifactMetadata> getArtifactsByChecksum( String repoId, String checksum ) { return null; } public void removeArtifact( String repositoryId, String namespace, String project, String version, String id ) { } public void removeRepository( String repoId ) { } public Collection<ArtifactMetadata> getArtifacts( String repoId, String namespace, String projectId, String projectVersion ) { return null; } public void save() { } public void close() { } public void revert() { } public boolean canObtainAccess( Class<?> aClass ) { return false; } public <T>T obtainAccess( Class<T> aClass ) { return null; } public List<ArtifactMetadata> getArtifacts( String repositoryId ) { return null; } public void removeArtifact( String repositoryId, String namespace, String project, String version, MetadataFacet metadataFacet ) throws MetadataRepositoryException { throw new UnsupportedOperationException(); } public void removeArtifact( ArtifactMetadata artifactMetadata, String baseVersion ) throws MetadataRepositoryException { throw new UnsupportedOperationException(); } public void removeNamespace( String repositoryId, String namespace ) throws MetadataRepositoryException { } public void removeProjectVersion( String repoId, String namespace, String projectId, String projectVersion ) throws MetadataRepositoryException { } public void removeProject( String repositoryId, String namespace, String projectId ) throws MetadataRepositoryException { throw new UnsupportedOperationException(); } public boolean hasMetadataFacet( String repositoryId, String facetId ) throws MetadataRepositoryException { return false; } }
26.495536
119
0.66588
36a2dbc65f42d8dfb99387f189e3502c4e08951c
235
package com.shangame.fiction.ui.my.account.coin; /** * Create by Speedy on 2019/1/3 */ public class CoinState { public static final int VALID = 0; public static final int USED = 1; public static final int EXPIRE = 2; }
19.583333
48
0.680851
828984bab045dc054fa4d19ec9b0b5650cef024f
4,182
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2021 Adobe ~ ~ 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.adobe.cq.commerce.core.components.internal.models.v1.page; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.Set; import com.adobe.cq.export.json.ComponentExporter; import com.adobe.cq.wcm.core.components.models.HtmlPageItem; import com.adobe.cq.wcm.core.components.models.NavigationItem; import com.adobe.cq.wcm.core.components.models.Page; import com.adobe.cq.wcm.core.components.models.datalayer.ComponentData; abstract class AbstractPageDelegator implements Page { protected abstract Page getDelegate(); @Override public String getLanguage() { return getDelegate().getLanguage(); } @Override public Calendar getLastModifiedDate() { return getDelegate().getLastModifiedDate(); } @Override public String[] getKeywords() { return getDelegate().getKeywords(); } @Override public String getDesignPath() { return getDelegate().getDesignPath(); } @Override public String getStaticDesignPath() { return getDelegate().getStaticDesignPath(); } @Override @Deprecated public Map<String, String> getFavicons() { return getDelegate().getFavicons(); } @Override public String getTitle() { return getDelegate().getTitle(); } @Override public String getBrandSlug() { return getDelegate().getBrandSlug(); } @Override public String[] getClientLibCategories() { return getDelegate().getClientLibCategories(); } @Override public String[] getClientLibCategoriesJsBody() { return getDelegate().getClientLibCategoriesJsBody(); } @Override public String[] getClientLibCategoriesJsHead() { return getDelegate().getClientLibCategoriesJsHead(); } @Override public String getTemplateName() { return getDelegate().getTemplateName(); } @Override public String getAppResourcesPath() { return getDelegate().getAppResourcesPath(); } @Override public String getCssClassNames() { return getDelegate().getCssClassNames(); } @Override public NavigationItem getRedirectTarget() { return getDelegate().getRedirectTarget(); } @Override public boolean hasCloudconfigSupport() { return getDelegate().hasCloudconfigSupport(); } @Override public Set<String> getComponentsResourceTypes() { return getDelegate().getComponentsResourceTypes(); } @Override public String[] getExportedItemsOrder() { return getDelegate().getExportedItemsOrder(); } @Override public Map<String, ? extends ComponentExporter> getExportedItems() { return getDelegate().getExportedItems(); } @Override public String getExportedType() { return getDelegate().getExportedType(); } @Override public String getMainContentSelector() { return getDelegate().getMainContentSelector(); } @Override public List<HtmlPageItem> getHtmlPageItems() { return getDelegate().getHtmlPageItems(); } @Override public String getId() { return getDelegate().getId(); } @Override public ComponentData getData() { return getDelegate().getData(); } @Override public String getAppliedCssClasses() { return getDelegate().getAppliedCssClasses(); } }
26.301887
80
0.654232
0b1fb4e355e5d366404e9937001d39e515ac475d
1,348
package com.ruverq.mauris.compatibility; import com.ruverq.mauris.items.ItemsLoader; import com.ruverq.mauris.items.MaurisItem; import io.lumine.xikage.mythicmobs.adapters.bukkit.BukkitItemStack; import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicDropLoadEvent; import io.lumine.xikage.mythicmobs.drops.droppables.ItemDrop; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; public class MythicMobsLoot implements Listener { @EventHandler public void onLootLoad(MythicDropLoadEvent e){ if(!e.getDropName().equalsIgnoreCase("mauris")) return; String line = e.getContainer().getLine(); String[] args = line.split(" "); MaurisItem item = ItemsLoader.getMaurisItem(args[1]); MaurisItem item2 = ItemsLoader.getMaurisItem(args[2]); if(args.length == 4 && item != null){ ItemStack itemstack = item.getAsItemStack(); ItemDrop itemDrop = new ItemDrop(line, e.getConfig(), new BukkitItemStack(itemstack)); e.register(itemDrop); }else if(args.length == 3 && item2 != null){ ItemStack itemstack = item2.getAsItemStack(); ItemDrop itemDrop = new ItemDrop(line, e.getConfig(), new BukkitItemStack(itemstack)); e.register(itemDrop); } } }
36.432432
98
0.697329
4e4f2345a6afccd2a782867221e41115d9e88b99
22,664
package br.com.gplab.analysis.mappings; import org.json.JSONObject; public class PepAnalysisConsts { private String splitChar = "\\t"; public String getSplitChar() { return splitChar; } public void setSplitChar(String splitChar) { this.splitChar = splitChar; } private int rawFile_ndx = -1; //0 public int getRawFile_ndx() { return rawFile_ndx; } public void setRawFile_ndx(int rawFile_ndx) { this.rawFile_ndx = rawFile_ndx; } private int type_ndx = -1; //1 public int getType_ndx() { return type_ndx; } public void setType_ndx(int type_ndx) { this.type_ndx = type_ndx; } private int charge_ndx = -1; //2 public int getCharge_ndx() { return charge_ndx; } public void setCharge_ndx(int charge_ndx) { this.charge_ndx = charge_ndx; } private int massCharge_ndx = -1; //3 public int getMassCharge_ndx() { return massCharge_ndx; } public void setMassCharge_ndx(int massCharge_ndx) { this.massCharge_ndx = massCharge_ndx; } private int mass_ndx = -1; //4 public int getMass_ndx() { return mass_ndx; } public void setMass_ndx(int mass_ndx) { this.mass_ndx = mass_ndx; } private int uncalibratedMZ_ndx = -1; //5 public int getUncalibratedMZ_ndx() { return uncalibratedMZ_ndx; } public void setUncalibratedMZ_ndx(int uncalibratedMZ_ndx) { this.uncalibratedMZ_ndx = uncalibratedMZ_ndx; } private int resolution_ndx = -1; //6 public int getResolution_ndx() { return resolution_ndx; } public void setResolution_ndx(int resolution_ndx) { this.resolution_ndx = resolution_ndx; } private int nDataPoints_ndx = -1; //7 public int getNDataPoints_ndx() { return nDataPoints_ndx; } public void setNDataPoints_ndx(int nDataPoints_ndx) { this.nDataPoints_ndx = nDataPoints_ndx; } private int nScans_ndx = -1; //8 public int getNScans_ndx() { return nScans_ndx; } public void setNScans_ndx(int nDataPoints_ndx) { this.nDataPoints_ndx = nScans_ndx; } private int nIsotopicPeaks_ndx = -1; //9 public int getNIsotopicPeaks_ndx() { return nIsotopicPeaks_ndx; } public void setNIsotopicPeaks_ndx(int nIsotopicPeaks_ndx) { this.nIsotopicPeaks_ndx = nIsotopicPeaks_ndx; } private int massFractional_ndx = -1; //11 public int getMassFractional_ndx() { return massFractional_ndx; } public void setMassFractional_ndx(int massFractional_ndx) { this.massFractional_ndx = massFractional_ndx; } private int massDeficit_ndx = -1; //12 public int getMassDeficit_ndx() { return massDeficit_ndx; } public void setMassDeficit_ndx(int massDeficit_ndx) { this.massDeficit_ndx = massDeficit_ndx; } private int massPrecision_ndx = -1; //13 public int getMassPrecision_ndx() { return massPrecision_ndx; } public void setMassPrecision_ndx(int massPrecision_ndx) { this.massPrecision_ndx = massPrecision_ndx; } private int maxPrecision_ndx = -1; //14 public int getMaxPrecision_ndx() { return maxPrecision_ndx; } public void setMaxPrecision_ndx(int maxPrecision_ndx) { this.maxPrecision_ndx = maxPrecision_ndx; } private int retentionTime_ndx = -1; //15 public int getRetentionTime_ndx() { return retentionTime_ndx; } public void setRetentionTime_ndx(int retentionTime_ndx) { this.retentionTime_ndx = retentionTime_ndx; } private int retentionLength_ndx = -1; //16 public int getRetentionLength_ndx() { return retentionLength_ndx; } public void setRetentionLength_ndx(int retentionLength_ndx) { this.retentionLength_ndx = retentionLength_ndx; } private int minScanNumber_ndx = -1; //18 public int getMinScanNumber_ndx() { return minScanNumber_ndx; } public void setMinScanNumber_ndx(int minScanNumber_ndx) { this.minScanNumber_ndx = minScanNumber_ndx; } private int maxScanNumber_ndx = -1; //19 public int getMaxScanNumber_ndx() { return maxScanNumber_ndx; } public void setMaxScanNumber_ndx(int maxScanNumber_ndx) { this.maxScanNumber_ndx = maxScanNumber_ndx; } private int msmsIds_ndx= -1; //21 public int getMsmsIds_ndx() { return msmsIds_ndx; } public void setMsmsIds_ndx(int msmsIds_ndx) { this.msmsIds_ndx = msmsIds_ndx; } private int sequence_ndx= -1; //22 public int getSequence_ndx() { return sequence_ndx; } public void setSequence_ndx(int sequence_ndx) { this.sequence_ndx = sequence_ndx; } private int modifications_ndx= -1; //24 public int getModifications_ndx() { return modifications_ndx; } public void setModifications_ndx(int modifications_ndx) { this.modifications_ndx = modifications_ndx; } private int modifiedSequence_ndx = -1; //25 public int getModifiedSequence_ndx() { return modifiedSequence_ndx; } public void setModifiedSequence_ndx(int modifiedSequence_ndx) { this.modifiedSequence_ndx = modifiedSequence_ndx; } private int proteins_ndx = -1; //26 public int getProteins_ndx() { return proteins_ndx; } public void setProteins_ndx(int proteins_ndx) { this.proteins_ndx = proteins_ndx; } private int score_ndx = -1; //27 public int getScore_ndx() { return score_ndx; } public void setScore_ndx(int score_ndx) { this.score_ndx = score_ndx; } private int intensity_ndx = -1; //28 public int getIntensity_ndx() { return intensity_ndx; } public void setIntensity_ndx(int intensity_ndx) { this.intensity_ndx = intensity_ndx; } private int intensities_ndx = -1; //29 public int getIntensities_ndx() { return intensities_ndx; } public void setIntensities_ndx(int intensities_ndx) { this.intensities_ndx = intensities_ndx; } private int msmsCount_ndx = -1; //30 public int getMsmsCount_ndx() { return msmsCount_ndx; } public void setMsmsCount_ndx(int msmsCount_ndx) { this.msmsCount_ndx = msmsCount_ndx; } private int msmsScanNs_ndx = -1; //31 public int getMsmsScanNs_ndx() { return msmsScanNs_ndx; } public void setMsmsScanNs_ndx(int msmsScanNs_ndx) { this.msmsScanNs_ndx = msmsScanNs_ndx; } private int msmsIsotopeNdxs_ndx = -1; //32 public int getMsmsIsotopeNdxs_ndx() { return msmsIsotopeNdxs_ndx; } public void setMsmsIsotopeNdxs_ndx(int msmsIsotopeNdxs_ndx) { this.msmsIsotopeNdxs_ndx = msmsIsotopeNdxs_ndx; } private int dpMassDifference_ndx = -1; //33 public int getDpMassDifference_ndx() { return dpMassDifference_ndx; } public void setDpMassDifference_ndx(int dpMassDifference_ndx) { this.dpMassDifference_ndx = dpMassDifference_ndx; } private int dpTimeDifference_ndx = -1; //34 public int getDpTimeDifference_ndx() { return dpTimeDifference_ndx; } public void setDpTimeDifference_ndx(int dpTimeDifference_ndx) { this.dpTimeDifference_ndx = dpTimeDifference_ndx; } private int dpScore_ndx = -1; //35 public int getDpScore_ndx() { return dpScore_ndx; } public void setDpScore_ndx(int dpScore_ndx) { this.dpScore_ndx = dpScore_ndx; } private int dpPep_ndx = -1; //36 public int getDpPep_ndx() { return dpPep_ndx; } public void setDpPep_ndx(int dpPep_ndx) { this.dpPep_ndx = dpPep_ndx; } private int dpPositionalProbability_ndx = -1; //37 public int getDpPositionalProbability_ndx() { return dpPositionalProbability_ndx; } public void setDpPositionalProbability_ndx(int dpPositionalProbability_ndx) { this.dpPositionalProbability_ndx = dpPositionalProbability_ndx; } private int dpBaseSequence_ndx = -1; //38 public int getDpBaseSequence_ndx() { return dpBaseSequence_ndx; } public void setDpBaseSequence_ndx(int dpBaseSequence_ndx) { this.dpBaseSequence_ndx = dpBaseSequence_ndx; } private int dpProbabilities_ndx = -1; //39 public int getDpProbabilities_ndx() { return dpProbabilities_ndx; } public void setDpProbabilities_ndx(int dpProbabilities_ndx) { this.dpProbabilities_ndx = dpProbabilities_ndx; } private int dpAA_ndx = -1; //40 public int getDpAA_ndx() { return dpAA_ndx; } public void setDpAA_ndx(int dpAA_ndx) { this.dpAA_ndx = dpAA_ndx; } private int dpBaseScanNum_ndx = -1; //41 public int getDpBaseScanNum_ndx() { return dpBaseScanNum_ndx; } public void setDpBaseScanNum_ndx(int dpBaseScanNum_ndx) { this.dpBaseScanNum_ndx = dpBaseScanNum_ndx; } private int dpModScanNum_ndx = -1; //42 public int getDpModScanNum_ndx() { return dpModScanNum_ndx; } public void setDpModScanNum_ndx(int dpModScanNum_ndx) { this.dpModScanNum_ndx = dpModScanNum_ndx; } private int dpDecoy_ndx = -1; //43 public int getDpDecoy_ndx() { return dpDecoy_ndx; } public void setDpDecoy_ndx(int dpDecoy_ndx) { this.dpDecoy_ndx = dpDecoy_ndx; } private int dpProteins_ndx = -1; //44 public int getDpProteins_ndx() { return dpProteins_ndx; } public void setDpProteins_ndx(int dpProteins_ndx) { this.dpProteins_ndx = dpProteins_ndx; } private int dpClusterIndex_ndx = -1; //45 public int getDpClusterIndex_ndx() { return dpClusterIndex_ndx; } public void setDpClusterIndex_ndx(int dpClusterIndex_ndx) { this.dpClusterIndex_ndx = dpClusterIndex_ndx; } private int dpClusterMass_ndx = -1; //46 public int getDpClusterMass_ndx() { return dpClusterMass_ndx; } public void setDpClusterMass_ndx(int dpClusterMass_ndx) { this.dpClusterMass_ndx = dpClusterMass_ndx; } private int dpClusterMassSD_ndx = -1; //47 public int getDpClusterMassSD_ndx() { return dpClusterMassSD_ndx; } public void setDpClusterMassSD_ndx(int dpClusterMassSD_ndx) { this.dpClusterMassSD_ndx = dpClusterMassSD_ndx; } private int dpClusterSizeTotal_ndx = -1; //48 public int getDpClusterSizeTotal_ndx() { return dpClusterSizeTotal_ndx; } public void setDpClusterSizeTotal_ndx(int dpClusterSizeTotal_ndx) { this.dpClusterSizeTotal_ndx = dpClusterSizeTotal_ndx; } private int dpClusterSizeForward_ndx = -1; //49 public int getDpClusterSizeForward_ndx() { return dpClusterSizeForward_ndx; } public void setDpClusterSizeForward_ndx(int dpClusterSizeForward_ndx) { this.dpClusterSizeForward_ndx = dpClusterSizeForward_ndx; } private int dpClusterSizeReverse_ndx = -1; //50 public int getDpClusterSizeReverse_ndx() { return dpClusterSizeReverse_ndx; } public void setDpClusterSizeReverse_ndx(int dpClusterSizeReverse_ndx) { this.dpClusterSizeReverse_ndx = dpClusterSizeReverse_ndx; } private int dpModification_ndx = -1; //51 public int getDpModification_ndx() { return dpModification_ndx; } public void setDpModification_ndx(int dpModification_ndx) { this.dpModification_ndx = dpModification_ndx; } private int dpPepLengthDiff_ndx = -1; //52 public int getDpPepLengthDiff_ndx() { return dpPepLengthDiff_ndx; } public void setDpPepLengthDiff_ndx(int dpPepLengthDiff_ndx) { this.dpPepLengthDiff_ndx = dpPepLengthDiff_ndx; } private int dpRatioMB_ndx = -1; //53 public int getDpRatioMB_ndx() { return dpRatioMB_ndx; } public void setDpRatioMB_ndx(int dpRatioMB_ndx) { this.dpRatioMB_ndx = dpRatioMB_ndx; } public void ConfigureApplication(JSONObject payload) { if (payload.has("splitChar")) setSplitChar(payload.getString("splitChar")); if (payload.has("rawFile_ndx")) setRawFile_ndx(payload.getInt("rawFile_ndx")); if (payload.has("type_ndx")) setType_ndx(payload.getInt("type_ndx")); if (payload.has("charge_ndx")) setCharge_ndx(payload.getInt("charge_ndx")); if (payload.has("massCharge_ndx")) setMassCharge_ndx(payload.getInt("massCharge_ndx")); if (payload.has("mass_ndx")) setMass_ndx(payload.getInt("mass_ndx")); if (payload.has("uncalibratedMZ_ndx")) setUncalibratedMZ_ndx(payload.getInt("uncalibratedMZ_ndx")); if (payload.has("resolution_ndx")) setResolution_ndx(payload.getInt("resolution_ndx")); if (payload.has("nDataPoints_ndx")) setNDataPoints_ndx(payload.getInt("nDataPoints_ndx")); if (payload.has("nScans_ndx")) setNScans_ndx(payload.getInt("nScans_ndx")); if (payload.has("nIsotopicPeaks_ndx")) setNIsotopicPeaks_ndx(payload.getInt("nIsotopicPeaks_ndx")); if (payload.has("massFractional_ndx")) setMassFractional_ndx(payload.getInt("massFractional_ndx")); if (payload.has("massDeficit_ndx")) setMassDeficit_ndx(payload.getInt("massDeficit_ndx")); if (payload.has("massPrecision_ndx")) setMassPrecision_ndx(payload.getInt("massPrecision_ndx")); if (payload.has("maxPrecision_ndx")) setMaxPrecision_ndx(payload.getInt("maxPrecision_ndx")); if (payload.has("retentionTime_ndx")) setRetentionTime_ndx(payload.getInt("retentionTime_ndx")); if (payload.has("retentionLength_ndx")) setRetentionLength_ndx(payload.getInt("retentionLength_ndx")); if (payload.has("minScanNumber_ndx")) setMinScanNumber_ndx(payload.getInt("minScanNumber_ndx")); if (payload.has("maxScanNumber_ndx")) setMaxScanNumber_ndx(payload.getInt("maxScanNumber_ndx")); if (payload.has("msmsIds_ndx")) setMsmsIds_ndx(payload.getInt("msmsIds_ndx")); if (payload.has("sequence_ndx")) setSequence_ndx(payload.getInt("sequence_ndx")); if (payload.has("modifications_ndx")) setModifications_ndx(payload.getInt("modifications_ndx")); if (payload.has("modifiedSequence_ndx")) setModifiedSequence_ndx(payload.getInt("modifiedSequence_ndx")); if (payload.has("proteins_ndx")) setProteins_ndx(payload.getInt("proteins_ndx")); if (payload.has("score_ndx")) setScore_ndx(payload.getInt("score_ndx")); if (payload.has("intensity_ndx")) setIntensity_ndx(payload.getInt("intensity_ndx")); if (payload.has("intensities_ndx")) setIntensities_ndx(payload.getInt("intensities_ndx")); if (payload.has("msmsCount_ndx")) setMsmsCount_ndx(payload.getInt("msmsCount_ndx")); if (payload.has("msmsScanNs_ndx")) setMsmsScanNs_ndx(payload.getInt("msmsScanNs_ndx")); if (payload.has("msmsIsotopeNdxs_ndx")) setMsmsIsotopeNdxs_ndx(payload.getInt("msmsIsotopeNdxs_ndx")); if (payload.has("dpMassDifference_ndx")) setDpMassDifference_ndx(payload.getInt("dpMassDifference_ndx")); if (payload.has("dpTimeDifference_ndx")) setDpTimeDifference_ndx(payload.getInt("dpTimeDifference_ndx")); if (payload.has("dpScore_ndx")) setDpScore_ndx(payload.getInt("dpScore_ndx")); if (payload.has("dpPep_ndx")) setDpPep_ndx(payload.getInt("dpPep_ndx")); if (payload.has("dpPositionalProbability_ndx")) setDpPositionalProbability_ndx(payload.getInt("dpPositionalProbability_ndx")); if (payload.has("dpBaseSequence_ndx")) setDpBaseSequence_ndx(payload.getInt("dpBaseSequence_ndx")); if (payload.has("dpProbabilities_ndx")) setDpProbabilities_ndx(payload.getInt("dpProbabilities_ndx")); if (payload.has("dpAA_ndx")) setDpAA_ndx(payload.getInt("dpAA_ndx")); if (payload.has("dpBaseScanNum_ndx")) setDpBaseScanNum_ndx(payload.getInt("dpBaseScanNum_ndx")); if (payload.has("dpModScanNum_ndx")) setDpModScanNum_ndx(payload.getInt("dpModScanNum_ndx")); if (payload.has("dpDecoy_ndx")) setDpDecoy_ndx(payload.getInt("dpDecoy_ndx")); if (payload.has("dpProteins_ndx")) setDpProteins_ndx(payload.getInt("dpProteins_ndx")); if (payload.has("dpClusterIndex_ndx")) setDpClusterIndex_ndx(payload.getInt("dpClusterIndex_ndx")); if (payload.has("dpClusterMass_ndx")) setDpClusterMass_ndx(payload.getInt("dpClusterMass_ndx")); if (payload.has("dpClusterMassSD_ndx")) setDpClusterMassSD_ndx(payload.getInt("dpClusterMassSD_ndx")); if (payload.has("dpClusterSizeTotal_ndx")) setDpClusterSizeTotal_ndx(payload.getInt("dpClusterSizeTotal_ndx")); if (payload.has("dpClusterSizeForward_ndx")) setDpClusterSizeForward_ndx(payload.getInt("dpClusterSizeForward_ndx")); if (payload.has("dpClusterSizeReverse_ndx")) setDpClusterSizeReverse_ndx(payload.getInt("dpClusterSizeReverse_ndx")); if (payload.has("dpModification_ndx")) setDpModification_ndx(payload.getInt("dpModification_ndx")); if (payload.has("dpPepLengthDiff_ndx")) setDpPepLengthDiff_ndx(payload.getInt("dpPepLengthDiff_ndx")); if (payload.has("dpRatioMB_ndx")) setDpRatioMB_ndx(payload.getInt("dpRatioMB_ndx")); }//--- End: ConfigureApplication (JSONObject) public void ConfigureApplication(PepAnalysisConsts payload) { if (payload.getSplitChar().length() > 0) setSplitChar(payload.getSplitChar()); if (payload.getRawFile_ndx() >= 0) setRawFile_ndx(payload.getRawFile_ndx()); if (payload.getType_ndx() >= 0) setType_ndx(payload.getType_ndx()); if (payload.getCharge_ndx() >= 0) setCharge_ndx(payload.getCharge_ndx()); if (payload.getMassCharge_ndx() >= 0) setMassCharge_ndx(payload.getMassCharge_ndx()); if (payload.getMass_ndx() >= 0) setMass_ndx(payload.getMass_ndx()); if (payload.getUncalibratedMZ_ndx() >= 0) setUncalibratedMZ_ndx(payload.getUncalibratedMZ_ndx()); if (payload.getResolution_ndx() >= 0) setResolution_ndx(payload.getResolution_ndx()); if (payload.getNDataPoints_ndx() >= 0) setNDataPoints_ndx(payload.getNDataPoints_ndx()); if (payload.getNScans_ndx() >= 0) setNScans_ndx(payload.getNScans_ndx()); if (payload.getNIsotopicPeaks_ndx() >= 0) setNIsotopicPeaks_ndx(payload.getNIsotopicPeaks_ndx()); if (payload.getMassFractional_ndx() >= 0) setMassFractional_ndx(payload.getMassFractional_ndx()); if (payload.getMassDeficit_ndx() >= 0) setMassDeficit_ndx(payload.getMassDeficit_ndx()); if (payload.getMassPrecision_ndx() >= 0) setMassPrecision_ndx(payload.getMassPrecision_ndx()); if (payload.getMaxPrecision_ndx() >= 0) setMaxPrecision_ndx(payload.getMaxPrecision_ndx()); if (payload.getRetentionTime_ndx() >= 0) setRetentionTime_ndx(payload.getRetentionTime_ndx()); if (payload.getRetentionLength_ndx() >= 0) setRetentionLength_ndx(payload.getRetentionLength_ndx()); if (payload.getMinScanNumber_ndx() >= 0) setMinScanNumber_ndx(payload.getMinScanNumber_ndx()); if (payload.getMaxScanNumber_ndx() >= 0) setMaxScanNumber_ndx(payload.getMaxScanNumber_ndx()); if (payload.getMsmsIds_ndx() >= 0) setMsmsIds_ndx(payload.getMsmsIds_ndx()); if (payload.getSequence_ndx() >= 0) setSequence_ndx(payload.getSequence_ndx()); if (payload.getModifications_ndx() >= 0) setModifications_ndx(payload.getModifications_ndx()); if (payload.getModifiedSequence_ndx() >= 0) setModifiedSequence_ndx(payload.getModifiedSequence_ndx()); if (payload.getProteins_ndx() >= 0) setProteins_ndx(payload.getProteins_ndx()); if (payload.getScore_ndx() >= 0) setScore_ndx(payload.getScore_ndx()); if (payload.getIntensity_ndx() >= 0) setIntensity_ndx(payload.getIntensity_ndx()); if (payload.getIntensities_ndx() >= 0) setIntensities_ndx(payload.getIntensities_ndx()); if (payload.getMsmsCount_ndx() >= 0) setMsmsCount_ndx(payload.getMsmsCount_ndx()); if (payload.getMsmsScanNs_ndx() >= 0) setMsmsScanNs_ndx(payload.getMsmsScanNs_ndx()); if (payload.getMsmsIsotopeNdxs_ndx() >= 0) setMsmsIsotopeNdxs_ndx(payload.getMsmsIsotopeNdxs_ndx()); if (payload.getDpMassDifference_ndx() >= 0) setDpMassDifference_ndx(payload.getDpMassDifference_ndx()); if (payload.getDpTimeDifference_ndx() >= 0) setDpTimeDifference_ndx(payload.getDpTimeDifference_ndx()); if (payload.getDpScore_ndx() >= 0) setDpScore_ndx(payload.getDpScore_ndx()); if (payload.getDpPep_ndx() >= 0) setDpPep_ndx(payload.getDpPep_ndx()); if (payload.getDpPositionalProbability_ndx() >= 0) setDpPositionalProbability_ndx(payload.getDpPositionalProbability_ndx()); if (payload.getDpBaseSequence_ndx() >= 0) setDpBaseSequence_ndx(payload.getDpBaseSequence_ndx()); if (payload.getDpProbabilities_ndx() >= 0) setDpProbabilities_ndx(payload.getDpProbabilities_ndx()); if (payload.getDpAA_ndx() >= 0) setDpAA_ndx(payload.getDpAA_ndx()); if (payload.getDpBaseScanNum_ndx() >= 0) setDpBaseScanNum_ndx(payload.getDpBaseScanNum_ndx()); if (payload.getDpModScanNum_ndx() >= 0) setDpModScanNum_ndx(payload.getDpModScanNum_ndx()); if (payload.getDpDecoy_ndx() >= 0) setDpDecoy_ndx(payload.getDpDecoy_ndx()); if (payload.getDpProteins_ndx() >= 0) setDpProteins_ndx(payload.getDpProteins_ndx()); if (payload.getDpClusterIndex_ndx() >= 0) setDpClusterIndex_ndx(payload.getDpClusterIndex_ndx()); if (payload.getDpClusterMass_ndx() >= 0) setDpClusterMass_ndx(payload.getDpClusterMass_ndx()); if (payload.getDpClusterMassSD_ndx() >= 0) setDpClusterMassSD_ndx(payload.getDpClusterMassSD_ndx()); if (payload.getDpClusterSizeTotal_ndx() >= 0) setDpClusterSizeTotal_ndx(payload.getDpClusterSizeTotal_ndx()); if (payload.getDpClusterSizeForward_ndx() >= 0) setDpClusterSizeForward_ndx(payload.getDpClusterSizeForward_ndx()); if (payload.getDpClusterSizeReverse_ndx() >= 0) setDpClusterSizeReverse_ndx(payload.getDpClusterSizeReverse_ndx()); if (payload.getDpModification_ndx() >= 0) setDpModification_ndx(payload.getDpModification_ndx()); if (payload.getDpPepLengthDiff_ndx() >= 0) setDpPepLengthDiff_ndx(payload.getDpPepLengthDiff_ndx()); if (payload.getDpRatioMB_ndx() >= 0) setDpRatioMB_ndx(payload.getDpRatioMB_ndx()); }//--- End: ConfigureApplication (AnalysisConsts) public void SetDefaults() { setSplitChar("\\t"); setRawFile_ndx(0); setType_ndx(1); setCharge_ndx(2); setMassCharge_ndx(3); setMass_ndx(4); setUncalibratedMZ_ndx(5); setResolution_ndx(6); setNDataPoints_ndx(7); setNScans_ndx(8); setNIsotopicPeaks_ndx(9); setMassFractional_ndx(11); setMassDeficit_ndx(12); setMassPrecision_ndx(13); setMaxPrecision_ndx(14); setRetentionTime_ndx(15); setRetentionLength_ndx(16); setMinScanNumber_ndx(18); setMaxScanNumber_ndx(19); setMsmsIds_ndx(21); setSequence_ndx(22); setModifications_ndx(24); setModifiedSequence_ndx(25); setProteins_ndx(26); setScore_ndx(27); setIntensity_ndx(28); setIntensities_ndx(29); setMsmsCount_ndx(30); setMsmsScanNs_ndx(31); setMsmsIsotopeNdxs_ndx(32); setDpMassDifference_ndx(33); setDpTimeDifference_ndx(34); setDpScore_ndx(35); setDpPep_ndx(36); setDpPositionalProbability_ndx(37); setDpBaseSequence_ndx(38); setDpProbabilities_ndx(39); setDpAA_ndx(40); setDpBaseScanNum_ndx(41); setDpModScanNum_ndx(42); setDpDecoy_ndx(43); setDpProteins_ndx(44); setDpClusterIndex_ndx(45); setDpClusterMass_ndx(46); setDpClusterMassSD_ndx(47); setDpClusterSizeTotal_ndx(48); setDpClusterSizeForward_ndx(49); setDpClusterSizeReverse_ndx(50); setDpModification_ndx(51); setDpPepLengthDiff_ndx(52); setDpRatioMB_ndx(53); }//--- End: SetDefaults }
38.675768
147
0.748544
3ec4c74f331ac7ae7aed352a508aa9e1bb6b8294
996
package com.ansar.jeticketprinter.model.dto; import com.ansar.jeticketprinter.model.pojo.IntervalProduct; import org.junit.Test; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; public class TestIntervalProduct { @Test public void testInsertIntervalProducts(){ Set<IntervalProduct> intervalProducts = new HashSet<>(); IntervalProduct intervalProduct1 = new IntervalProduct("a", "2", "2", "1", "2020-01-01 00:00"); IntervalProduct intervalProduct2 = new IntervalProduct("a", "2", "2", "1", "2021-01-01 00:00"); IntervalProduct intervalProduct3 = new IntervalProduct("a", "2", "2", "1", "2022-01-01 00:00"); intervalProducts.add(intervalProduct1); intervalProducts.add(intervalProduct2); intervalProducts.add(intervalProduct3); System.out.println(intervalProducts.size()); for (IntervalProduct product: intervalProducts) System.out.println(product.getDate()); } }
31.125
103
0.694779
886ed6e3846af8a594fa7aa80107b8c1106a71c3
591
/** * @Title: Content.java * @Package com.zgq.design._12strategypattern.example * @Description: TODO * @author Zhenggq * @date 2018年5月17日 * @version V1.0 */ package com.zhengq.designpattern._12strategypattern.example; /** * 锦囊(封装角色) * * @ClassName: Content * @Description: 它也叫做上下文角色,起承上启下封装作用,屏蔽高层模块对策略、算法的直接访问,封装可能存在的变化。 * * @author Zhenggq * @date 2018年5月17日 * */ public class Context { private IStrategy strategy; public Context(IStrategy _strategy) { this.strategy = _strategy; } // 使用计谋了,看我出招了 public void operate() { strategy.operate(); } }
17.909091
65
0.685279
3e58e63812a7c9f2df685d976fa2290f3a0e0285
7,249
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.lens.cube.metadata; import static java.util.Comparator.naturalOrder; import static org.apache.lens.cube.metadata.DateUtil.ABSDATE_PARSER; import java.util.Calendar; import java.util.Date; import java.util.Set; import java.util.stream.Stream; import org.apache.lens.cube.error.LensCubeErrorCode; import org.apache.lens.server.api.error.LensException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.ql.parse.ASTNode; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; /** * Timerange data structure */ @JsonIgnoreProperties({"astNode", "parent"}) @Data @EqualsAndHashCode(of = {"partitionColumn", "fromDate", "toDate"}) @Builder public class TimeRange { private final String partitionColumn; private final Date toDate; @NonNull private final Date fromDate; private final ASTNode astNode; private final ASTNode parent; private final int childIndex; public TimeRange truncate(Date candidateStartTime, Date candidateEndTime) { return TimeRange.builder().partitionColumn(getPartitionColumn()) .fromDate(Stream.of(getFromDate(), candidateStartTime).max(naturalOrder()).orElse(candidateStartTime)) .toDate(Stream.of(getToDate(), candidateEndTime).min(naturalOrder()).orElse(candidateEndTime)) .build(); } public boolean isCoverableBy(Set<UpdatePeriod> updatePeriods) { return DateUtil.isCoverableBy(fromDate, toDate, updatePeriods); } /** * Truncate time range using the update period. * The lower value of the truncated time range is the smallest date value equal to or larger than original * time range's lower value which lies at the update period's boundary. Similarly for higher value. * @param updatePeriod Update period to truncate time range with * @return truncated time range * @throws LensException If the truncated time range is invalid. */ public TimeRange truncate(UpdatePeriod updatePeriod) throws LensException { TimeRange timeRange = TimeRange.builder().partitionColumn(partitionColumn) .fromDate(updatePeriod.getCeilDate(fromDate)).toDate(updatePeriod.getFloorDate(toDate)).build(); timeRange.validate(); return timeRange; } public long milliseconds() { return toDate.getTime() - fromDate.getTime(); } public TimeRangeBuilder cloneAsBuilder() { return builder(). astNode(getAstNode()).childIndex(getChildIndex()).parent(getParent()).partitionColumn(getPartitionColumn()); } private boolean fromEqualsTo() { return fromDate.equals(toDate); } private boolean fromAfterTo() { return fromDate.after(toDate); } public boolean isValid() { return !(fromEqualsTo() || fromAfterTo()); } public void validate() throws LensException { if (partitionColumn == null || fromDate == null || toDate == null || fromEqualsTo()) { throw new LensException(LensCubeErrorCode.INVALID_TIME_RANGE.getLensErrorInfo()); } if (fromAfterTo()) { throw new LensException(LensCubeErrorCode.FROM_AFTER_TO.getLensErrorInfo(), fromDate.toString(), toDate.toString()); } } public String toTimeDimWhereClause(String prefix, String column) { if (StringUtils.isNotBlank(column)) { column = prefix + "." + column; } return column + " >= '" + DateUtil.HIVE_QUERY_DATE_PARSER.get().format(fromDate) + "'" + " AND " + column + " < '" + DateUtil.HIVE_QUERY_DATE_PARSER.get().format(toDate) + "'"; } @Override public String toString() { return partitionColumn + " [" + ABSDATE_PARSER.get().format(fromDate) + " to " + ABSDATE_PARSER.get().format(toDate) + ")"; } /** iterable from fromDate(including) to toDate(excluding) incrementing increment units of updatePeriod */ public static Iterable iterable(Date fromDate, Date toDate, UpdatePeriod updatePeriod, int increment) { return TimeRange.builder().fromDate(fromDate).toDate(toDate).build().iterable(updatePeriod, increment); } /** iterable from fromDate(including) incrementing increment units of updatePeriod. Do this numIters times */ public static Iterable iterable(Date fromDate, int numIters, UpdatePeriod updatePeriod, int increment) { return TimeRange.builder().fromDate(fromDate).build().iterable(updatePeriod, numIters, increment); } private Iterable iterable(UpdatePeriod updatePeriod, int numIters, int increment) { return new Iterable(updatePeriod, numIters, increment); } public Iterable iterable(UpdatePeriod updatePeriod, int increment) { if (increment == 0) { throw new UnsupportedOperationException("Can't iterate if iteration increment is zero"); } long numIters = DateUtil.getTimeDiff(fromDate, toDate, updatePeriod) / increment; return new Iterable(updatePeriod, numIters, increment); } /** Iterable so that foreach is supported */ public class Iterable implements java.lang.Iterable<Date> { private UpdatePeriod updatePeriod; private long numIters; private int increment; Iterable(UpdatePeriod updatePeriod, long numIters, int increment) { this.updatePeriod = updatePeriod; this.numIters = numIters; if (this.numIters < 0) { this.numIters = 0; } this.increment = increment; } @Override public Iterator iterator() { return new Iterator(); } public class Iterator implements java.util.Iterator<Date> { Calendar calendar; // Tracks the index of the item returned after the last next() call. // Index here refers to the index if the iterator were iterated and converted into a list. @Getter int counter = -1; public Iterator() { calendar = Calendar.getInstance(); calendar.setTime(fromDate); } @Override public boolean hasNext() { return counter < numIters - 1; } @Override public Date next() { Date cur = calendar.getTime(); updatePeriod.increment(calendar, increment); counter++; return cur; } public Date peekNext() { return calendar.getTime(); } @Override public void remove() { throw new UnsupportedOperationException("remove from timerange iterator"); } public long getNumIters() { return numIters; } } } }
34.35545
114
0.711546
e4a0a42fc25d083e8d1dddcd491c59e8d2ab3a9d
1,078
/* * Copyright (c) 2018. University of Applied Sciences and Arts Northwestern Switzerland FHNW. * All rights reserved. */ package ch.fhnw.digibp.examples.echo.dto; import java.io.Serializable; public class EchoData implements Serializable{ private String variableA; private String variableB; private String businessKey; private String processInstanceId; public String getVariableA() { return variableA; } public void setVariableA(String variableA) { this.variableA = variableA; } public String getVariableB() { return variableB; } public void setVariableB(String variableB) { this.variableB = variableB; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } }
22.458333
93
0.687384
f8b1ca4094eeb112b60f1d973c6b3a182eb6e811
11,558
package com.oubowu.ipanda.ui; import android.arch.lifecycle.ViewModelProvider; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.databinding.DataBindingUtil; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.oubowu.ipanda.R; import com.oubowu.ipanda.base.ObserverImpl; import com.oubowu.ipanda.bean.base.VideoList; import com.oubowu.ipanda.bean.home.HomeIndex; import com.oubowu.ipanda.callback.OnFragmentScrollListener; import com.oubowu.ipanda.databinding.FragmentHostBinding; import com.oubowu.ipanda.di.Injectable; import com.oubowu.ipanda.ui.adapter.FragmentDataBindingComponent; import com.oubowu.ipanda.ui.adapter.HostAdapter; import com.oubowu.ipanda.ui.widget.CarouselViewPager; import com.oubowu.ipanda.util.BarBehavior; import com.oubowu.ipanda.util.CommonUtil; import com.oubowu.ipanda.util.ToastUtil; import com.oubowu.ipanda.viewmodel.HostViewModel; import com.oubowu.stickyitemdecoration.StickyHeadContainer; import com.oubowu.stickyitemdecoration.StickyItemDecoration; import java.util.List; import javax.inject.Inject; public class HostFragment extends Fragment implements Injectable, SwipeRefreshLayout.OnRefreshListener { private static final String NAME = "name"; private static final String URL = "url"; private String mName; private String mUrl; private OnFragmentScrollListener mListener; private FragmentHostBinding mBinding; @Inject ViewModelProvider.Factory mFactory; private Context mContext; private HostAdapter mHostAdapter; private HostViewModel mHostViewModel; public HostFragment() { // Required empty public constructor } public static HostFragment newInstance(String name, String url) { HostFragment fragment = new HostFragment(); Bundle args = new Bundle(); args.putString(NAME, name); args.putString(URL, url); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mName = getArguments().getString(NAME); mUrl = getArguments().getString(URL); } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_host, container, false); mBinding.setTitle(mName); return mBinding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initSwipeRefreshLayout(); initRecyclerView(); controlSwipeRefreshLayout(); initStickyHeader(); getHomeIndex(); dispatchScrollEvent(); } private void dispatchScrollEvent() { CoordinatorLayout.LayoutParams clp = (CoordinatorLayout.LayoutParams) mBinding.toolbar.getLayoutParams(); CoordinatorLayout.Behavior behavior = clp.getBehavior(); if (behavior != null && behavior instanceof BarBehavior) { ((BarBehavior) behavior).setOnNestedScrollListener(new BarBehavior.OnNestedScrollListener() { @Override public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) { mListener.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); } @Override public boolean onNestedFling(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, float velocityX, float velocityY, boolean consumed) { return mListener.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed); } }); } } private void initStickyHeader() { final StickyHeadContainer container = mBinding.stickyHeadContainer; container.setDataCallback(pos -> { HomeIndex homeIndex = mHostAdapter.getHomeIndex(); switch (pos) { case 0: mBinding.setStickyTitle(homeIndex.pandaeye.title); break; case 1: mBinding.setStickyTitle(homeIndex.pandalive.title); break; case 2: mBinding.setStickyTitle(homeIndex.chinalive.title); break; case 3: mBinding.setStickyTitle(homeIndex.cctv.title); break; case 4: mBinding.setStickyTitle(homeIndex.list.get(0).title); break; default: break; } }); mBinding.recyclerView.addItemDecoration(new StickyItemDecoration(container, HostAdapter.TYPE_PANDA_NEWS, HostAdapter.TYPE_VIDEO_GRID)); } private void controlSwipeRefreshLayout() { mBinding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { // int topRowVerticalPosition = recyclerView.getChildCount() == 0 ? 0 : recyclerView.getChildAt(0).getTop(); float topRowVerticalPosition = mBinding.carouselViewPager.getY(); mBinding.swipeRefreshLayout.setEnabled(topRowVerticalPosition >= mBinding.toolbar.getHeight()); } }); mBinding.carouselViewPager.setPageChangeListener(new CarouselViewPager.OnPageChangeListenerAdapter() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mBinding.swipeRefreshLayout.setEnabled(false); } @Override public void onPageScrollStateChanged(int state) { if (mBinding.swipeRefreshLayout.getChildAt(mBinding.swipeRefreshLayout.getChildCount() - 1).getVisibility() == View.VISIBLE) { return; } if ((mBinding.carouselViewPager.getY() < mBinding.toolbar.getHeight())) { return; } if (state == ViewPager.SCROLL_STATE_IDLE) { mBinding.swipeRefreshLayout.setEnabled(true); } else { mBinding.swipeRefreshLayout.setEnabled(false); } } }); } private void initRecyclerView() { RecyclerView recyclerView = mBinding.recyclerView; recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)); recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.divider_panda_live_fragment); @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); if (position == 0) { outRect.top = 0; } else { outRect.top = drawable.getIntrinsicHeight(); if (position == parent.getAdapter().getItemCount() - 1) { outRect.bottom = drawable.getIntrinsicHeight(); } } } }); mHostAdapter = new HostAdapter(new FragmentDataBindingComponent(this)); recyclerView.setAdapter(mHostAdapter); } private void initSwipeRefreshLayout() { mBinding.toolbar.post(() -> { mBinding.swipeRefreshLayout.setProgressViewOffset(false, mBinding.toolbar.getBottom(), (int) (mBinding.toolbar.getBottom() * 1.5)); mBinding.swipeRefreshLayout.setRefreshing(true); mBinding.swipeRefreshLayout.setOnRefreshListener(this); }); } private void getHomeIndex() { if (mHostViewModel == null) { mHostViewModel = ViewModelProviders.of(this, mFactory).get(HostViewModel.class); } mHostViewModel.getHomeIndex(mUrl).observe(this, new ObserverImpl<HomeIndex>() { @Override protected void onError(@NonNull String errorMsg) { ToastUtil.showSuccessMsg(errorMsg); } @Override protected void onLoading() { ToastUtil.showSuccessMsg("加载中......"); } @Override protected void onSuccess(@NonNull HomeIndex data) { mBinding.carouselViewPager.setList(data.bigImg); mHostAdapter.replace(data); mBinding.swipeRefreshLayout.setRefreshing(false); if (CommonUtil.isNotEmpty(data.cctv.listurl)) { getWonderfulMomentIndex(data, mHostViewModel); } if (CommonUtil.isNotEmpty(data.list)) { getGungunVideoIndex(data, mHostViewModel); } } }); } private void getGungunVideoIndex(@NonNull HomeIndex data, HostViewModel hostViewModel) { HomeIndex.ListBeanXX listBean = data.list.get(0); if (CommonUtil.isNotEmpty(listBean.listUrl)) { hostViewModel.getGungunVideoIndex(listBean.listUrl).observe(HostFragment.this, new ObserverImpl<List<VideoList>>() { @Override protected void onSuccess(@NonNull List<VideoList> data) { listBean.list = data; mHostAdapter.notifyItemInserted(4); } }); } } private void getWonderfulMomentIndex(@NonNull HomeIndex homeIndex, HostViewModel hostViewModel) { hostViewModel.getWonderfulMomentIndex(homeIndex.cctv.listurl).observe(HostFragment.this, new ObserverImpl<List<VideoList>>() { @Override protected void onSuccess(@NonNull List<VideoList> data) { homeIndex.cctv.list = data; mHostAdapter.notifyItemInserted(3); } }); } @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; if (context instanceof OnFragmentScrollListener) { mListener = (OnFragmentScrollListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; // 取消所有异步任务 mContext = null; } @Override public void onRefresh() { getHomeIndex(); } }
37.163987
201
0.646219
4a48bf5666d4297bb2daa14d3abd9376c787f870
3,539
/** * The MIT License (MIT) * * Copyright (c) 2009-2015 FoundationDB, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.foundationdb.sql.optimizer.plan; import java.util.Collection; import java.util.List; public class GroupLoopScan extends BaseScan { private TableSource insideTable, outsideTable; private boolean insideParent; private List<ComparisonCondition> joinConditions; public GroupLoopScan(TableSource insideTable, TableSource outsideTable, boolean insideParent, List<ComparisonCondition> joinConditions) { this.insideTable = insideTable; this.outsideTable = outsideTable; this.insideParent = insideParent; this.joinConditions = joinConditions; } public TableSource getInsideTable() { return insideTable; } public TableSource getOutsideTable() { return outsideTable; } public boolean isInsideParent() { return insideParent; } public List<ComparisonCondition> getJoinConditions() { return joinConditions; } @Override public Collection<? extends ConditionExpression> getConditions() { return getJoinConditions(); } @Override public void visitComparands(ExpressionRewriteVisitor v) { } @Override public void visitComparands(ExpressionVisitor v) { } public ColumnExpression getOutsideJoinColumn() { ComparisonCondition joinCondition = joinConditions.get(0); ColumnExpression joinColumn = (ColumnExpression)joinCondition.getLeft(); if (joinColumn.getTable() == outsideTable) return joinColumn; joinColumn = (ColumnExpression)joinCondition.getRight(); assert (joinColumn.getTable() == outsideTable); return joinColumn; } @Override public boolean accept(PlanVisitor v) { if (v.visitEnter(this)) { // Don't own tables, right? } return v.visitLeave(this); } @Override public String summaryString(SummaryConfiguration configuration) { StringBuilder str = new StringBuilder(super.summaryString(configuration)); str.append('('); str.append(outsideTable.getName()); str.append(" - "); str.append(insideTable.getName()); if (getCostEstimate() != null) { str.append(", "); str.append(getCostEstimate()); } str.append(")"); return str.toString(); } }
33.704762
82
0.684092
90858f608a22223479538ba9dc98c1e0f9462d59
2,884
package io.github.processthis.springserver.controller; import static org.hamcrest.Matchers.hasSize; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.processthis.springserver.BaseControllerTest; import io.github.processthis.springserver.SpringServerApplicationTest; import io.github.processthis.springserver.model.entity.Sketch; import io.github.processthis.springserver.model.entity.UserProfile; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.MethodMode; import org.springframework.test.web.servlet.ResultActions; import org.springframework.web.context.WebApplicationContext; @ExtendWith(RestDocumentationExtension.class) @SpringBootTest(classes = SpringServerApplicationTest.class) class SketchControllerTest extends BaseControllerTest { @Autowired protected SketchControllerTest(ObjectMapper mapper, WebApplicationContext context) { super(mapper, context); } @Test void addSketch() throws Exception { StringBuilder builder = new StringBuilder(); addUser("Billy","isauth") .andDo(mvcResult -> { UserProfile userProfile = getMapper().readValue(mvcResult.getResponse().getContentAsString(), UserProfile.class); builder.append(userProfile.getId().toString()); }); String temp = builder.toString(); getMockMvc().perform(post("users/{temp}/sketches",temp)); } @Test void getUserSketches() throws Exception { StringBuilder builder = new StringBuilder(); addUser("Billy","isauth") .andDo(mvcResult -> { UserProfile userProfile = getMapper().readValue(mvcResult.getResponse().getContentAsString(), UserProfile.class); builder.append(userProfile.getId().toString()); }); String temp = builder.toString(); getMockMvc().perform(post("users/{temp}/sketches",temp)) .andDo(mvcResult -> { Sketch sketch = getMapper().readValue(mvcResult.getResponse().getContentAsString(),Sketch.class); builder.replace(0,temp.length(),sketch.getId().toString()); }); String temp2 = builder.toString(); getMockMvc().perform(get("users/{temp}/sketches/{temp2}", temp, temp2)); } }
41.797101
123
0.775312
b06d985ba4c26c1487d325d9e213ffa7e71c2700
2,615
package condensation.document; import java.util.Iterator; class Notifier implements Runnable { public final Document document; // State int count = 0; Notifier(Document document) { this.document = document; } @Override public void run() { new Run(); } class Run { final Item[] items; final int[] subTreeEnd; final byte[] notifyFlags; int w; Run() { // Create a snapshot of all changes, and reset the changes at the same time items = new Item[count]; subTreeEnd = new int[count]; notifyFlags = new byte[count]; w = 0; addItem(document.rootItem()); count = 0; // Notify //Condensation.startPerformance(); while (w > 0) { w -= 1; Item item = items[w]; if ((notifyFlags[w] & Item.notifyValueParent) != 0) for (BranchListener listener : item.branchListeners) listener.onBranchChanged(new ChangeSet()); if ((notifyFlags[w] & Item.notifyValueItem) != 0) for (ValueListener listener : item.valueListeners) listener.onValueChanged(); if ((notifyFlags[w] & Item.notifyPrune) != 0) item.pruneIfPossible(); } //Condensation.logPerformance("checked " + items.length + " potentially pruned " + countPruned + " remaining " + dataTree.itemsBySelector.size()); } private void addItem(Item item) { int index = w; items[index] = item; notifyFlags[index] = item.notifyFlags; item.notifyFlags = 0; w += 1; Item current = item.notifyChild; item.notifyChild = null; while (current != null) { addItem(current); Item next = current.notifySibling; current.notifySibling = null; current = next; } subTreeEnd[index] = w; } class ChangeSet implements Iterable<Selector> { final int start; final int end; ChangeSet() { this.start = w; this.end = subTreeEnd[w]; } @Override public Iterator<Selector> iterator() { return new ChangeIterator(start, end); } } class ChangeIterator implements Iterator<Selector> { int current; final int end; ChangeIterator(int start, int end) { this.current = start - 1; this.end = end; moveToNext(); } void moveToNext() { while (true) { current += 1; if (current >= end) return; if ((notifyFlags[current] & Item.notifyValueItem) != 0) return; } } @Override public boolean hasNext() { return current < end; } @Override public Selector next() { if (current >= end) return null; Selector result = items[current].selector; moveToNext(); return result; } @Override public void remove() { } } } }
20.429688
149
0.63327
89c22a2033d2b73b2a8ecf37008ace7b3094dbc4
711
package org.appsec.securityRAT.repository; import org.appsec.securityRAT.domain.TrainingCategoryNode; import org.appsec.securityRAT.domain.TrainingTreeNode; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.Param; import java.util.List; /** * Spring Data JPA repository for the TrainingCategoryNode entity. */ public interface TrainingCategoryNodeRepository extends JpaRepository<TrainingCategoryNode,Long> { @Query("select distinct trainingCategoryNode from TrainingCategoryNode trainingCategoryNode where trainingCategoryNode.node = :node") TrainingCategoryNode getTrainingCategoryNodeByTrainingTreeNode(@Param("node") TrainingTreeNode node); }
37.421053
137
0.835443
d95690ead1e4dcced3f246efd088928f47dffde1
22,892
package jhi.germinate.server.util.importer; import jhi.germinate.server.Database; import jhi.germinate.server.database.codegen.enums.AttributesDatatype; import jhi.germinate.server.database.codegen.tables.records.*; import jhi.germinate.server.database.pojo.*; import jhi.germinate.server.util.StringUtils; import org.dhatim.fastexcel.reader.*; import org.jooq.DSLContext; import java.io.*; import java.math.BigDecimal; import java.sql.*; import java.util.*; import static jhi.germinate.server.database.codegen.tables.Attributedata.*; import static jhi.germinate.server.database.codegen.tables.Attributes.*; import static jhi.germinate.server.database.codegen.tables.Collaborators.*; import static jhi.germinate.server.database.codegen.tables.Countries.*; import static jhi.germinate.server.database.codegen.tables.Datasetcollaborators.*; import static jhi.germinate.server.database.codegen.tables.Datasetlocations.*; import static jhi.germinate.server.database.codegen.tables.Datasets.*; import static jhi.germinate.server.database.codegen.tables.Experiments.*; import static jhi.germinate.server.database.codegen.tables.Institutions.*; import static jhi.germinate.server.database.codegen.tables.Locations.*; /** * @author Sebastian Raubach */ public abstract class DatasheetImporter extends AbstractExcelImporter { private static final String[] METADATA_LABELS = {"Title", "Description", "Rights", "Date of creation", "Publisher", "Format", "Language", "Source", "Type", "Subject", "Contact"}; protected DatasetsRecord dataset; protected int datasetStateId; protected Map<String, Integer> locationNameToId = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); private Map<String, Integer> countryCode2ToId; protected Map<String, Integer> metadataLabelToRowIndex; private Map<String, Integer> attributeToId = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); public DatasheetImporter(File input, boolean isUpdate, int datasetStateId, boolean deleteOnFail, int userId) { super(input, isUpdate, deleteOnFail, userId); this.datasetStateId = datasetStateId; } @Override protected void prepare() { try (Connection conn = Database.getConnection()) { DSLContext context = Database.getContext(conn); countryCode2ToId = context.selectFrom(COUNTRIES) .fetchMap(COUNTRIES.COUNTRY_CODE2, COUNTRIES.ID); context.selectFrom(ATTRIBUTES) .where(ATTRIBUTES.TARGET_TABLE.eq("datasets")) .forEach(a -> attributeToId.put(a.getName(), a.getId())); } catch (SQLException e) { e.printStackTrace(); addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } @Override protected void checkFile(ReadableWorkbook wb) { wb.findSheet("METADATA") .ifPresent(this::checkMetadataSheet); wb.findSheet("LOCATION") .ifPresent(this::checkLocationSheet); wb.findSheet("ATTRIBUTES") .ifPresent(this::checkAttributeSheet); wb.findSheet("COLLABORATORS") .ifPresent(this::checkCollaboratorsSheet); } private void checkAttributeSheet(Sheet s) { try { s.openStream() .findFirst() .ifPresent(r -> { if (allCellsEmpty(r)) return; if (!Objects.equals(getCellValue(r, 0), "Attribute")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Attribute"); if (!Objects.equals(getCellValue(r, 1), "Type")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 1, "Type"); if (!Objects.equals(getCellValue(r, 2), "Value")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 2, "Value"); }); s.openStream() .skip(1) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String attribute = getCellValue(r, 0); String dataType = getCellValue(r, 1); AttributesDatatype dt = null; try { dt = AttributesDatatype.valueOf(dataType); } catch (Exception e) { } String value = getCellValue(r, 2); if (dt == null && StringUtils.isEmpty(attribute) && StringUtils.isEmpty(value)) return; if (dt == null) addImportResult(ImportStatus.GENERIC_INVALID_DATATYPE, r.getRowNum(), "Data Type: " + dataType); if (StringUtils.isEmpty(attribute)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, r.getRowNum(), "Attribute"); if (StringUtils.isEmpty(value)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, r.getRowNum(), "Value"); }); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } private void checkCollaboratorsSheet(Sheet s) { try { s.openStream() .findFirst() .ifPresent(r -> { if (allCellsEmpty(r)) return; if (!Objects.equals(getCellValue(r, 0), "Last Name")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Last Name"); if (!Objects.equals(getCellValue(r, 1), "First Name")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "First Name"); if (!Objects.equals(getCellValue(r, 2), "Email")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Email"); if (!Objects.equals(getCellValue(r, 3), "Phone")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Phone"); if (!Objects.equals(getCellValue(r, 4), "Contributor")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Contributor"); if (!Objects.equals(getCellValue(r, 5), "Address")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Address"); if (!Objects.equals(getCellValue(r, 6), "Country")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Country"); }); s.openStream() .skip(2) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String firstName = getCellValue(r, 0); String lastName = getCellValue(r, 1); String country = getCellValue(r, 6); if (StringUtils.isEmpty(firstName)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, r.getRowNum(), "First Name"); if (StringUtils.isEmpty(lastName)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, r.getRowNum(), "Last Name"); if (!StringUtils.isEmpty(country) && !countryCode2ToId.containsKey(country)) addImportResult(ImportStatus.GENERIC_INVALID_COUNTRY_CODE, r.getRowNum(), country); }); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } private void checkMetadataSheet(Sheet s) { try { s.openStream() .findFirst() .ifPresent(this::checkMetadataHeaders); checkMetadataLabels(s); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } protected List<String> checkLocationSheet(Sheet s) { try { List<String> result = new ArrayList<>(); // Check the headers s.openStream() .findFirst() .ifPresent(r -> { if (!Objects.equals(getCellValue(r, 0), "Name")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Name"); if (!Objects.equals(getCellValue(r, 1), "Short name")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Short name"); if (!Objects.equals(getCellValue(r, 2), "Country")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Country"); if (!Objects.equals(getCellValue(r, 3), "Elevation")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Elevation"); if (!Objects.equals(getCellValue(r, 4), "Latitude")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Latitude"); if (!Objects.equals(getCellValue(r, 5), "Longitude")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "Longitude"); }); // Check the data s.openStream() .skip(1) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String name = getCellValue(r, 0); String shortName = getCellValue(r, 1); String country = getCellValue(r, 2); String elevation = getCellValue(r, 3); String latitude = getCellValue(r, 4); String longitude = getCellValue(r, 5); result.add(name); if (StringUtils.isEmpty(name)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, r.getRowNum(), "Location Name"); if (!StringUtils.isEmpty(shortName) && shortName.length() > 22) addImportResult(ImportStatus.GENERIC_VALUE_TOO_LONG, r.getRowNum(), "Location Short Name: " + shortName + " is longer than 22 characters."); if (!StringUtils.isEmpty(country) && !countryCode2ToId.containsKey(country)) addImportResult(ImportStatus.GENERIC_INVALID_COUNTRY_CODE, r.getRowNum(), country); if (!StringUtils.isEmpty(elevation)) { try { Double.parseDouble(elevation); } catch (Exception e) { addImportResult(ImportStatus.GENERIC_INVALID_NUMBER, r.getRowNum(), elevation); } } if (!StringUtils.isEmpty(latitude)) { try { Double.parseDouble(latitude); } catch (Exception e) { addImportResult(ImportStatus.GENERIC_INVALID_NUMBER, r.getRowNum(), latitude); } } if (!StringUtils.isEmpty(longitude)) { try { Double.parseDouble(longitude); } catch (Exception e) { addImportResult(ImportStatus.GENERIC_INVALID_NUMBER, r.getRowNum(), longitude); } } }); return result; } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } return null; } private void checkMetadataHeaders(Row r) { if (!Objects.equals(getCellValue(r, 0), "LABEL")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "LABEL"); if (!Objects.equals(getCellValue(r, 1), "DEFINITION")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "DEFINITION"); if (!Objects.equals(getCellValue(r, 2), "VALUE")) addImportResult(ImportStatus.GENERIC_MISSING_COLUMN, 0, "VALUE"); } protected void checkMetadataLabels(Sheet s) { try { List<Row> rows = s.read(); readMetadataLabels(rows); Arrays.stream(METADATA_LABELS) .forEachOrdered(c -> { if (!metadataLabelToRowIndex.containsKey(c)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, -1, c); }); Integer index = metadataLabelToRowIndex.get("Title"); if (index != null) { String name = getCellValue(rows.get(index), 0); if (StringUtils.isEmpty(name)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, index, "Title"); } index = metadataLabelToRowIndex.get("Description"); if (index != null) { String description = getCellValue(rows.get(index), 0); if (StringUtils.isEmpty(description)) addImportResult(ImportStatus.GENERIC_MISSING_REQUIRED_VALUE, index, "Description"); } } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } private void readMetadataLabels(List<Row> rows) { metadataLabelToRowIndex = new HashMap<>(); for (int i = 1; i < rows.size(); i++) { Row r = rows.get(i); if (allCellsEmpty(r)) break; String label = getCellValue(r, 0); metadataLabelToRowIndex.put(label, i); } } @Override protected void importFile(ReadableWorkbook wb) { try (Connection conn = Database.getConnection()) { DSLContext context = Database.getContext(conn); wb.findSheet("METADATA") .ifPresent(s -> { try { List<Row> rows = s.read(); readMetadataLabels(rows); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } }); getOrCreateLocations(context, wb); getOrCreateDataset(context, wb); getOrCreateAttributes(context, wb); getOrCreateCollaborators(context, wb); } catch (SQLException e) { e.printStackTrace(); addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } } private void getOrCreateAttributes(DSLContext context, ReadableWorkbook wb) { wb.findSheet("ATTRIBUTES") .ifPresent(s -> { try { s.openStream() .skip(1) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String attribute = getCellValue(r, 0); String dataType = getCellValue(r, 1); AttributesDatatype dt = null; try { dt = AttributesDatatype.valueOf(dataType); } catch (Exception e) { } String value = getCellValue(r, 2); if (dt == null && StringUtils.isEmpty(attribute) && StringUtils.isEmpty(value)) return; Integer attributeId = attributeToId.get(attribute); if (attributeId == null) { AttributesRecord a = context.newRecord(ATTRIBUTES); a.setName(attribute); a.setTargetTable("datasets"); a.setDatatype(dt); a.setCreatedOn(new Timestamp(System.currentTimeMillis())); a.store(); attributeId = a.getId(); attributeToId.put(a.getName(), a.getId()); } AttributedataRecord ad = context.newRecord(ATTRIBUTEDATA); ad.setAttributeId(attributeId); ad.setValue(value); ad.setForeignId(dataset.getId()); ad.setCreatedOn(new Timestamp(System.currentTimeMillis())); ad.store(); }); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } }); } private void getOrCreateCollaborators(DSLContext context, ReadableWorkbook wb) { wb.findSheet("COLLABORATORS") .ifPresent(s -> { try { s.openStream() .skip(2) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String lastName = getCellValue(r, 0); String firstName = getCellValue(r, 1); String email = getCellValue(r, 2); String phone = getCellValue(r, 3); String institutionName = getCellValue(r, 4); String address = getCellValue(r, 5); String countryCode = getCellValue(r, 6); Integer countryId = countryCode2ToId.get(countryCode); InstitutionsRecord institution = context.selectFrom(INSTITUTIONS) .where(INSTITUTIONS.NAME.isNotDistinctFrom(institutionName)) .and(INSTITUTIONS.ADDRESS.isNotDistinctFrom(address)) .and(INSTITUTIONS.COUNTRY_ID.isNotDistinctFrom(countryId)) .fetchAny(); if (!StringUtils.isEmpty(institutionName) && institution == null) { institution = context.newRecord(INSTITUTIONS); institution.setName(institutionName); institution.setAddress(address); institution.setCountryId(countryId); institution.setCreatedOn(new Timestamp(System.currentTimeMillis())); institution.store(); } CollaboratorsRecord collaborator = context.selectFrom(COLLABORATORS) .where(COLLABORATORS.FIRST_NAME.isNotDistinctFrom(firstName)) .and(COLLABORATORS.LAST_NAME.isNotDistinctFrom(lastName)) .and(COLLABORATORS.EMAIL.isNotDistinctFrom(email)) .and(COLLABORATORS.PHONE.isNotDistinctFrom(phone)) .and(COLLABORATORS.INSTITUTION_ID.isNotDistinctFrom(institution == null ? null : institution.getId())) .fetchAny(); if (collaborator == null) { collaborator = context.newRecord(COLLABORATORS); collaborator.setFirstName(firstName); collaborator.setLastName(lastName); collaborator.setEmail(email); collaborator.setPhone(phone); collaborator.setInstitutionId(institution == null ? null : institution.getId()); collaborator.setCreatedOn(new Timestamp(System.currentTimeMillis())); collaborator.store(); } DatasetcollaboratorsRecord dsCollab = context.selectFrom(DATASETCOLLABORATORS) .where(DATASETCOLLABORATORS.DATASET_ID.isNotDistinctFrom(dataset.getId())) .and(DATASETCOLLABORATORS.COLLABORATOR_ID.isNotDistinctFrom(collaborator.getId())) .fetchAny(); if (dsCollab == null) { dsCollab = context.newRecord(DATASETCOLLABORATORS); dsCollab.setDatasetId(dataset.getId()); dsCollab.setCollaboratorId(collaborator.getId()); dsCollab.setCreatedOn(new Timestamp(System.currentTimeMillis())); dsCollab.store(); } }); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } }); } private void getOrCreateLocations(DSLContext context, ReadableWorkbook wb) { wb.findSheet("LOCATION") .ifPresent(s -> { try { s.openStream() .skip(1) .forEachOrdered(r -> { if (allCellsEmpty(r)) return; String name = getCellValue(r, 0); String shortName = getCellValue(r, 1); String country = getCellValue(r, 2); Integer countryId = countryCode2ToId.get(country); BigDecimal ele = getCellValueBigDecimal(r, 3); BigDecimal lat = getCellValueBigDecimal(r, 4); BigDecimal lng = getCellValueBigDecimal(r, 5); LocationsRecord location = context.selectFrom(LOCATIONS) .where(LOCATIONS.SITE_NAME.isNotDistinctFrom(name)) .and(LOCATIONS.SITE_NAME_SHORT.isNotDistinctFrom(shortName)) .and(LOCATIONS.COUNTRY_ID.isNotDistinctFrom(countryId)) .and(LOCATIONS.ELEVATION.isNotDistinctFrom(ele)) .and(LOCATIONS.LATITUDE.isNotDistinctFrom(lat)) .and(LOCATIONS.LONGITUDE.isNotDistinctFrom(lng)) .fetchAny(); if (location == null) { location = context.newRecord(LOCATIONS); location.setSiteName(name); location.setSiteNameShort(shortName); location.setCountryId(countryId); location.setLocationtypeId(2); location.setElevation(ele); location.setLatitude(lat); location.setLongitude(lng); location.store(); } locationNameToId.put(location.getSiteName(), location.getId()); }); } catch (IOException e) { addImportResult(ImportStatus.GENERIC_IO_ERROR, -1, e.getMessage()); } }); } private void getOrCreateDataset(DSLContext context, ReadableWorkbook wb) { wb.findSheet("METADATA") .ifPresent(s -> { try { DublinCore dublinCore = new DublinCore(); String name = null; String description = null; Integer datasetType = getDatasetTypeId(); List<Row> rows = s.read(); Integer index = metadataLabelToRowIndex.get("Title"); if (index != null) { name = getCellValue(rows.get(index), 2); dublinCore.setTitle(new String[]{name}); } index = metadataLabelToRowIndex.get("Description"); if (index != null) { description = getCellValue(rows.get(index), 2); dublinCore.setTitle(new String[]{description}); } index = metadataLabelToRowIndex.get("Rights"); if (index != null) dublinCore.setRights(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Date of creation"); if (index != null) dublinCore.setDate(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Publisher"); if (index != null) dublinCore.setPublisher(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Format"); if (index != null) dublinCore.setFormat(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Language"); if (index != null) dublinCore.setLanguage(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Source"); if (index != null) dublinCore.setSource(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Type"); if (index != null) dublinCore.setType(new String[]{getCellValue(rows.get(index), 2)}); index = metadataLabelToRowIndex.get("Subject"); if (index != null) dublinCore.setSubject(new String[]{getCellValue(rows.get(index), 2)}); // Check if the dataset exists (assuming name+description are unique dataset = context.selectFrom(DATASETS) .where(DATASETS.NAME.isNotDistinctFrom(name)) .and(DATASETS.DESCRIPTION.isNotDistinctFrom(description)) .and(DATASETS.DATASETTYPE_ID.eq(datasetType)) .fetchAny(); if (dataset == null) { // If it doesn't, check if the experiment exists ExperimentsRecord experiment = context.selectFrom(EXPERIMENTS) .where(EXPERIMENTS.EXPERIMENT_NAME.isNotDistinctFrom(name)) .and(EXPERIMENTS.DESCRIPTION.isNotDistinctFrom(description)) .fetchAny(); if (experiment == null) { // If it doesn't, create it experiment = context.newRecord(EXPERIMENTS); experiment.setExperimentName(name); experiment.setDescription(description); experiment.store(); } // Then create the dataset dataset = context.newRecord(DATASETS); dataset.setExperimentId(experiment.getId()); dataset.setDatasettypeId(getDatasetTypeId()); dataset.setName(name); dataset.setDatasetStateId(datasetStateId); dataset.setDescription(description); index = metadataLabelToRowIndex.get("Contact"); if (index != null) dataset.setContact(getCellValue(rows.get(index), 2)); dataset.setDublinCore(dublinCore); dataset.store(); for (Integer locationId : locationNameToId.values()) { DatasetlocationsRecord dslr = context.selectFrom(DATASETLOCATIONS) .where(DATASETLOCATIONS.LOCATION_ID.eq(locationId)) .and(DATASETLOCATIONS.DATASET_ID.eq(dataset.getId())) .fetchAny(); if (dslr == null) { dslr = context.newRecord(DATASETLOCATIONS); dslr.setDatasetId(dataset.getId()); dslr.setLocationId(locationId); dslr.store(); } } } } catch (IOException e) { throw new RuntimeException(e); } }); } protected boolean areEqual(Row one, Row two) { if (one.getCellCount() != two.getCellCount()) return false; for (int i = 0; i < one.getCellCount(); i++) { if (!Objects.equals(getCellValue(one, i), getCellValue(two, i))) return false; } return true; } @Override protected void updateFile(ReadableWorkbook wb) { // We don't support updates, simply import importFile(wb); } protected abstract int getDatasetTypeId(); }
32.287729
179
0.659488
51704c099465e2569a6a66074b7b7e4fd4dd56f3
13,492
// Copyright (c) 2020, Steiner Pascal, Strässle Nikolai, Radinger Martin // All rights reserved. // Licensed under LICENSE, see LICENSE file package ch.mse.quiz; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.List; import java.util.Locale; import ch.mse.quiz.app.App; import ch.mse.quiz.ble.BleGattCallback; import ch.mse.quiz.listeners.FirebaseQuestionListener; import ch.mse.quiz.listeners.StartQuizListener; import ch.mse.quiz.models.Question; import nl.dionsegijn.konfetti.KonfettiView; import nl.dionsegijn.konfetti.models.Shape; import nl.dionsegijn.konfetti.models.Size; public class QuestionActivity extends AppCompatActivity { public static final String SCORE = "ch.mse.quiz.extra.SCORE"; private static final String LOG_TAG = QuestionActivity.class.getSimpleName(); private CountDownTimer countDownTimer; private long remainingTime; private int correctAnswer; private int currentQuestion; private int questionNumber; private String quizTopic; private int userScore; private List<Question> questions = new ArrayList<>(); private final Handler handler = new Handler(); private TextView tvTimer; private TextView tvProgress; private TextView tvQuestion; private TextView buttonAnswerA; private TextView buttonAnswerB; private TextView buttonAnswerC; private TextView buttonAnswerD; private TextView tvDispenserState; private KonfettiView konfettiView; //BLE private final BleGattCallback bleGattCallback = BleGattCallback.getInstance(); private final Runnable showResultActivity = () -> { Log.d(LOG_TAG, "display QuizResultActivity!"); Bundle extras = new Bundle(); extras.putInt(StartQuizListener.QUESTION_NUMBER, questionNumber); extras.putInt(SCORE, userScore); extras.putString(StartQuizListener.QUESTION_TOPIC, quizTopic); Intent intent = new Intent(QuestionActivity.this, QuizResultActivity.class); intent.putExtras(extras); startActivity(intent); App.removeActivity(this); finish(); }; private final Runnable newQuestion = () -> { createQuestion(currentQuestion); tvProgress.setText(String.format(Locale.GERMAN, "Topic %s Question %d out of %d", quizTopic, currentQuestion, questionNumber)); resetButtonColor(); startTimer(30000); }; private TextView tvFillingLevel; private Thread fillingLevelThread; private Thread dispenseStatusThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); App.addActivity(this); setContentView(R.layout.activity_question); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); } //how many questions to do? get data from MainActivity calling Intent intent = getIntent(); Bundle extras = intent.getExtras(); questionNumber = extras.getInt(StartQuizListener.QUESTION_NUMBER); quizTopic = extras.getString(StartQuizListener.QUESTION_TOPIC); //read required amount of questions from DB getQuestions(); konfettiView = findViewById(R.id.viewKonfetti); tvProgress = findViewById(R.id.textView_questionProgress); tvTimer = findViewById(R.id.quiz_Timer); tvDispenserState = findViewById(R.id.textView_dispenserState); tvFillingLevel = findViewById(R.id.tvFillingLevel); tvQuestion = findViewById(R.id.textView_questionText); buttonAnswerA = findViewById(R.id.textView_answerA); buttonAnswerB = findViewById(R.id.textView_answerB); buttonAnswerC = findViewById(R.id.textView_answerC); buttonAnswerD = findViewById(R.id.textView_answerD); //set initial values currentQuestion = 1; userScore = 0; remainingTime = 30000; //filling level from sensor initFillingLevelThread(); dispenseCandy(); //Button Listeners buttonAnswerA.setOnClickListener(v -> { submit(1); Log.d(LOG_TAG, "checkAnswerA"); }); buttonAnswerB.setOnClickListener(v -> { submit(2); Log.d(LOG_TAG, "checkAnswerB"); }); buttonAnswerC.setOnClickListener(v -> { submit(3); Log.d(LOG_TAG, "checkAnswerC"); }); buttonAnswerD.setOnClickListener(v -> { submit(4); Log.d(LOG_TAG, "checkAnswerD"); }); Log.d(LOG_TAG, "-----"); Log.d(LOG_TAG, "on create"); } //firebase //Getting Firebase Instance final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference dbRef; public void getQuestions() { dbRef = database.getReference("topics/" + quizTopic + "/questions"); dbRef.addListenerForSingleValueEvent(new FirebaseQuestionListener(questions, questionNumber, this)); } @Override protected void onStart() { super.onStart(); Log.d(LOG_TAG, "onStart"); //set first question UI tvDispenserState.setText(""); if (!fillingLevelThread.isAlive()) { fillingLevelThread.start(); } if (!dispenseStatusThread.isAlive()) { dispenseStatusThread.start(); } resetButtonColor(); startTimer(remainingTime); } @Override protected void onPause() { super.onPause(); Log.d(LOG_TAG, "onPause"); //stopTimer countDownTimer.cancel(); countDownTimer = null; } @Override protected void onResume() { super.onResume(); Log.d(LOG_TAG, "onResume"); //restart Timer if (countDownTimer == null) { startTimer(remainingTime); } } //BLE private void dispenseCandy() { dispenseStatusThread = new Thread(() -> { while (!dispenseStatusThread.isInterrupted()) { try { Thread.sleep(100); runOnUiThread(() -> { String dispenseStatus; if (bleGattCallback.isDispenserState()) { dispenseStatus = getString(R.string.grapMnM); } else { dispenseStatus = getString(R.string.nothingToTake); } tvDispenserState.setText(dispenseStatus); }); } catch (InterruptedException e) { dispenseStatusThread.interrupt(); } } }); } public void initFillingLevelThread() { fillingLevelThread = new Thread(() -> { while (!fillingLevelThread.isInterrupted()) { try { Thread.sleep(1000); runOnUiThread(() -> tvFillingLevel.setText(String.format(Locale.GERMAN, "%s %d%%", getResources().getString(R.string.tv_filling_level), Math.round(bleGattCallback.getFillingLevelPercentage())))); } catch (InterruptedException e) { fillingLevelThread.interrupt(); } Log.d(LOG_TAG, "onResume"); } }); } //create new question from list and set UI accordingly public void createQuestion(int i) { if (questions.isEmpty()) { return; } Log.d(LOG_TAG, "new question created!"); tvProgress.setText(String.format(Locale.GERMAN, "Topic %s Question %d out of %d", quizTopic, currentQuestion, questionNumber)); Question q = questions.get(i - 1); tvQuestion.setText(q.getQuestionText()); buttonAnswerA.setText(q.getAnswer1()); buttonAnswerB.setText(q.getAnswer2()); buttonAnswerC.setText(q.getAnswer3()); buttonAnswerD.setText(q.getAnswer4()); correctAnswer = q.getCorrectAnswer(); } //timer private void startTimer(long runtime) { Log.d(LOG_TAG, "Time is running!"); countDownTimer = new CountDownTimer(runtime, 1000) { @Override public void onTick(long millisUntilFinished) { tvTimer.setText(String.valueOf(millisUntilFinished / 1000L)); remainingTime = millisUntilFinished; } @Override public void onFinish() { tvTimer.setText(getString(R.string.timerIsUp)); endQuestion(); } }.start(); } //end timer private void endTimer() { countDownTimer.cancel(); } //user out of time private void endQuestion() { Log.d(LOG_TAG, "User out of time, end question!"); currentQuestion = currentQuestion + 1; Toast.makeText(getBaseContext(), getString(R.string.timerIsUp), Toast.LENGTH_SHORT).show(); setButtonColor(); //more questions? then create new one if (currentQuestion <= questionNumber) { handler.postDelayed(newQuestion, 3000); } else { //otherwise result page handler.postDelayed(showResultActivity, 3000); } } //UI changers private void resetButtonColor() { buttonAnswerA.setBackgroundColor(getResources().getColor(R.color.secondaryColor, getTheme())); buttonAnswerB.setBackgroundColor(getResources().getColor(R.color.secondaryColor, getTheme())); buttonAnswerC.setBackgroundColor(getResources().getColor(R.color.secondaryColor, getTheme())); buttonAnswerD.setBackgroundColor(getResources().getColor(R.color.secondaryColor, getTheme())); } private void setButtonColor() { for (int i = 1; i <= 4; i++) { if (i == correctAnswer) { switch (i) { case 1: buttonAnswerA.setBackgroundColor(getResources().getColor(R.color.green, getTheme())); break; case 2: buttonAnswerB.setBackgroundColor(getResources().getColor(R.color.green, getTheme())); break; case 3: buttonAnswerC.setBackgroundColor(getResources().getColor(R.color.green, getTheme())); break; default: buttonAnswerD.setBackgroundColor(getResources().getColor(R.color.green, getTheme())); break; } } else { switch (i) { case 1: buttonAnswerA.setBackgroundColor(getResources().getColor(R.color.red, getTheme())); break; case 2: buttonAnswerB.setBackgroundColor(getResources().getColor(R.color.red, getTheme())); break; case 3: buttonAnswerC.setBackgroundColor(getResources().getColor(R.color.red, getTheme())); break; default: buttonAnswerD.setBackgroundColor(getResources().getColor(R.color.red, getTheme())); break; } } } } //Quiz handlers //check for correct answer and change UI private void submit(int answer) { Log.d(LOG_TAG, "checking if answer correct"); currentQuestion = currentQuestion + 1; //correct answer, fireworks! if (answer == correctAnswer) { userScore = userScore + 1; //visuals konfettiView.build() .addColors(Color.YELLOW, Color.GREEN, Color.MAGENTA) .setDirection(0.0, 359.0) .setSpeed(1f, 5f) .setFadeOutEnabled(true) .setTimeToLive(2000L) .addShapes(Shape.Square.INSTANCE, Shape.Circle.INSTANCE) .addSizes(new Size(12, 5f)) .setPosition(-50f, konfettiView.getWidth() + 50f, -50f, -50f) .streamFor(300, 3000L); //activate M&M dispenser via BLE bleGattCallback.dispense(); } else { Toast.makeText(getBaseContext(), "Better luck next time!", Toast.LENGTH_SHORT).show(); } //set button backgrounds: correct answer=green, wrong answer=red setButtonColor(); //more questions to answer? create new question, otherwise display quiz results if (currentQuestion <= questionNumber) { endTimer(); handler.postDelayed(newQuestion, 3000); } else { endTimer(); handler.postDelayed(showResultActivity, 3000); } } public int getCorrectAnswer() { return correctAnswer; } public void setQuestions(List<Question> questions) { this.questions = questions; } }
35.319372
215
0.603098
6691ae8ec6c5dff5f6457928e4bb04f1a6c696f7
3,133
/* Copyright (c) IBM Corporation 2016. All Rights Reserved. * Project name: Object Generator * This project is licensed under the Apache License 2.0, see LICENSE. */ package com.ibm.og.util.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.InputStream; import java.io.OutputStream; import java.util.Random; import com.ibm.og.api.Body; import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; /** * A utility class for creating input and output streams * * @since 1.0 */ public class Streams { public static final int REPEAT_LENGTH = 1024; private static final byte[] ZERO_BUF = new byte[REPEAT_LENGTH]; private static final InputStream NONE_INPUTSTREAM = new InputStream() { @Override public int read() { return -1; } @Override public boolean markSupported() { return true; } @Override public void reset() {} }; private Streams() {} /** * Creates an input stream from the provided body description. The size of this stream and its * data are determined by the provided body's size and type, respectively. * * @param body the description of an body * @return an input stream instance */ public static InputStream create(final Body body) { checkNotNull(body); switch (body.getDataType()) { case NONE: return NONE_INPUTSTREAM; case ZEROES: return create(ZERO_BUF, body.getSize()); case CUSTOM: return create(body.getContent().getBytes(Charsets.UTF_8), body.getSize()); default: return create(createRandomBuffer(body.getRandomSeed()), body.getSize()); } } private static InputStream create(final byte[] buf, final long size) { return ByteStreams.limit(new InfiniteInputStream(buf), size); } private static byte[] createRandomBuffer(final long seed) { final byte[] buf = new byte[REPEAT_LENGTH]; new Random(seed).nextBytes(buf); return buf; } /** * Creates an input stream which is throttled with a maximum throughput * * @param in the backing input stream to throttle * @param bytesPerSecond the maximum throughput this input stream is allowed to read at * @return an instance of an input stream, throttled with a maximum rate of {@code bytesPerSecond} * @throws IllegalArgumentException if bytesPerSecond is negative or zero */ public static InputStream throttle(final InputStream in, final long bytesPerSecond) { return new ThrottledInputStream(in, bytesPerSecond); } /** * Creates an output stream which is throttled with a maximum throughput * * @param out the backing output stream to throttle * @param bytesPerSecond the maximum throughput this input stream is allowed to write at * @return an instance of an output stream, throttled with a maximum rate of * {@code bytesPerSecond} * @throws IllegalArgumentException if bytesPerSecond is negative or zero */ public static OutputStream throttle(final OutputStream out, final long bytesPerSecond) { return new ThrottledOutputStream(out, bytesPerSecond); } }
31.646465
100
0.711778
9fcc4cfa2d5817ae0bd5f9df753014d1302d14e4
216
package net.mybluemix.asmilk.data; public enum WechatStatus { NEW, JSLOGINED, LOGINED, REDIRECTED, INITIALIZED, NOTIFIED, CHECKED, SYNCHRONIZED, READED, DO_DICT, DO_FOREX, FAILED; }
11.368421
35
0.671296
70e3cfc25cf38c8832853d1271f8e28fd41b9068
574
/* * Copyright (c) 2012. Adam Wells. */ package com.megaport.api.dto; public enum UsageAlgorithm { BYTES_TRANSFERRED, TIME_AT_RATE, RATE_PLAN, POST_PAID_FIXED, // post paid, but regardless of hours or speed - ports (not a product yet) POST_PAID_HOURLY, // new VXC pricing, mrc plus rate based charging POST_PAID_HOURLY_SPEED, // used for long haul VXC POST_PAID_HOURLY_SPEED_MCR, POST_PAID_HOURLY_SPEED_METRO_VXC, POST_PAID_HOURLY_SPEED_LONG_HAUL_VXC, NOT_POST_PAID, // ie pre-paid, used for Ports, and legacy metro VXCs etc POST_PAID_HOURLY_SPEED_METRO_IX }
28.7
92
0.785714
18737d3e833e77185d4fbae9b0fa7479d9eb463c
1,206
package org.code4everything.demo.algorithm.leetcode.contest.before; import org.code4everything.demo.algorithm.common.annotation.LeetCode; import org.code4everything.demo.algorithm.common.enums.Difficulty; /** * @author pantao * @since 2019-01-27 */ public class Contest984 { @LeetCode(id = 984, difficulty = Difficulty.MEDIUM, title = "不含 AAA 或 BBB 的字符串") public String strWithout3a3b(int a, int b) { char[] cs = new char[a + b]; boolean aWritable = a >= b; char pre = '0'; for (int i = 0; i < cs.length; i++) { if (aWritable && a > 0) { cs[i] = 'a'; a--; } else if (b > 0) { cs[i] = 'b'; b--; } if (a <= 0) { aWritable = false; } else if (b <= 0) { aWritable = true; } else if (cs[i] == pre) { aWritable = !aWritable; } else if (a > b && (a / b >= 2)) { aWritable = true; } else if (b > a && (b / a >= 2)) { aWritable = false; } pre = cs[i]; } return String.valueOf(cs); } }
29.414634
84
0.456053
97591ad190a9a408be0dd7df224d304222a6d469
383
package de.feli490.feliutils.search.query.expressions.logic.factories; import de.feli490.feliutils.search.query.expressions.Expression; import de.feli490.feliutils.search.query.expressions.ExpressionFactory; public abstract class AbstractLogicExpressionFactory implements ExpressionFactory<Expression> { @Override public boolean isLogical() { return true; } }
29.461538
95
0.798956
607dd98f87ef6d8b00a7895d03e01bf01be82c3c
1,473
package com.acn.submenu.popup.actions; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.handlers.HandlerUtil; import com.acn.osb.customtools.browseroperations.BrowserOperations; import com.acn.osb.customtools.utils.CustomToolsHelper; import com.acn.osb.customtools.variables.Resource; import com.acn.osb.customtools.variables.Settings; import com.acn.submenu.Activator; import com.acn.submenu.Utils; public class CopyPathToClipboardHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { try { Resource res = Utils.getResourceFromAction(); if (res == null || res.path == null || res.path.length() == 0) return null; Settings settings=Activator.getSettings(); BrowserOperations browserOperations=new BrowserOperations(settings); String result = browserOperations.getServerPath(res); System.out.println("copy:" +res.toString()); CustomToolsHelper.copyStringToClipboard(result); } catch (Exception e) { MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), "Error", e.toString()); } return null; } }
33.477273
113
0.765105
d8dc90b45957b510bfbac0e001da9f19627bcf0a
1,935
package cardgame.Cards.ImplementedCards; import cardgame.Cards.AbstractCardEffect; import cardgame.Cards.Card; import cardgame.Cards.Effect; import cardgame.Cards.Targettable; import cardgame.Game.Phases; import cardgame.Game.Player; import cardgame.Game.SkipPhase; import cardgame.Utils; /** * Created by Fabio on 29/03/2016. */ //DONE public class Fatigue implements Card { private class FatigueEffect extends AbstractCardEffect implements Targettable{ protected FatigueEffect(Player p, Card c) { super(p, c); } //Salva il giocatore che subirà l'effetto Player target; @Override public boolean play(){ setTarget(); return super.play(); } @Override public void resolve() { SkipPhase skipPhase = new SkipPhase(Phases.DRAW, 1); target.set_phase(Phases.DRAW, skipPhase); } @Override public boolean hasTarget(){ return true; } @Override public boolean setTarget(){ System.out.println(owner.get_name() + ": Vuoi colpire l'avversario o te stesso? \n1.avversario\n2.te stesso"); int result = Utils.readIntRange(1,2); if(result == 0) target = opponent; else target = owner; return true; } } @Override public Effect get_effect(Player owner) { return new FatigueEffect(owner, this); } @Override public String name() { return "Fatigue"; } @Override public String type() { return "Sorcery"; } @Override public String rule_text() { return "Target player skip her or his next Draw step"; } @Override public boolean isInstant() { return false; } public String toString(){ return name() + "[" + rule_text() +"]"; } }
22.764706
122
0.58708
73be2d4efc20df261fd7063e294d4a1f540b50d0
402
package com.medusa.gruul.account.api.enums; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author whh * @date 2019/12/03 */ @Getter @AllArgsConstructor public enum BlacklistEnum { /** * 禁用类型 */ REJECT_COMMENT(2, "限制评论"), REJECT_ORDER(1, "限制下单"); /** * 授权类型 */ private Integer type; /** * 类型名称 */ private String name; }
12.967742
43
0.584577
b1da2261ac01bcfa6048f142bc1b23f0d55686ed
2,096
package com.test.demo.controller; import com.google.gson.Gson; import com.test.demo.po.Business; import com.test.demo.po.Product; import com.test.demo.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * Created by 杨帅 on 2017/3/13. */ @Controller @RequestMapping(value="/AppServer") public class ProductController { @Autowired ProductService productService; @RequestMapping(value="/GetMyProductServlet", method = RequestMethod.POST) @ResponseBody //通过商家名字获得当前商家下面的所有商品 public Object GetMyProductServlet(@RequestBody String json){ Gson gson = new Gson(); Business business = gson.fromJson(json, Business.class); String businessName = business.getBusinessName(); String result = "GetMyProductError"; try { List<Product> productList = productService.getMyProduct(businessName); result = gson.toJson(productList); } catch (Exception e) { //e.printStackTrace(); } return result; } @RequestMapping(value="/SelectProductByNameServlet", method = RequestMethod.POST) @ResponseBody //通过商品名字查找商品 public Object SelectProductByNameServlet(@RequestBody String json){ Gson gson = new Gson(); Product product = gson.fromJson(json,Product.class); String productName = product.getProductName(); String result = "SelectProductError"; try { List<Product> productList = productService.selectByName(productName); result = gson.toJson(productList); if(productList.size() == 0) result ="SelectProductError"; } catch (Exception e) { //e.printStackTrace(); } return result; } }
33.806452
85
0.692271
9a9cbefe17664db8f8b26cd3a2185585cfb41631
1,569
// https://practice.geeksforgeeks.org/problems/frequency-count/1/?track=Java-Collections-HashMap&batchId=318 //Initial Template for Java /*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG { public static void main (String[] args) { //taking input using Scanner class Scanner sc = new Scanner(System.in); //taking total testcases int t=sc.nextInt(); while(t-->0) { //taking total elements int n=sc.nextInt(); //Declaring a new ArrayList ArrayList<Integer>arr=new ArrayList<>(); //adding elements to the ArrayList for(int i=0;i<n;i++) { arr.add(sc.nextInt()); } //calling the frequncyCount method and //storing the result in new ArrayList ArrayList<Integer>ans=frequencyCount(arr, n); //printing the elements //of the ArrayList for(int i:ans) System.out.print(i+" "); System.out.println(); } } // } Driver Code Ends //User function Template for Java public static ArrayList<Integer> frequencyCount(ArrayList<Integer>arr, int n) { //Your code here LinkedHashMap<Integer,Integer> lm = new LinkedHashMap<>(); ArrayList<Integer> result = new ArrayList<>(); for(int i=0;i<n; i++){ lm.put(arr.get(i), lm.getOrDefault(arr.get(i),0)+1); } for(Map.Entry<Integer, Integer> m: lm.entrySet()) result.add(m.getValue()); return result; } // { Driver Code Starts. } // } Driver Code Ends
23.772727
108
0.612492
647a0bdd4d1b200ad8709b48856a05cfc65ba846
3,234
package jenkins.plugins.git; import hudson.FilePath; import hudson.Functions; import hudson.model.Queue; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.recipes.LocalData; import java.io.File; import java.io.IOException; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class GitBranchSCMHeadTest { @Rule public JenkinsRule j = new JenkinsRule() { @Override public void before() throws Throwable { if (!isWindows() && "testMigrationNoBuildStorm".equals(this.getTestDescription().getMethodName())) { URL res = getClass().getResource("/jenkins/plugins/git/GitBranchSCMHeadTest/testMigrationNoBuildStorm_repositories.zip"); final File path = new File("/tmp/JENKINS-48061"); if (path.exists()) { if (path.isDirectory()) { FileUtils.deleteDirectory(path); } else { path.delete(); } } new FilePath(new File(res.toURI())).unzip(new FilePath(path.getParentFile())); } super.before(); } }; @After public void removeRepos() throws IOException { final File path = new File("/tmp/JENKINS-48061"); if (path.exists() && path.isDirectory()) { FileUtils.deleteDirectory(path); } } @Issue("JENKINS-48061") @Test @LocalData @Deprecated // getBuilds.size() public void testMigrationNoBuildStorm() throws Exception { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; } final WorkflowMultiBranchProject job = j.jenkins.getItemByFullName("job", WorkflowMultiBranchProject.class); assertEquals(4, job.getItems().size()); WorkflowJob master = job.getItem("master"); assertEquals(1, master.getBuilds().size()); WorkflowJob dev = job.getItem("dev"); assertEquals(1, dev.getBuilds().size()); WorkflowJob v4 = job.getItem("v4"); assertEquals(0, v4.getBuilds().size()); final Queue.Item item = job.scheduleBuild2(0); assertNotNull(item); item.getFuture().waitForStart(); j.waitUntilNoActivity(); assertEquals(4, job.getItems().size()); master = job.getItem("master"); assertEquals(1, master.getBuilds().size()); dev = job.getItem("dev"); assertEquals(1, dev.getBuilds().size()); v4 = job.getItem("v4"); assertEquals(0, v4.getBuilds().size()); } /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ private boolean isWindows() { return File.pathSeparatorChar==';'; } }
35.152174
137
0.631107
0dfdf91da80d0c48c05f0d112a9a7d201e35fcaa
443
package lg.com.thirdlibstraining.activity_pic; import android.widget.BaseAdapter; import lg.com.thirdlibstraining.activity_cache.BaseCacheActivity; import lg.com.thirdlibstraining.adapter.NewsGlideAdapter; import lg.com.thirdlibstraining.adapter.NewsPicassoAdapter; public class GlideAty extends BaseCacheActivity { @Override protected BaseAdapter getAdapter() { return new NewsGlideAdapter(this, newsBeanList, lv); } }
29.533333
65
0.808126
ceab33f9c3a4d3023c99b2dbeed6379269928672
995
package com.github.willwbowen.customerservice.models; public class Salon { String salonId; String name; String contactName; String contactEmail; String contactPhone; public String getSalonId() { return salonId; } public void setSalonId(String salonId) { this.salonId = salonId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getContactEmail() { return contactEmail; } public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } }
19.9
54
0.638191
99d0141bcf779abdda5e159b61e1644e391f700c
908
package com.example.vmac.chatbotmaster; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ImageView; public class Stats extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stats); webView= findViewById(R.id.webview); webView.setWebChromeClient(new WebChromeClient()); webView.loadUrl("https://www.covid19india.org/"); webView.getSettings().setJavaScriptEnabled(true); } // public void previous(View view) // { // Intent intent =new Intent(Stats.this, Profile_page.class); // startActivity(intent); // } }
25.942857
68
0.722467
7aaa5e153963c6f37f77f595d1f6ea513478b811
1,151
package org.md.api.auth.service; import javax.xml.bind.DatatypeConverter; import org.md.api.auth.model.Token; import org.md.api.auth.model.TokenDetails; import org.md.api.auth.model.exception.InvalidTokenException; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; @SpringBootConfiguration public class TokenVerificationService implements ITokenVerificationService { @Value("${jwt.secret.key}") private String secretKey; public TokenDetails verifyTokenDetails(Token token) throws InvalidTokenException { if (token == null || "".equals(token.getToken())) { throw new InvalidTokenException(); } Claims claims = decodeJWT(token.getToken()); return new TokenDetails(claims.toString(), claims.getExpiration(), 0); } private Claims decodeJWT(String jwt) { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey)) .parseClaimsJws(jwt).getBody(); return claims; } }
32.885714
86
0.718506
83e14784b0bcab71d5fa0f78cb74bf0ad9a5b2a2
1,582
package play.learn.java.design.balking; import java.util.concurrent.TimeUnit; // https://java-design-patterns.com/patterns/balking/ // balk : hesitate or be unwilling to accept an idea or undertaking. public class WashingMachine { private final DelayProvider delayProvider; private WashingMachineState washingMachineState; public WashingMachine() { this((interval, timeUnit, task) -> { try { Thread.sleep(timeUnit.toMillis(interval)); } catch (InterruptedException ie) { ie.printStackTrace(); } task.run(); }); } public WashingMachine(DelayProvider delayProvider) { this.delayProvider = delayProvider; this.washingMachineState = WashingMachineState.ENABLED; } public WashingMachineState getWashingMachineState() { return washingMachineState; } public void wash() { synchronized (this) { System.out.format("%s: Actual machine state: %s %n", Thread.currentThread().getName(), getWashingMachineState()); if (washingMachineState == WashingMachineState.WASHING) { System.err.println("ERROR: Cannot wash if the machine has been already washing!"); return; } washingMachineState = WashingMachineState.WASHING; } System.out.format("%s: Doing the washing %n", Thread.currentThread().getName()); this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); } public synchronized void endOfWashing() { washingMachineState = WashingMachineState.ENABLED; System.out.format("%s: Washing completed. %n", Thread.currentThread().getId()); } }
29.296296
121
0.719343
dd434b6220b0e2aa788e10252d599b69aa823551
7,732
package zyh.ml.regression; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import zyh.ml.data.IndexedSample; import zyh.ml.optimization.StochasticGradientDescent; import zyh.ml.optimization.TargetFunction; import zyh.ml.utils.Logger; import zyh.ml.utils.TaskDispatcher; /** * L2 Regularized Multinomial Logistic Regression * @author zhaoyuhan */ public class LogisticRegression implements TargetFunction, Serializable { /** * */ private static final long serialVersionUID = 3666084436866079637L; private int numberOfClasses; private int numberOfFeatures; private int numberOfThreads = 10; private boolean usingL2Regularization = true; public void setUsingL2Regularization(boolean usingL2Regularization) { this.usingL2Regularization = usingL2Regularization; } private double regularizationCoefficient = 1.0; private double[] thetas = null; private Logger logger = new Logger(1); private int finishedThreads; private ThreadStatus threadStatus = ThreadStatus.ShouldWait; private double logLikelihood; private int correctLabels; private double[] gradient; private List<IndexedSample> trainingSamples; private List<Double> sampleWeights; private List<Thread> threads = new ArrayList<>(); private Lock lock; private Condition workerCondition; private Condition masterCondition; public LogisticRegression(int numberOfClasses, int numberOfFeatures) { this.numberOfClasses = numberOfClasses; this.numberOfFeatures = numberOfFeatures; } private enum ThreadStatus { ShouldWait, ShouldStart, ShouldStop; } private class Worker implements Runnable { public Lock lock; public Condition workerCondition; public Condition masterCondition; public Object writeLock; public int beginIndex; public int endIndex; @Override public void run() { while (true) { lock.lock(); try { while (threadStatus == ThreadStatus.ShouldWait) workerCondition.await(); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } if (threadStatus == ThreadStatus.ShouldStop) break; for (int i = beginIndex; i < endIndex; i++) { final IndexedSample sample = trainingSamples.get(i); final double[] probabilities = probabilityPredict(sample); final int predictedLabel = getPredictedLabel(probabilities); synchronized(writeLock) { if (predictedLabel == sample.label) correctLabels++; logLikelihood -= sampleWeights.get(i) * Math.log(probabilities[sample.label]); for (int j = numberOfClasses - 2; j >= 0; j--) { int startIndex = j * numberOfFeatures; double multiplier = -probabilities[j]; if (sample.label == j) multiplier += 1.0; for (Entry<Integer, Double> entry : sample.features.entrySet()) gradient[startIndex + entry.getKey()] -= sampleWeights.get(i) * entry.getValue() * multiplier; } } } lock.lock(); if (++finishedThreads == numberOfThreads) { threadStatus = ThreadStatus.ShouldWait; masterCondition.signal(); } lock.unlock(); } } } @Override public int numberOfArguments() { return (numberOfClasses - 1) * numberOfFeatures; } @Override public void initializeArguments(double[] arguments) { if (thetas != null && thetas.length == arguments.length) { System.arraycopy(thetas, 0, arguments, 0, thetas.length); logger.log("Resuming training..."); } } @Override public void updateArguments(double[] arguments) { lock.lock(); threadStatus = ThreadStatus.ShouldStop; workerCondition.signalAll(); lock.unlock(); for (final Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } threads.clear(); workerCondition = null; masterCondition = null; lock = null; thetas = arguments; } @Override public double evaluate(double[] arguments, double[] gradient) { if (threads.size() == 0) { TaskDispatcher dispatcher = new TaskDispatcher(trainingSamples.size(), numberOfThreads); Object writeLock = new Object(); lock = new ReentrantLock(); workerCondition = lock.newCondition(); masterCondition = lock.newCondition(); for (int i = 0; i < numberOfThreads; i++) { Worker worker = new Worker(); worker.writeLock = writeLock; worker.lock = lock; worker.workerCondition = workerCondition; worker.masterCondition = masterCondition; worker.beginIndex = dispatcher.begin(i); worker.endIndex = dispatcher.end(i); threads.add(new Thread(worker)); } for (final Thread thread : threads) thread.start(); } lock.lock(); logLikelihood = 0.0; correctLabels = 0; finishedThreads = 0; this.thetas = arguments; this.gradient = gradient; for (int i = 0; i < gradient.length; i++) gradient[i] = 0.0; threadStatus = ThreadStatus.ShouldStart; try { workerCondition.signalAll(); while (finishedThreads < numberOfThreads) masterCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } lock.unlock(); for (int i = 0; i < gradient.length; i++) gradient[i] *= trainingSamples.size(); logLikelihood *= trainingSamples.size(); if (usingL2Regularization) { double l2reg = 0.0; for (int i = 0; i < arguments.length; i++) l2reg += arguments[i] * arguments[i]; for (int i = 0; i < gradient.length; i++) gradient[i] += 2 * regularizationCoefficient * arguments[i]; logLikelihood += regularizationCoefficient * l2reg; } return logLikelihood; } @Override public List<String> additionalInfoTitles() { List<String> titles = new ArrayList<>(); titles.add("Accuracy"); return titles; } @Override public void setAdditionalInfo(Map<String, Double> infoMap) { infoMap.put("Accuracy", ((double) correctLabels) / trainingSamples.size()); } public boolean fit(List<IndexedSample> samples, List<Double> weights, int numberOfIterations) { StochasticGradientDescent sgd = new StochasticGradientDescent(this, numberOfIterations, StochasticGradientDescent.Algorithm.BFGS); trainingSamples = samples; sampleWeights = weights; try { sgd.run(); } catch (Exception e) { e.printStackTrace(); logger.log("Stopping threads..."); updateArguments(null); return false; } return true; } private int getPredictedLabel(double[] probabilities) { double maxProb = 0.0; int predictedLabel = 0; for (int i = 0; i < probabilities.length; i++) { if (probabilities[i] > maxProb) { maxProb = probabilities[i]; predictedLabel = i; } } return predictedLabel; } public int predict(IndexedSample sample) { return getPredictedLabel(probabilityPredict(sample)); } public double[] probabilityPredict(IndexedSample sample) { double[] probabilities = new double[numberOfClasses]; for (int i = numberOfClasses - 2; i >= 0; i--) { probabilities[i] = Math.exp(multiply(i, sample)); } probabilities[numberOfClasses - 1] = 1.0; double invertedSum = 0.0; for (int i = 0; i < numberOfClasses; i++) invertedSum += probabilities[i]; invertedSum = 1.0 / invertedSum; for (int i = 0; i < numberOfClasses; i++) probabilities[i] *= invertedSum; return probabilities; } public double multiply(int thetaIndex, IndexedSample sample) { double sum = 0.0; int startIndex = thetaIndex * numberOfFeatures; for (Entry<Integer, Double> entry : sample.features.entrySet()) sum += thetas[startIndex + entry.getKey()] * entry.getValue(); return sum; } }
25.022654
102
0.700078
e017cd9511b42bc3d22e0ff9c19bc8450f51a528
4,158
package mage.abilities.keyword; import java.util.ArrayList; import java.util.List; import java.util.UUID; import mage.MageObject; import mage.ObjectColor; import mage.abilities.StaticAbility; import mage.cards.Card; import mage.constants.Zone; import mage.filter.Filter; import mage.filter.FilterCard; import mage.filter.FilterObject; import mage.filter.FilterPermanent; import mage.filter.FilterSpell; import mage.filter.predicate.Predicates; import mage.filter.predicate.mageobject.ColorPredicate; import mage.game.Game; import mage.game.permanent.Permanent; import mage.game.stack.Spell; import mage.game.stack.StackObject; /** * * @author BetaSteward_at_googlemail.com */ public class ProtectionAbility extends StaticAbility { protected Filter filter; protected boolean removeAuras; protected static List<ObjectColor> colors = new ArrayList<>(); protected UUID auraIdNotToBeRemoved; // defines an Aura objectId that will not be removed from this protection ability public ProtectionAbility(Filter filter) { super(Zone.BATTLEFIELD, null); this.filter = filter; this.removeAuras = true; this.auraIdNotToBeRemoved = null; } public ProtectionAbility(final ProtectionAbility ability) { super(ability); this.filter = ability.filter.copy(); this.removeAuras = ability.removeAuras; this.auraIdNotToBeRemoved = ability.auraIdNotToBeRemoved; } public static ProtectionAbility from(ObjectColor color) { FilterObject filter = new FilterObject(color.getDescription()); filter.add(new ColorPredicate(color)); colors.add(color); return new ProtectionAbility(filter); } public static ProtectionAbility from(ObjectColor color1, ObjectColor color2) { FilterObject filter = new FilterObject(color1.getDescription() + " and from " + color2.getDescription()); filter.add(Predicates.or(new ColorPredicate(color1), new ColorPredicate(color2))); colors.add(color1); colors.add(color2); return new ProtectionAbility(filter); } @Override public ProtectionAbility copy() { return new ProtectionAbility(this); } @Override public String getRule() { return "protection from " + filter.getMessage() + (removeAuras ? "" : ". This effect doesn't remove auras."); } public boolean canTarget(MageObject source, Game game) { if (filter instanceof FilterPermanent) { if (source instanceof Permanent) { return !filter.match(source, game); } return true; } if (filter instanceof FilterCard) { if (source instanceof Card) { return !filter.match(source, game); } return true; } if (filter instanceof FilterSpell) { if (source instanceof Spell) { return !filter.match(source, game); } // Problem here is that for the check if a player can play a Spell, the source // object is still a card and not a spell yet. So return only if the source object can't be a spell // otherwise the following FilterObject check will be applied if (source instanceof StackObject || (!source.isInstant() && !source.isSorcery())) { return true; } } if (filter instanceof FilterObject) { return !filter.match(source, game); } return true; } public Filter getFilter() { return filter; } public void setFilter(FilterCard filter) { this.filter = filter; } public void setRemovesAuras(boolean removeAuras) { this.removeAuras = removeAuras; } public boolean removesAuras() { return removeAuras; } public List<ObjectColor> getColors() { return colors; } public UUID getAuraIdNotToBeRemoved() { return auraIdNotToBeRemoved; } public void setAuraIdNotToBeRemoved(UUID auraIdNotToBeRemoved) { this.auraIdNotToBeRemoved = auraIdNotToBeRemoved; } }
31.029851
122
0.659692
0cd4dde304d11e38da658c2720170d142c14ed83
7,566
package com.game.client; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.security.PublicKey; import java.util.Random; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.mina.core.RuntimeIoException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.client.engine.Camera; import com.game.client.ui.ClientFrame; import com.game.client.ui.HUD; import com.game.client.ui.LoginWindow; import com.game.common.codec.Packet; import com.game.common.codec.PacketBuilder; import com.game.common.model.Hash; import com.game.common.model.Item; import com.game.common.model.PlayerProfile; import com.game.common.util.PersistenceManager; import com.game.graphics.renderer.Graphics; import com.game.graphics.renderer.Graphics2D; import com.game.graphics.renderer.Graphics3D; public final class Client extends ClientFrame { private static final Logger log = LoggerFactory.getLogger(Client.class); public static final String DEFAULT_HOST = "localhost"; public static final int DEFAULT_PORT = 36954; public static final int[] ICON_SIZES = {128, 64, 32, 16}; public static final int DEFAULT_WIDTH = 800; public static final int DEFAULT_HEIGHT = 600; protected static final Options options; static { options = new Options(); options.addOption("h", "help", false, "print this help."); options.addOption("v", "disable-vsync", false, "disable vsync, default false."); options.addOption("p", "port", true, "server port number to connect to, default " + DEFAULT_PORT + "."); options.addOption("s", "server", true, "server hostname to connect to, default " + DEFAULT_HOST + "."); } public static final void main(String[] args) { try { CommandLineParser parser = new PosixParser(); CommandLine config = parser.parse(options, args); if (config.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("java " + Client.class.getSimpleName(), options); return; } Client client = new Client(config); client.run(); } catch (ParseException e) { log.error("Error parsing command line options: " + e); } catch (RuntimeException e) { log.error(e.getMessage()); } } protected static BufferedImage[] loadIcons(String name, int[] sizes) { BufferedImage[] iconImages = new BufferedImage[sizes.length]; for (int i = 0;i < iconImages.length;i++) { try { URL resource = Client.class.getResource(name + sizes[i] + ".png"); if (resource == null) { // fatal error throw new RuntimeException("Resource not found: icon" + name + sizes[i] + ".png"); } iconImages[i] = ImageIO.read(resource); } catch (IOException e) { // fatal error throw new RuntimeException("Error loading icon: " + e); } } return iconImages; } protected LoginWindow loginWindow; protected final CommandLine config; protected final Connection connection; protected final WorldManager world; protected final Camera camera; protected final HUD hud; protected final PublicKey publicKey; public Client(CommandLine config) { super ("Test Client", DEFAULT_WIDTH, DEFAULT_HEIGHT, Client.loadIcons("icon", ICON_SIZES)); this.config = config; if (config.hasOption("v")) super.setVSync(false); loginWindow = new LoginWindow(this); connection = new Connection(this); world = new WorldManager(this); camera = world.getCamera(); hud = new HUD(this); publicKey = (PublicKey) PersistenceManager.load(Client.class.getResource("publickey.xml")); // Pre-load the item definitions Item.load(); log.info("New client started"); } public HUD getHUD() { return hud; } public Connection getConnection() { return connection; } public WorldManager getWorldManager() { return world; } public boolean isLoggedIn() { return loginWindow == null; } public void login(final String username, final String password) { new Thread(new Runnable() { @Override public void run() { Random random = new Random(); String hostname = config.getOptionValue("s", DEFAULT_HOST); int port = DEFAULT_PORT; if (config.hasOption("p")) { try { port = Integer.parseInt(config.getOptionValue("p")); } catch (NumberFormatException e) { log.error("Invalid port number: " + config.getOptionValue("p") + ", trying default: " + port); } } try { connection.open(hostname, port); Hash usernameHash = new Hash(username.toLowerCase());// Clean the username and hash it to get the users ID Hash passwordHash = new Hash(usernameHash + password); // Salt the password and hash it PacketBuilder packet = new PacketBuilder(Packet.Type.LOGIN_SEND); packet.putHash(usernameHash); packet.putHash(passwordHash); long encryptionSeed = random.nextLong(); packet.putLong(encryptionSeed); long decryptionSeed = random.nextLong(); packet.putLong(decryptionSeed); // Encrypt the login packet with our public key packet.encrypt(publicKey); connection.write(packet); // from now on we want to encrypt outgoing packets connection.enableEncryption(encryptionSeed, decryptionSeed); } catch (RuntimeIoException rioe) { connection.close(); log.warn("Failed to connect to: " + hostname + ":" + port); loginWindow.failed("Failed to connect to the game server."); } } }).start(); } public void loginSuccess(PlayerProfile profile) { world.init(profile); loginWindow = null; log.info("Successfully logged in."); } public void loginFailed(String message) { loginWindow.failed(message); connection.close(); } public void handleLogout() { if (loginWindow != null) return; connection.close(); loginWindow = new LoginWindow(this); } @Override protected void update(long now) { // Update the connection connection.update(now); // If there is a login window, update it if (loginWindow != null) { loginWindow.update(now); return; } // Update the world world.update(now); // Update the HUD hud.update(now); } @Override public void display(Graphics g) { Graphics2D g2d = g.get2D(); // If there is a login window, display it if (loginWindow != null) { g2d.begin(); { loginWindow.display(g2d); } g2d.end(); return; } Graphics3D g3d = g.get3D(); g3d.begin(world.getLocation(), camera.getZoom(), camera.getRotation()); { // Display the world world.display(g3d); } g3d.end(); g2d.begin(); { // Draw the HUD on-top of the world hud.display(g2d); } g2d.end(); } @Override public void mouseClicked(int x, int y, boolean left) { // If there is a login window, it was clicked if (loginWindow != null) { loginWindow.mouseClicked(x, y, left); return; } // If the HUD was clicked, don't pass the key to the world if (hud.mouseClicked(x, y, left)) return; // Pass the click to the world world.mouseClicked(x, y, left); } @Override public void keyPressed(int keyCode, char keyChar) { // If there is a login window, the key goes there if (loginWindow != null) { loginWindow.keyPressed(keyCode, keyChar); return; } // Send the key to the HUD hud.keyPressed(keyCode, keyChar); } @Override protected void close() { connection.destroy(); } }
25.304348
111
0.695348
1d96fd2fe263b72e7dcd837fd2830dd9a75078be
15,400
package experiments; import core.algo.vertical.*; import core.config.DataConfig; import db.schema.BenchmarkTables; import db.schema.entity.Table; import java.util.HashSet; import java.util.Set; import static core.algo.vertical.AbstractAlgorithm.Algo.*; /** * Class for running the algorithms on different tables for a specified cost model. * * @author Endre Palatinus */ public class AlgorithmRunner { public static final String[] allTPCHQueries = new String[22]; static { for (int i=1; i<=22; i++) { allTPCHQueries[i-1] = "Q" + i;} }; public String[] querySet; public static final int replicationFactor = 1; public static final double THRESHOLD = 0.0; public static final double LINE_ITEM_THRESHOLD = 0.25; protected static boolean RUN_TROJAN = true; protected static boolean RUN_NAVATHE = true; protected static boolean RUN_OPTIMAL = true; public static final double[] generalCGrpThreshold = new double[]{THRESHOLD/*, THRESHOLD, THRESHOLD*/}; public static final double[] lineitemCGrpThreshold = new double[]{LINE_ITEM_THRESHOLD/*, LINE_ITEM_THRESHOLD, LINE_ITEM_THRESHOLD*/}; protected DreamPartitioner dreamPartitioner; protected AutoPart autoPart; protected HillClimb hillClimb; protected HYRISE hyrise; protected NavatheAlgorithm navatheAlgo; protected O2P o2p; protected TrojanLayout trojanLayout; protected Optimal optimal; protected double[] runTimes; protected AbstractAlgorithm.AlgorithmConfig config; protected BenchmarkTables.BenchmarkConfig benchmarkConf; /** The list of algorithms to run. */ protected Set<AbstractAlgorithm.Algo> algos; /** The default list of algorithms to run. */ public static final AbstractAlgorithm.Algo[] ALL_ALGOS = {AUTOPART, HILLCLIMB, HYRISE, NAVATHE, O2P, TROJAN, OPTIMAL, DREAM, COLUMN, ROW}; /* JVM and testing specific parameters. */ /** Iterations performed initially just to allow for the JVM to optimize the code. */ protected static final int JVM_HEAT_UP_ITERATIONS = 5; /** Number of times a single experiment is repeated. */ protected static final int REPETITIONS = 5; /** The limit on the runtime of the algorithms for which we perform only one run. */ public static final double NO_REPEAT_TIME_LIMIT = 30; public AlgorithmResults results; /** * Default constructor which creates a set-up for running all algorithms, scale factor 10 and HDD cost model. */ public AlgorithmRunner() { this(null, 10.0, new AbstractAlgorithm.HDDAlgorithmConfig(BenchmarkTables.randomTable(1, 1))); } /** * Constructor which creates a set-up for running all queries. * * @param algos The list of algorithms to run. * @param scaleFactor The scale factor of the benchmark dataset. * @param config The algorithm config including the cost calculator type used. */ public AlgorithmRunner(Set<AbstractAlgorithm.Algo> algos, double scaleFactor, AbstractAlgorithm.AlgorithmConfig config) { this(algos, scaleFactor, null, config); } /** * Constructor where you can specify every aspect of the experiment. * * @param algos The list of algorithms to run. * @param scaleFactor The scale factor of the benchmark dataset. * @param querySet The list of queries to run. * @param config The algorithm config including the cost calculator type used. */ public AlgorithmRunner(Set<AbstractAlgorithm.Algo> algos, double scaleFactor, String[] querySet, AbstractAlgorithm.AlgorithmConfig config) { this.config = config; benchmarkConf = new BenchmarkTables.BenchmarkConfig(null, scaleFactor, DataConfig.tableType); runTimes = new double[AbstractAlgorithm.Algo.values().length]; results = new AlgorithmResults(); if (algos == null) { this.algos = new HashSet<AbstractAlgorithm.Algo>(); for (AbstractAlgorithm.Algo algo : AlgorithmRunner.ALL_ALGOS) { this.algos.add(algo); } } else { this.algos = algos; } this.querySet = querySet; } /** * Method for running the experiment for all TPC-H tables. */ public void runTPC_H_Tables() { runTPC_H_Customer(); runTPC_H_LineItem(true); runTPC_H_Orders(); runTPC_H_Supplier(); runTPC_H_Part(); runTPC_H_PartSupp(); runTPC_H_Nation(); runTPC_H_Region(); } /*Begin Debugging Begin*/ public void runTPC_H_All() { RUN_TROJAN = false; RUN_OPTIMAL = false; RUN_NAVATHE = false; Table table = BenchmarkTables.tpchAll(benchmarkConf); config.setTable(table); runAlgorithms(config, lineitemCGrpThreshold); //runAlgorithms(config, generalCGrpThreshold); RUN_TROJAN = true; RUN_OPTIMAL = true; RUN_NAVATHE = true; } /*End Debugging End*/ /** * Method for running the experiment for TPC-H Customer. */ public void runTPC_H_Customer() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchCustomer(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H LineItem. */ public void runTPC_H_LineItem(boolean runOptimal) { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchLineitem(benchmarkConf), null, querySet); config.setTable(table); RUN_OPTIMAL = runOptimal; runAlgorithms(config, lineitemCGrpThreshold); RUN_OPTIMAL = true; } /** * Method for running the experiment for TPC-H LineItem. */ public void runTPC_H_LineItem(String[] queries) { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchLineitem(benchmarkConf), null, querySet); config.setTable(table); RUN_TROJAN = false; RUN_OPTIMAL = false; runAlgorithms(config, lineitemCGrpThreshold); RUN_TROJAN = true; RUN_OPTIMAL = true; } /** * Method for running the experiment for TPC-H Part. */ public void runTPC_H_Part() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchPart(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Part. */ public void runTPC_H_Part(String[] queries) { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchPart(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Supplier. */ public void runTPC_H_Supplier() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchSupplier(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H PartSupp. */ public void runTPC_H_PartSupp() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchPartSupp(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Orders. */ public void runTPC_H_Orders() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchOrders(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Orders. */ public void runTPC_H_Orders(String[] queries) { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchOrders(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Nation. */ public void runTPC_H_Nation() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchNation(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for TPC-H Region. */ public void runTPC_H_Region() { Table table = BenchmarkTables.partialTable(BenchmarkTables.tpchRegion(benchmarkConf), null, querySet); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /**********************************/ /************** SSB ***************/ /** * Method for running the experiment for all SSB tables. * @param runOptimal Whether to run optimal for this table or not. */ public void runSSB_Tables(boolean runOptimal) { runSSB_Customer(); runSSB_Part(); runSSB_Supplier(); runSSB_Date(); runSSB_LineOrder(runOptimal); } /** * Method for running the experiment for SSB Customer. */ public void runSSB_Customer() { Table table = BenchmarkTables.ssbCustomer(benchmarkConf); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for SSB LineOrder. * @param runOptimal Whether to run optimal for this table or not. */ public void runSSB_LineOrder(boolean runOptimal) { Table table = BenchmarkTables.ssbLineOrder(benchmarkConf); config.setTable(table); RUN_OPTIMAL = runOptimal; runAlgorithms(config, lineitemCGrpThreshold); RUN_OPTIMAL = true; } /** * Method for running the experiment for SSB Part. */ public void runSSB_Part() { Table table = BenchmarkTables.ssbPart(benchmarkConf); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for SSB Supplier. */ public void runSSB_Supplier() { Table table = BenchmarkTables.ssbSupplier(benchmarkConf); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /** * Method for running the experiment for SSB Date. */ public void runSSB_Date() { Table table = BenchmarkTables.ssbDate(benchmarkConf); config.setTable(table); runAlgorithms(config, generalCGrpThreshold); } /**********************************/ /** * Method for running all the algorithms on the same table with the specified cost model and workload. * @param config The config that all algorithms should use. * @param trojanLayoutThresholds The pruning thresholds for Trojan layout. */ public void runAlgorithms(AbstractAlgorithm.AlgorithmConfig config, double[] trojanLayoutThresholds) { //create storage for the current table String tableName = config.getTable().name; results.addResultsForTable(tableName); dreamPartitioner = new DreamPartitioner(config); runAlgorithm(dreamPartitioner, tableName); autoPart = new AutoPart(config); autoPart.setReplicationFactor(0.0); runAlgorithm(autoPart, tableName); hillClimb = new HillClimb(config); runAlgorithm(hillClimb, tableName); hyrise = new HYRISE(config); runAlgorithm(hyrise, tableName); navatheAlgo = new NavatheAlgorithm(config); if (RUN_NAVATHE) { runAlgorithm(navatheAlgo, tableName); } o2p = new O2P(config); runAlgorithm(o2p, tableName); optimal = new Optimal(config); if (RUN_OPTIMAL) { runAlgorithm(optimal, tableName); } if (RUN_TROJAN) { trojanLayout = new TrojanLayout(config); trojanLayout.setReplicationFactor(replicationFactor); trojanLayout.setPruningThresholds(trojanLayoutThresholds); // CAUTION: this is only correct for replication factor 1! trojanLayout = runTrojan(trojanLayout, config, trojanLayoutThresholds, tableName); } } private void runAlgorithm(AbstractAlgorithm algorithm, String tableName) { if (!algos.contains(algorithm.type)) { return; } runTimes[algorithm.type.ordinal()] = 0.0; for (int i = 0; i < JVM_HEAT_UP_ITERATIONS + REPETITIONS; i++) { algorithm.partition(); if (algorithm.getTimeTaken() > NO_REPEAT_TIME_LIMIT) { runTimes[algorithm.type.ordinal()] = algorithm.getTimeTaken(); results.storeResults(tableName, algorithm, runTimes[algorithm.type.ordinal()]); return; } if (i >= JVM_HEAT_UP_ITERATIONS) { runTimes[algorithm.type.ordinal()] += algorithm.getTimeTaken(); } } runTimes[algorithm.type.ordinal()] /= REPETITIONS; results.storeResults(tableName, algorithm, runTimes[algorithm.type.ordinal()]); } private TrojanLayout runTrojan(TrojanLayout algorithm, AbstractAlgorithm.AlgorithmConfig config, double[] trojanLayoutThresholds, String tableName) { if (!algos.contains(algorithm.type)) { return null; } runTimes[algorithm.type.ordinal()] = 0.0; for (int i = 0; i < JVM_HEAT_UP_ITERATIONS + REPETITIONS; i++) { algorithm = new TrojanLayout(config); algorithm.setReplicationFactor(replicationFactor); algorithm.setPruningThresholds(trojanLayoutThresholds); algorithm.setPruningThreshold(THRESHOLD); algorithm.partition(); if (algorithm.getTimeTaken() > NO_REPEAT_TIME_LIMIT) { runTimes[algorithm.type.ordinal()] = algorithm.getTimeTaken(); results.storeResults(tableName, algorithm, runTimes[algorithm.type.ordinal()]); return algorithm; } if (i >= JVM_HEAT_UP_ITERATIONS) { runTimes[algorithm.type.ordinal()] += algorithm.getTimeTaken(); } } runTimes[algorithm.type.ordinal()] /= REPETITIONS; results.storeResults(tableName, algorithm, runTimes[algorithm.type.ordinal()]); return algorithm; } /*Begin Debugging Begin*/ public static void main(String[] args) { String[] queries = {"A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10"}; Set<AbstractAlgorithm.Algo> algos_sel = new HashSet<AbstractAlgorithm.Algo>(); //AbstractAlgorithm.Algo[] ALL_ALGOS_SEL = {AUTOPART, HILLCLIMB, HYRISE}; AbstractAlgorithm.Algo[] ALL_ALGOS_SEL = {TROJAN}; for (AbstractAlgorithm.Algo algo : ALL_ALGOS_SEL) { algos_sel.add(algo); } AlgorithmRunner algoRunner = new AlgorithmRunner(algos_sel, 10, queries, new AbstractAlgorithm.HDDAlgorithmConfig(BenchmarkTables.randomTable(1, 1))); algoRunner.runTPC_H_All(); String output = AlgorithmResults.exportResults(algoRunner.results); System.out.println(output); } /*End Debugging End*/ }
33.261339
158
0.653312
d5cb1619f7d0285ec066fa4d6e7a99064757f1d0
1,194
package ar.com.bbva.got.model; import java.util.Date; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @XmlRootElement @Entity @Table(name = "tramite_autorizado") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class TramiteAutorizado { @EmbeddedId private TramiteAutorizadoKey id; @ManyToOne @JoinColumn(insertable = false, updatable = false) private Autorizado autorizado; @ApiModelProperty(notes = "The creator user", required = true) private String usuAlta; @ApiModelProperty(notes = "The creation date", required = true) @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX") private Date fechaAlta; @ApiModelProperty(notes = "Indicates if this Autorizado finalize the Tramite", required = false) private boolean finalizoTramite; }
27.767442
101
0.746231
b8ab1b5e223251c3933f58d02451290d7b9f4795
4,957
package com.amazonaws.wafv2.rulegroup; import com.amazonaws.wafv2.commons.CommonVariables; import com.amazonaws.wafv2.commons.CustomerAPIClientBuilder; import com.amazonaws.wafv2.commons.ExceptionTranslationWrapper; import lombok.RequiredArgsConstructor; import software.amazon.awssdk.services.wafv2.Wafv2Client; import software.amazon.awssdk.services.wafv2.model.DeleteRuleGroupRequest; import software.amazon.awssdk.services.wafv2.model.DeleteRuleGroupResponse; import software.amazon.awssdk.services.wafv2.model.GetRuleGroupRequest; import software.amazon.awssdk.services.wafv2.model.GetRuleGroupResponse; import software.amazon.awssdk.services.wafv2.model.WafUnavailableEntityException; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.HandlerErrorCode; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.OperationStatus; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; @RequiredArgsConstructor public class DeleteHandler extends BaseHandler<CallbackContext> { private final Wafv2Client client; public DeleteHandler() { this.client = CustomerAPIClientBuilder.getClient(); } @Override public ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final Logger logger) { final ResourceModel model = request.getDesiredResourceState(); final CallbackContext currentContext = callbackContext == null ? CallbackContext.builder() .stabilizationRetriesRemaining(CommonVariables.NUMBER_OF_STATE_POLL_RETRIES) .build() : callbackContext; if (currentContext.getStabilizationRetriesRemaining() <= 0) { return ProgressEvent.<ResourceModel, CallbackContext>builder() .status(OperationStatus.FAILED) .errorCode(HandlerErrorCode.NotStabilized) .build(); } try { deleteRuleGroupExceptionWrapper(proxy, model).execute(); return ProgressEvent.<ResourceModel, CallbackContext>builder() .status(OperationStatus.SUCCESS) .build(); } catch (WafUnavailableEntityException e) { // entity still being sequenced return ProgressEvent.<ResourceModel, CallbackContext>builder() .resourceModel(model) .status(OperationStatus.IN_PROGRESS) .callbackContext(CallbackContext.builder() .stabilizationRetriesRemaining(currentContext.getStabilizationRetriesRemaining() - 1) .build()) .callbackDelaySeconds(CommonVariables.CALLBACK_DELAY_SECONDS) .build(); } catch (RuntimeException e) { // handle error code return ProgressEvent.<ResourceModel, CallbackContext>builder() .status(OperationStatus.FAILED) .errorCode(ExceptionTranslationWrapper.translateExceptionIntoErrorCode(e)) .message(e.getMessage()) .build(); } } private ExceptionTranslationWrapper<DeleteRuleGroupResponse> deleteRuleGroupExceptionWrapper( final AmazonWebServicesClientProxy proxy, final ResourceModel model) { return new ExceptionTranslationWrapper<DeleteRuleGroupResponse>() { @Override public DeleteRuleGroupResponse doWithTranslation() throws RuntimeException { final DeleteRuleGroupRequest deleteRuleGroupRequest = DeleteRuleGroupRequest.builder() .name(model.getName()) .id(model.getId()) .lockToken(getLockToken(proxy, model)) .scope(model.getScope()) .build(); final DeleteRuleGroupResponse response = proxy.injectCredentialsAndInvokeV2( deleteRuleGroupRequest, client::deleteRuleGroup); return response; } }; } private String getLockToken(final AmazonWebServicesClientProxy proxy, final ResourceModel model) { final GetRuleGroupRequest getRuleGroupRequest = GetRuleGroupRequest.builder() .name(model.getName()) .id(model.getId()) .scope(model.getScope()) .build(); final GetRuleGroupResponse response = proxy.injectCredentialsAndInvokeV2( getRuleGroupRequest, client::getRuleGroup); return response.lockToken(); } }
47.209524
113
0.66633
2e9b8ff07e96ccb2ca54cade9dab0ea75594bb73
932
package SimulationTest.one.exam6; class MyClass7 { MyClass7() { System.out.println(101); } } class MySubClass extends MyClass7 { //Constructors cannot use final, abstract or static modifiers. As no-argument constructor of MySubClass uses final modifier, therefore it causes compilation error. //final MySubClass() { MySubClass() { System.out.println(202); } final public void getTrip(){ } final void getJob(){ } } final class MyClassA extends MySubClass{ //'getJob()' cannot override 'getJob()' in 'SimulationTest.one.exam6.MySubClass'; overridden method is final //public void getJob(){} } //Cannot inherit from final 'SimulationTest.one.exam6.MyClassA' //class MyClassB extends MyClassA{ class MyClassB{ public void getJob1(){ } } public class Test7 { public static void main(String[] args) { System.out.println(new MySubClass()); } }
23.3
167
0.68133
ac666cf4cde5a946cfd71c0686171b8dc6f98d57
3,051
package com.example.wojciech.fibaro_hc2_control.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.example.wojciech.fibaro_hc2_control.MainActivity; import com.example.wojciech.fibaro_hc2_control.R; import com.example.wojciech.fibaro_hc2_control.model.HC2; import java.lang.reflect.Field; public class HC2InfoFragment extends Fragment { private static final String ARG_PARAM1 = "hc2_info"; private TableLayout tableLayout; private HC2 hC2; public HC2InfoFragment() { // Required empty public constructor } public static HC2InfoFragment newInstance() { HC2InfoFragment fragment = new HC2InfoFragment(); return fragment; } public static HC2InfoFragment newInstance(HC2 hC2) { HC2InfoFragment fragment = new HC2InfoFragment(); return fragment; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(ARG_PARAM1, hC2); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_hc2_info, container, false); tableLayout = (TableLayout) v.findViewById(R.id.table_layout); if (savedInstanceState != null) { hC2 = savedInstanceState.getParcelable(ARG_PARAM1); setUpData(hC2); } return v; } public void setUpData(HC2 hC2) { if (tableLayout != null && hC2 != null) { this.hC2=hC2; tableLayout.removeAllViews(); for (Field field : hC2.getClass().getFields()) { if (field.getName().contains("CREATOR") || field.getName().contains("CONTENTS_FILE_DESCRIPTOR") || field.getName().contains("PARCELABLE_WRITE_RETURN_VALUE")) continue; try { TableRow row = new TableRow(getContext()); TextView t = new TextView(getContext()); t.setText(field.getName()); TextView t2 = new TextView(getContext()); t2.setText(field.get(hC2).toString()); // add the TextView to the new TableRow row.addView(t); row.addView(t2); // add the TableRow to the TableLayout tableLayout.addView(row); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } @Override public void onAttach(Context context) { super.onAttach(context); ((MainActivity) context).onSectionAttached(1); } }
32.115789
85
0.615536
09512cdb441484eb00e7fbc9de006351fd09efce
1,343
package com.someguyssoftware.dungeonsengine.model; import java.util.List; import com.someguyssoftware.dungeonsengine.config.DungeonConfig; import com.someguyssoftware.dungeonsengine.style.Theme; /** * * @author Mark Gottschling on Sep 28, 2018 * */ public interface IDungeon { /** * @return the levels */ List<ILevel> getLevels(); /** * @param levels the levels to set */ void setLevels(List<ILevel> levels); /** * @return the entrance */ IRoom getEntrance(); /** * @param entrance the entrance to set */ void setEntrance(IRoom entrance); /** * @return the shafts */ List<Shaft> getShafts(); /** * * @param shafts */ void setShafts(List<Shaft> shafts); /** * @return the config */ DungeonConfig getConfig(); /** * @param config the config to set */ void setConfig(DungeonConfig config); /** * @return the name */ String getName(); /** * @param name the name to set */ void setName(String name); // TEMP Theme getTheme(); void setTheme(Theme theme); Integer getMaxX(); void setMaxX(Integer maxX); Integer getMinY(); void setMinY(Integer minY); Integer getMaxY(); void setMaxY(Integer maxY); Integer getMinZ(); void setMinZ(Integer minZ); Integer getMinX(); void setMinX(Integer minX); Integer getMaxZ(); void setMaxZ(Integer maxZ); }
14.287234
64
0.664185
3e184f9146b397229008efc068cdc3bf304d4197
1,529
/* * Copyright 2014 Alexey Andreev. * * 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.teavm.dependency; import org.teavm.model.CallLocation; import org.teavm.model.ClassReader; /** * * @author Alexey Andreev */ public class ClassDependency implements ClassDependencyInfo { private DependencyChecker checker; private String className; private ClassReader classReader; ClassDependency(DependencyChecker checker, String className, ClassReader classReader) { this.checker = checker; this.className = className; this.classReader = classReader; } @Override public String getClassName() { return className; } @Override public boolean isMissing() { return classReader == null; } public ClassReader getClassReader() { return classReader; } public void initClass(CallLocation callLocation) { if (!isMissing()) { checker.initClass(this, callLocation); } } }
27.303571
91
0.691956
d38bbc5fa575799710834459e5b435f8cb487109
1,493
package com.example.android.sunshine.sync; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataItem; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.WearableListenerService; /** * Created by scott on 2/11/2017. */ public class WearableRequestForDataListenerService extends WearableListenerService { // private static final String LOG_TAG = "DataListenerService"; @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { for (DataEvent event : dataEventBuffer) { if (event.getType() == DataEvent.TYPE_CHANGED) { DataItem item = event.getDataItem(); DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap(); String path = item.getUri().getPath(); if (path.equals("/data_request")) { for (String key : dataMap.keySet()) { if (!dataMap.containsKey(key)) { continue; } switch (key) { case "data_request": SunshineSyncUtils.startImmediateSync(getApplicationContext()); break; } } } } } } }
33.177778
94
0.574682
57aa4ec54d75f4f2c4a0453bb832daac62005dad
27,350
package com.example.valarmorghulis.firebaseauth; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.androidstudy.daraja.Daraja; import com.bumptech.glide.Glide; import com.example.valarmorghulis.firebaseauth.Model.AccessToken; import com.example.valarmorghulis.firebaseauth.Services.DarajaApiClient; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import com.example.valarmorghulis.firebaseauth.Model.STKPush; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import timber.log.Timber; import static com.example.valarmorghulis.firebaseauth.Constants.BUSINESS_SHORT_CODE; import static com.example.valarmorghulis.firebaseauth.Constants.CALLBACKURL; import static com.example.valarmorghulis.firebaseauth.Constants.PARTYB; import static com.example.valarmorghulis.firebaseauth.Constants.PASSKEY; import static com.example.valarmorghulis.firebaseauth.Constants.TRANSACTION_TYPE; public class BuyFragment extends Fragment { ImageView pImage; private TextView name; private TextView price; private TextView seller; private TextView location; private TextView openHours; private TextView closeHours; private TextView deliveryLocation; private TextView sellDate; private TextView Desc_tag; private TextView Desc_text; private TextView display_quantity; private TextView buyer_pickup_time; private TextView delivery_locations; private TextView total_price; private TextView order_details; private TextView choose_method; private LinearLayout quantity; private EditText mEditTextPickUpTime; private EditText bPhone; private RadioGroup radioGroup; private RadioGroup radioGroup2; private RadioButton location1; private RadioButton location2; private RadioButton location3; private RadioButton location4; private RadioButton location5; private Button button_make_offer; private Button button_message; private Button button_add_to_cart; private Button button_delete; private Button button_increase; private Button button_decrease; private Button mButtonTimePicker; boolean mItemClicked = false; private String sName; private String sEmail; private String pName; private String bName; private String bEmail; private String sLocation; private String sOpenHours; private String sCloseHours; private String delLocation1; private String delLocation2; private String delLocation3; private String delLocation4; private String delLocation5; private String delCharge1; private String delCharge2; private String delCharge3; private String delCharge4; private String delCharge5; private int position; private int mHour, mMinute; int totalPrice; String pPrice; private String key; int imagePosition; int minteger; String stringImageUri; FirebaseAuth mAuth; DatabaseReference mDatabaseRef; private FirebaseStorage mStorage; private ValueEventListener mDBListener; DatabaseReference userDatabase; private List<User> mUser; private List<Upload> mUploads; Daraja daraja; // private ApiClient mApiClient; private DarajaApiClient mApiClient; private ProgressDialog mProgressDialog; @Override public void onStart() { super.onStart(); NetworkConnection networkConnection = new NetworkConnection(); if (networkConnection.isConnectedToInternet(getActivity()) || networkConnection.isConnectedToMobileNetwork(getActivity()) || networkConnection.isConnectedToWifi(getActivity())) { } else { networkConnection.showNoInternetAvailableErrorDialog(getActivity()); return; } String testEmail = mAuth.getInstance().getCurrentUser().getEmail(); if (testEmail.equals(sEmail)) { button_make_offer.setVisibility(View.GONE); button_message.setVisibility(View.GONE); // button_add_to_cart.setVisibility(View.GONE); button_delete.setVisibility(View.VISIBLE); order_details.setVisibility(View.GONE); quantity.setVisibility(View.GONE); bPhone.setVisibility(View.GONE); choose_method.setVisibility(View.GONE); radioGroup.setVisibility(View.GONE); total_price.setVisibility(View.GONE); delivery_locations.setVisibility(View.GONE); radioGroup2.setVisibility(View.GONE); buyer_pickup_time.setVisibility(View.GONE); mButtonTimePicker.setVisibility(View.GONE); Toast.makeText(getActivity(), "You are seller of this product", Toast.LENGTH_SHORT).show(); } } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_buy, container, false); name = (TextView) v.findViewById(R.id.product_name); price = (TextView) v.findViewById(R.id.product_price); seller = (TextView) v.findViewById(R.id.product_seller); sellDate = (TextView) v.findViewById(R.id.product_date); location = (TextView) v.findViewById(R.id.seller_location); deliveryLocation = (TextView) v.findViewById(R.id.delivery_location); openHours = (TextView) v.findViewById(R.id.seller_open_hours); closeHours = (TextView) v.findViewById(R.id.seller_close_hours); delivery_locations = (TextView) v.findViewById(R.id.delivery_locations); button_make_offer = (Button) v.findViewById(R.id.offer_button); button_message = (Button) v.findViewById(R.id.msg_button); // button_add_to_cart = (Button) v.findViewById(R.id.cart_button); button_delete = (Button) v.findViewById(R.id.delete_button); display_quantity = (TextView) v.findViewById(R.id.integer_number); button_increase = (Button) v.findViewById(R.id.increase); button_decrease = (Button) v.findViewById(R.id.decrease); mButtonTimePicker = (Button) v.findViewById(R.id.pickup_time_button); pImage = (ImageView) v.findViewById(R.id.product_image); Desc_tag = (TextView) v.findViewById(R.id.Description_tag); Desc_text = (TextView) v.findViewById(R.id.Description); bName = mAuth.getInstance().getCurrentUser().getDisplayName(); bEmail = mAuth.getInstance().getCurrentUser().getEmail(); minteger = 0; display(minteger); location1 = (RadioButton) v.findViewById(R.id.location1); location2 = (RadioButton) v.findViewById(R.id.location2); location3 = (RadioButton) v.findViewById(R.id.location3); location4 = (RadioButton) v.findViewById(R.id.location4); location5 = (RadioButton) v.findViewById(R.id.location5); total_price = (TextView) v.findViewById(R.id.total_price); order_details = (TextView) v.findViewById(R.id.Details_tag); quantity = (LinearLayout) v.findViewById(R.id.quantity); choose_method = (TextView) v.findViewById(R.id.choose); buyer_pickup_time = (TextView) v.findViewById(R.id.buyer_time); mEditTextPickUpTime = (EditText) v.findViewById(R.id.pickup_time); bPhone = (EditText) v.findViewById(R.id.text_view_phone); radioGroup = (RadioGroup) v.findViewById(R.id.groupradio); radioGroup2 = (RadioGroup) v.findViewById(R.id.groupradio2); mUploads = new ArrayList<>(); mStorage = FirebaseStorage.getInstance(); mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads"); mProgressDialog = new ProgressDialog(getActivity()); mApiClient = new DarajaApiClient(); mApiClient.setIsDebug(true); //Set True to enable logging, false to disable. getAccessToken(); Bundle bundle = getArguments(); if (bundle != null) { position = bundle.getInt("position"); pName = bundle.getString("name"); String pImageUrl = bundle.getString("imageUrl"); pPrice = bundle.getString("price"); //Bitmap bitmapImage = bundle.getParcelable("bitmapImage"); sName = bundle.getString("userName"); key = bundle.getString("key"); String date = bundle.getString("date"); String desc = bundle.getString("desc"); sEmail = bundle.getString("email"); sLocation = bundle.getString("location"); sOpenHours = bundle.getString("openTime"); sCloseHours = bundle.getString("closeTime"); delLocation1 = bundle.getString("location1"); delLocation2 = bundle.getString("location2"); delLocation3 = bundle.getString("location3"); delLocation4 = bundle.getString("location4"); delLocation5 = bundle.getString("location5"); delCharge1 = bundle.getString("deliveryCharge1"); delCharge2 = bundle.getString("deliveryCharge2"); delCharge3 = bundle.getString("deliveryCharge3"); delCharge4 = bundle.getString("deliveryCharge4"); delCharge5 = bundle.getString("deliveryCharge5"); name.setText(pName); price.setText("Ksh " + pPrice); seller.setText(sName); sellDate.setText(date); location.setText(sLocation); openHours.setText(sOpenHours); closeHours.setText(sCloseHours); location1.setText(delLocation1); location2.setText(delLocation2); location3.setText(delLocation3); location4.setText(delLocation4); location5.setText(delLocation5); if (delLocation1 != null) { deliveryLocation.setText("Yes"); }else { deliveryLocation.setText("No"); } if (desc != null) { Desc_tag.setVisibility(View.VISIBLE); Desc_text.setVisibility(View.VISIBLE); Desc_text.setText(desc); } //pImage.setImageURI(Uri.parse(pImageUrl)); // if (bitmapImage != null) // pImage.setImageBitmap(bitmapImage); if (pImageUrl != null) { String photoUrl = pImageUrl; Glide.with(this) .load(photoUrl) .into(pImage); } /*DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); DatabaseReference current = ref.child("fir-auth-431b5").child("user").child("token"); //User currentUser = mUser.get(email); */ } radioGroup.clearCheck(); radioGroup.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radioButton = (RadioButton) group.findViewById(checkedId); int selectedId = radioGroup.getCheckedRadioButtonId(); switch(selectedId) { case R.id.rb_delivery: delivery_locations.setVisibility(View.VISIBLE); radioGroup2.setVisibility(View.VISIBLE); buyer_pickup_time.setVisibility(View.GONE); mButtonTimePicker.setVisibility(View.GONE); break; case R.id.rb_pickup: buyer_pickup_time.setVisibility(View.VISIBLE); mButtonTimePicker.setVisibility(View.VISIBLE); delivery_locations.setVisibility(View.GONE); radioGroup2.setVisibility(View.GONE); break; } } }); radioGroup2.clearCheck(); radioGroup2.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radioButton2 = (RadioButton) group.findViewById(checkedId); int selectedId2 = radioGroup2.getCheckedRadioButtonId(); switch(selectedId2) { case R.id.location1: totalPrice = Integer.parseInt(delCharge1) + totalPrice; total_price.setText("Ksh " + totalPrice); break; case R.id.location2: totalPrice = Integer.parseInt(delCharge2) + totalPrice; total_price.setText("Ksh " + totalPrice); break; case R.id.location3: totalPrice = Integer.parseInt(delCharge3) + totalPrice; total_price.setText("Ksh " + totalPrice); break; case R.id.location4: totalPrice = Integer.parseInt(delCharge4) + totalPrice; total_price.setText("Ksh " + totalPrice); break; case R.id.location5: totalPrice = Integer.parseInt(delCharge5) + totalPrice; total_price.setText("Ksh " + totalPrice); break; } } }); mButtonTimePicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openTimeChooser(); } }); button_increase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { minteger = minteger + 1; display(minteger); totalPrice = Integer.parseInt(pPrice) * minteger; total_price.setText("Ksh " + totalPrice); } }); button_decrease.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { minteger = minteger - 1; display(minteger); totalPrice = Integer.parseInt(pPrice) * minteger; total_price.setText("Ksh " + totalPrice); } }); button_message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MsgFragment msgFragment = new MsgFragment(); Bundle bundle = new Bundle(); bundle.putString("sEmail", sEmail); bundle.putString("pName", pName); bundle.putString("sName", sName); bundle.putString("bName", mAuth.getInstance().getCurrentUser().getDisplayName()); bundle.putString("bEmail", mAuth.getInstance().getCurrentUser().getEmail()); msgFragment.setArguments(bundle); getActivity() .getSupportFragmentManager() .beginTransaction().replace(R.id.frag_container, msgFragment) .addToBackStack(null).commit(); // startActivity(new Intent(getActivity(), MsgActivity.class)); // getActivity().finish(); } }); button_make_offer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (minteger == 0) { Toast.makeText(getActivity(), "No quantity has been selected", Toast.LENGTH_SHORT).show(); } if (mEditTextPickUpTime.getText().toString().trim().isEmpty()) { mEditTextPickUpTime.setError("Pickup time required"); mEditTextPickUpTime.requestFocus(); }else{ mEditTextPickUpTime.getText().toString(); } int selectedId = radioGroup.getCheckedRadioButtonId(); if (selectedId == -1) { Toast.makeText(getActivity(), "No method has been selected", Toast.LENGTH_SHORT).show(); } else { RadioButton radioButton = (RadioButton) radioGroup.findViewById(selectedId); // Toast.makeText(getActivity(), radioButton.getText(), Toast.LENGTH_SHORT).show(); int selectedId2 = radioGroup2.getCheckedRadioButtonId(); if (selectedId2 == -1) { Toast.makeText(getActivity(), "No location has been selected", Toast.LENGTH_SHORT).show(); }else { RadioButton radioButton2 = (RadioButton) radioGroup2.findViewById(selectedId2); // Toast.makeText(getActivity(), radioButton2.getText(), Toast.LENGTH_SHORT).show(); } if (bPhone.getText().toString().trim().isEmpty()) { bPhone.setError("Phone number required"); bPhone.requestFocus(); }else{ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Do you wish to submit this order?"); // builder.setMessage("This will send an email notification along with your email id to the seller."); builder.setMessage("Payment is via MPESA.The number you provided will be billed."); builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // sendEmailToSeller(); // sendEmailToBuyer(); String phone_number = bPhone.getText().toString(); int amount = totalPrice; performSTKPush(phone_number, amount); } }); builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog ad = builder.create(); ad.show(); } } } }); mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mUploads.clear(); for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { Upload upload = postSnapshot.getValue(Upload.class); upload.setKey(postSnapshot.getKey()); mUploads.add(upload); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); button_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Alert!"); builder.setMessage("Deletion is permanent. Are you sure you want to delete?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteProduct(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog ad = builder.create(); ad.show(); } }); return v; } private void openTimeChooser() { final Calendar c = Calendar.getInstance(); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mEditTextPickUpTime.setText(hourOfDay + ":" + minute); } }, mHour, mMinute, false); timePickerDialog.show(); } private void display(int number) { display_quantity.setText("" + number); } private void deleteProduct(){ Upload selectedItem = mUploads.get(position); final String selectedKey = selectedItem.getKey(); StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl()); imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { startActivity(new Intent(getActivity(), DrawerActivity.class)); mDatabaseRef.child(selectedKey).removeValue(); Toast.makeText(getActivity(), "Item deleted", Toast.LENGTH_SHORT).show(); getActivity().finish(); } }); } public void getAccessToken() { mApiClient.setGetAccessToken(true); mApiClient.mpesaService().getAccessToken().enqueue(new Callback<AccessToken>() { @Override public void onResponse(@NonNull Call<AccessToken> call, @NonNull Response<AccessToken> response) { if (response.isSuccessful()) { mApiClient.setAuthToken(response.body().accessToken); } } @Override public void onFailure(@NonNull Call<AccessToken> call, @NonNull Throwable t) { } }); } public void performSTKPush(String phone_number,int amount) { mProgressDialog.setMessage("Processing your request"); mProgressDialog.setTitle("Please Wait..."); mProgressDialog.setIndeterminate(true); mProgressDialog.show(); String timestamp = Utils.getTimestamp(); int businessCode = Integer.parseInt(BUSINESS_SHORT_CODE); int partyB = Integer.parseInt(PARTYB); long phoneNo = Long.parseLong(phone_number); STKPush stkPush = new STKPush( businessCode, Utils.getPassword(businessCode, PASSKEY, timestamp), timestamp, TRANSACTION_TYPE, amount, phoneNo, partyB, Utils.sanitizePhoneNumber(phone_number), CALLBACKURL, "CENT Limited", //Account reference "Payment of Product" //Transaction description ); mApiClient.setGetAccessToken(false); //Sending the data to the Mpesa API, remember to remove the logging when in production. mApiClient.mpesaService().sendPush(stkPush).enqueue(new Callback<STKPush>() { @Override public void onResponse(@NonNull Call<STKPush> call, @NonNull Response<STKPush> response) { mProgressDialog.dismiss(); try { if (response.isSuccessful()) { Timber.d("post submitted to API. %s", response.body()); } else { Timber.e("Response %s", response.errorBody().string()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(@NonNull Call<STKPush> call, @NonNull Throwable t) { mProgressDialog.dismiss(); Timber.e(t); } }); } public void onPointerCaptureChanged(boolean hasCapture) { } private void sendEmailToSeller() { String email = sEmail; String subject = "[Cent] Request for product " + pName; String msg = "unknown-user"; if (bName != "") msg = bName; String thankMsg = "\n\nThank you for using Cent :)"; String autoMsg = "\n\nThis is an auto generated email. Please do not reply to this email."; String message = "Hey " + sName + ". " + msg + " is requesting for your product \"" + pName + "\". Wait for further response from " + msg + ". If you want you can write to " + msg + " on email id " + bEmail + " ." + thankMsg + autoMsg; SendMail sm2s = new SendMail(getActivity(), email, subject, message); sm2s.execute(); } private void sendEmailToBuyer() { String email = bEmail; String subject = "[Cent] Request Successful for " + pName; String thankMsg = "\n\nThank you for using Cent :)"; String autoMsg = "\n\nThis is an auto generated email. Please do not reply to this email."; String message = "Hello " + bName + ". You have requested " + sName +" for \"" + pName + "\". You can send message to " + sName + " in the app by clicking on message button." + thankMsg + autoMsg ; SendMail sm2b = new SendMail(getActivity(), email, subject, message); sm2b.execute(); } }
41.439394
243
0.594771
600458ab13320f28017ffc20aa1f7ff98f2fed6f
1,168
package com.panly.urm.manager.right.vo; import com.panly.urm.page.core.DataTablePageBase; public class OperLogParamsVo extends DataTablePageBase{ private String userName; private String url; /* 访问地址 */ private String operType; /* 和 menu 中模块对应 */ private String startCreateTime; private String endCreateTime; private Integer success; public String getStartCreateTime() { return startCreateTime; } public void setStartCreateTime(String startCreateTime) { this.startCreateTime = startCreateTime; } public String getEndCreateTime() { return endCreateTime; } public void setEndCreateTime(String endCreateTime) { this.endCreateTime = endCreateTime; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOperType() { return operType; } public void setOperType(String operType) { this.operType = operType; } public Integer getSuccess() { return success; } public void setSuccess(Integer success) { this.success = success; } }
21.62963
57
0.737158
d72dc8e544097274a44b882a26c22fb060c65990
731
/* * Copyright (c) 2018-2020, Antonio Gabriel Muñoz Conejo <antoniogmc at gmail dot com> * Distributed under the terms of the MIT License */ package com.github.tonivade.purefun.control; import com.github.tonivade.purefun.Function1; public abstract class Stateful<R, S, E> extends StateMarker implements Handler<R, E> { private final Field<S> state; public Stateful(S init) { this.state = field(init); } public <T> Control<T> useState(Function1<S, Function1<Function1<T, Function1<S, Control<R>>>, Control<R>>> body) { return this.use(resume -> state.get().flatMap(before -> body.apply(before).apply(value -> after -> state.set(after).andThen(resume.apply(value))) ) ); } }
29.24
116
0.679891
702bf9ebf6cccfbc34d1835c829fa9c333fee030
28,069
package org.afplib.samples; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.afplib.ResourceKey; import org.afplib.afplib.AfplibFactory; import org.afplib.afplib.BDG; import org.afplib.afplib.BFM; import org.afplib.afplib.BMM; import org.afplib.afplib.BRG; import org.afplib.afplib.BRS; import org.afplib.afplib.EDG; import org.afplib.afplib.EFM; import org.afplib.afplib.EMM; import org.afplib.afplib.ERG; import org.afplib.afplib.ERS; import org.afplib.afplib.FGD; import org.afplib.afplib.FullyQualifiedName; import org.afplib.afplib.FullyQualifiedNameFQNType; import org.afplib.afplib.IMM; import org.afplib.afplib.IOB; import org.afplib.afplib.IPG; import org.afplib.afplib.IPO; import org.afplib.afplib.IPS; import org.afplib.afplib.MCC; import org.afplib.afplib.MCF; import org.afplib.afplib.MCF1; import org.afplib.afplib.MCF1RG; import org.afplib.afplib.MCFRG; import org.afplib.afplib.MDD; import org.afplib.afplib.MDR; import org.afplib.afplib.MDRRG; import org.afplib.afplib.MFC; import org.afplib.afplib.MMC; import org.afplib.afplib.MMD; import org.afplib.afplib.MMO; import org.afplib.afplib.MMORG; import org.afplib.afplib.MMT; import org.afplib.afplib.MPG; import org.afplib.afplib.MPO; import org.afplib.afplib.MPORG; import org.afplib.afplib.MPS; import org.afplib.afplib.MPSRG; import org.afplib.afplib.ObjectClassification; import org.afplib.afplib.PEC; import org.afplib.afplib.PGP; import org.afplib.afplib.PGP1; import org.afplib.afplib.PMC; import org.afplib.afplib.ResourceObjectType; import org.afplib.afplib.ResourceObjectTypeObjType; import org.afplib.afplib.SFName; import org.afplib.base.SF; import org.afplib.base.Triplet; import org.afplib.io.AfpFilter; import org.afplib.io.AfpInputStream; import org.afplib.io.AfpOutputStream; import org.afplib.io.Filter; import org.afplib.io.Filter.STATE; import org.apache.commons.lang3.StringUtils; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AfpCombine { private static final Logger log = LoggerFactory.getLogger(AfpCombine.class); class Resource { long start, end, ersPos; byte[] content; String hash; } class MediumMap { long start, end; byte[] content; LinkedList<SF> sfs = new LinkedList<SF>(); String hash; } class InputFile { File file; List<ResourceKey> resources = new LinkedList<ResourceKey>(); Map<ResourceKey, Resource> filePos = new HashMap<ResourceKey, Resource>(); Map<ResourceKey, String> renamings = new HashMap<ResourceKey, String>(); Map<String, String> renameIMM = new HashMap<String, String>(); long documentStart; LinkedList<SF> formdef = new LinkedList<SF>(); LinkedList<String> mmNames = new LinkedList<String>(); Map<String, MediumMap> mediumMaps = new HashMap<String, MediumMap>(); } public static void main(String[] args) { log.info("starting..."); LinkedList<String> f = new LinkedList<String>(); String out = null; for(int i=0; i<args.length; i++) { if(args[i].equals("-o") && i+1<args.length) out = args[++i]; else f.add(args[i]); } log.debug("in: {}", StringUtils.join(f, ':')); log.debug("out: {}", out); try { new AfpCombine(out, (String[]) f.toArray(new String[f.size()])).run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } log.info("done."); } private String outFile; private String[] inFiles; private InputFile[] files; private MessageDigest algorithm; private LinkedList<String> resourceNames = new LinkedList<String>(); private LinkedList<String> mmNames = new LinkedList<String>(); private SF[] formdef; private boolean checkResourceEquality = true; public AfpCombine(String outFile, String[] inFiles) { this.outFile = outFile; this.inFiles = inFiles; files = new InputFile[inFiles.length]; try { algorithm = MessageDigest.getInstance(System.getProperty("security.digest", "MD5")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public void run() throws IOException { scanResources(); buildRenamingTable(); buildFormdef(); writeResourceGroup(); writeDocuments(); } private void scanResources() throws IOException, FileNotFoundException { for(int i=0; i<inFiles.length; i++) { files[i] = new InputFile(); files[i].file = new File(inFiles[i]); try(FileInputStream fin = new FileInputStream(files[i].file); AfpInputStream ain = new AfpInputStream(new BufferedInputStream(fin))) { SF sf; long filepos = 0, prevFilePos = 0; ByteArrayOutputStream buffer = null; ResourceKey key = null; Resource resource = null; String mmName = null; MediumMap mediumMap = null; boolean processingFormdef = false, isFirstFormdef = true; while((sf = ain.readStructuredField()) != null) { filepos = ain.getCurrentOffset(); if(sf instanceof ERG) { files[i].documentStart = filepos; break; } if(sf instanceof BRS) { key = ResourceKey.toResourceKey((BRS) sf); if(key.getType() == ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE) { key = null; // do not save formdef resources } else { buffer = new ByteArrayOutputStream(); files[i].resources.add(key); files[i].filePos.put(key, resource = new Resource()); resource.start = prevFilePos; } } if(sf instanceof BFM && isFirstFormdef) { log.debug("processing formdef"); processingFormdef = true; } if(processingFormdef) files[i].formdef.add(sf); if(sf instanceof BMM && isFirstFormdef) { BMM bmm = (BMM) sf; mmName = bmm.getMMName(); log.debug("{}: found medium map {}", files[i].file, mmName); files[i].mmNames.add(mmName); files[i].mediumMaps.put(mmName, mediumMap = new MediumMap()); mediumMap.start = prevFilePos; buffer = new ByteArrayOutputStream(); } if(processingFormdef && mediumMap != null) { mediumMap.sfs.add(sf); } if(buffer != null) buffer.write(ain.getLastReadBuffer()); if(sf instanceof EMM && isFirstFormdef) { mediumMap.end = filepos; byte[] byteArray = buffer.toByteArray(); mediumMap.hash = getHash(byteArray); if(checkResourceEquality) mediumMap.content = byteArray; if(!mmNames.contains(mmName)) mmNames.add(mmName); log.debug("{}@{}-{}: found {}, hash {}", files[i].file, mediumMap.start, mediumMap.end, mmName, mediumMap.hash); mmName = null; mediumMap = null; buffer = null; } if(sf instanceof EFM) { processingFormdef = false; } if(sf instanceof ERS) { if(buffer == null) { // this is the end of a formdef, which we don't save isFirstFormdef = false; } else { resource.ersPos = prevFilePos; resource.end = filepos; byte[] byteArray = buffer.toByteArray(); resource.hash = getHash(byteArray); if(checkResourceEquality) resource.content = byteArray; if(!resourceNames.contains(key.getName())) resourceNames.add(key.getName()); log.debug("{}@{}-{}: found {}, hash {}", files[i].file, resource.start, resource.end, key, resource.hash); buffer = null; key = null; resource = null; } } prevFilePos = filepos; } } } } private void buildRenamingTable() { for(int i=0; i<files.length; i++) { for(int j=i+1; j<files.length; j++) { InputFile f1 = files[i]; InputFile f2 = files[j]; log.debug("comparing resources in {} and {}", f1.file.getName(), f2.file.getName()); for(ResourceKey k1 : f1.resources) { if(f2.resources.contains(k1) && !f2.renamings.containsKey(k1)) { // can this ever happen???? String h1 = f1.filePos.get(k1).hash; String h2 = f2.filePos.get(k1).hash; if(h1.equals(h2) && equals(f1.filePos.get(k1).content, f2.filePos.get(k1).content)) { if(f1.renamings.containsKey(k1)) { String newName = f1.renamings.get(k1); log.debug("resource {} is same in {} and {}, but being renamed to {}", k1.getName(), f1.file.getName(), f2.file.getName(), newName); f2.renamings.put(k1, newName); } else { log.debug("resource {} is same in {} and {}", k1.getName(), f1.file.getName(), f2.file.getName()); } } else { String newName = getNewResourceName(k1.getName(), h2); f2.renamings.put(k1, newName); resourceNames.add(newName); log.debug("{}: renaming resource {} to {}", f2.file.getName(), k1.getName(), newName ); } } } for(String mmName : f1.mmNames) { if(f2.mmNames.contains(mmName) && !f2.renameIMM.containsKey(mmName)) { String h1 = f1.mediumMaps.get(mmName).hash; String h2 = f1.mediumMaps.get(mmName).hash; if(h1.equals(h2) && equals(f1.mediumMaps.get(mmName).content, f2.mediumMaps.get(mmName).content)) { if(f1.renameIMM.containsKey(mmName)) { String newName = f1.renameIMM.get(mmName); log.debug("medium map {} is same in {} and {}, but being renamed to {}", mmName, f1.file.getName(), f2.file.getName(), newName); f2.renameIMM.put(mmName, newName); } else { log.debug("medium map {} is same in {} and {}", mmName, f1.file.getName(), f2.file.getName()); } } else { String newName = getNewFormdefName(mmName, h2); f2.renameIMM.put(mmName, newName); mmNames.add(newName); log.debug("{}: renaming medium map {} to {}", f2.file.getName(), mmName, newName); } } } } } } private boolean equals(byte[] b1, byte[] b2) { if(!checkResourceEquality) return true; return Arrays.equals(b1, b2); } private void buildFormdef() { LinkedList<SF> formdef = new LinkedList<SF>(); LinkedList<String> mmsWritten = new LinkedList<String>(); formdef.add(AfplibFactory.eINSTANCE.createBFM()); for(int i=0; i<inFiles.length; i++) { // build environment group LinkedList<SF> bdg = new LinkedList<SF>(); boolean isbdg = false; for(SF sf : files[i].formdef) { if(sf instanceof BDG) { isbdg = true; continue; } if(sf instanceof EDG) isbdg = false; if(isbdg) bdg.add(sf); } for(String mmName : files[i].mmNames) { MediumMap map = files[i].mediumMaps.get(mmName); Iterator<SF> it = map.sfs.iterator(); BMM bmm = (BMM) it.next(); if(files[i].renameIMM.containsKey(mmName)) { String newName = files[i].renameIMM.get(mmName); if(mmsWritten.contains(newName)) { log.debug("not writing resource {} as {} again", mmName, newName); continue; } bmm.setMMName(newName); log.debug("writing medium map {} as {} from {}", mmName, bmm.getMMName(), files[i].file.getName()); } else if(mmsWritten.contains(mmName)) { log.debug("not writing medium map {} again", mmName); continue; } else { log.debug("writing medium map {} from {}", mmName, files[i].file.getName()); } formdef.add(bmm); // add allowed sfs from the map inherited // by the environment group if needed add(formdef, bdg, map.sfs, FGD.class); add(formdef, bdg, map.sfs, MMO.class); add(formdef, bdg, map.sfs, MPO.class); add(formdef, bdg, map.sfs, MMT.class); add(formdef, bdg, map.sfs, MMD.class); add(formdef, bdg, map.sfs, MDR.class); add(formdef, bdg, map.sfs, PGP.class); add(formdef, bdg, map.sfs, MDD.class); add(formdef, bdg, map.sfs, MCC.class); add(formdef, bdg, map.sfs, MMC.class); add(formdef, bdg, map.sfs, PMC.class); add(formdef, bdg, map.sfs, MFC.class); add(formdef, bdg, map.sfs, PEC.class); formdef.add(AfplibFactory.eINSTANCE.createEMM()); mmsWritten.add(bmm.getMMName()); } } formdef.add(AfplibFactory.eINSTANCE.createEFM()); this.formdef = (SF[]) formdef.toArray(new SF[formdef.size()]); } @SuppressWarnings("unchecked") private <T extends SF> void add(LinkedList<SF> dest, LinkedList<SF> bdg, LinkedList<SF> map, Class<T> clazz) { LinkedList<T> result = new LinkedList<T>(); for(SF sf : map) { if(clazz.isInstance(sf) || (clazz.equals(PGP.class) && sf instanceof PGP1)) { result.add((T) sf); } } if(result.isEmpty()) { for(SF sf : bdg) { if(clazz.isInstance(sf) || (clazz.equals(PGP.class) && sf instanceof PGP1)) { result.add((T) sf); } } } dest.addAll(result); } private void writeResourceGroup() throws IOException { LinkedList<ResourceKey> resourcesWritten = new LinkedList<ResourceKey>(); try(AfpOutputStream aout = new AfpOutputStream(new BufferedOutputStream(new FileOutputStream(outFile, false)))) { BRG brg = AfplibFactory.eINSTANCE.createBRG(); aout.writeStructuredField(brg); { BRS brs = AfplibFactory.eINSTANCE.createBRS(); brs.setRSName("F1INLINE"); ResourceObjectType type = AfplibFactory.eINSTANCE.createResourceObjectType(); type.setConData(new byte[] {0,0,0,0}); type.setObjType(ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE); brs.getTriplets().add(type); aout.writeStructuredField(brs); for(SF sf : formdef) aout.writeStructuredField(sf); ERS ers = AfplibFactory.eINSTANCE.createERS(); aout.writeStructuredField(ers); } log.info("writing resource group"); for(int i=0; i<inFiles.length; i++) { FileInputStream fin; try(AfpInputStream ain = new AfpInputStream(fin = new FileInputStream(inFiles[i]))) { for(ResourceKey key : files[i].resources) { if(key.getType() == ResourceObjectTypeObjType.CONST_FORM_MAP_VALUE) { log.debug("not writing formdef {}", key.getName()); continue; } ain.position(files[i].filePos.get(key).start); BRS brs = (BRS) ain.readStructuredField(); if(files[i].renamings.containsKey(key)) { String newName = files[i].renamings.get(key); ResourceKey newkey = new ResourceKey(key.getType(), newName, key.getObjId()); if(resourcesWritten.contains(newkey)) { log.debug("not writing resource {} as {} again", key.getName(), newName); continue; } renameBRSERS(brs, newName); resourcesWritten.add(newkey); log.debug("writing resource {} as {} from {}", key.getName(), newName, files[i].file.getName()); } else if(resourcesWritten.contains(key)) { log.debug("not writing resource {} again", key.getName()); continue; } else { resourcesWritten.add(key); log.debug("writing resource {} from {}", key.getName(), files[i].file.getName()); } aout.writeStructuredField(brs); byte[] buffer = new byte[8 * 1024]; int l; long left = files[i].filePos.get(key).ersPos - ain.getCurrentOffset(); while((l = fin.read(buffer, 0, left > buffer.length ? buffer.length : (int) left)) > 0) { aout.write(buffer, 0, l); left-=l; } if(left > 0) throw new IOException("couldn't copy resource from "+files[i].file.getName()); ERS ers = (ERS) ain.readStructuredField(); if(files[i].renamings.containsKey(key)) { String newName = files[i].renamings.get(key); renameBRSERS(ers, newName); } aout.writeStructuredField(ers); } } } ERG erg = AfplibFactory.eINSTANCE.createERG(); aout.writeStructuredField(erg); } } private void renameBRSERS(SF sf, String newName) { if(sf instanceof BRS) { ((BRS)sf).setRSName(newName); EList<Triplet> triplets = ((BRS)sf).getTriplets(); for(Object t : triplets) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; if(fqn.getFQNType() == null) continue; if(FullyQualifiedNameFQNType.CONST_REPLACE_FIRST_GID_NAME_VALUE != fqn.getFQNType().intValue()) continue; fqn.setFQName(newName); break; } } } else { ((ERS)sf).setRSName(newName); } } private void writeDocuments() throws IOException { for(int i=0; i<inFiles.length; i++) { log.info("writing documents from {}", files[i].file.getName()); try (AfpInputStream in = new AfpInputStream(new FileInputStream(inFiles[i])); AfpOutputStream out = new AfpOutputStream( new BufferedOutputStream(new FileOutputStream(outFile, true)))) { in.position(files[i].documentStart); final InputFile file = files[i]; AfpFilter.filter(in, out, new Filter() { @Override public STATE onStructuredField(SF sf) { log.trace("{}", sf); switch(sf.getId()) { case SFName.IMM_VALUE: return rename(file, (IMM)sf); case SFName.IOB_VALUE: return rename(file, (IOB)sf); case SFName.IPG_VALUE: return rename(file, (IPG)sf); case SFName.IPO_VALUE: return rename(file, (IPO)sf); case SFName.IPS_VALUE: return rename(file, (IPS)sf); case SFName.MCF_VALUE: return rename(file, (MCF)sf); case SFName.MCF1_VALUE: return rename(file, (MCF1)sf); case SFName.MDR_VALUE: return rename(file, (MDR)sf); case SFName.MMO_VALUE: return rename(file, (MMO)sf); case SFName.MPG_VALUE: return rename(file, (MPG)sf); case SFName.MPO_VALUE: return rename(file, (MPO)sf); case SFName.MPS_VALUE: return rename(file, (MPS)sf); } return STATE.UNTOUCHED; } }); } } } private void overrideGid(EList<Triplet> triplets, String newName) { for(Object t : triplets) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; if(fqn.getFQNType() == null) continue; if(FullyQualifiedNameFQNType.CONST_REPLACE_FIRST_GID_NAME_VALUE != fqn.getFQNType().intValue()) continue; fqn.setFQName(newName); break; } } } private Filter.STATE rename(InputFile file, IMM sf) { IMM imm = (IMM) sf; if(file.renameIMM.containsKey(imm.getMMPName())) { String newName = file.renameIMM.get(imm.getMMPName()); imm.setMMPName(newName); overrideGid(imm.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IOB sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setObjName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPG sf) { return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPO sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setOvlyName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, IPS sf) { ResourceKey key = ResourceKey.toResourceKey(sf); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); sf.setPsegName(newName); overrideGid(sf.getTriplets(), newName); log.trace("rename {}", newName); return Filter.STATE.MODIFIED; } return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, MCF sf) { Filter.STATE result = Filter.STATE.UNTOUCHED; for(MCFRG rg : sf.getRG()) { for(Triplet t : rg.getTriplets()) { if(t instanceof FullyQualifiedName) { FullyQualifiedName fqn = (FullyQualifiedName) t; log.trace("{}", fqn); if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_FONT_CHARACTER_SET_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_FONT_CHARACTER_SET, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_CODE_PAGE_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODE_PAGE, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } if(fqn.getFQNType() == FullyQualifiedNameFQNType.CONST_CODED_FONT_NAME_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODED_FONT, fqn.getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); fqn.setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } } return result; } private Filter.STATE rename(InputFile file, MCF1 sf) { STATE result = Filter.STATE.UNTOUCHED; for(MCF1RG rg : sf.getRG()) { log.trace("{}", rg); byte[] fcsname = rg.getFCSName().getBytes(Charset.forName("IBM500")); if(fcsname[0] != (byte) 0xff && fcsname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_FONT_CHARACTER_SET, rg.getFCSName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setFCSName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } byte[] cfname = rg.getCFName().getBytes(Charset.forName("IBM500")); if(cfname[0] != (byte) 0xff && cfname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODED_FONT, rg.getCFName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setCFName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } byte[] cpname = rg.getCPName().getBytes(Charset.forName("IBM500")); if(cpname[0] != (byte) 0xff && cpname[1] != (byte) 0xff) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_CODE_PAGE, rg.getCPName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setCPName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } return result; } private Filter.STATE rename(InputFile file, MDR sf) { STATE result = Filter.STATE.UNTOUCHED; for(MDRRG rg : sf.getRG()) { EList<Triplet> mcfGroup = rg.getTriplets(); for(EObject triplet : mcfGroup) { if(triplet instanceof FullyQualifiedName) { log.trace("{}", triplet); int fqnType = ((FullyQualifiedName) triplet).getFQNType(); String name = ((FullyQualifiedName) triplet).getFQName(); ResourceKey key = null; if(fqnType == FullyQualifiedNameFQNType.CONST_RESOURCE_OBJECT_REFERENCE_VALUE) { key = new ResourceKey(ResourceObjectTypeObjType.CONST_IOCA, name); } else if(fqnType == FullyQualifiedNameFQNType.CONST_OTHER_OBJECT_DATA_REFERENCE_VALUE) { for(Triplet t : rg.getTriplets()) { if(t instanceof ObjectClassification) { ObjectClassification clazz = (ObjectClassification) t; key = new ResourceKey(ResourceObjectTypeObjType.CONST_OBJECT_CONTAINER, name, clazz.getRegObjId()); } } } else if(fqnType == FullyQualifiedNameFQNType.CONST_DATA_OBJECT_EXTERNAL_RESOURCE_REFERENCE_VALUE) { for(Triplet t : rg.getTriplets()) { if(t instanceof ObjectClassification) { ObjectClassification clazz = (ObjectClassification) t; key = new ResourceKey(ResourceObjectTypeObjType.CONST_OBJECT_CONTAINER, name, clazz.getRegObjId()); } } } if(key != null) { if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); ((FullyQualifiedName)triplet).setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } } return result; } private Filter.STATE rename(InputFile file, MMO sf) { STATE result = Filter.STATE.UNTOUCHED; for(MMORG rg : sf.getRg()) { log.trace("{}", rg); ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_OVERLAY, rg.getOVLname()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setOVLname(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } return result; } private Filter.STATE rename(InputFile file, MPG sf) { log.warn("MPG is not supported: {}", sf); return Filter.STATE.UNTOUCHED; } private Filter.STATE rename(InputFile file, MPO sf) { STATE result = Filter.STATE.UNTOUCHED; for(MPORG rg : sf.getRG()) { log.trace("{}", rg); for(Triplet t : rg.getTriplets()) { if(t instanceof FullyQualifiedName) if(((FullyQualifiedName) t).getFQNType().intValue() == FullyQualifiedNameFQNType.CONST_RESOURCE_OBJECT_REFERENCE_VALUE) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_OVERLAY, ((FullyQualifiedName) t).getFQName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); ((FullyQualifiedName)t).setFQName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } } } return result; } private Filter.STATE rename(InputFile file, MPS sf) { STATE result = Filter.STATE.UNTOUCHED; for(MPSRG rg : sf.getFixedLengthRG()) { ResourceKey key = new ResourceKey(ResourceObjectTypeObjType.CONST_PAGE_SEGMENT, rg.getPsegName()); if(file.renamings.containsKey(key)) { String newName = file.renamings.get(key); rg.setPsegName(newName); log.trace("rename {}", newName); result = Filter.STATE.MODIFIED; } } return result; } private String getNewResourceName(String oldName, String hash) { for (int i = 0; i < hash.length() - 5; i++) { String res = oldName.substring(0, 2) + hash.substring(i, i + 6); if (!resourceNames.contains(res)) return res.toUpperCase(); } for(int i=0; i<999999; i++) { String res = oldName.substring(0, 2) + String.format("%06d", i); if (!resourceNames.contains(res)) return res.toUpperCase(); } log.error("unable to find a resource name for hash " + hash); throw new IllegalStateException( "unable to find a resource name for hash " + hash); } private String getNewFormdefName(String oldName, String hash) { for (int i = 0; i < hash.length() - 5; i++) { String res = oldName.substring(0, 2) + hash.substring(i, i + 6); if (!mmNames.contains(res)) return res.toUpperCase(); } for(int i=0; i<999999; i++) { String res = oldName.substring(0, 2) + String.format("%06d", i); if (!mmNames.contains(res)) return res.toUpperCase(); } log.error("unable to find a resource name for hash " + hash); throw new IllegalStateException( "unable to find a resource name for hash " + hash); } private String getHash(byte[] bytes) { algorithm.reset(); algorithm.update(bytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } }
32.524913
140
0.663437
9da6ff45475357744d479139663179595f670d96
4,408
import java.lang.Math; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class Queens { private static final int GRID_SIZE = 12; private static class BoardState { int size; int columns[]; public BoardState(int size, int columns[]) { this.size = size; this.columns = new int[size]; for(int i = 0; i < size; i++) { this.columns[i] = columns[i]; } } public BoardState(int size) { this.size = size; this.columns = new int[size]; Arrays.fill(columns, -1); } public BoardState(BoardState s) { this(s.size, s.columns); } public boolean tryQueen(int row, int col) { if(row >= size || col >= size || columns[row] >= 0) { return false; // invalid state } for(int i = 0; i < row; i++) { if(columns[i] == col || (columns[i] >= 0 && (Math.abs(columns[i] - col) == row - i))) { return false; } } return true; } public void putQueen(int row, int col) { if(row >= size || col >= size) { return; // invalid state } columns[row] = col; } private boolean testConflictDiagonals(int row, int col) { return false; } public void print() { System.out.print(" "); for(int i = 0; i < size; i++) { System.out.print(" " + i%10); } System.out.println(); System.out.print(" "); for(int i = 0; i < size; i++) { System.out.print("__"); } System.out.println(); for(int r = 0; r < size; r++) { System.out.format("%02d |", r); for(int c = 0; c < size; c++) { if(columns[r] == c) { System.out.print(" Q"); } else { System.out.print(" ."); } } System.out.println("|"); } System.out.print(" "); for(int i = 0; i < size; i++) { System.out.print("--"); } System.out.println(); } } // My solution runs slower than the book solution, but allows for different numbers of queens to board sizes public static void main(String[] args) { long startTime = System.currentTimeMillis(); // Core Function here List<BoardState> states = positionQueens(8,8); for(BoardState s : states) { s.print(); } System.out.println("Total amount of states: " + states.size()); List<Integer[]> res = new ArrayList<Integer[]>(); placeQueensByBook(0, new Integer[GRID_SIZE], res); System.out.println("Total amount of states: " + res.size()); double duration = System.currentTimeMillis() - startTime; System.out.println(); System.out.print("Processing time: "); System.out.format("%.3f", duration / 1000); System.out.println(" seconds."); } public static List<BoardState> positionQueens(int queens, int size) { List<BoardState> initStates = new ArrayList<BoardState>(); List<BoardState> finishedStates = new ArrayList<BoardState>(); initStates.add(new BoardState(size)); positionQueens(queens, 0, size, initStates,finishedStates); return finishedStates; } public static void positionQueens(int queens, int row, int maxRow, List<BoardState> workingStates, List<BoardState> finishedStates) { if(queens == 0) { finishedStates.addAll(workingStates); return; } if(row > maxRow) { return; } List<BoardState> nextWorkingStates = new ArrayList<BoardState>(); for(BoardState s : workingStates) { for(int col = 0; col < maxRow; col++) { if(s.tryQueen(row, col)) { BoardState ns = new BoardState(s); ns.putQueen(row, col); nextWorkingStates.add(ns); } } } if(maxRow - row > queens) { positionQueens(queens, row+1, maxRow, workingStates, finishedStates); } positionQueens(queens-1, row+1, maxRow, nextWorkingStates, finishedStates); } public static void placeQueensByBook(int row, Integer[] columns, List<Integer[]> results) { if(row == GRID_SIZE) { results.add(columns.clone()); } else { for(int col = 0; col < GRID_SIZE; col++) { if(checkValid(columns, row, col)) { columns[row] = col; // place queen placeQueensByBook(row + 1, columns, results); } } } } private static boolean checkValid(Integer[] columns, int row1, int column1) { for(int row2 = 0; row2 < row1; row2++) { int column2 = columns[row2]; if(column1 == column2) { return false; } int columnDist = Math.abs(column2 - column1); int rowDist = row1 - row2; if(columnDist == rowDist) { return false; } } return true; } }
25.627907
137
0.614338
1a306791a7ae89db288e2f860dfd3bddb1f86af7
814
package poweraqua.core.plugin; public abstract class OntoDatabasePlugin implements OntologyPlugin { private String name; private String subType; private String serverURL; private String repositoryName; public void setUrlID(String url) { this.serverURL = url; } public String getUrlID() { return this.serverURL; } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } public String getRepositoryName() { return this.repositoryName; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void setSubType(String subType) { this.subType = this.name; } public String getSubType() { return this.subType; } }
15.653846
54
0.675676
099ab3b45311aba6e3bea9aa2bc27a394d2334fc
778
package mekanism.common.capabilities.basic; import javax.annotation.Nonnull; import mekanism.api.IAlloyInteraction; import mekanism.api.tier.AlloyTier; import mekanism.common.capabilities.basic.DefaultStorageHelper.NullStorage; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraftforge.common.capabilities.CapabilityManager; public class DefaultAlloyInteraction implements IAlloyInteraction { public static void register() { CapabilityManager.INSTANCE.register(IAlloyInteraction.class, new NullStorage<>(), DefaultAlloyInteraction::new); } @Override public void onAlloyInteraction(PlayerEntity player, Hand hand, ItemStack stack, @Nonnull AlloyTier tier) { } }
37.047619
120
0.811054
0c56045d3b5d3a99f08f56648ca73dc3e2339551
489
package io.github.juanmuscaria.blockheads; import io.github.juanmuscaria.blockheads.network.ENetServer; public class BHServer { private ENetServer eNetServer; protected volatile boolean isRunning = true; public BHServer(){ eNetServer = new ENetServer(null,15152); } public void runServerLoop(){ while (isRunning){ eNetServer.processEvents(); } } public synchronized void stopServer(){ isRunning = false; } }
21.26087
60
0.664622
47edc7de0a350bc814a4f663f57b2b9df744a04e
795
package leetcode.easy.string_all.morse_unqiue_code; import java.util.HashSet; /** * Created by qindongliang on 2018/12/9. */ public class UniqueMorseCode { String[] morseCodes = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; public int uniqueMorseRepresentations(String[] words) { HashSet<String> unique=new HashSet<>(); for (String word:words){ StringBuilder sb=new StringBuilder(); for(char c : word.toCharArray()){ sb.append( morseCodes[c-'a']); } unique.add(sb.toString()); } return unique.size(); } public static void main(String[] args) { } }
23.382353
188
0.466667
a610780e133fec7a4a411ffb6ef2207a966edcda
277
package com.baiyi.opscloud.mapper.opscloud; import com.baiyi.opscloud.domain.generator.opscloud.DatasourceInstanceAssetRelation; import tk.mybatis.mapper.common.Mapper; public interface DatasourceInstanceAssetRelationMapper extends Mapper<DatasourceInstanceAssetRelation> { }
39.571429
104
0.873646
e2f889b7af53630fb020ace609489446ec290869
1,461
package webtesting.helper; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class WindowHelper { private static WindowHelper windowHelper; private static WebDriver wdDriver; private WebElement element; private WindowHelper(WebDriver driver){ wdDriver = driver; } public static WindowHelper getInstance(WebDriver driver){ if(windowHelper == null || wdDriver.hashCode() != driver.hashCode()) windowHelper = new WindowHelper(driver); return windowHelper; } private List<String> getWindowIds(){ ArrayList<String> windowIds = new ArrayList<>(wdDriver.getWindowHandles()); return Collections.unmodifiableList(windowIds); } public void switchToWindow(int index){ ArrayList<String> windowIds = new ArrayList<>(getWindowIds()); if(index < 0 || index > windowIds.size()) throw new IllegalArgumentException("Index is not valid " + index); wdDriver.switchTo().window(windowIds.get(index)); } public void switchToParent(){ ArrayList<String> windowIds = new ArrayList<>(getWindowIds()); wdDriver.switchTo().window(windowIds.get(0)); } public void switchToParentWithClose(){ ArrayList<String> windowIds = new ArrayList<>(getWindowIds()); for(int i = 1; i < windowIds.size(); i++){ wdDriver.switchTo().window(windowIds.get(i)); wdDriver.close(); } switchToParent(); } }
24.762712
77
0.729637
089c5f157129409466c5b4c47bbca0dc5c2187d9
9,329
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.query; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.jdbc.PhoenixDriver; import org.apache.phoenix.schema.SaltingUtil; import org.apache.phoenix.schema.types.PChar; import org.apache.phoenix.schema.types.PDate; import org.apache.phoenix.schema.types.PVarchar; import org.apache.phoenix.util.ByteUtil; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.StringUtil; import org.junit.BeforeClass; import org.junit.Test; public class ConnectionlessTest { private static final int saltBuckets = 200; private static final String orgId = "00D300000000XHP"; private static final String keyPrefix1 = "111"; private static final String keyPrefix2 = "112"; private static final String entityHistoryId1 = "123456789012"; private static final String entityHistoryId2 = "987654321098"; private static final String name1 = "Eli"; private static final String name2 = "Simon"; private static final Date now = new Date(System.currentTimeMillis()); private static final byte[] unsaltedRowKey1 = ByteUtil.concat( PChar.INSTANCE.toBytes(orgId), PChar.INSTANCE.toBytes(keyPrefix1), PChar.INSTANCE.toBytes(entityHistoryId1)); private static final byte[] unsaltedRowKey2 = ByteUtil.concat( PChar.INSTANCE.toBytes(orgId), PChar.INSTANCE.toBytes(keyPrefix2), PChar.INSTANCE.toBytes(entityHistoryId2)); private static final byte[] saltedRowKey1 = ByteUtil.concat( new byte[] {SaltingUtil.getSaltingByte(unsaltedRowKey1, 0, unsaltedRowKey1.length, saltBuckets)}, unsaltedRowKey1); private static final byte[] saltedRowKey2 = ByteUtil.concat( new byte[] {SaltingUtil.getSaltingByte(unsaltedRowKey2, 0, unsaltedRowKey2.length, saltBuckets)}, unsaltedRowKey2); private static String getUrl() { return PhoenixRuntime.JDBC_PROTOCOL + PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + PhoenixRuntime.CONNECTIONLESS; } @BeforeClass public static void verifyDriverRegistered() throws SQLException { assertTrue(DriverManager.getDriver(getUrl()) == PhoenixDriver.INSTANCE); } @Test public void testConnectionlessUpsert() throws Exception { testConnectionlessUpsert(null); } @Test public void testSaltedConnectionlessUpsert() throws Exception { testConnectionlessUpsert(saltBuckets); } private void testConnectionlessUpsert(Integer saltBuckets) throws Exception { String dmlStmt = "create table core.entity_history(\n" + " organization_id char(15) not null, \n" + " key_prefix char(3) not null,\n" + " entity_history_id char(12) not null,\n" + " created_by varchar,\n" + " created_date date\n" + " CONSTRAINT pk PRIMARY KEY (organization_id, key_prefix, entity_history_id) ) " + (saltBuckets == null ? "" : (PhoenixDatabaseMetaData.SALT_BUCKETS + "=" + saltBuckets)); Properties props = new Properties(); Connection conn = DriverManager.getConnection(getUrl(), props); PreparedStatement statement = conn.prepareStatement(dmlStmt); statement.execute(); String upsertStmt = "upsert into core.entity_history(organization_id,key_prefix,entity_history_id, created_by, created_date)\n" + "values(?,?,?,?,?)"; statement = conn.prepareStatement(upsertStmt); statement.setString(1, orgId); statement.setString(2, keyPrefix2); statement.setString(3, entityHistoryId2); statement.setString(4, name2); statement.setDate(5,now); statement.execute(); statement.setString(1, orgId); statement.setString(2, keyPrefix1); statement.setString(3, entityHistoryId1); statement.setString(4, name1); statement.setDate(5,now); statement.execute(); Iterator<Pair<byte[],List<KeyValue>>> dataIterator = PhoenixRuntime.getUncommittedDataIterator(conn); Iterator<KeyValue> iterator = dataIterator.next().getSecond().iterator(); byte[] expectedRowKey1 = saltBuckets == null ? unsaltedRowKey1 : saltedRowKey1; byte[] expectedRowKey2 = saltBuckets == null ? unsaltedRowKey2 : saltedRowKey2; if (Bytes.compareTo(expectedRowKey1, expectedRowKey2) < 0) { assertRow1(iterator, expectedRowKey1); assertRow2(iterator, expectedRowKey2); } else { assertRow2(iterator, expectedRowKey2); assertRow1(iterator, expectedRowKey1); } assertFalse(iterator.hasNext()); assertFalse(dataIterator.hasNext()); conn.rollback(); // to clear the list of mutations for the next } private static void assertRow1(Iterator<KeyValue> iterator, byte[] expectedRowKey1) { KeyValue kv; assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey1, kv.getRow()); assertEquals(name1, PVarchar.INSTANCE.toObject(kv.getValue())); assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey1, kv.getRow()); assertEquals(now, PDate.INSTANCE.toObject(kv.getValue())); assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey1, kv.getRow()); assertEquals(QueryConstants.EMPTY_COLUMN_VALUE, PVarchar.INSTANCE.toObject(kv.getValue())); } private static void assertRow2(Iterator<KeyValue> iterator, byte[] expectedRowKey2) { KeyValue kv; assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey2, kv.getRow()); assertEquals(name2, PVarchar.INSTANCE.toObject(kv.getValue())); assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey2, kv.getRow()); assertEquals(now, PDate.INSTANCE.toObject(kv.getValue())); assertTrue(iterator.hasNext()); kv = iterator.next(); assertArrayEquals(expectedRowKey2, kv.getRow()); assertEquals(QueryConstants.EMPTY_COLUMN_VALUE, PVarchar.INSTANCE.toObject(kv.getValue())); } @Test public void testMultipleConnectionQueryServices() throws Exception { String url1 = getUrl(); String url2 = url1 + PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + "LongRunningQueries"; Connection conn1 = DriverManager.getConnection(url1); try { assertEquals(StringUtil.EMPTY_STRING, conn1.getMetaData().getUserName()); Connection conn2 = DriverManager.getConnection(url2); try { assertEquals("LongRunningQueries", conn2.getMetaData().getUserName()); ConnectionQueryServices cqs1 = conn1.unwrap(PhoenixConnection.class).getQueryServices(); ConnectionQueryServices cqs2 = conn2.unwrap(PhoenixConnection.class).getQueryServices(); assertTrue(cqs1 != cqs2); Connection conn3 = DriverManager.getConnection(url1); try { ConnectionQueryServices cqs3 = conn3.unwrap(PhoenixConnection.class).getQueryServices(); assertTrue(cqs1 == cqs3); Connection conn4 = DriverManager.getConnection(url2); try { ConnectionQueryServices cqs4 = conn4.unwrap(PhoenixConnection.class).getQueryServices(); assertTrue(cqs2 == cqs4); } finally { conn4.close(); } } finally { conn3.close(); } } finally { conn2.close(); } } finally { conn1.close(); } } }
44.850962
137
0.674456
227431c6f89846409054b7e6f2327dec2de1d19d
2,996
/* * Copyright 2019 NAVER Corp. * * 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.navercorp.pinpoint.grpc.server; import com.navercorp.pinpoint.grpc.Header; import com.navercorp.pinpoint.grpc.HeaderReader; import io.grpc.Context; import io.grpc.Contexts; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; /** * @author Woonduk Kang(emeroad) */ public class HeaderPropagationInterceptor implements ServerInterceptor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final HeaderReader<Header> headerReader; private final Context.Key<Header> contextKey; public HeaderPropagationInterceptor(HeaderReader<Header> headerReader) { this(headerReader, ServerContext.getAgentInfoKey()); } public HeaderPropagationInterceptor(HeaderReader<Header> headerReader, Context.Key<Header> contextKey) { this.headerReader = Objects.requireNonNull(headerReader, "headerReader"); this.contextKey = Objects.requireNonNull(contextKey, "contextKey"); } @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { Header headerObject; try { headerObject = headerReader.extract(headers); } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Header extract fail cause={}, method={} headers={}, attr={}", e.getMessage(), call.getMethodDescriptor().getFullMethodName(), headers, call.getAttributes(), e); } call.close(Status.INVALID_ARGUMENT.withDescription(e.getMessage()), new Metadata()); return new ServerCall.Listener<ReqT>() { }; } final Context currentContext = Context.current(); final Context newContext = currentContext.withValue(contextKey, headerObject); if (logger.isDebugEnabled()) { logger.debug("headerPropagation method={}, headers={}, attr={}", call.getMethodDescriptor().getFullMethodName(), headers, call.getAttributes()); } ServerCall.Listener<ReqT> contextPropagateInterceptor = Contexts.interceptCall(newContext, call, headers, next); return contextPropagateInterceptor; } }
39.421053
157
0.712951
630f18ad9e53804605ab4f5b3c322ce58846bbe7
176
package com.example.weatherapi; import org.springframework.data.repository.CrudRepository; public interface ImageRepository extends CrudRepository<ImageModel, Integer>{ }
29.333333
77
0.835227
d56c23bc0fda481a8a11efa7c9bfc07956b07b9f
14,770
/* * Copyright 2011 Stefan C. Mueller. * * 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.smurn.jply.lwjgldemo; import org.smurn.jply.Element; import java.nio.FloatBuffer; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.apache.commons.io.IOUtils; import org.lwjgl.BufferUtils; import org.smurn.jply.PlyReader; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.ARBShaderObjects; import static org.lwjgl.opengl.ARBVertexBufferObject.*; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.Util; import org.smurn.jply.ElementReader; import org.smurn.jply.PlyReaderFile; import org.smurn.jply.util.NormalMode; import org.smurn.jply.util.NormalizingPlyReader; import org.smurn.jply.util.TesselationMode; import org.smurn.jply.util.TextureMode; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.ARBShaderObjects.*; import static org.lwjgl.opengl.ARBVertexShader.*; import static org.lwjgl.opengl.ARBFragmentShader.*; import org.lwjgl.input.Mouse; /** * jPLY Demo: jPLY viewer using JWJGL. * * This example is using state-of-the-art vertex-buffer-objects and * GLSL shaders instead of the immediate mode rendering often seen in * examples. This makes the code a bit more complicated but its the way * this things are done in real-world applications. * * The code doesn't perform proper error checking and will just fail if * run on a computer with an old graphics-card (or old drivers). This way * the code remains much more readable and simple. */ public class LWJGLDemo { public static void main(String[] args) throws LWJGLException, IOException { // Open a openGL enabled window. Display.setTitle("jPLY LWJGL Demo"); Display.setDisplayMode(new DisplayMode(600, 600)); Display.create(); // Open the PLY file PlyReader plyReader = new PlyReaderFile( ClassLoader.getSystemResourceAsStream("bunny.ply")); // Normalize the data in the PLY file to ensure that we only get // triangles and that the vertices have normal vectors assigned. plyReader = new NormalizingPlyReader(plyReader, TesselationMode.TRIANGLES, NormalMode.ADD_NORMALS_CCW, TextureMode.PASS_THROUGH); // We can get the number of vertices and triangles before // reading it. We will use this to allocate buffers of the right size. int vertexCount = plyReader.getElementCount("vertex"); int triangleCount = plyReader.getElementCount("face"); // Number of bytes we need per vertex. // Three position coordinates and three normal vector coordinates // all stored as 32-bit float. int vertexSize = 3 * 4 + 3 * 4; // Number of bytes we need per triangle. // Three indices to vertices stored as 32-bit integer. int triangleSize = 3 * 4; // A bit of opengl magic to allocate a vertex-buffer-object to // store the vertices. int vertexBufferId = glGenBuffersARB(); glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBufferId); glBufferDataARB(GL_ARRAY_BUFFER_ARB, vertexCount * vertexSize, GL_STATIC_DRAW_ARB); FloatBuffer vertexBuffer = glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB, null).asFloatBuffer(); // The same magic again for the index buffer storing the triangles. int indexBufferId = glGenBuffersARB(); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indexBufferId); glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, triangleCount * triangleSize, GL_STATIC_DRAW_ARB); IntBuffer indexBuffer = glMapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB, null).asIntBuffer(); // Now we READ THE PLY DATA into the buffers. // We also measure the size of the model so that we can later fit // arbitrary models into the screen. RectBounds bounds = fillBuffers(plyReader, vertexBuffer, indexBuffer); // Tell openGL that we filled the buffers. glUnmapBufferARB(GL_ARRAY_BUFFER_ARB); glUnmapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB); // Create the vertex and fragment shader for nice phong shading. int programId = createShaders(); // The shaders have a few parameters to configure the three lights. // Each parameter has an identifier which we query here. // Vector in the direction towards the light. int[] lightDirection = new int[]{ glGetUniformLocationARB(programId, "lightDir[0]"), glGetUniformLocationARB(programId, "lightDir[1]"), glGetUniformLocationARB(programId, "lightDir[2]") }; // Color of the diffuse part of the light. int[] diffuseColor = new int[]{ glGetUniformLocationARB(programId, "diffuseColor[0]"), glGetUniformLocationARB(programId, "diffuseColor[1]"), glGetUniformLocationARB(programId, "diffuseColor[2]") }; // Color of the specular (high-lights) part of the light. int[] specularColor = new int[]{ glGetUniformLocationARB(programId, "specularColor[0]"), glGetUniformLocationARB(programId, "specularColor[1]"), glGetUniformLocationARB(programId, "specularColor[2]") }; // Exponent controlling the size of the specular light. int[] shininess = new int[]{ glGetUniformLocationARB(programId, "shininess[0]"), glGetUniformLocationARB(programId, "shininess[1]"), glGetUniformLocationARB(programId, "shininess[2]") }; // Configure the three light sources. glUseProgramObjectARB(programId); glUniform3fARB(lightDirection[0], -0.9f, 0.9f, 1f); glUniform4fARB(diffuseColor[0], 0.7f, 0.7f, 0.7f, 1.0f); glUniform4fARB(specularColor[0], 1.0f, 1.0f, 1.0f, 1.0f); glUniform1fARB(shininess[0], 50.0f); glUniform3fARB(lightDirection[1], 0.6f, 0.1f, 1f); glUniform4fARB(diffuseColor[1], 0.1f, 0.1f, 0.1f, 1.0f); glUniform4fARB(specularColor[1], 0.0f, 0.0f, 0.0f, 1.0f); glUniform1fARB(shininess[1], 50.0f); glUniform3fARB(lightDirection[2], 0.0f, 0.8f, -1f); glUniform4fARB(diffuseColor[2], 0.8f, 0.8f, 0.8f, 1.0f); glUniform4fARB(specularColor[2], 0.0f, 0.0f, 0.0f, 1.0f); glUniform1fARB(shininess[2], 50.0f); // Some more openGL setup. glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1, 1, -1, 1, -100, 100); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); // Tell openGL to use the buffers we filled with the data from // the PLY file. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indexBufferId); glVertexPointer(3, GL11.GL_FLOAT, 24, 0); glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBufferId); glNormalPointer(GL11.GL_FLOAT, 24, 12); // Find out to where we need to move the object and how we need // to scale it such that it fits into the window. double scale = bounds.getScaleToUnityBox() * 1.5; double[] center = bounds.getCenter(); // Some state variables to let the model rotate via mouse double yawStart = 0; double pitchStart = 0; boolean mouseMoves = false; int mouseStartX = 0; int mouseStartY = 0; // See if we've run into a problem so far. Util.checkGLError(); // Rendering loop until the window is clsoed. while (!Display.isCloseRequested()) { // Empty the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Mouse handling for the model rotation double yaw = yawStart; double pitch = pitchStart; if (mouseMoves) { double deltaX = Mouse.getX() - mouseStartX; double deltaY = Mouse.getY() - mouseStartY; double deltaYaw = deltaX * 0.3; double deltaPitch = -deltaY * 0.3; yaw += deltaYaw; pitch += deltaPitch; if (!Mouse.isButtonDown(0)) { mouseMoves = false; yawStart += deltaYaw; pitchStart += deltaPitch; } } else if (!mouseMoves && Mouse.isButtonDown(0)) { mouseStartX = Mouse.getX(); mouseStartY = Mouse.getY(); mouseMoves = true; } // Build the model matrix that fits the model into the // screen and does the rotation. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotated(pitch, 1, 0, 0); glRotated(yaw, 0, 1, 0); glScaled(scale, scale, scale); glTranslated(-center[0], -center[1], -center[2]); // Finally we can draw the model! glDrawElements(GL_TRIANGLES, triangleCount * 3, GL_UNSIGNED_INT, 0); // See if we've run into a problem. Util.checkGLError(); // Lets show what we just have drawn. Display.update(); } // Cleanup opengl. Display.destroy(); } /** * Loads the data from the PLY file into the buffers. */ private static RectBounds fillBuffers( PlyReader plyReader, FloatBuffer vertexBuffer, IntBuffer indexBuffer) throws IOException { // Get all element readers and find the two providing // the vertices and triangles. ElementReader reader = plyReader.nextElementReader(); RectBounds bounds = null; while (reader != null) { if (reader.getElementType().getName().equals("vertex")) { bounds = fillVertexBuffer(reader, vertexBuffer); } else if (reader.getElementType().getName().equals("face")) { fillIndexBuffer(reader, indexBuffer); } reader.close(); reader = plyReader.nextElementReader(); } return bounds; } /** * Fill the vertex buffer with the data from the PLY file. */ private static RectBounds fillVertexBuffer( ElementReader reader, FloatBuffer vertexBuffer) throws IOException { // Just go though the vertices and store the coordinates in the buffer. Element vertex = reader.readElement(); RectBounds bounds = new RectBounds(); while (vertex != null) { double x = vertex.getDouble("x"); double y = vertex.getDouble("y"); double z = vertex.getDouble("z"); double nx = vertex.getDouble("nx"); double ny = vertex.getDouble("ny"); double nz = vertex.getDouble("nz"); vertexBuffer.put((float) x); vertexBuffer.put((float) y); vertexBuffer.put((float) z); vertexBuffer.put((float) nx); vertexBuffer.put((float) ny); vertexBuffer.put((float) nz); bounds.addPoint(x, y, z); vertex = reader.readElement(); } return bounds; } /** * Fill the index buffer with the data from the PLY file. */ private static void fillIndexBuffer( ElementReader reader, IntBuffer indexBuffer) throws IOException { // Just go though the triangles and store the indices in the buffer. Element triangle = reader.readElement(); while (triangle != null) { int[] indices = triangle.getIntList("vertex_index"); for (int index : indices) { indexBuffer.put(index); } triangle = reader.readElement(); } } /** * Loads the vertex and fragment shader. */ private static int createShaders() throws IOException { // load and compile the vertex shader. String vertexShaderCode = IOUtils.toString( ClassLoader.getSystemResourceAsStream("vertexShader.glsl")); int vertexShaderId = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); glShaderSourceARB(vertexShaderId, vertexShaderCode); glCompileShaderARB(vertexShaderId); printLogInfo(vertexShaderId); // load and compile the fragment shader. String fragmentShaderCode = IOUtils.toString( ClassLoader.getSystemResourceAsStream("fragmentShader.glsl")); int fragmentShaderId = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); glShaderSourceARB(fragmentShaderId, fragmentShaderCode); glCompileShaderARB(fragmentShaderId); printLogInfo(fragmentShaderId); // combine the two into a program. int programId = ARBShaderObjects.glCreateProgramObjectARB(); glAttachObjectARB(programId, vertexShaderId); glAttachObjectARB(programId, fragmentShaderId); glValidateProgramARB(programId); glLinkProgramARB(programId); printLogInfo(programId); return programId; } /** * Helper to get the log messages from the shader compiler. */ private static boolean printLogInfo(int obj) { IntBuffer iVal = BufferUtils.createIntBuffer(1); ARBShaderObjects.glGetObjectParameterARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB, iVal); int length = iVal.get(); if (length > 1) { // We have some info we need to output. ByteBuffer infoLog = BufferUtils.createByteBuffer(length); iVal.flip(); ARBShaderObjects.glGetInfoLogARB(obj, iVal, infoLog); byte[] infoBytes = new byte[length]; infoLog.get(infoBytes); String out = new String(infoBytes); System.out.println("Info log:\n" + out); } else { return true; } return false; } }
39.281915
80
0.633378
49c84c829e67a57057024263f5faca75ba89ef96
962
package cz.polankam.pcrf.trafficgenerator.scenario.actions.impl.call; import cz.polankam.pcrf.trafficgenerator.scenario.ScenarioContext; import cz.polankam.pcrf.trafficgenerator.scenario.actions.ScenarioAction; import cz.polankam.pcrf.trafficgenerator.scenario.actions.impl.factory.RxRequestsFactory; import cz.polankam.pcrf.trafficgenerator.utils.DumpUtils; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.rx.events.RxSessionTermRequest; /** * Action which will send STR request to the Rx interface. */ public class RxStr_SendAction implements ScenarioAction { @Override public void perform(ScenarioContext context, AppRequestEvent request, AppAnswerEvent answer) throws Exception { RxSessionTermRequest req = RxRequestsFactory.createStr(context); context.getRxSession().sendSessionTermRequest(req); DumpUtils.dumpMessage(req.getMessage(), true); } }
40.083333
115
0.806653
4c01c1dda7890250c2d314911d0f11eb32b0e323
577
/* Programa: Subclasse de Clinete Objetivo: Adiciona os atributos "nome" e "cpf" Entrada: N/A Saída: N/A Autor: Artur Uhli Frohlich Data: 08/03/2022 */ package classes; public class ClientePF extends classes.Cliente { // Atributos private String nome; private String cpf; // Cpnstrutor public ClientePF(String dataCadastro, String nome, String cpf){ super(dataCadastro); this.nome = nome; this.cpf = cpf; } // Métodos public void imprimeDadosPF(){ System.out.print("Nome: "+nome+"\nCPF: "+cpf+"\n"); } }
19.896552
67
0.641248
3db27b64292c5029ac827ef29ba131b912800d12
5,494
/* * Copyright 2018 Paul Schaub. * * 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.pgpainless.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.junit.jupiter.api.Test; import org.pgpainless.PGPainless; import org.pgpainless.algorithm.KeyFlag; import org.pgpainless.key.generation.KeySpec; import org.pgpainless.key.generation.type.KeyType; import org.pgpainless.key.generation.type.rsa.RsaLength; import org.pgpainless.key.util.KeyRingUtils; public class BCUtilTest { private static final Logger LOGGER = Logger.getLogger(BCUtil.class.getName()); @Test public void keyRingToCollectionTest() throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException { PGPSecretKeyRing sec = PGPainless.generateKeyRing() .withSubKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)) .withKeyFlags(KeyFlag.ENCRYPT_COMMS) .withDefaultAlgorithms()) .withMasterKey(KeySpec.getBuilder(KeyType.RSA(RsaLength._3072)) .withKeyFlags(KeyFlag.CERTIFY_OTHER, KeyFlag.SIGN_DATA) .withDefaultAlgorithms()) .withPrimaryUserId("[email protected]").withoutPassphrase().build(); PGPPublicKeyRing pub = KeyRingUtils.publicKeyRingFrom(sec); LOGGER.log(Level.FINER, "Main ID: " + sec.getPublicKey().getKeyID() + " " + pub.getPublicKey().getKeyID()); int secSize = 1; Iterator<PGPPublicKey> secPubIt = sec.getPublicKeys(); while (secPubIt.hasNext()) { PGPPublicKey k = secPubIt.next(); LOGGER.log(Level.FINER, secSize + " " + k.getKeyID() + " " + k.isEncryptionKey() + " " + k.isMasterKey()); secSize++; } LOGGER.log(Level.FINER, "After BCUtil.publicKeyRingFromSecretKeyRing()"); int pubSize = 1; Iterator<PGPPublicKey> pubPubIt = pub.getPublicKeys(); while (pubPubIt.hasNext()) { PGPPublicKey k = pubPubIt.next(); LOGGER.log(Level.FINER, pubSize + " " + k.getKeyID() + " " + k.isEncryptionKey() + " " + k.isMasterKey()); pubSize++; } assertEquals(secSize, pubSize); PGPSecretKeyRingCollection secCol = BCUtil.keyRingsToKeyRingCollection(sec); int secColSize = 0; Iterator<PGPSecretKeyRing> secColIt = secCol.getKeyRings(); while (secColIt.hasNext()) { PGPSecretKeyRing r = secColIt.next(); LOGGER.log(Level.FINER, "" + r.getPublicKey().getKeyID()); secColSize++; } LOGGER.log(Level.FINER, "SecCol: " + secColSize); PGPPublicKeyRingCollection pubCol = BCUtil.keyRingsToKeyRingCollection(pub); int pubColSize = 0; Iterator<PGPPublicKeyRing> pubColIt = pubCol.getKeyRings(); while (pubColIt.hasNext()) { PGPPublicKeyRing r = pubColIt.next(); LOGGER.log(Level.FINER, "" + r.getPublicKey().getKeyID()); pubColSize++; } LOGGER.log(Level.FINER, "PubCol: " + pubColSize); } @Test public void removeUnsignedKeysTest() throws PGPException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { @SuppressWarnings("deprecation") PGPSecretKeyRing alice = PGPainless.generateKeyRing().simpleRsaKeyRing("[email protected]", RsaLength._1024); PGPSecretKeyRing mallory = PGPainless.generateKeyRing().simpleEcKeyRing("[email protected]"); PGPSecretKey subKey = null; Iterator<PGPSecretKey> sit = mallory.getSecretKeys(); while (sit.hasNext()) { PGPSecretKey s = sit.next(); if (!s.isMasterKey()) { subKey = s; break; } } assertNotNull(subKey); PGPSecretKeyRing alice_mallory = PGPSecretKeyRing.insertSecretKey(alice, subKey); // Check, if alice_mallory contains mallory's key assertNotNull(alice_mallory.getSecretKey(subKey.getKeyID())); PGPSecretKeyRing cleaned = BCUtil.removeUnassociatedKeysFromKeyRing(alice_mallory, alice.getPublicKey()); assertNull(cleaned.getSecretKey(subKey.getKeyID())); } }
40.10219
120
0.682381
bce19c6384d9e1ae45ef23b9cb6553fbfa334b8c
2,170
package group144.goldov; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; public final class SecondPartTasks { private SecondPartTasks() {} // Найти строки из переданных файлов, в которых встречается указанная подстрока. public static List<String> findQuotes(List<String> paths, CharSequence sequence) { return paths.stream().filter(s -> s.contains(sequence)).collect(Collectors.toList()); } // В квадрат с длиной стороны 1 вписана мишень. // Стрелок атакует мишень и каждый раз попадает в произвольную точку квадрата. // Надо промоделировать этот процесс с помощью класса java.util.Random и посчитать, какова вероятность попасть в мишень. public static double piDividedBy4() { class Point { private Random random = new Random(); private double x = random.nextDouble(); private double y = random.nextDouble(); public boolean isInDisk() { return x * x + y * y <= 1; } } int numberOfPoints = 999999; return (double) Stream.generate(Point::new).limit(numberOfPoints) .filter(Point::isInDisk).count() / numberOfPoints; } // Дано отображение из имени автора в список с содержанием его произведений. // Надо вычислить, чья общая длина произведений наибольшая. public static String findPrinter(Map<String, List<String>> compositions) { return compositions.entrySet().stream().max(Comparator.comparing(entry -> entry.getValue() .stream().mapToInt(String::length).sum())).get().getKey(); } // Вы крупный поставщик продуктов. Каждая торговая сеть делает вам заказ в виде Map<Товар, Количество>. // Необходимо вычислить, какой товар и в каком количестве надо поставить. public static Map<String, Integer> calculateGlobalOrder(List<Map<String, Integer>> orders) { return orders.stream().flatMap(map -> map.entrySet().stream()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::sum)); } }
42.54902
124
0.682488
ea1e45f7dec8caf4c89398afa36703088a157dce
1,386
package org.springframework.samples.petclinic.web; import java.time.LocalDate; import org.springframework.samples.petclinic.model.Booking; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; @Component public class BookingValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Booking.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { Booking booking = (Booking) obj; LocalDate checkIn= booking.getCheckIn(); LocalDate checkOut= booking.getCheckOut(); LocalDate fechaActual = LocalDate.now(); if (checkIn==null) { errors.rejectValue("checkIn", "Campo obligatorio", "Por favor, introduzca una fecha"); } else if(checkIn.isBefore(fechaActual)) { errors.rejectValue("checkIn", "La fecha de la reserva no puede ser anterior al día de hoy", "La fecha de la reserva no puede ser anterior al día de hoy"); } if (checkOut==null) { errors.rejectValue("checkOut", "Campo obligatorio", "Por favor, introduzca una fecha"); } else if(checkOut.isBefore(checkIn)) { errors.rejectValue("checkOut", "La fecha de fin de reserva no puede ser anterior al fecha de inicio", "La fecha de fin de reserva no puede ser anterior al fecha de inicio"); } } }
30.130435
106
0.735209
7d7c63e4af7f18fc6edbf8172bac9acb09a0396c
3,612
// Agenda | Dynamic Programming // Climb Stairs With Variable Jumps // Min Cost In Maze Traversal import java.io.*; import java.util.*; public class Main { public static int solve(int[] a, int src, int dest) { if (src == dest) return 1; int count = 0; for (int jump = 1; jump <= a[src] && src + jump <= dest; jump++) { count += solve(a, src + jump, dest); // new src = src + jump } return count; } public static int solveM(int[] a, int src, int dest, int[] dp) { if (src == dest) return dp[src] = 1; if (dp[src] != 0) return dp[src]; int count = 0; for (int jump = 1; jump <= a[src] && src + jump <= dest; jump++) { count += solveM(a, src + jump, dest, dp); } return dp[src] = count; } public static int solveT(int[] arr, int SRC, int dest, int[] dp) { for (int src = dp.length - 1; src >= SRC; src--) { if (src == dest) { dp[src] = 1; continue; } int count = 0; for (int jump = 1; jump <= arr[src] && jump + src <= dest; jump++) { count += dp[src + jump];// solveM(arr, src + jump, dest, dp); } dp[src] = count; } return dp[SRC]; } public static void main(String[] args) throws Exception { // Climb stairs with variable jumps // Recursive Solution // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int[] a = new int[n]; // for (int i = 0; i < n; i++) { // a[i] = sc.nextInt(); // } // int ans = solve(a, 0, n); // arr, src, dest // System.out.println(ans); // Memoize Solution // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int[] a = new int[n]; // for (int i = 0; i < n; i++) { // a[i] = sc.nextInt(); // } // int[] dp = new int[n + 1]; // int ans = solveM(a, 0, n, dp); // System.out.println(ans); // sc.close(); // Tabulation // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int[] a = new int[n]; // for (int i = 0; i < n; i++) { // a[i] = sc.nextInt(); // } // int[] dp = new int[n + 1]; // int ans = solveT(a, 0, n, dp); // System.out.println(ans); // sc.close(); // Min Cost In Maze Traversal (Tabulation) Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = sc.nextInt(); } } int[][] dp = new int[n][m]; for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { if (i == n - 1 && j == m - 1) { // single block dp[i][j] = a[i][j]; } else if (i == n - 1) { // last row dp[i][j] = a[i][j] + dp[i][j + 1]; } else if (j == m - 1) { // last column dp[i][j] = a[i][j] + dp[i + 1][j]; } else { // all other blocks dp[i][j] = Math.min(dp[i + 1][j], dp[i][j + 1]) + a[i][j]; } } } System.out.println(dp[0][0]); sc.close(); } }
30.610169
80
0.396456
029cfbe16e28247c0507e79065f65480b26d195e
997
package com.example.demo.cache.route.aspect; import org.springframework.context.expression.MethodBasedEvaluationContext; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.expression.EvaluationException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * 表达式取值上下文 */ class EvaluationContext extends MethodBasedEvaluationContext { private final List<String> unavailableVariables = new ArrayList(); EvaluationContext(Object rootObject, Method method, Object[] args, ParameterNameDiscoverer paramDiscoverer) { super(rootObject, method, args, paramDiscoverer); } public void addUnavailableVariable(String name) { this.unavailableVariables.add(name); } public Object lookupVariable(String name) { if(this.unavailableVariables.contains(name)) { throw new EvaluationException(name); } else { return super.lookupVariable(name); } } }
31.15625
113
0.74323
fb8f274c517581e7500d5a4d473bf262a7798df8
1,882
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.binding.value.support; import javax.swing.event.ListDataEvent; import org.easymock.IArgumentMatcher; /** * Custom ArgumentMatcher for EasyMock. * * @author Peter De Bruycker */ public class ListDataEventArgumentMatcher implements IArgumentMatcher { private ListDataEvent expected; public ListDataEventArgumentMatcher(ListDataEvent expected) { this.expected = expected; } public void appendTo(StringBuffer sb) { sb.append("javax.swing.event.ListDataEvent["); sb.append("type=").append(expected.getType()).append(", "); sb.append("index0=").append(expected.getIndex0()).append(", "); sb.append("index1=").append(expected.getIndex1()).append(", "); sb.append("]"); } public boolean matches(Object value) { if (!(value instanceof ListDataEvent)) { return false; } ListDataEvent actual = (ListDataEvent) value; boolean matches = true; matches = matches && actual.getSource().equals(expected.getSource()); matches = matches && actual.getType() == expected.getType(); matches = matches && actual.getIndex0() == expected.getIndex0(); matches = matches && actual.getIndex1() == expected.getIndex1(); return matches; } }
30.354839
81
0.700319
7fb02738d4357b88f69ecc202f13a4d6b26fc5c6
5,332
package block_party.client.skybox; import block_party.BlockParty; import block_party.client.ShrineLocation; import block_party.custom.CustomParticles; import block_party.custom.CustomTags; import block_party.db.BlockPartyDB; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import com.mojang.math.Matrix4f; import com.mojang.math.Vector3f; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import java.util.Optional; @Mod.EventBusSubscriber public class JapanRenderer { private static final ResourceLocation FUJI_TEXTURE = BlockParty.source("textures/fuji.png"); private static final int size = 288; private static int horizon = 0; private static float distance = Float.POSITIVE_INFINITY; private static float bearing = 0.0F; private static float r = 0.0F; private static float g = 0.0F; private static float b = 0.0F; private static float factor = 0.0F; @SubscribeEvent public static void fuji(RenderWorldLastEvent e) { PoseStack stack = e.getMatrixStack(); RenderSystem.enableTexture(); RenderSystem.enableBlend(); RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); stack.pushPose(); stack.mulPose(Vector3f.XP.rotationDegrees(-90.0F)); stack.mulPose(Vector3f.YP.rotationDegrees(180.0F)); stack.mulPose(Vector3f.ZP.rotationDegrees(bearing - 90.0F)); stack.translate(0, 0, -156); RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(r, g, b, factor); RenderSystem.setShaderTexture(0, FUJI_TEXTURE); Matrix4f matrix = stack.last().pose(); Tesselator tesselator = Tesselator.getInstance(); BufferBuilder buffer = tesselator.getBuilder(); buffer.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); buffer.vertex(matrix, -size / 2, horizon, -size / 2).uv(0.0F, 0.0F).endVertex(); buffer.vertex(matrix, size / 2, horizon, -size / 2).uv(1.0F, 0.0F).endVertex(); buffer.vertex(matrix, size / 2, horizon, size / 2).uv(1.0F, 1.0F).endVertex(); buffer.vertex(matrix, -size / 2, horizon, size / 2).uv(0.0F, 1.0F).endVertex(); tesselator.end(); stack.popPose(); } @SubscribeEvent public static void fireflies(TickEvent.PlayerTickEvent e) { Level level = e.player.level; if (level instanceof ServerLevel || factor < 0.8F) { return; } long time = level.getDayTime() % 24000; if (21500 < time || time < 12500) { return; } for (int generation = 0; generation < 3; ++generation) { float x = level.random.nextInt(128) - 64; float z = level.random.nextInt(128) - 64; for (int y = 0; y > e.player.getY() - 255; --y) { BlockPos pos = e.player.blockPosition().offset(x, y, z); if (level.getBlockState(pos).is(CustomTags.Blocks.FIREFLY_BLOCKS)) { level.addParticle(CustomParticles.FIREFLY.get(), pos.getX(), pos.getY(), pos.getZ(), bearing, distance, factor); break; } } } } @SubscribeEvent public static void fogData(EntityViewRenderEvent.FogColors e) { horizon = Minecraft.getInstance().options.renderDistance * 16; Optional<BlockPos> shrine = BlockPartyDB.ShrineLocation.get(player().blockPosition()); if (shrine.isPresent()) { BlockPos pos = shrine.get(); float x1 = player().getBlockX(); float x2 = pos.getX(); float x = x1 - x2; float z1 = player().getBlockZ(); float z2 = pos.getZ(); float z = z1 - z2; bearing = (float) (Math.atan2(z, x) * 180 / Math.PI); distance = Math.abs(x) + Math.abs(z); factor = (float) (-Math.sqrt(distance / 2048.0 - 0.03125) + 1.0); if (distance < 64) { factor = 1.0F; } if (distance > 2048) { factor = 0; } } else { distance = Float.POSITIVE_INFINITY; factor = 0; } e.setRed(r = ((0.95F - e.getRed()) * factor * 0.5F + e.getRed())); e.setGreen(g = ((0.36F - e.getGreen()) * factor * 0.5F + e.getGreen())); e.setBlue(b = ((0.38F - e.getBlue()) * factor * 0.5F + e.getBlue())); } private static LocalPlayer player() { return Minecraft.getInstance().player; } }
44.066116
205
0.634846
18afe0f86e6379155fe808881bbbe2ae21b8fd62
8,559
/* * Fatture in Cloud API v2 - API Reference * Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. * * The version of the OpenAPI document: 2.0.11 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package it.fattureincloud.sdk.model; import com.google.gson.Gson; import it.fattureincloud.sdk.JSON; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; /** * Model tests for ReceivedDocumentTotals */ public class ReceivedDocumentTotalsTest { private ReceivedDocumentTotals model; @BeforeEach public void init() { model = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); } /** * Model tests for ReceivedDocumentTotals */ @Test public void testReceivedDocumentTotals() { JSON jsonManager = new JSON(); Gson gson = jsonManager.getGson(); String json = gson.toJson(model); String str = "{\"amount_net\":10,\"amount_vat\":10,\"amount_gross\":10,\"amount_withholding_tax\":10,\"amount_other_withholding_tax\":10,\"amount_due\":10,\"payments_sum\":10}"; assertEquals(str, json); ReceivedDocumentTotals generated = gson.fromJson(str, ReceivedDocumentTotals.class); assertEquals(model, generated); Object o = model; assertEquals(model, o); assertFalse(model.equals(null)); assertFalse(model.equals(Integer.getInteger("5"))); } /** * Test the property 'amountNet' */ @Test public void amountNetTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountNet()); model.setAmountNet(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountNet()); ReceivedDocumentTotals i = model.amountNet(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'amountVat' */ @Test public void amountVatTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountVat()); model.setAmountVat(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountVat()); ReceivedDocumentTotals i = model.amountVat(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'amountGross' */ @Test public void amountGrossTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountGross()); model.setAmountGross(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountGross()); ReceivedDocumentTotals i = model.amountGross(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'amountWithholdingTax' */ @Test public void amountWithholdingTaxTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountWithholdingTax()); model.setAmountWithholdingTax(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountWithholdingTax()); ReceivedDocumentTotals i = model.amountWithholdingTax(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'amountOtherWithholdingTax' */ @Test public void amountOtherWithholdingTaxTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountOtherWithholdingTax()); model.setAmountOtherWithholdingTax(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountOtherWithholdingTax()); ReceivedDocumentTotals i = model.amountOtherWithholdingTax(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'amountDue' */ @Test public void amountDueTest() { assertEquals(BigDecimal.valueOf(10), model.getAmountDue()); model.setAmountDue(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getAmountDue()); ReceivedDocumentTotals i = model.amountDue(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } /** * Test the property 'paymentsSum' */ @Test public void paymentsSumTest() { assertEquals(BigDecimal.valueOf(10), model.getPaymentsSum()); model.setPaymentsSum(BigDecimal.valueOf(100)); assertEquals(BigDecimal.valueOf(100), model.getPaymentsSum()); ReceivedDocumentTotals i = model.paymentsSum(BigDecimal.valueOf(10)); ReceivedDocumentTotals expected = new ReceivedDocumentTotals() .amountNet(BigDecimal.valueOf(10)) .amountVat(BigDecimal.valueOf(10)) .amountGross(BigDecimal.valueOf(10)) .amountWithholdingTax(BigDecimal.valueOf(10)) .amountOtherWithholdingTax(BigDecimal.valueOf(10)) .amountDue((BigDecimal.valueOf(10))) .paymentsSum((BigDecimal.valueOf(10))); assertEquals(expected, i); } }
40.372642
263
0.650426
1c394531d4a4ef0b34caeadb5796b73c9a7976d8
4,445
//package uk.ac.ebi.atlas.experimentimport.admin; // //import com.google.common.base.Joiner; //import com.google.common.collect.ImmutableList; //import com.google.gson.Gson; //import com.google.gson.JsonArray; //import com.google.gson.JsonObject; //import org.junit.After; //import org.junit.Ignore; //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.mock.web.MockHttpServletResponse; //import org.springframework.test.context.ContextConfiguration; //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //import org.springframework.test.context.web.WebAppConfiguration; //import uk.ac.ebi.atlas.experimentimport.ExperimentCrudIT; // //import javax.inject.Inject; // //import java.io.IOException; // //import static org.hamcrest.Matchers.is; //import static org.hamcrest.Matchers.not; //import static org.junit.Assert.assertThat; // //@WebAppConfiguration //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(classes = TestConfig.class) //public class ExpressionAtlasExperimentAdminControllerIT { // // @Inject // private ExpressionAtlasExperimentAdminController subject; // // private static final String ACCESSION = ExperimentCrudIT.RNASEQ_BASELINE_ACCESSION; // // @After // public void tryCleanUp() throws IOException { // subject.doOp(ACCESSION, Op.CLEAR_LOG.name(), new MockHttpServletResponse()); // subject.doOp(ACCESSION, Op.DELETE.name(), new MockHttpServletResponse()); // subject.doOp(ACCESSION, Op.CLEAR_LOG.name(), new MockHttpServletResponse()); // } // // @Ignore // public void ourScenario() throws IOException { // MockHttpServletResponse response; // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Op.CACHE_READ.name(), response); // isError( // "Before import cache read should report not found", // response.getContentAsString() // ); // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Joiner.on(",").join(ImmutableList.copyOf(Op.opsForParameter("LOAD"))), response); // isOk( // "Load is fine", // response.getContentAsString() // ); // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Op.CACHE_READ.name(), response); // isOk( // "Cache read after load is fine", // response.getContentAsString() // ); // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Op.DELETE.name(), response); // isOk( // "Delete is fine", // response.getContentAsString() // ); // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Op.CACHE_READ.name(), response); // isError( // "After delete cache read should report not found", // response.getContentAsString() // ); // // response = new MockHttpServletResponse(); // subject.doOp(ACCESSION, Op.CLEAR_LOG.name(), response); // isOk( // "Clear log is fine", // response.getContentAsString() // ); // // } // // private void isOk(String messageAboutWhatIsExpected, String result) { // isOk( // messageAboutWhatIsExpected+", was: " + result , // new Gson().fromJson(result, JsonArray.class).get(0).getAsJsonObject()); // } // // private void isError(String messageAboutWhatIsExpected, String result) { // isError( // messageAboutWhatIsExpected+", was: " + result , // new Gson().fromJson(result, JsonArray.class).get(0).getAsJsonObject()); // } // // private void isOk(String message, JsonObject object) { // assertAboutResponseObject(message, object, true); // } // // private void isError(String message, JsonObject object) { // assertAboutResponseObject(message, object, false); // } // // private void assertAboutResponseObject(String message, JsonObject object, boolean expectedSuccessful) { // assertThat( // message, // object.has("result"), // is(expectedSuccessful) // ); // assertThat( // message, // object.has("error"), // is(not(expectedSuccessful)) // ); // } // //}
35.56
115
0.628346