blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
e6c82a686df07c97722a329c92d3ef0d1f6dae3a
a105a4e329b9c9c9b38d259e0b7a510de2191a72
/challenge_1/src/com/company/DebitCard.java
c7f028c4f8594edf671e8c75fea8766691577c1e
[]
no_license
OscarHernandez375/Challenge1
cfb0c9b7de190e76b05534be0f5d374d4b89d2b9
8f6d0ec5df2452f38ef318a6677228bbdb0a3a1f
refs/heads/master
2020-03-24T01:30:21.878931
2018-07-25T19:57:26
2018-07-25T19:57:26
142,305,158
0
0
null
null
null
null
UTF-8
Java
false
false
886
java
package com.company; import java.util.Date; public class DebitCard extends PaymentMethod{ private double number; private Date expDate; private Issuer issuer; public void authorize(){ System.out.println("Debit card Authorized"); } public DebitCard(double number, Date expDate, Issuer issuer) { this.number = number; this.expDate = expDate; this.issuer = issuer; } //setters public void setNumber(double number) { this.number = number; } public void setExpDate(Date expDate) { this.expDate = expDate; } public void setIssuer(Issuer issuer) { this.issuer = issuer; } //getters public double getNumber() { return number; } public Date getExpDate() { return expDate; } public Issuer getIssuer() { return issuer; } }
[ "Oscar.Hernandez@endava.com" ]
Oscar.Hernandez@endava.com
e08836307daf4509459ce878be394b96b5467ddc
8cd8c2c5d76611436dc9ecd1fb70e318d0ec914e
/src/main/java/ma/emsi/cinema/services/ICinemaInitService.java
203773a1432fa50bca672f863b8a1d63995f4669
[]
no_license
MERZAK-X/CinemaSpringAngularDemo
b4c8305bf3e95731091906d0eb0cef4f9357ca83
37b1b2839f3ee0d10ba86e0e5af3bf959c01ae7b
refs/heads/master
2023-06-16T12:38:12.591672
2021-07-10T17:30:07
2021-07-10T17:30:07
370,165,498
0
0
null
null
null
null
UTF-8
Java
false
false
265
java
package ma.emsi.cinema.services; public interface ICinemaInitService { void initVilles(); void initCinema(); void initSalles(); void initPlaces(); void initSeances(); void initFilms(); void initCategories(); void initProjections(); void initTickets(); }
[ "MERZAK_MOHAMED@emsi-edu.ma" ]
MERZAK_MOHAMED@emsi-edu.ma
e5391a5dd1efacd85ebaa23e7f64409a6d0f1f6d
66de872ffe864373ec1b669bd3e15e7b0d12a537
/instacapture/src/main/java/com/tarek360/instacapture/screenshot/ScreenshotTaker.java
3034b586acb246dcab7fd2c720b4b354075b576c
[ "Apache-2.0" ]
permissive
anasanasanas/InstaCapture
a6914cb5eb8ed84620c44040e847c0c8c8578757
5408c75671387fe1d6b89d515af9e5b6b4a2b25f
refs/heads/develop
2021-01-12T05:39:51.314179
2016-10-15T07:18:20
2016-10-15T07:18:20
77,161,408
1
0
null
2016-12-22T16:55:05
2016-12-22T16:55:05
null
UTF-8
Java
false
false
7,204
java
package com.tarek360.instacapture.screenshot; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.os.Build; import android.support.annotation.RequiresApi; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import com.tarek360.instacapture.exception.ScreenCapturingFailedException; import com.tarek360.instacapture.utility.Logger; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.opengles.GL10; /** * Created by tarek on 5/17/16. */ public final class ScreenshotTaker { private ScreenshotTaker() { } /** * Capture screenshot for the current activity and return bitmap of it. * * @param activity current activity. * @param ignoredViews from the screenshot. * @return Bitmap of screenshot. * @throws ScreenCapturingFailedException if unexpected error is occurred during capturing * screenshot */ public static Bitmap getScreenshotBitmap(Activity activity, View[] ignoredViews) { if (activity == null) { throw new IllegalArgumentException("Parameter activity cannot be null."); } final List<RootViewInfo> viewRoots = FieldHelper.getRootViews(activity); Logger.d("viewRoots count: " + viewRoots.size()); View main = activity.getWindow().getDecorView(); final Bitmap bitmap; try { bitmap = Bitmap.createBitmap(main.getWidth(), main.getHeight(), Bitmap.Config.ARGB_8888); } catch (final IllegalArgumentException e) { return null; } drawRootsToBitmap(viewRoots, bitmap, ignoredViews); return bitmap; } //static int count = 0 ; private static void drawRootsToBitmap(List<RootViewInfo> viewRoots, Bitmap bitmap, View[] ignoredViews) { //count = 0; for (RootViewInfo rootData : viewRoots) { drawRootToBitmap(rootData, bitmap, ignoredViews); } } private static void drawRootToBitmap(final RootViewInfo rootViewInfo, Bitmap bitmap, View[] ignoredViews) { // support dim screen if ((rootViewInfo.getLayoutParams().flags & WindowManager.LayoutParams.FLAG_DIM_BEHIND) == WindowManager.LayoutParams.FLAG_DIM_BEHIND) { Canvas dimCanvas = new Canvas(bitmap); int alpha = (int) (255 * rootViewInfo.getLayoutParams().dimAmount); dimCanvas.drawARGB(alpha, 0, 0, 0); } final Canvas canvas = new Canvas(bitmap); canvas.translate(rootViewInfo.getLeft(), rootViewInfo.getTop()); int[] ignoredViewsVisibility = null; if (ignoredViews != null) { ignoredViewsVisibility = new int[ignoredViews.length]; } if (ignoredViews != null) { for (int i = 0; i < ignoredViews.length; i++) { if (ignoredViews[i] != null) { ignoredViewsVisibility[i] = ignoredViews[i].getVisibility(); ignoredViews[i].setVisibility(View.INVISIBLE); } } } rootViewInfo.getView().draw(canvas); //Draw undrawable views drawUnDrawableViews(rootViewInfo.getView(), canvas); if (ignoredViews != null) { for (int i = 0; i < ignoredViews.length; i++) { if (ignoredViews[i] != null) { ignoredViews[i].setVisibility(ignoredViewsVisibility[i]); } } } } private static ArrayList<View> drawUnDrawableViews(View v, Canvas canvas) { if (!(v instanceof ViewGroup)) { ArrayList<View> viewArrayList = new ArrayList<>(); viewArrayList.add(v); return viewArrayList; } ArrayList<View> result = new ArrayList<>(); ViewGroup viewGroup = (ViewGroup) v; for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); ArrayList<View> viewArrayList = new ArrayList<>(); viewArrayList.add(v); viewArrayList.addAll(drawUnDrawableViews(child, canvas)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && child instanceof TextureView) { drawTextureView((TextureView) child, canvas); } if (child instanceof GLSurfaceView) { drawGLSurfaceView((GLSurfaceView) child, canvas); } result.addAll(viewArrayList); } return result; } private static void drawGLSurfaceView(GLSurfaceView surfaceView, Canvas canvas) { Logger.d("Drawing GLSurfaceView"); if (surfaceView.getWindowToken() != null) { int[] location = new int[2]; surfaceView.getLocationOnScreen(location); final int width = surfaceView.getWidth(); final int height = surfaceView.getHeight(); final int x = 0; final int y = 0; int[] b = new int[width * (y + height)]; final IntBuffer ib = IntBuffer.wrap(b); ib.position(0); //To wait for the async call to finish before going forward final CountDownLatch countDownLatch = new CountDownLatch(1); surfaceView.queueEvent(new Runnable() { @Override public void run() { EGL10 egl = (EGL10) EGLContext.getEGL(); egl.eglWaitGL(); GL10 gl = (GL10) egl.eglGetCurrentContext().getGL(); gl.glFinish(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } gl.glReadPixels(x, 0, width, y + height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, ib); countDownLatch.countDown(); } }); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } int[] bt = new int[width * height]; int i = 0; for (int k = 0; i < height; k++) { for (int j = 0; j < width; j++) { int pix = b[(i * width + j)]; int pb = pix >> 16 & 0xFF; int pr = pix << 16 & 0xFF0000; int pix1 = pix & 0xFF00FF00 | pr | pb; bt[((height - k - 1) * width + j)] = pix1; } i++; } Bitmap sb = Bitmap.createBitmap(bt, width, height, Bitmap.Config.ARGB_8888); Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP)); canvas.drawBitmap(sb, location[0], location[1], paint); sb.recycle(); } } @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) private static void drawTextureView(TextureView textureView, Canvas canvas) { Logger.d("Drawing TextureView"); int[] textureViewLocation = new int[2]; textureView.getLocationOnScreen(textureViewLocation); Bitmap textureViewBitmap = textureView.getBitmap(); if (textureViewBitmap != null) { Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP)); canvas.drawBitmap(textureViewBitmap, textureViewLocation[0], textureViewLocation[1], paint); textureViewBitmap.recycle(); } } }
[ "ahmed.tarek@code95.com" ]
ahmed.tarek@code95.com
66003bc6537e5c8d5bfb216082dba5828df2c6d4
34c2eeed18d55d9dc33a378f22e7bad119549cdf
/src/xonix/Model/IMovable.java
b3c756d9cfd91fc31c05a885fefe0a9c439c54ff
[]
no_license
RuurdBijlsma/Xonix
9df7ca5d3b732b4e624ba1255ac24574f25354db
099dd699d1a3a3c9a93392102d8689c43950eb93
refs/heads/master
2021-03-24T12:28:02.090113
2016-12-14T13:00:08
2016-12-14T13:00:08
74,698,407
0
0
null
null
null
null
UTF-8
Java
false
false
306
java
package xonix.Model; import java.awt.geom.Point2D; /** * Interface for any moveable objects */ public interface IMovable { int getWidth(); void setWidth(int width); int getHeight(); void setHeight(int height); Point2D getLocation(); void setLocation(Point2D.Float loc); }
[ "ruurdbijlsma@gmail.com" ]
ruurdbijlsma@gmail.com
5c112628ee44161c1e8684813b44256274c8d2c1
c9edd21bdf3e643fe182c5b0f480d7deb218737c
/dy-agent-log4j/dy-agent-log4j-core/src/main/java/com/hust/foolwc/dy/agent/log4j/core/layout/MarkerPatternSelector.java
2ee1d568ba2e316cea267f4b6e0e3eb03265a2de
[]
no_license
foolwc/dy-agent
f302d2966cf3ab9fe8ce6872963828a66ca8a34e
d7eca9df2fd8c4c4595a7cdc770d6330e7ab241c
refs/heads/master
2022-11-22T00:13:52.434723
2022-02-18T09:39:15
2022-02-18T09:39:15
201,186,332
10
4
null
2022-11-16T02:45:38
2019-08-08T05:44:02
Java
UTF-8
Java
false
false
9,123
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package com.hust.foolwc.dy.agent.log4j.core.layout; import com.hust.foolwc.dy.agent.log4j.Logger; import com.hust.foolwc.dy.agent.log4j.Marker; import com.hust.foolwc.dy.agent.log4j.core.LogEvent; import com.hust.foolwc.dy.agent.log4j.core.config.Configuration; import com.hust.foolwc.dy.agent.log4j.core.config.Node; import com.hust.foolwc.dy.agent.log4j.core.config.plugins.Plugin; import com.hust.foolwc.dy.agent.log4j.core.config.plugins.PluginBuilderAttribute; import com.hust.foolwc.dy.agent.log4j.core.config.plugins.PluginBuilderFactory; import com.hust.foolwc.dy.agent.log4j.core.config.plugins.PluginConfiguration; import com.hust.foolwc.dy.agent.log4j.core.config.plugins.PluginElement; import com.hust.foolwc.dy.agent.log4j.core.pattern.PatternFormatter; import com.hust.foolwc.dy.agent.log4j.core.pattern.PatternParser; import com.hust.foolwc.dy.agent.log4j.status.StatusLogger; import java.util.HashMap; import java.util.List; import java.util.Map; import com.hust.foolwc.dy.agent.log4j.Logger; import com.hust.foolwc.dy.agent.log4j.Marker; import com.hust.foolwc.dy.agent.log4j.core.pattern.PatternFormatter; import com.hust.foolwc.dy.agent.log4j.core.pattern.PatternParser; /** * Selects the pattern to use based on the Marker in the LogEvent. */ @Plugin(name = "MarkerPatternSelector", category = Node.CATEGORY, elementType = PatternSelector.ELEMENT_TYPE, printObject = true) public class MarkerPatternSelector implements PatternSelector { /** * Custom MarkerPatternSelector builder. Use the {@link MarkerPatternSelector#newBuilder() builder factory method} to create this. */ public static class Builder implements com.hust.foolwc.dy.agent.log4j.core.util.Builder<MarkerPatternSelector> { @PluginElement("PatternMatch") private PatternMatch[] properties; @PluginBuilderAttribute("defaultPattern") private String defaultPattern; @PluginBuilderAttribute(value = "alwaysWriteExceptions") private boolean alwaysWriteExceptions = true; @PluginBuilderAttribute(value = "disableAnsi") private boolean disableAnsi; @PluginBuilderAttribute(value = "noConsoleNoAnsi") private boolean noConsoleNoAnsi; @PluginConfiguration private Configuration configuration; @Override public MarkerPatternSelector build() { if (defaultPattern == null) { defaultPattern = PatternLayout.DEFAULT_CONVERSION_PATTERN; } if (properties == null || properties.length == 0) { LOGGER.warn("No marker patterns were provided with PatternMatch"); return null; } return new MarkerPatternSelector(properties, defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi, configuration); } public Builder setProperties(final PatternMatch[] properties) { this.properties = properties; return this; } public Builder setDefaultPattern(final String defaultPattern) { this.defaultPattern = defaultPattern; return this; } public Builder setAlwaysWriteExceptions(final boolean alwaysWriteExceptions) { this.alwaysWriteExceptions = alwaysWriteExceptions; return this; } public Builder setDisableAnsi(final boolean disableAnsi) { this.disableAnsi = disableAnsi; return this; } public Builder setNoConsoleNoAnsi(final boolean noConsoleNoAnsi) { this.noConsoleNoAnsi = noConsoleNoAnsi; return this; } public Builder setConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } } private final Map<String, PatternFormatter[]> formatterMap = new HashMap<>(); private final Map<String, String> patternMap = new HashMap<>(); private final PatternFormatter[] defaultFormatters; private final String defaultPattern; private static Logger LOGGER = StatusLogger.getLogger(); /** * @deprecated Use {@link #newBuilder()} instead. This will be private in a future version. */ @Deprecated public MarkerPatternSelector(final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final Configuration config) { this(properties, defaultPattern, alwaysWriteExceptions, false, noConsoleNoAnsi, config); } private MarkerPatternSelector(final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean disableAnsi, final boolean noConsoleNoAnsi, final Configuration config) { final PatternParser parser = PatternLayout.createPatternParser(config); for (final PatternMatch property : properties) { try { final List<PatternFormatter> list = parser.parse(property.getPattern(), alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi); formatterMap.put(property.getKey(), list.toArray(new PatternFormatter[list.size()])); patternMap.put(property.getKey(), property.getPattern()); } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + property.getPattern() + "'", ex); } } try { final List<PatternFormatter> list = parser.parse(defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi); defaultFormatters = list.toArray(new PatternFormatter[list.size()]); this.defaultPattern = defaultPattern; } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + defaultPattern + "'", ex); } } @Override public PatternFormatter[] getFormatters(final LogEvent event) { final Marker marker = event.getMarker(); if (marker == null) { return defaultFormatters; } for (final String key : formatterMap.keySet()) { if (marker.isInstanceOf(key)) { return formatterMap.get(key); } } return defaultFormatters; } /** * Creates a builder for a custom ScriptPatternSelector. * * @return a ScriptPatternSelector builder. */ @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } /** * Deprecated, use {@link #newBuilder()} instead. * @param properties * @param defaultPattern * @param alwaysWriteExceptions * @param noConsoleNoAnsi * @param configuration * @return a new MarkerPatternSelector. * @deprecated Use {@link #newBuilder()} instead. */ @Deprecated public static MarkerPatternSelector createSelector( final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final Configuration configuration) { final Builder builder = newBuilder(); builder.setProperties(properties); builder.setDefaultPattern(defaultPattern); builder.setAlwaysWriteExceptions(alwaysWriteExceptions); builder.setNoConsoleNoAnsi(noConsoleNoAnsi); builder.setConfiguration(configuration); return builder.build(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); boolean first = true; for (final Map.Entry<String, String> entry : patternMap.entrySet()) { if (!first) { sb.append(", "); } sb.append("key=\"").append(entry.getKey()).append("\", pattern=\"").append(entry.getValue()).append("\""); first = false; } if (!first) { sb.append(", "); } sb.append("default=\"").append(defaultPattern).append("\""); return sb.toString(); } }
[ "liwencheng@douyu.tv" ]
liwencheng@douyu.tv
20b612db47ed717f86214424c7aa938965e3abc0
82f716a8b888104c31bec1fdab535bdf2c2a62e5
/app/src/main/java/com/example/credit/Activitys/ObeyedActivity.java
a65fc4568bfe36da84a2db3e96a809559003a765
[]
no_license
RabbitMQF/Credit
2475995547724e3e1ca202b3752c53b1adfd50e8
0afa8613bd435775efadad13693e967992ecf6e3
refs/heads/master
2021-06-03T16:06:21.929583
2016-10-09T08:25:11
2016-10-09T08:25:11
282,768,219
1
0
null
2020-07-27T01:46:42
2020-07-27T01:46:41
null
UTF-8
Java
false
false
1,659
java
package com.example.credit.Activitys; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; import com.example.credit.Adapters.Obeyed_Adapter; import com.example.credit.Entitys.DataManager; import com.example.credit.R; import com.example.credit.Views.MyListView; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; /** *守合同重信用界面 */ public class ObeyedActivity extends BaseActivity { @ViewInject(R.id.b_return) LinearLayout b_return; @ViewInject(R.id.b_topname) TextView b_topname; @ViewInject(R.id.o_scs) ScrollView o_scs; @ViewInject(R.id.oListView1) MyListView oListView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_obeyed); ViewUtils.inject(this); o_scs.smoothScrollTo(0,20); Intent i=getIntent(); String Tname=i.getStringExtra("Tname"); b_topname.setText(Tname); b_return.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); overridePendingTransition(R.anim.finish_tran_one, R.anim.finish_tran_two); } }); Obeyed_Adapter adapter=new Obeyed_Adapter(ObeyedActivity.this, DataManager.obeyedInfoList); oListView1.setAdapter(adapter); } }
[ "936230422@qq.com" ]
936230422@qq.com
f8a05755363fed18cad4b589db54eb30b8f61ab7
ab5a734feba2d1471d77cca67b43b71bc928d95f
/Core/src/main/java/net/cogzmc/core/player/message/FClickAction.java
0c1ef41a384997d3495cfaef2704f348062a571e
[ "Apache-2.0" ]
permissive
TigerHix/Core
667a17a29be7ab146717644a78d30b00447339e8
925a08ac4b46e2e3eb02299fbef08265e228d861
refs/heads/master
2021-01-15T23:03:10.496337
2014-08-23T04:42:53
2014-08-23T04:42:53
23,252,675
2
0
null
null
null
null
UTF-8
Java
false
false
373
java
package net.cogzmc.core.player.message; import lombok.Data; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) @Data public final class FClickAction extends FAction { private final String value; private final FClickActionType clickActionType; @Override protected String getAction() { return clickActionType.toString(); } }
[ "joey.sacchini264@gmail.com" ]
joey.sacchini264@gmail.com
01580461392ea1756fac3140052d2d4fdd132c5e
f949c966cb83e439eca568c097739b1d5cdac753
/siri/siri_retriever/siri-0.1/src/main/java/eu/datex2/schema/_1_0/_1_0/EffectOnRoadLayoutEnum.java
af6eb29e80d8560c82752089f85331ecf5f95364
[]
no_license
hasadna/open-bus
d32bd55680b72ef75022e546e2c58413ae365703
1e972a43ca5141bf42f0662d2e21196fa8ff8438
refs/heads/master
2022-12-13T11:43:43.476402
2021-06-05T13:48:36
2021-06-05T13:48:36
62,209,334
95
44
null
2022-12-09T17:13:43
2016-06-29T08:29:01
Java
UTF-8
Java
false
false
3,523
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.11.14 at 03:28:36 PM PST // package eu.datex2.schema._1_0._1_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for EffectOnRoadLayoutEnum. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="EffectOnRoadLayoutEnum"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="carriagewayClosures"/> * &lt;enumeration value="contraflow"/> * &lt;enumeration value="laneClosures"/> * &lt;enumeration value="lanesDeviated"/> * &lt;enumeration value="narrowLanes"/> * &lt;enumeration value="newRoadworksLayout"/> * &lt;enumeration value="obstacleSignalling"/> * &lt;enumeration value="roadLayoutUnchanged"/> * &lt;enumeration value="temporaryTrafficLights"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "EffectOnRoadLayoutEnum") @XmlEnum public enum EffectOnRoadLayoutEnum { /** * Roadworks are resulting in carriageway closures at the specified location. * */ @XmlEnumValue("carriagewayClosures") CARRIAGEWAY_CLOSURES("carriagewayClosures"), /** * Roadworks are resulting in contraflow of traffic at the specified location. * */ @XmlEnumValue("contraflow") CONTRAFLOW("contraflow"), /** * Roadworks are resulting in lane closures at the specified location. * */ @XmlEnumValue("laneClosures") LANE_CLOSURES("laneClosures"), /** * Roadworks are resulting in lane deviations at the specified location. * */ @XmlEnumValue("lanesDeviated") LANES_DEVIATED("lanesDeviated"), /** * Roadworks are resulting in narrow lanes at the specified location. * */ @XmlEnumValue("narrowLanes") NARROW_LANES("narrowLanes"), /** * A new layout of lanes/carriageway has been implemeted associated with the roadworks. * */ @XmlEnumValue("newRoadworksLayout") NEW_ROADWORKS_LAYOUT("newRoadworksLayout"), /** * Signs are being put out before or around an obstacle to protect drivers. * */ @XmlEnumValue("obstacleSignalling") OBSTACLE_SIGNALLING("obstacleSignalling"), /** * The existing road layout is unchanged during the period of roadworks. * */ @XmlEnumValue("roadLayoutUnchanged") ROAD_LAYOUT_UNCHANGED("roadLayoutUnchanged"), /** * Traffic is being controlled by temporary traffic lights (red-yellow-green or red-green). * */ @XmlEnumValue("temporaryTrafficLights") TEMPORARY_TRAFFIC_LIGHTS("temporaryTrafficLights"); private final String value; EffectOnRoadLayoutEnum(String v) { value = v; } public String value() { return value; } public static EffectOnRoadLayoutEnum fromValue(String v) { for (EffectOnRoadLayoutEnum c: EffectOnRoadLayoutEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
[ "evyatar@tikalk.com" ]
evyatar@tikalk.com
7670967d1b84c8d495b8bddaca746727d1c3b5a4
2aa88f635607185918204b546afc9f61f20db679
/test/gen/com/eastagile/android/test/R.java
6c7f06c8d18da469a5d1d81f8288592c0f9c1dd6
[]
no_license
tamtran/TrafficAlert
241a8b87bc133d9733a437c94587cec0331d36a6
9239171ac19d0895273fd1c0c8e6a0bbbac98039
refs/heads/master
2016-09-05T09:20:19.904000
2011-05-18T11:43:50
2011-05-18T11:43:50
1,754,496
0
0
null
null
null
null
UTF-8
Java
false
false
625
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.eastagile.android.test; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }
[ "tam.tran@eastagile.com" ]
tam.tran@eastagile.com
1f8282d144755e9a3be146383a1955063e54a885
f2a8df7197aa90fca07716d61366fb350b4db7fb
/src/main/java/motiflab/engine/data/NumericSequenceData.java
a33d77b755d9545b102e649ea04f6830b5386c6c
[]
no_license
kjetilkl/motiflab
cac62025f17d45b04d6b9b5bba91800a5431285d
9a2d45631c3d502dea0b7c7b5cb89f126e04df48
refs/heads/master
2022-07-18T11:05:00.281036
2020-06-10T09:35:50
2020-06-10T09:35:50
164,119,903
1
0
null
2022-06-29T17:18:54
2019-01-04T14:52:59
Java
UTF-8
Java
false
false
38,249
java
/* */ package motiflab.engine.data; import java.util.Arrays; import motiflab.engine.ExecutionError; /** * This class holds feature data for a single sequence from a specified * region in a genome. The type of data contained in these objects are "wiggle data" * that specify a different value for each position along the sequence. * * The data in this object is stored as an array of double values with one entry for each position in the sequence (direct orientation). * * @author kjetikl */ public class NumericSequenceData extends FeatureSequenceData implements Cloneable { private double[] numericdata; // The data should come from the direct strand so that numericdata[0] corresponds to the smaller genomic coordinate // the three values below should only be used to determine range for visualization purposes private double min=0; // these are only for local use. Query the parent to find dataset min/max/baseline values private double max=1; // these are only for local use. Query the parent to find dataset min/max/baseline values private double baseline=0; // these are only for local use. Query the parent to find dataset min/max/baseline values private static String typedescription="Numeric data"; /** * Constructs a new NumericSequenceData object from the supplied data * * @param sequenceName * @param geneName * @param chromosome * @param startPosition * @param endPosition * @param TSS * @param TES * @param orientation * @param sequencedata */ public NumericSequenceData(String sequenceName, String geneName, String chromosome, int startPosition, int endPosition, Integer TSS, Integer TES, int orientation, double[] numerictrack){ setSequenceName(sequenceName); setChromosome(chromosome); setRegionStart(startPosition); setRegionEnd(endPosition); // the geneName, TSS, TES and orientation attributes are no longer stored in FeatureSequenceData objects but only derived from Sequence objects. They are kept in the constructor for backwards compatibility this.numericdata=numerictrack; for (int i=0;i<numerictrack.length;i++) { if (numerictrack[i]>max) max=numerictrack[i]; if (numerictrack[i]<min) min=numerictrack[i]; } } /** * Constructs a new NumericSequenceData object from the supplied data * * @param sequenceName * @param chromosome * @param startPosition * @param endPosition * @param sequencedata */ public NumericSequenceData(String sequenceName, String chromosome, int startPosition, int endPosition, double[] numerictrack){ setSequenceName(sequenceName); setChromosome(chromosome); setRegionStart(startPosition); setRegionEnd(endPosition); this.numericdata=numerictrack; for (int i=0;i<numerictrack.length;i++) { if (numerictrack[i]>max) max=numerictrack[i]; if (numerictrack[i]<min) min=numerictrack[i]; } } /** * Constructs a new "empty" NumericSequenceData object * * @param sequenceName * @param geneName * @param chromosome * @param startPosition * @param endPosition * @param TSS * @param orientation */ public NumericSequenceData(String sequenceName, String geneName, String chromosome, int startPosition, int endPosition, Integer TSS, Integer TES, int orientation, double defaultvalue){ setSequenceName(sequenceName); setChromosome(chromosome); setRegionStart(startPosition); setRegionEnd(endPosition); // the geneName,TSS,TES and orientation attributes are no longer stored in FeatureSequenceData objects but only derived from Sequence objects. They are kept in the constructor for backwards compatibility this.numericdata=new double[endPosition-startPosition+1]; setAllPositionsToValue(defaultvalue); //for (int i=0;i<numericdata.length;i++) numericdata[i]=(double)Math.random(); } /** * Creates a new initially "empty" NumericSequenceData object based on the given Sequence template * @param sequence */ public NumericSequenceData(Sequence sequence, double defaultvalue) { setSequenceName(sequence.getName()); setChromosome(sequence.getChromosome()); setRegionStart(sequence.getRegionStart()); setRegionEnd(sequence.getRegionEnd()); this.numericdata=new double[endPosition-startPosition+1]; setAllPositionsToValue(defaultvalue); } /** Resets the allowed min and max values based on the current data * the range will include the baseline. Note that the baseline value will always * be included in the returned range, so the two numbers might not necessarily reflect * the actual min and max values in the dataset * @return a double array with two components [0]=>min, [1]=>max */ public double[] updateAllowedMinMaxValuesFromDataRange() { min=getBaselineValue(); max=getBaselineValue(); for (int i=0;i<numericdata.length;i++) { if (numericdata[i]>max) max=numericdata[i]; if (numericdata[i]<min) min=numericdata[i]; } return new double[]{min,max}; } /** Returns min and max values based on the current data * @return a double array with two components [0]=>min, [1]=>max */ public double[] getMinMaxFromData() { double datamin=Double.MAX_VALUE; double datamax=-Double.MAX_VALUE; for (int i=0;i<numericdata.length;i++) { if (numericdata[i]>datamax) datamax=numericdata[i]; if (numericdata[i]<datamin) datamin=numericdata[i]; } return new double[]{datamin,datamax}; } /** Returns min and max values based on the current data within the range * given as relative positions. getMinMaxFromData() is equal to getMinMaxFromData(0,sequencelength-1) * @param fromPos * @param toPos * @return */ public double[] getMinMaxFromData(int fromPos, int toPos) { double datamin=Double.MAX_VALUE; double datamax=-Double.MAX_VALUE; for (int i=fromPos;i<=toPos;i++) { if (numericdata[i]>datamax) datamax=numericdata[i]; if (numericdata[i]<datamin) datamin=numericdata[i]; } return new double[]{datamin,datamax}; } public final void setAllPositionsToValue(double defaultvalue) { for (int i=0;i<numericdata.length;i++) numericdata[i]=defaultvalue; min=defaultvalue; max=defaultvalue; } @Override public Object getValue() {return numericdata;} @Override public Object getValueInGenomicInterval(int start, int end) { if (end<getRegionStart() || start>getRegionEnd() || end<start) return null; if (start<getRegionStart()) start=getRegionStart(); if (end>getRegionEnd()) end=getRegionEnd(); int length=end-start+1; int relativeStart=getRelativePositionFromGenomic(start); double[] subset=new double[end-start+1]; for (int i=0;i<length;i++) { subset[i]=numericdata[relativeStart+i]; } return subset; } /** * Returns the data value at the specified position relative to the * start of the sequence (if position==0 it returns the value of the first * position in the sequence.) If the position is outside the boundaries of the * sequence it returns null * * @return the data value at the specified position, or null */ @Override public Double getValueAtRelativePosition(int position) { if (position<0 || position>=numericdata.length) return null; else return new Double(numericdata[position]); } /** * Returns the DNA base at the specified genomic position. * If the position is outside the boundaries of the sequence it returns null. * @param chromosome * @param position * @return the DNA base at the specified position, or null */ @Override public Double getValueAtGenomicPosition(String chromosome, int position) { if (!chromosome.equalsIgnoreCase(this.chromosome)) return null; if (position<this.startPosition || position>this.endPosition) return null; return new Double(numericdata[position-this.startPosition]); } /** * Returns the DNA base at the specified genomic position for the chromosome of this gene. * If the position is outside the boundaries of the sequence it returns null. * @param position * @return the DNA base at the specified position, or null */ @Override public Double getValueAtGenomicPosition(int position) { if (position<this.startPosition || position>this.endPosition) return null; return new Double(numericdata[position-this.startPosition]); } /** * Sets a new value at the specified genomic position * @param position The genomic position * @param value The new value at this position * @return FALSE if position is outside bounds of sequence else true */ public boolean setValueAtGenomicPosition(int position, double value) { if (position<this.startPosition || position>this.endPosition) return false; numericdata[position-this.startPosition]=value; if (value>max) max=value; if (value<min) min=value; if (parent!=null) { if (max>((NumericDataset)parent).getMaxAllowedValue()) ((NumericDataset)parent).setMaxAllowedValue(max); if (min<((NumericDataset)parent).getMinAllowedValue()) ((NumericDataset)parent).setMinAllowedValue(min); } return true; } /** * Sets a new value at the specified genomic position * @param chrom the chromsome * @param position The genomic position * @param value The new value at this position * @return FALSE if position is outside bounds of sequence else true */ public boolean setValueAtGenomicPosition(String chrom, int position, double value) { if (chrom==null || chrom.equals(this.chromosome)) return false; if (position<this.startPosition || position>this.endPosition) return false; numericdata[position-this.startPosition]=value; if (value>max) max=value; if (value<min) min=value; if (parent!=null) { if (max>((NumericDataset)parent).getMaxAllowedValue()) ((NumericDataset)parent).setMaxAllowedValue(max); if (min<((NumericDataset)parent).getMinAllowedValue()) ((NumericDataset)parent).setMinAllowedValue(min); } return true; } /** * Sets a new value at the specified position relative to the start of the sequence * @param position The genomic position * @param value The new value at this position * @return FALSE if position is outside bounds of sequence else true */ public boolean setValueAtRelativePosition(int position, double value) { if (position<0 || position>=numericdata.length) return false; numericdata[position]=value; if (value>max) max=value; if (value<min) min=value; if (parent!=null) { if (max>((NumericDataset)parent).getMaxAllowedValue()) ((NumericDataset)parent).setMaxAllowedValue(max); if (min<((NumericDataset)parent).getMinAllowedValue()) ((NumericDataset)parent).setMinAllowedValue(min); } return true; } @Override public void setParent(FeatureDataset parent) { this.parent=parent; if (parent==null) return; if (max>((NumericDataset)parent).getMaxAllowedValue()) ((NumericDataset)parent).setMaxAllowedValue(max); if (min<((NumericDataset)parent).getMinAllowedValue()) ((NumericDataset)parent).setMinAllowedValue(min); } /** * Returns the maximum value allowed for this dataset * @return the maximum allowed value */ public Double getMaxAllowedValue() { if (parent==null) return max; else return ((NumericDataset)parent).getMaxAllowedValue(); } /** * Returns the minimum value allowed for this dataset * @return the minimum allowed value */ public Double getMinAllowedValue() { if (parent==null) return min; else return ((NumericDataset)parent).getMinAllowedValue(); } /** Returns the smallest value found in this sequence, or the baseline value (if this is smaller still) */ public double getMinValueFromThisSequence() { return min; } /** Returns the largest value found in this sequence, or the baseline value (if this is greater still) */ public double getMaxValueFromThisSequence() { return max; } /** Returns the baseline value from this sequence */ public double getBaselineValueFromThisSequence() { return baseline; } /** * Returns the baseline value for this dataset * @return the baseline value */ public Double getBaselineValue() { if (parent==null) return baseline; else return ((NumericDataset)parent).getBaselineValue(); } public void setData(double[] data) { // replaces the current array of values with the one provided numericdata=data; min=baseline; max=baseline; for (int i=0;i<numericdata.length;i++) { if (numericdata[i]>max) max=numericdata[i]; else if (numericdata[i]<min) min=numericdata[i]; } if (parent!=null) { if (max>((NumericDataset)parent).getMaxAllowedValue()) ((NumericDataset)parent).setMaxAllowedValue(max); if (min<((NumericDataset)parent).getMinAllowedValue()) ((NumericDataset)parent).setMinAllowedValue(min); } } public double[] getData() { return numericdata; } /** * Returns the smallest value in this Numeric sequence within the specified interval * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The minimum value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getMinValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double minval=Double.MAX_VALUE; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; for (int i=start;i<=end;i++) { if (numericdata[i]<minval) minval=numericdata[i]; } return minval; } /** * Returns the largest value in this Numeric sequence within the specified interval * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The maximum value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getMaxValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double maxval=-Double.MAX_VALUE; // Note: Double.MIN_VALUE is the smallest POSITIVE number! if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; for (int i=start;i<=end;i++) { if (numericdata[i]>maxval) maxval=numericdata[i]; } return maxval; } /** * Returns the value with largest magnitude in this Numeric sequence within the specified interval * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The most extreme value in the interval between start and end (inclusive), i.e. the value with largest absolute value * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getExtremeValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; // outside range double extreme=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; for (int i=start;i<=end;i+=1) { if (Math.abs(numericdata[i])>Math.abs(extreme)) extreme=numericdata[i]; } return extreme; } /** This method does the same as the getExtremeValueInInterval(start,end) method * except that when the size of the segment is larger than the cutoff, the value * will not be the extreme from all positions within the segment but rather the * extreme of a limited number of positions sampled at equal distances throughout * the interval * @param start * @param end * @param cutoff The size threshold above which sampling should be performed rather than including all positions * @param sample The number of positions to sample in the interval */ public Double getExtremeValueInInterval(int start, int end, int cutoff, int sample) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; // outside range double extreme=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; int step=(end-start<=cutoff)?1:(int)((end-start)/sample); // if (step<=0) step=1; for (int i=start;i<=end;i+=step) { if (Math.abs(numericdata[i])>Math.abs(extreme)) extreme=numericdata[i]; } return extreme; } public Double getCenterValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; // outside range if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; int centerPosition=start+(end-start)/2; return numericdata[centerPosition]; } /** * Returns the average value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The average value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getAverageValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double avg=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; double length=end-start+1; for (int i=start;i<=end;i++) { avg+=numericdata[i]; } avg=avg/length; // note that length can not be 0 since length=end-start+1 (and start is always smaller than end) return avg; } /** * This method does the same as the getAverageValueInInterval(start,end) method * except that when the size of the segment is larger than the cutoff, the value * will not be the average from all positions within the segment but rather the * average of a limited number of positions sampled at equal distances throughout * the interval * @param start * @param end * @param cutoff The size threshold above which sampling should be performed rather than including all positions * @param sample The number of positions to sample in the interval * @return */ public Double getAverageValueInInterval(int start, int end, int cutoff, int sample) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double avg=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; double length=0; int step=(end-start<=cutoff)?1:(int)((end-start)/sample); // if the segment is very long, sample only a few positions for efficiency if (step<=0) step=1; for (int i=start;i<=end;i+=step) { avg+=numericdata[i]; length++; } return (length>0)?(avg=avg/length):avg; } /** * Returns the sum of values within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The sum of the values in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getSumValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double sum=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; for (int i=start;i<=end;i++) { sum+=numericdata[i]; } return sum; } /** * Returns the product of values within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The product of the values in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getProductValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double product=1.0f; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; for (int i=start;i<=end;i++) { product*=numericdata[i]; } return product; } /** * Returns the median value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The median value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getMedianValueInInterval(int start, int end) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double median=0; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; int length=end-start+1; double[] buffer=new double[length]; int j=0; for (int i=start;i<=end;i++) { buffer[j]=numericdata[i]; j++; } Arrays.sort(buffer); if (length%2==0) { // even number of values. Note that the length can NOT be 0! int index=length/2; median=(buffer[index-1]+buffer[index])/2; } else { // odd number of values median=buffer[(int)length/2]; } return median; } /** * Returns the smallest weighted value in this Numeric sequence within the specified interval * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @param weights An array containing weights. The value in each position in the sequence (pos=start+i) will be weighted by the corresponding value in this array (at pos=i) * @return The weighted minimum value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedMinValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double minval=Double.MAX_VALUE; for (int i=0;i<weights.length;i++) { int pos=start+i; if (pos<0 || pos>=numericdata.length) continue; double weightedvalue=numericdata[pos]*weights[i]; if (weightedvalue<minval) minval=weightedvalue; } return minval; } /** * Returns the largest weighted value in this Numeric sequence within the specified interval * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @param weights An array containing weights. The value in each position in the sequence (pos=start+i) will be weighted by the corresponding value in this array (at pos=i) * @return The weighted maximum value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return NULL * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedMaxValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double maxval=-Double.MAX_VALUE; for (int i=0;i<weights.length;i++) { int pos=start+i; if (pos<0 || pos>=numericdata.length) continue; double weightedvalue=numericdata[pos]*weights[i]; if (weightedvalue>maxval) maxval=weightedvalue; } return maxval; } /** * Returns the weighted average value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @param weights An array containing weights. The value in each position in the sequence (pos=start+i) will be weighted by the corresponding value in this array (at pos=i) * @return The weighted average value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedAverageValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double sum=0; if (weights==null || weights.length!=(end-start+1)) return null; double weightssum=0; for (int i=0;i<weights.length;i++) weightssum+=weights[i]; if (weightssum==0) return sum; for (int i=0;i<weights.length;i++) { int pos=start+i; if (pos<0 || pos>=numericdata.length) continue; sum+=(numericdata[pos]*(weights[i]/weightssum)); // the weights are normalized here so they sum to 1 by diving by the sum } return sum; // } /** * Returns the weighted sum value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @param weights An array containing weights. The value in each position in the sequence (pos=start+i) will be weighted by the corresponding value in this array (at pos=i) * @return The weighted sum value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedSumValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double sum=0; if (weights==null || weights.length!=(end-start+1)) return null; for (int i=0;i<weights.length;i++) { int pos=start+i; if (pos<0 || pos>=numericdata.length) continue; sum+=(numericdata[pos]*weights[i]); } return sum; } /** * Returns the weighted product value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @param weights An array containing weights. The value in each position in the sequence (pos=start+i) will be weighted by the corresponding value in this array (at pos=i) * @return The weighted product value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedProductValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double product=1f; if (weights==null || weights.length!=(end-start+1)) return null; for (int i=0;i<weights.length;i++) { int pos=start+i; if (pos<0 || pos>=numericdata.length) continue; product*=(numericdata[pos]*weights[i]); } return product; } /** * Returns the median value within the specified interval in this Numeric sequence * @param start The start position of the interval (offset from beginning of sequence, i.e. relative position) * @param end The end position of the interval (offset from beginning of sequence, i.e. relative position) * @return The weighted median value in the interval between start and end (inclusive). * If the interval lies fully outside the defined sequence the function will return null * If the interval lies partially outside the defined sequence, only the covered region will be considered * */ public Double getWeightedMedianValueInInterval(int start, int end, double[] weights) { if (end<start) {int end2=end;end=start;start=end2;} // swap if (end<0 || start>numericdata.length-1) return null; double median=0; int seqstart=start; if (start<0) start=0; if (end>numericdata.length-1) end=numericdata.length-1; int length=end-start+1; double[] buffer=new double[length]; for (int i=0;i<=weights.length;i++) { int pos=seqstart+i; if (pos<0 || pos>=numericdata.length) continue; buffer[i]=(numericdata[pos]*weights[i]); } Arrays.sort(buffer); if (length%2==0) { // even number of values. Note that the length can NOT be 0! int index=length/2; median=(buffer[index-1]+buffer[index])/2; } else { // odd number of values median=buffer[(int)length/2]; } return median; } /** * Returns a deep copy of this NumericSequenceData object */ @Override public NumericSequenceData clone() { double[] newvalues=new double[numericdata.length]; System.arraycopy(numericdata, 0, newvalues, 0, numericdata.length); NumericSequenceData newdata=new NumericSequenceData(sequenceName, chromosome, startPosition, endPosition, newvalues); newdata.max=this.max; newdata.min=this.min; newdata.baseline=this.baseline; newdata.parent=this.parent; return newdata; } @Override public void importData(Data source) throws ClassCastException { super.importData(source); this.max=((NumericSequenceData)source).max; this.min=((NumericSequenceData)source).min; this.baseline=((NumericSequenceData)source).baseline; setData(((NumericSequenceData)source).numericdata); //notifyListenersOfDataUpdate(); } @Override public void cropTo(int relativeStart, int relativeEnd) throws ExecutionError { if (relativeStart<0 || relativeStart>=numericdata.length || relativeEnd<0 || relativeEnd>=numericdata.length || relativeEnd<relativeStart) throw new ExecutionError("Crop out of bounds"); if (relativeStart==0 && relativeEnd==numericdata.length-1) return; double[] newnumericdata=Arrays.copyOfRange(numericdata, relativeStart, relativeEnd+1); numericdata=newnumericdata; int oldstart=getRegionStart(); setRegionStart(oldstart+relativeStart); setRegionEnd(oldstart+relativeEnd); } public static String getType() {return typedescription;} @Override public String getDynamicType() { return typedescription; } @Override public String getTypeDescription() {return typedescription;} @Override public boolean containsSameData(Data other) { if (other==null || !(other instanceof NumericSequenceData)) return false; if (!super.containsSameData(other)) return false; if (this.max!=((NumericSequenceData)other).max) return false; if (this.min!=((NumericSequenceData)other).min) return false; if (this.baseline!=((NumericSequenceData)other).baseline) return false; return (Arrays.equals(this.numericdata,((NumericSequenceData)other).numericdata)); } /** Returns a hashcode based on the contents of the numeric sequence */ public int getDebugHashCode() { return Arrays.hashCode(numericdata); } /** Outputs information about this dataset into the buffer */ public StringBuilder debug(StringBuilder builder) { if (builder==null) builder=new StringBuilder(); builder.append(" - "+getName()+" : "+getRegionAsString()+", size="+getSize()+", buffersize="+((numericdata==null)?0:numericdata.length)+", dataDebugHashcode="+getDebugHashCode()+", ["+System.identityHashCode(this)+"]"); return builder; } // ------------ Serialization --------- private static final long serialVersionUID = 1L; private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { short currentinternalversion=1; // this is an internal version number for serialization of objects of this type out.writeShort(currentinternalversion); out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { short currentinternalversion=in.readShort(); // the internalversion number is used to determine correct format of data if (currentinternalversion==1) { in.defaultReadObject(); } else if (currentinternalversion>1) throw new ClassNotFoundException("Newer version"); } }
[ "kjetil.klepper@ntnu.no" ]
kjetil.klepper@ntnu.no
237379fdbac73706d2043a97c27e2406840087c8
da2bef708704762072e89a32702d9dea1f712a75
/src/part003线程间通信/part3_1等待通知机制/part3_1_11生产者消费者模式实现/一生产与多消费__操作栈_解决wait条件改变与假死/stack_2_old/P_Thread.java
c14c324b14c7c94fe5d4a0900200be78a502406b
[]
no_license
chenjie-sau/thread
b2681a90ded160e417d4bac4c38bea2e3508515f
cae756141440ca5c698aedff2d57491c8b1c1237
refs/heads/master
2022-12-01T15:52:08.681829
2020-08-14T07:58:35
2020-08-14T07:58:35
230,549,372
0
1
null
null
null
null
UTF-8
Java
false
false
454
java
package part003线程间通信.part3_1等待通知机制.part3_1_11生产者消费者模式实现.一生产与多消费__操作栈_解决wait条件改变与假死.stack_2_old; /** * Created by chenjie on 2020/2/16. */ public class P_Thread extends Thread { private P p; public P_Thread(P p){ super(); this.p = p; } @Override public void run() { while (true){ p.pushService(); } } }
[ "Emperor_CJ@126.com" ]
Emperor_CJ@126.com
7af761979207a13602feef5d78d9d2dc03aeb157
435d9ddf1944e287b965f9357909e7a32b23edcd
/src/test/java/org/work/demo/SuiteConfiguration.java
3ffda7eaca214a8adcbb04245a41543fb9e98895
[]
no_license
vinodrkumars/junit-selenium-demo
a629c472af85b00b729adafa478ddcd23faece63
9b23c693e3983caeaaaa439a1baef55e3a14c2ca
refs/heads/main
2023-05-27T04:30:10.746965
2021-06-09T02:57:45
2021-06-09T02:57:45
375,169,120
0
0
null
null
null
null
UTF-8
Java
false
false
1,887
java
package org.work.demo; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.io.IOException; import java.util.Properties; /** * Loads test suite configuration from resource files. */ public class SuiteConfiguration { private static final String DEBUG_PROPERTIES = "/debug.properties"; private Properties properties; public SuiteConfiguration() throws IOException { this(System.getProperty("application.properties", DEBUG_PROPERTIES)); } public SuiteConfiguration(String fromResource) throws IOException { properties = new Properties(); properties.load(SuiteConfiguration.class.getResourceAsStream(fromResource)); } public Capabilities getCapabilities() throws IOException { String capabilitiesFile = properties.getProperty("capabilities"); Properties capsProps = new Properties(); capsProps.load(SuiteConfiguration.class.getResourceAsStream(capabilitiesFile)); DesiredCapabilities capabilities = new DesiredCapabilities(); for (String name : capsProps.stringPropertyNames()) { String value = capsProps.getProperty(name); System.out.println("vk:" + "Name: " + name + " Value: "+ value); if (value.toLowerCase().equals("true") || value.toLowerCase().equals("false")) { capabilities.setCapability(name, Boolean.valueOf(value)); } else if (value.startsWith("file:")) { capabilities.setCapability(name, new File(".", value.substring(5)).getCanonicalFile().getAbsolutePath()); } else { capabilities.setCapability(name, value); } } return capabilities; } public boolean hasProperty(String name) { return properties.containsKey(name); } public String getProperty(String name) { return properties.getProperty(name); } }
[ "vinodrkumars@gmail.com" ]
vinodrkumars@gmail.com
126120a16fcf0e9501e955c87cf2009fd917c9a2
0ba6978a2263032778d9190cfd00ed0f34197cca
/src/main/java/com/vios/enterprise/warehouse/domain/entity/SimEntity.java
3d0cefa00aa857106f30f10209f1cb4bb44366f0
[]
no_license
shantojoseph/warehouse-api-service
e87764c277f9b8816dfd97a85fef81bf64f672c6
65ad9cf1d15616833e71567d2f4eb5e764c6023a
refs/heads/main
2023-06-11T10:37:34.111579
2021-07-06T15:40:09
2021-07-06T15:40:09
383,512,433
0
0
null
null
null
null
UTF-8
Java
false
false
601
java
package com.vios.enterprise.warehouse.domain.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.stereotype.Component; import javax.persistence.*; @Getter @Setter @NoArgsConstructor @Entity @Component @Table(name = "SIM") public class SimEntity extends AuditEntity { @Id private String id; @Transient private boolean isNew = true; @Column(name = "Operator_code") private String operatorCode; @Column(name = "Country") private String country; @Column(name = "status") private String status; }
[ "shanto.joseph@outlook.com" ]
shanto.joseph@outlook.com
48a71f324c287dacbe857eed6aa7e5306a9a2d36
4b533c1db53cb485f1981da02f57c0da0912d753
/com.syhan.rcp.geftut4/src/com/syhan/rcp/geftut4/editor/part/tree/EnterpriseTreeEditPart.java
99f7d053a9cbd8d5d704bdb660dbeaf72ef1eead
[]
no_license
Lareinahe/Exercise.gef
cd1705625f1c743db3864435d1bdedf31c98a7db
c699b9a4f1a71e03a47c8c18fe0bff75088c6da8
refs/heads/master
2021-12-09T16:23:49.737212
2016-06-02T08:50:46
2016-06-02T08:50:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
652
java
package com.syhan.rcp.geftut4.editor.part.tree; import java.beans.PropertyChangeEvent; import java.util.List; import com.syhan.rcp.geftut4.editor.model.Enterprise; import com.syhan.rcp.geftut4.editor.model.Node; public class EnterpriseTreeEditPart extends AppAbstractTreeEditPart { // @Override protected List<Node> getModelChildren() { // return ((Enterprise)getModel()).getChildren(); } @Override public void propertyChange(PropertyChangeEvent evt) { // if (evt.getPropertyName().equals(Node.PROPERTY_ADD)) { refreshChildren(); } if (evt.getPropertyName().equals(Node.PROPERTY_REMOVE)) { refreshChildren(); } } }
[ "syhan@nextree.co.kr" ]
syhan@nextree.co.kr
c47f1afda79f214e24129f902d7676f2530e002e
27e3f1c631066ac1cf3b6e0d27801f5a08a3c9a0
/src/main/java/com/klenio/dto/InputParametersDto.java
9cfc3e5d77431699d9cef775d4aedd1e161d1d24
[]
no_license
niokle/password-creator
fe38d0605cf9285275d478893ae0f8b850b23b1e
4b018605fc80cae238afd365918ec7b3cd3ef07b
refs/heads/master
2022-12-29T15:13:12.183373
2020-10-20T08:09:48
2020-10-20T08:09:48
283,483,847
0
0
null
null
null
null
UTF-8
Java
false
false
543
java
package com.klenio.dto; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Getter; import org.springframework.stereotype.Component; @AllArgsConstructor @NoArgsConstructor @Getter @Component public class InputParametersDto { private String userName; private String masterPassword; private String appName; private String appAddress; private int numberOfSigns; private boolean smallLetters; private boolean largeLetters; private boolean numbers; private boolean specialSigns; }
[ "myszapl@gmail.com" ]
myszapl@gmail.com
53252b7445e43a33b604450fac65ec4d82f2fb7a
d2d7cbbb71b3662771db12f2b7d3226170bb4523
/app/src/main/java/com/template/customview/Chapter7bActivity.java
7ab37f15485fd72a61bd0e93f41b77bc4141c062
[ "Apache-2.0" ]
permissive
wkboys/CustomView
693c7b5e4ea5971ab3c52da42b8a13eb54dc2d9f
0f14483c2c9ddc7d1d32bffaff3b64d69e192047
refs/heads/main
2023-02-17T14:48:53.778108
2021-01-13T05:44:11
2021-01-13T05:44:11
324,261,713
0
0
null
null
null
null
UTF-8
Java
false
false
387
java
package com.template.customview; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class Chapter7bActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chapter_g_b); setTitle("Chapter7bActivity"); } }
[ "wangyu@pdmi.com" ]
wangyu@pdmi.com
d7d3bdad674baadc781e21043b0c054760dd9c9a
a2ed12650e771e52ff94bea49710bd048fe38e21
/judge-impl/src/main/java/com/dwarfeng/judge/impl/service/telqos/EvaluateLocalCacheCommand.java
1234482391758c44579f642db066a36a48cbf79a
[ "Apache-2.0" ]
permissive
DwArFeng/judge
e36720f4018afc549c661e9d82966dcb489f69a3
801f99b9d34ce8783a1ceef17fde214544de1dce
refs/heads/master
2023-08-17T03:23:37.438421
2021-06-22T07:03:10
2021-06-22T07:03:10
251,041,700
0
0
Apache-2.0
2023-08-31T13:38:41
2020-03-29T13:42:43
Java
UTF-8
Java
false
false
4,060
java
package com.dwarfeng.judge.impl.service.telqos; import com.dwarfeng.judge.stack.bean.EvaluateInfo; import com.dwarfeng.judge.stack.bean.entity.JudgerInfo; import com.dwarfeng.judge.stack.handler.Judger; import com.dwarfeng.judge.stack.service.EvaluateQosService; import com.dwarfeng.springtelqos.sdk.command.CliCommand; import com.dwarfeng.springtelqos.stack.command.Context; import com.dwarfeng.springtelqos.stack.exception.TelqosException; import com.dwarfeng.subgrade.stack.bean.key.LongIdKey; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Objects; @Component public class EvaluateLocalCacheCommand extends CliCommand { private static final Logger LOGGER = LoggerFactory.getLogger(EvaluateLocalCacheCommand.class); private static final String IDENTITY = "elc"; private static final String DESCRIPTION = "本地缓存操作"; private static final String CMD_LINE_SYNTAX_C = "elc -c"; private static final String CMD_LINE_SYNTAX_S = "elc -s section-id"; private static final String CMD_LINE_SYNTAX = CMD_LINE_SYNTAX_C + System.lineSeparator() + CMD_LINE_SYNTAX_S; public EvaluateLocalCacheCommand() { super(IDENTITY, DESCRIPTION, CMD_LINE_SYNTAX); } @Autowired private EvaluateQosService evaluateQosService; @Override protected List<Option> buildOptions() { return CommandUtils.buildLcOptions(); } @SuppressWarnings("DuplicatedCode") @Override protected void executeWithCmd(Context context, CommandLine cmd) throws TelqosException { try { Pair<String, Integer> pair = CommandUtils.analyseLcCommand(cmd); if (pair.getRight() != 1) { context.sendMessage("下列选项必须且只能含有一个: -c -s"); context.sendMessage(CMD_LINE_SYNTAX); return; } switch (pair.getLeft()) { case "c": handleC(context); break; case "s": handleS(context, cmd); break; } } catch (Exception e) { throw new TelqosException(e); } } private void handleC(Context context) throws Exception { evaluateQosService.clearLocalCache(); context.sendMessage("缓存已清空"); } @SuppressWarnings("DuplicatedCode") private void handleS(Context context, CommandLine cmd) throws Exception { long sectionId; try { sectionId = ((Number) cmd.getParsedOptionValue("s")).longValue(); } catch (ParseException e) { LOGGER.warn("解析命令选项时发生异常,异常信息如下", e); context.sendMessage("命令行格式错误,正确的格式为: " + CMD_LINE_SYNTAX_S); context.sendMessage("请留意选项 s 后接参数的类型应该是数字 "); return; } EvaluateInfo evaluateInfo = evaluateQosService.getContext(new LongIdKey(sectionId)); if (Objects.isNull(evaluateInfo)) { context.sendMessage("not exists!"); return; } context.sendMessage(String.format("section: %s", evaluateInfo.getSection().toString())); context.sendMessage(""); context.sendMessage("judgers:"); int index = 0; for (Map.Entry<JudgerInfo, Judger> entry : evaluateInfo.getJudgerMap().entrySet()) { if (index != 0) { context.sendMessage(""); } context.sendMessage(String.format(" %-3d %s", ++index, entry.getKey().toString())); context.sendMessage(String.format(" %-3d %s", index, entry.getValue().toString())); } } }
[ "915724865@qq.com" ]
915724865@qq.com
4d1f5798394469c02f36357f51eeff017f79a432
c9754b80cb687625468a93e68eabfe7fdd30d9f9
/src/test/java/ua/com/khrypko/family/budget/user/service/FamilyServiceImplTest.java
e2fbc36ea3ae68d2e8210eb13e91249dc7bd72c6
[]
no_license
Khrypko/f_budget
b2ef595e31824cbe980c2701acf08571133dada0
84cd5b45134be22ea1f83c4bd83e9058a124cc17
refs/heads/master
2021-05-11T20:51:41.413576
2018-02-25T15:51:36
2018-02-25T15:51:36
117,452,294
0
0
null
null
null
null
UTF-8
Java
false
false
3,629
java
package ua.com.khrypko.family.budget.user.service; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import ua.com.khrypko.family.budget.exception.NoSuchEntity; import ua.com.khrypko.family.budget.user.dto.FamilyDto; import ua.com.khrypko.family.budget.user.dto.FamilyDtoWithUsers; import ua.com.khrypko.family.budget.user.entity.Family; import ua.com.khrypko.family.budget.user.repository.FamilyRepository; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static ua.com.khrypko.family.budget.user.UserTestUtil.*; /** * Created by Maks on 25.02.2018. */ @RunWith(MockitoJUnitRunner.class) public class FamilyServiceImplTest { public static final String NEW_NAME = "test_changed"; private FamilyService familyService; @Mock private FamilyRepository familyRepository; @Before public void setUp() throws Exception { familyService = new FamilyServiceImpl(familyRepository); } @Test(expected = NoSuchEntity.class) public void testGetNonExistingFamilyThrowsException() throws Exception { when(familyRepository.getOne(anyLong())).thenReturn(null); familyService.getFamily(1L); } @Test public void testGetNonExistingFamilySuccessful() throws Exception { when(familyRepository.getOne(anyLong())).thenReturn(new Family()); familyService.getFamily(1L); } @Test(expected = NoSuchEntity.class) public void testGetNonExistingFamilyByUserThrowsException() throws Exception { when(familyService.getFamilyByUser(anyLong())).thenReturn(null); familyService.getFamilyByUser(1L); } @Test public void testCreateFamilyWithoutNameSuccessful() throws Exception { when(familyRepository.save(any(Family.class))).thenAnswer(i -> i.getArguments()[0]); FamilyDto familyDto = createFamilyDTO(); familyDto.setName(null); Family family = familyService.createFamily(familyDto); verify(familyRepository, times(1)).save(any(Family.class)); assertNotNull(family.getUniqueUrl()); assertNotNull(family.getName()); } @Test public void testCreateFamilyWithNameSuccessful() throws Exception { when(familyRepository.save(any(Family.class))).thenAnswer(i -> i.getArguments()[0]); FamilyDto familyDto = createFamilyDTO(); Family family = familyService.createFamily(familyDto); verify(familyRepository, times(1)).save(any(Family.class)); assertNotNull(family.getUniqueUrl()); assertNotNull(family.getName()); assertEquals(familyDto.getName(), family.getName()); } @Test public void testUniqueIdWontBeDuplicatedWhenCreateFamily(){ when(familyRepository.existsByUniqueUrl(anyString())).thenReturn(true).thenReturn(false); familyService.createFamily(createFamilyDTO()); verify(familyRepository, times(2)).existsByUniqueUrl(anyString()); } @Test public void testUpdateFamilySuccessful(){ when(familyRepository.save(any(Family.class))).thenAnswer(i -> i.getArguments()[0]); Family family = testFamily(); family.setName(NEW_NAME); family.addUser(getUser()); Family familyAfterUpdate = familyService.updateFamily(family); verify(familyRepository, times(1)).save(any(Family.class)); assertEquals(NEW_NAME, familyAfterUpdate.getName()); assertTrue(familyAfterUpdate.getUsers().size() == 1); assertTrue(familyAfterUpdate.getUsers().contains(getUser())); } }
[ "khrypko.m@gmail.com" ]
khrypko.m@gmail.com
d7fbcd8692332811228c51fe5ab42a1a51099a09
6dbae30c806f661bcdcbc5f5f6a366ad702b1eea
/Corpus/tomcat70/985.java
73e72c04870affb1b379e501da2f647e6d69ab4a
[ "MIT" ]
permissive
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
d3fd21745dfddb2979e8ac262588cfdfe471899f
0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0
refs/heads/master
2020-03-31T15:52:01.005505
2018-10-01T23:38:50
2018-10-01T23:38:50
152,354,327
1
0
MIT
2018-10-10T02:57:02
2018-10-10T02:57:02
null
UTF-8
Java
false
false
5,551
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.http.fileupload.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * An input stream, which limits its data size. This stream is * used, if the content length is unknown. */ public abstract class LimitedInputStream extends FilterInputStream implements Closeable { /** * The maximum size of an item, in bytes. */ private final long sizeMax; /** * The current number of bytes. */ private long count; /** * Whether this stream is already closed. */ private boolean closed; /** * Creates a new instance. * * @param inputStream The input stream, which shall be limited. * @param pSizeMax The limit; no more than this number of bytes * shall be returned by the source stream. */ public LimitedInputStream(InputStream inputStream, long pSizeMax) { super(inputStream); sizeMax = pSizeMax; } /** * Called to indicate, that the input streams limit has * been exceeded. * * @param pSizeMax The input streams limit, in bytes. * @param pCount The actual number of bytes. * @throws IOException The called method is expected * to raise an IOException. */ protected abstract void raiseError(long pSizeMax, long pCount) throws IOException; /** * Called to check, whether the input streams * limit is reached. * * @throws IOException The given limit is exceeded. */ private void checkLimit() throws IOException { if (count > sizeMax) { raiseError(sizeMax, count); } } /** * Reads the next byte of data from this input stream. The value * byte is returned as an <code>int</code> in the range * <code>0</code> to <code>255</code>. If no byte is available * because the end of the stream has been reached, the value * <code>-1</code> is returned. This method blocks until input data * is available, the end of the stream is detected, or an exception * is thrown. * <p> * This method * simply performs <code>in.read()</code> and returns the result. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @throws IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public int read() throws IOException { int res = super.read(); if (res != -1) { count++; checkLimit(); } return res; } /** * Reads up to <code>len</code> bytes of data from this input stream * into an array of bytes. If <code>len</code> is not zero, the method * blocks until some input is available; otherwise, no * bytes are read and <code>0</code> is returned. * <p> * This method simply performs <code>in.read(b, off, len)</code> * and returns the result. * * @param b the buffer into which the data is read. * @param off The start offset in the destination array * <code>b</code>. * @param len the maximum number of bytes read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @throws NullPointerException If <code>b</code> is <code>null</code>. * @throws IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>b.length - off</code> * @throws IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public int read(byte[] b, int off, int len) throws IOException { int res = super.read(b, off, len); if (res > 0) { count += res; checkLimit(); } return res; } /** * Returns, whether this stream is already closed. * * @return True, if the stream is closed, otherwise false. * @throws IOException An I/O error occurred. */ @Override public boolean isClosed() throws IOException { return closed; } /** * Closes this input stream and releases any system resources * associated with the stream. * This * method simply performs <code>in.close()</code>. * * @throws IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public void close() throws IOException { closed = true; super.close(); } }
[ "masudcseku@gmail.com" ]
masudcseku@gmail.com
a7eb23ba4e3c2d8d5e70bcd23b70d0328fd0e73c
3dca6bd7b656e31abdf13e3d02d8baaf0ba450c5
/dd-oj-web/src/main/java/com/ddoj/web/controller/format/user/PullUsersIntoContestFormat.java
effca802331631fe9b6a69a27b7e0b55829a1d92
[]
no_license
zhengdayday/dd-oj
33968fcb3307d7b716dd0942d677c02be7f5cc0d
fd6789f191af4cbc3d532c26587970312fbe2cae
refs/heads/master
2020-03-12T21:46:29.401439
2018-04-24T10:03:37
2018-04-24T10:03:37
130,834,549
0
0
null
null
null
null
UTF-8
Java
false
false
665
java
package com.ddoj.web.controller.format.user; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.NotNull; /** * @author zhengtt **/ public class PullUsersIntoContestFormat { @Length(min = 1, max = 6) private String password; @NotNull @Range(min = 1) private Integer cid; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } }
[ "1157790064@qq.com" ]
1157790064@qq.com
5a1e66d3ba6105ef5e8ba2ca73bbc9cc308f1c79
5484d6124366533d5b10911cb927348aaaddaa1f
/Spring/Spring-1/src/com/abc/spring/bean/generic/di/BaseService.java
7c20c710cea2a5b9b854c6192c409020a97e00f9
[]
no_license
hegao12/learningNote
c6b04051bd17b6606755812b6f69ac8f7f35ad4f
751baad79d6d4a79e530fc1fc3032e8f3eb0f5dc
refs/heads/master
2022-01-22T21:02:21.423252
2019-08-02T11:39:13
2019-08-02T11:39:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package com.abc.spring.bean.generic.di; import org.springframework.beans.factory.annotation.Autowired; public class BaseService<T> { @Autowired protected BaseRepository<T> repository; public void add() { System.out.println("addd in service"); System.out.println(repository); } }
[ "gaohe124@126.com" ]
gaohe124@126.com
bb1024e5cfe7594ecaf0a5a91ea0b35f6b758260
b7f5dcfa788c1310b48320ba299163bf326b3a7c
/src/com/cloudfire/entity/AllEnviDevEntity.java
add9ae84e6d33a208ce034cf3ab14f88fe33cc17
[ "Apache-2.0" ]
permissive
bingo1118/zdst_service
4a18ab499a2ae2c4142e33000794dc1381dfed06
6d1a743ea681e38494cb8d7732fa221dbb881e73
refs/heads/master
2022-01-20T10:40:51.893803
2019-05-13T01:21:47
2019-05-13T01:21:47
186,324,000
1
2
null
null
null
null
GB18030
Java
false
false
3,831
java
package com.cloudfire.entity; import java.util.List; public class AllEnviDevEntity { /** * error : 获取烟感成功) * errorCode : 0 * smoke : [{"address":"深圳市 红坳村148号","areaName":"南凤派出所","camera":{"areaName":"","cameraAddress":"","cameraId":"","cameraName":"","cameraPwd":"","latitude":"","longitude":"","placeType":"","principal1":"","principal1Phone":"","principal2":"","principal2Phone":""},"deviceType":1,"ifDealAlarm":1,"latitude":"22.724359","longitude":"113.943216","mac":"1C491730","name":"郝宜祥诊所","netState":1,"placeType":"其它店","placeeAddress":"","principal1":"郝宜祥","principal1Phone":"13510914166","principal2":"","principal2Phone":"","repeater":"03091620"},{"address":"中国广东省广州市番禺区石中二路","areaName":"番禺区大石镇金河产业园区","camera":{"areaName":"","cameraAddress":"","cameraId":"","cameraName":"","cameraPwd":"","latitude":"","longitude":"","placeType":"","principal1":"","principal1Phone":"","principal2":"","principal2Phone":""},"deviceType":1,"ifDealAlarm":1,"latitude":"23.016331","longitude":"113.294726","mac":"360D43CC","name":"测试1","netState":0,"placeType":"其它店","placeeAddress":"","principal1":"张志伟","principal1Phone":"18312712709","principal2":"","principal2Phone":"","repeater":"03111620"},{"address":"中国广东省广州市番禺区石北工业路","areaName":"番禺区大石镇金河产业园区","camera":{"areaName":"","cameraAddress":"","cameraId":"","cameraName":"","cameraPwd":"","latitude":"","longitude":"","placeType":"","principal1":"","principal1Phone":"","principal2":"","principal2Phone":""},"deviceType":1,"ifDealAlarm":1,"latitude":"23.018769","longitude":"113.294216","mac":"536A1831","name":"左仓库三梁1","netState":1,"placeType":"工厂","placeeAddress":"","principal1":"%E8%8B%8F%E5%85%88%E7%94%9F","principal1Phone":"13710800611","principal2":"","principal2Phone":"","repeater":"03111620"},{"address":"中国广东省广州市番禺区石北工业路","areaName":"番禺区大石镇金河产业园区","camera":{"areaName":"","cameraAddress":"","cameraId":"","cameraName":"","cameraPwd":"","latitude":"","longitude":"","placeType":"","principal1":"","principal1Phone":"","principal2":"","principal2Phone":""},"deviceType":1,"ifDealAlarm":0,"latitude":"23.01857","longitude":"113.294144","mac":"40461730","name":"左仓库三梁2","netState":1,"placeType":"工厂","placeeAddress":"","principal1":"苏先生","principal1Phone":"13710800611","principal2":"","principal2Phone":"","repeater":"03111620"}] */ private String error="获取烟感失败"; private int errorCode=2; /** * address : 深圳市 红坳村148号 * areaName : 南凤派出所 * camera : {"areaName":"","cameraAddress":"","cameraId":"","cameraName":"","cameraPwd":"","latitude":"","longitude":"","placeType":"","principal1":"","principal1Phone":"","principal2":"","principal2Phone":""} * deviceType : 1 * ifDealAlarm : 1 * latitude : 22.724359 * longitude : 113.943216 * mac : 1C491730 * name : 郝宜祥诊所 * netState : 1 * placeType : 其它店 * placeeAddress : * principal1 : 郝宜祥 * principal1Phone : 13510914166 * principal2 : * principal2Phone : * repeater : 03091620 */ private List<EnviDevBean> smoke=null; public String getError() { return error; } public void setError(String error) { this.error = error; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public List<EnviDevBean> getSmoke() { return smoke; } public void setSmoke(List<EnviDevBean> smoke) { this.smoke = smoke; } }
[ "447292486@qq.com" ]
447292486@qq.com
16d30f322c36c8a55de8040403f5a76825caa81d
5111cd4d27e846053fc844335ab96b42f60e3b16
/zy-gis-service/src/main/java/com/zy/dzzw/gis/service/SpatialTemporalConfigService.java
7924dfe9f33d1ec87f877d0ea6d25ada269a1ac8
[]
no_license
wellsmitch/officeMap
d259b7cdd8cc2c22e1688b1c8b56f834c680ce78
9777a5066f5b9eb061a64efee7f263b831cbaa9e
refs/heads/master
2023-04-15T07:39:09.090910
2021-04-23T02:22:23
2021-04-23T02:22:23
360,738,366
0
0
null
null
null
null
UTF-8
Java
false
false
1,284
java
package com.zy.dzzw.gis.service; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import com.zy.dzzw.gis.entity.SpatialTemporalInfo; import com.zy.dzzw.gis.repository.SpatialTemporalRepository; @Service public class SpatialTemporalConfigService { @Autowired SpatialTemporalRepository spatialTemporalRepository; public List<SpatialTemporalInfo> find(String name) { if(StringUtils.isBlank(name)) { return spatialTemporalRepository.find(); } else { return spatialTemporalRepository.find(new Query().addCriteria(Criteria.where("name").regex(name + ".*"))); } } public SpatialTemporalInfo findById(long id) { return spatialTemporalRepository.findById(id); } public SpatialTemporalInfo save(SpatialTemporalInfo spatialTemporal) { spatialTemporalRepository.save(spatialTemporal); return spatialTemporal; } public long remove(SpatialTemporalInfo spatialTemporal) { return spatialTemporalRepository.delete(spatialTemporal); } }
[ "1970083855@qq.com" ]
1970083855@qq.com
69eb4642ffa7a3a8e3cccf968d29d7aeaac3f1d4
78908df86f9bd25e11027d8da4fd1301ac537113
/plugins/org.springframework.ide.eclipse.quickfix.tests/src/org/springframework/ide/eclipse/quickfix/tests/QuickfixUtilsTest.java
c79b11ee3a3a6c22c2bd62a9a8a7cc01294084f4
[]
no_license
strikingraghu/spring-ide
aa234e41e59742e4b3265df6ac1f3e92be7391dd
8cf3c470a9379646764bc67133e13c35b68cf756
refs/heads/master
2020-04-26T09:37:30.306637
2019-02-28T21:04:08
2019-02-28T21:04:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,531
java
/******************************************************************************* * Copyright (c) 2012 VMware, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VMware, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.eclipse.quickfix.tests; import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; import org.springframework.ide.eclipse.config.core.schemas.BeansSchemaConstants; import org.springframework.ide.eclipse.quickfix.QuickfixUtils; import org.springframework.ide.eclipse.quickfix.proposals.tests.AbstractBeanFileQuickfixTestCase; /** * Tests method of QuickfixUtils * @author Terry Denney * @author Leo Dos Santos * @author Christian Dupuis */ @SuppressWarnings("restriction") public class QuickfixUtilsTest extends AbstractBeanFileQuickfixTestCase { @Override protected void setUp() throws Exception { super.setUp(); openBeanEditor("src/quickfix-util.xml"); } public void testGetEnclosingBeanNode() { assertNull("Does not expect to have enclosing bean node", QuickfixUtils .getEnclosingBeanNode((IDOMNode) beansNode)); IDOMNode beanNode = QuickfixTestUtil.getNode(BeansSchemaConstants.ELEM_BEAN, "enclosingBeanTest", beansNode .getChildNodes()); assertEquals(beanNode, QuickfixUtils.getEnclosingBeanNode(beanNode)); IDOMNode propertyNode = QuickfixTestUtil.getFirstNode(BeansSchemaConstants.ELEM_PROPERTY, beanNode .getChildNodes()); assertEquals(beanNode, QuickfixUtils.getEnclosingBeanNode(propertyNode)); IDOMNode innerBeanNode = QuickfixTestUtil.getFirstNode(BeansSchemaConstants.ELEM_BEAN, propertyNode .getChildNodes()); assertEquals("Expects enclosing bean node to match bean node", innerBeanNode, QuickfixUtils .getEnclosingBeanNode(innerBeanNode)); } // public void testGetFile() { // IDOMNode beanNode = // QuickfixTestUtil.getFirstNode(BeansSchemaConstants.ELEM_BEAN, // beansNode.getChildNodes()); // assertEquals(file, // QuickfixUtils.getFile(beanNode.getFirstStructuredDocumentRegion())); // assertEquals(file, // QuickfixUtils.getFile(beanNode.getLastStructuredDocumentRegion())); // assertEquals(file, // QuickfixUtils.getFile(beanNode.getEndStructuredDocumentRegion())); // } }
[ "leo.dos.santos@tasktop.com" ]
leo.dos.santos@tasktop.com
05e0da24c2c4409b82c6bebf336222c1c1152078
d4c235decea922f93f1d284e1b4929b5e370869d
/src/main/java/pl/sdacademy/views/ClientView.java
6a945b6395ff8cbd28caac070fa790855a3c3af0
[]
no_license
marcincagara/Ksiegowosc
8e56cbabfb28874d5a22e577a593911dbcbd3988
722be73d8cba743aad2e7c93808547dbde56ad2b
refs/heads/master
2021-05-12T16:28:23.606999
2018-01-07T14:13:35
2018-01-07T14:13:35
117,014,216
0
0
null
null
null
null
UTF-8
Java
false
false
57
java
package pl.sdacademy.views; public class ClientView { }
[ "marcincag@gmail.com" ]
marcincag@gmail.com
93b7deebb1ee0b9ecb2e4854f0d9086b3b1b9bcb
3cb753efbf328e5d7a67b3d57e3a7a557e961a42
/apollo-core/src/main/java/com/haitao/apollo/service/schedule/impl/appraise/UserAppraiseTimeoutStrategy.java
f702fd7135ce04c9e590563fd18ba42ba2c9ca9c
[]
no_license
120386135/apollo
a1b4f334f31925f303dbf5808ebc193ed297c7dd
045c1bc2464a2561f9ca9f438de688e14f12b061
refs/heads/master
2020-06-12T03:43:57.842352
2018-04-02T08:17:20
2018-04-02T08:17:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,584
java
package com.haitao.apollo.service.schedule.impl.appraise; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.haitao.apollo.enums.IsDefaultEnum; import com.haitao.apollo.plugin.database.page.Page; import com.haitao.apollo.pojo.order.SaleOrder; import com.haitao.apollo.service.order.SaleOrderService; import com.haitao.apollo.service.user.UserAppraiseService; /** * 用户48小时未评价全部默认好评 + 晒单 * @author zengbin */ @Component public class UserAppraiseTimeoutStrategy extends AbstractAppraiseTimeoutStrategy { @Autowired protected SaleOrderService saleOrderService; @Autowired protected UserAppraiseService userAppraiseService; @Transactional @Override public void execute(Long appraiseTimeout) { Integer sum = this.saleOrderService.countAppraiseTimeoutSaleOrderList(appraiseTimeout); if(Page.DEFAULT_SUM.equals(sum)){ return; } int totalPages = Page.getTotalPages(sum); for(int i=0;i<totalPages;i++){ List<SaleOrder> saleOrderList = this.saleOrderService.getAppraiseTimeoutSaleOrderList(appraiseTimeout, i * Page.DEFAULT_PAGE_SIZE, Page.DEFAULT_PAGE_SIZE); for(SaleOrder saleOrder : saleOrderList){ this.userAppraiseService.appraise(saleOrder.getUserId(), saleOrder.getPurchaserId(), IsDefaultEnum.DEFAULT_NO.getCode(), saleOrder.getId(), UserAppraiseService.SCORE_5, "系统默认好评"); } } } }
[ "zengbin@zafh.com.cn" ]
zengbin@zafh.com.cn
77a346e01dbd5f70f607b896497fed304742ff13
43918bda38275a89b1201ea8c5e8cc7b0f229575
/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
44c3723c6df346b5ebbdf572ff253f19ee19895a
[ "Apache-2.0" ]
permissive
binghua-zheng/spring-framework-5.0.x
9d87b5bcb632f2bce90b3272806bb1eddb05b754
770dc3cb85ba1dd46bd553ea462453e57b7e0119
refs/heads/master
2023-01-14T03:56:24.455143
2020-11-25T15:39:14
2020-11-25T15:39:14
307,368,791
0
0
null
null
null
null
UTF-8
Java
false
false
20,434
java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; import org.springframework.beans.factory.parsing.SourceExtractor; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinitionReader; import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.MethodMetadata; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Reads a given fully-populated set of ConfigurationClass instances, registering bean * definitions with the given {@link BeanDefinitionRegistry} based on its contents. * * <p>This class was modeled after the {@link BeanDefinitionReader} hierarchy, but does * not implement/extend any of its artifacts as a set of configuration classes is not a * {@link Resource}. * * @author Chris Beams * @author Juergen Hoeller * @author Phillip Webb * @author Sam Brannen * @since 3.0 * @see ConfigurationClassParser */ class ConfigurationClassBeanDefinitionReader { private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class); private static final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver(); private final BeanDefinitionRegistry registry; private final SourceExtractor sourceExtractor; private final ResourceLoader resourceLoader; private final Environment environment; private final BeanNameGenerator importBeanNameGenerator; private final ImportRegistry importRegistry; private final ConditionEvaluator conditionEvaluator; /** * Create a new {@link ConfigurationClassBeanDefinitionReader} instance * that will be used to populate the given {@link BeanDefinitionRegistry}. */ ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor, ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator, ImportRegistry importRegistry) { this.registry = registry; this.sourceExtractor = sourceExtractor; this.resourceLoader = resourceLoader; this.environment = environment; this.importBeanNameGenerator = importBeanNameGenerator; this.importRegistry = importRegistry; this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader); } /** * Read {@code configurationModel}, registering bean definitions * with the registry based on its contents. */ public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) { // 用于过滤@Conditional注解的bean TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator(); for (ConfigurationClass configClass : configurationModel) { // 重新加载配置类的BeanDefinition,开始进一步解析 loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator); } } /** * Read a particular {@link ConfigurationClass}, registering bean definitions * for the class itself and all of its {@link Bean} methods. */ private void loadBeanDefinitionsForConfigurationClass( ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) { // 判断此配置bean是否要满足@Conditional条件,不满足则从beanDefinitionMap中删除 if (trackedConditionEvaluator.shouldSkip(configClass)) { String beanName = configClass.getBeanName(); // 如果beanDefinitionMap中包含此beanDefinition,则删除此beanDefinition,后续不创建此bean. if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) { this.registry.removeBeanDefinition(beanName); } // 此类如果被@Import注解,则删除Import内的类,并且返回,不需要后续的解析和注册。 this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName()); return; } // 执行到这里,说明此配置类满足注册bean的条件,准备解析为BeanDefinition,注册到容器中。 // 如果是通过Import导入的类,则将此bean注册到容器中 if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); } // 解析其中的@Bean方法,判断内部判断方法上是否有@Condition注解,且为REGISTER_BEAN阶段 // 将此bean注册到容器中, for (BeanMethod beanMethod : configClass.getBeanMethods()) { loadBeanDefinitionsForBeanMethod(beanMethod); } // 解析@ImportResource中的xml资源 loadBeanDefinitionsFromImportedResources(configClass.getImportedResources()); // 解析其中的@Import中class类型为ImportBeanDefinitionRegistrar的bean // 执行registerBeanDefinitions方法 loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars()); } /** * Register the {@link Configuration} class itself as a bean definition. */ private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) { AnnotationMetadata metadata = configClass.getMetadata(); // 声明BeanDefinition AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata); // 解析作用域 ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef); configBeanDef.setScope(scopeMetadata.getScopeName()); // 生成beanName String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry); // 设置通用的注解BeanDefinition属性 AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 通过registry注册到容器中 this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition()); configClass.setBeanName(configBeanName); if (logger.isDebugEnabled()) { logger.debug("Registered bean definition for imported class '" + configBeanName + "'"); } } /** * Read the given {@link BeanMethod}, registering bean definitions * with the BeanDefinitionRegistry based on its contents. */ private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { ConfigurationClass configClass = beanMethod.getConfigurationClass(); MethodMetadata metadata = beanMethod.getMetadata(); String methodName = metadata.getMethodName(); // Do we need to mark the bean as skipped by its condition? // 判断是否需要跳过此bean的注册,是否满足Condition条件,不满足则直接返回。 if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) { configClass.skippedBeanMethods.add(methodName); return; } if (configClass.skippedBeanMethods.contains(methodName)) { return; } // 满足Condition条件,则解析@Bean注解,准备注册到容器中 AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class); Assert.state(bean != null, "No @Bean annotation attributes"); // Consider name and any aliases List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name"))); String beanName = (!names.isEmpty() ? names.remove(0) : methodName); // Register aliases even when overridden for (String alias : names) { this.registry.registerAlias(beanName, alias); } // Has this effectively been overridden before (e.g. via XML)? if (isOverriddenByExistingDefinition(beanMethod, beanName)) { if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) { throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() + "' clashes with bean name for containing configuration class; please make those names unique!"); } return; } // @Bean方法的beanDefinition类型 ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata); beanDef.setResource(configClass.getResource()); beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource())); if (metadata.isStatic()) { // static @Bean method // 静态方法设置FactoryMethodName-工厂方法 beanDef.setBeanClassName(configClass.getMetadata().getClassName()); beanDef.setFactoryMethodName(methodName); } else { // instance @Bean method // 设置FactoryBeanName beanDef.setFactoryBeanName(configClass.getBeanName()); beanDef.setUniqueFactoryMethodName(methodName); } // 默认为构造器注入 beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); beanDef.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE); AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata); // 特殊指定注入方式 Autowire autowire = bean.getEnum("autowire"); if (autowire.isAutowire()) { beanDef.setAutowireMode(autowire.value()); } // 初始化方法 String initMethodName = bean.getString("initMethod"); if (StringUtils.hasText(initMethodName)) { beanDef.setInitMethodName(initMethodName); } // 销毁方法 String destroyMethodName = bean.getString("destroyMethod"); beanDef.setDestroyMethodName(destroyMethodName); // Consider scoping ScopedProxyMode proxyMode = ScopedProxyMode.NO; AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class); if (attributes != null) { beanDef.setScope(attributes.getString("value")); proxyMode = attributes.getEnum("proxyMode"); if (proxyMode == ScopedProxyMode.DEFAULT) { proxyMode = ScopedProxyMode.NO; } } // Replace the original bean definition with the target one, if necessary BeanDefinition beanDefToRegister = beanDef; if (proxyMode != ScopedProxyMode.NO) { BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy( new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS); beanDefToRegister = new ConfigurationClassBeanDefinition( (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata); } if (logger.isDebugEnabled()) { logger.debug(String.format("Registering bean definition for @Bean method %s.%s()", configClass.getMetadata().getClassName(), beanName)); } // 注册到容器中 this.registry.registerBeanDefinition(beanName, beanDefToRegister); } protected boolean isOverriddenByExistingDefinition(BeanMethod beanMethod, String beanName) { if (!this.registry.containsBeanDefinition(beanName)) { return false; } BeanDefinition existingBeanDef = this.registry.getBeanDefinition(beanName); // Is the existing bean definition one that was created from a configuration class? // -> allow the current bean method to override, since both are at second-pass level. // However, if the bean method is an overloaded case on the same configuration class, // preserve the existing bean definition. if (existingBeanDef instanceof ConfigurationClassBeanDefinition) { ConfigurationClassBeanDefinition ccbd = (ConfigurationClassBeanDefinition) existingBeanDef; return ccbd.getMetadata().getClassName().equals( beanMethod.getConfigurationClass().getMetadata().getClassName()); } // A bean definition resulting from a component scan can be silently overridden // by an @Bean method, as of 4.2... if (existingBeanDef instanceof ScannedGenericBeanDefinition) { return false; } // Has the existing bean definition bean marked as a framework-generated bean? // -> allow the current bean method to override it, since it is application-level if (existingBeanDef.getRole() > BeanDefinition.ROLE_APPLICATION) { return false; } // At this point, it's a top-level override (probably XML), just having been parsed // before configuration class processing kicks in... if (this.registry instanceof DefaultListableBeanFactory && !((DefaultListableBeanFactory) this.registry).isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "@Bean definition illegally overridden by existing bean definition: " + existingBeanDef); } if (logger.isInfoEnabled()) { logger.info(String.format("Skipping bean definition for %s: a definition for bean '%s' " + "already exists. This top-level bean definition is considered as an override.", beanMethod, beanName)); } return true; } private void loadBeanDefinitionsFromImportedResources( Map<String, Class<? extends BeanDefinitionReader>> importedResources) { Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<>(); importedResources.forEach((resource, readerClass) -> { // Default reader selection necessary? if (BeanDefinitionReader.class == readerClass) { if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) { // When clearly asking for Groovy, that's what they'll get... readerClass = GroovyBeanDefinitionReader.class; } else { // Primarily ".xml" files but for any other extension as well readerClass = XmlBeanDefinitionReader.class; } } BeanDefinitionReader reader = readerInstanceCache.get(readerClass); if (reader == null) { try { // Instantiate the specified BeanDefinitionReader reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry); // Delegate the current ResourceLoader to it if possible if (reader instanceof AbstractBeanDefinitionReader) { AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader); abdr.setResourceLoader(this.resourceLoader); abdr.setEnvironment(this.environment); } readerInstanceCache.put(readerClass, reader); } catch (Throwable ex) { throw new IllegalStateException( "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]"); } } // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations reader.loadBeanDefinitions(resource); }); } private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) { registrars.forEach((registrar, metadata) -> registrar.registerBeanDefinitions(metadata, this.registry)); } /** * {@link RootBeanDefinition} marker subclass used to signify that a bean definition * was created from a configuration class as opposed to any other configuration source. * Used in bean overriding cases where it's necessary to determine whether the bean * definition was created externally. */ @SuppressWarnings("serial") private static class ConfigurationClassBeanDefinition extends RootBeanDefinition implements AnnotatedBeanDefinition { private final AnnotationMetadata annotationMetadata; private final MethodMetadata factoryMethodMetadata; public ConfigurationClassBeanDefinition(ConfigurationClass configClass, MethodMetadata beanMethodMetadata) { this.annotationMetadata = configClass.getMetadata(); this.factoryMethodMetadata = beanMethodMetadata; setLenientConstructorResolution(false); } public ConfigurationClassBeanDefinition( RootBeanDefinition original, ConfigurationClass configClass, MethodMetadata beanMethodMetadata) { super(original); this.annotationMetadata = configClass.getMetadata(); this.factoryMethodMetadata = beanMethodMetadata; } private ConfigurationClassBeanDefinition(ConfigurationClassBeanDefinition original) { super(original); this.annotationMetadata = original.annotationMetadata; this.factoryMethodMetadata = original.factoryMethodMetadata; } @Override public AnnotationMetadata getMetadata() { return this.annotationMetadata; } @Override public MethodMetadata getFactoryMethodMetadata() { return this.factoryMethodMetadata; } @Override public boolean isFactoryMethod(Method candidate) { return (super.isFactoryMethod(candidate) && BeanAnnotationHelper.isBeanAnnotated(candidate)); } @Override public ConfigurationClassBeanDefinition cloneBeanDefinition() { return new ConfigurationClassBeanDefinition(this); } } /** * Evaluate {@code @Conditional} annotations, tracking results and taking into * account 'imported by'. */ private class TrackedConditionEvaluator { private final Map<ConfigurationClass, Boolean> skipped = new HashMap<>(); public boolean shouldSkip(ConfigurationClass configClass) { // 从缓存中尝试获取,如果有值,说明当前类是被Import进来的类,来源Class已经被判断过。 Boolean skip = this.skipped.get(configClass); // 如果没有值,说明第一次判断 if (skip == null) { // 判断此类是否为被Import导入的类 if (configClass.isImported()) { // 预设skipped为true,应该跳过此类,不注册。 boolean allSkipped = true; // 获取此Import类的Source类,也就是它的来源类,判断此类是否要跳过,不注册。 for (ConfigurationClass importedBy : configClass.getImportedBy()) { // shouldSkip判断是否要跳过,如果不满足Condition条件,返回false,不需要跳过。终止判断,解除skipped预设的true. if (!shouldSkip(importedBy)) { allSkipped = false; break; } } // 如果到这里,allSkipped为true,说明满足了跳过注册的条件。 if (allSkipped) { // The config classes that imported this one were all skipped, therefore we are skipped... // 设置skip状态为true。需要跳过此类,不需要注册到容器中。 skip = true; } } if (skip == null) { // REGISTER_BEAN阶段,判断是否要注册此bean。返回true则表示满足要过滤的条件。 skip = conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN); } // 缓存此bean的class this.skipped.put(configClass, skip); } return skip; } } }
[ "binghuazheng@163.com" ]
binghuazheng@163.com
b6839a7d3713cdb434d9755c8c593af90167a557
92134f5f7e02b42e8da9e4c9d307d7f55355f994
/src/main/java/com/zxsoft/fanfanfamily/base/service/impl/BaseServiceImpl.java
bd5d16be22ae1551e5efee22aed81aaadb03494c
[]
no_license
ZXSoftCN/FanF
4764c88872c16bf9493906b60db07209b8e3fefe
e82d26b137e2d0457daa481a0cbdfe0dba702c11
refs/heads/master
2020-03-23T15:40:40.612921
2018-09-27T07:42:04
2018-09-27T07:42:04
141,766,107
0
0
null
null
null
null
UTF-8
Java
false
false
19,052
java
package com.zxsoft.fanfanfamily.base.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.zxsoft.fanfanfamily.base.domain.EntityIncrease; import com.zxsoft.fanfanfamily.base.domain.Menu; import com.zxsoft.fanfanfamily.base.domain.vo.AvatorLoadFactor; import com.zxsoft.fanfanfamily.base.repository.EntityIncreaseDao; import com.zxsoft.fanfanfamily.base.service.BaseService; import com.zxsoft.fanfanfamily.base.service.StorageException; import com.zxsoft.fanfanfamily.common.EntityManagerUtil; import com.zxsoft.fanfanfamily.config.AppPropertiesConfig; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.resource.ResourceUrlProvider; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.nio.channels.FileChannel; import java.nio.file.*; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @Service public abstract class BaseServiceImpl<T> implements BaseService<T> { protected Logger logger = LoggerFactory.getLogger(getClass()); private Path origUploadPath; protected Path rootUploadPath; protected Path avatarUploadPath; protected final String avatar = "avatar"; //初始化流水号 private final int INIT_NUM = 0; @Autowired protected AppPropertiesConfig appPropertiesConfig; @Autowired protected WebApplicationContext applicationContext; @Autowired private EntityIncreaseDao entityIncreaseDao; @Autowired protected EntityManagerUtil entityManagerUtil; // @Autowired // public BaseServiceImpl(ApplicalitionProperties applicalitionProperties){ // this.rootUploadPath = Paths.get(applicalitionProperties.getUploadPath()); // } // // public BaseServiceImpl(){ //// initPath(); // // } @Override public String getEntityName() { return null; } @Override public AtomicInteger getSortNoMax() { return null; } @Override public void initSortNoMax() { try{ if (StringUtils.isBlank(this.getEntityName()) && getSortNoMax() == null) { return ; } Optional<Integer> sortNoMax = entityIncreaseDao.getSortNoMax(this.getEntityName()); // if(!sortNoMax.isPresent() || sortNoMax.get()<INIT_NUM){ // sortNoMax = Optional.of(INIT_NUM); // // } if(logger.isDebugEnabled()){ logger.debug(String.format("初始化%s序号最大值为:%d",getEntityName(),sortNoMax.orElse(INIT_NUM))); } getSortNoMax().set(sortNoMax.orElse(INIT_NUM)); }catch(Exception e){ logger.error(String.format("初始化获取%s序号最大值异常:%s",getEntityName(),e.getMessage())); } } /** * @Author javaloveiphone * @Description :获取最新分组编号 * @return * int * 注:此方法并没有使用synchronized进行同步,因为共享的编号自增操作是原子操作,线程安全的 */ @Override public int getNewSortNo() { //线程安全的原子操作,所以此方法无需同步 int newSortNo = getSortNoMax().incrementAndGet(); return newSortNo; } @Override public AtomicInteger getCodeNumMax() { return null; } @Override public void initCodeNumMax() { try{ if (StringUtils.isBlank(this.getEntityName()) && getCodeNumMax() == null) { return ; } Optional<Integer> codeNumMax = entityIncreaseDao.getCodeNumMax(this.getEntityName()); if(logger.isDebugEnabled()){ logger.debug(String.format("初始化%s编号最大值为:%d",getEntityName(),codeNumMax.orElse(INIT_NUM))); } getCodeNumMax().set(codeNumMax.orElse(INIT_NUM)); }catch(Exception e){ logger.error(String.format("初始化获取%s编号最大值异常:%s",getEntityName(),e.getMessage())); } } @Override public String getNewCode() { String newCode = null; Optional<EntityIncrease> itemIncrease = entityIncreaseDao.findFirstByEntityNameIgnoreCase(getEntityName()); if (itemIncrease.isPresent()) { String datePart = null; if (!StringUtils.isBlank(itemIncrease.get().getDateFormat())) { DateTimeFormatter df = DateTimeFormatter.ofPattern(itemIncrease.get().getDateFormat()); datePart = DateTime.now().toString(itemIncrease.get().getDateFormat()); } String prefixPart = itemIncrease.get().getPrefix(); int codeNumLength = itemIncrease.get().getCodeNumLength(); String separate = itemIncrease.get().getSeparate(); String maxNumPlus = "1" + StringUtils.repeat("0",codeNumLength); Long maxNumLong = Long.decode(maxNumPlus) + getCodeNumMax().incrementAndGet(); String numPart = maxNumLong.toString().substring(1);//去除首位字符1 List<String> lstJoin = new ArrayList<>(); if (!StringUtils.isEmpty(prefixPart)) { lstJoin.add(prefixPart); } if (!StringUtils.isEmpty(datePart)) { lstJoin.add(datePart); } lstJoin.add(numPart); newCode = StringUtils.join(lstJoin.iterator(),separate); } return newCode; } public Path getDefaultAvatar() { String strClasses = applicationContext.getClassLoader().getResource("").getPath().substring(1); return Paths.get(String.format("%s/%s",strClasses,appPropertiesConfig.getDefaultAvatar())); } protected String getClassesPath(){ return applicationContext.getClassLoader().getResource("").getPath().substring(1); } @Override public Path getOriginPath(){return origUploadPath;} //构造函数执行时applicalitionProperties还未装配完成。 //装配动作是在构造完成之后进行 protected void initPath() { this.origUploadPath = Paths.get(String.format("%s/%s",getClassesPath(),appPropertiesConfig.getUploadPath())); this.rootUploadPath = Paths.get(String.format("%s/%s",getClassesPath(),appPropertiesConfig.getUploadPath())); this.avatarUploadPath = Paths.get(String.format("%s/%s",getClassesPath(),appPropertiesConfig.getUploadPath())); } @Override public Path getPath() { if (this.rootUploadPath == null) { initPath();//此处注意:会出现子类通过super.getPath()调用时,initPath()再执行是子类的方法,而造成循环。 } try { if (!Files.exists(this.rootUploadPath)) { Files.createDirectories(this.rootUploadPath); } } catch (IOException ex) { logger.error(String.format("创建资源文件夹%s失败,异常:%s", this.rootUploadPath.toString(),ex.getMessage())); } return this.rootUploadPath ; } @Override public Path getAvatarPath(){ if (this.avatarUploadPath == null) { initPath();//此处注意:会出现子类通过super.getPath()调用时,initPath()再执行是子类的方法,而造成循环。 } try { if (!Files.exists(this.avatarUploadPath)) { Files.createDirectories(this.avatarUploadPath); } } catch (IOException ex) { logger.error(String.format("创建图标头像文件夹%s失败,异常:%s", this.avatarUploadPath.toString(),ex.getMessage())); } return this.avatarUploadPath ; } @Override public String getBannedFile() { return ""; } @Override public abstract JpaRepository<T,String> getBaseDao(); @Override public Optional<T> getById(String id) { return getBaseDao().findById(id); } /** * 默认使用id。下行实体根据自身关键字属性进行实现,如按code或name查询。 * @param key * @return */ @Override public Optional<T> getByKey(String key) { return getBaseDao().findById(key); } @Override public Path storeFile(MultipartFile file) { Path filePath; try { if (file.isEmpty()) { throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); } String postfix = StringUtils.substringAfter(file.getOriginalFilename(),"."); String newFileName = String.format("%s.%s",appPropertiesConfig.getRandomString(),postfix); filePath = this.rootUploadPath.resolve(newFileName); Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); } return filePath; } @Override public T save(T t) { CrudRepository<T,String> dao = getBaseDao(); return dao.save(t); } @Override public List<T> findAll() { Iterator<T> coll = getBaseDao().findAll().iterator(); return IteratorUtils.toList(coll); } @Override public Page<T> findAll(Pageable pageable) { Page<T> coll = getBaseDao().findAll(pageable); return coll; } @Override @Transactional public T add(T t) { return getBaseDao().save(t); } @Override @Transactional public T modify(T t) { return getBaseDao().save(t); } @Override @Transactional public List<T> saveBatch(List<T> collT) { return getBaseDao().saveAll(collT); } @Override public Boolean delete(String id) { Boolean rlt = false; Optional<T> t = getBaseDao().findById(id); if (t.isPresent()) { getBaseDao().delete(t.get()); rlt = true; } return rlt; } @Override public Boolean deleteBatch(List<String> ids) { Boolean rlt = false; List<T> lst = getBaseDao().findAllById(ids); if (!lst.isEmpty()) { getBaseDao().deleteAll(lst); rlt = true; } return rlt; } @Override public String uploadAvatar( MultipartFile file) { try { if (file.isEmpty()) { throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); } String postfix = StringUtils.substringAfter(file.getOriginalFilename(),"."); //按日期+随机数生成新文件名 String currDate = DateTime.now().toString(appPropertiesConfig.getAppShortDateFormat()); String newFileName = String.format("%s%d.%s",currDate, appPropertiesConfig.getRandomInt(),postfix); Path itemNew = getAvatarPath().resolve(newFileName); while (Files.exists(itemNew)) { newFileName = String.format("%s%d.%s",currDate, appPropertiesConfig.getRandomInt(),postfix); itemNew = getAvatarPath().resolve(newFileName); } Files.copy(file.getInputStream(), itemNew,StandardCopyOption.REPLACE_EXISTING); String strOppoPath = StringUtils.replace(itemNew.toString().replace("\\","/"),getClassesPath(),""); return strOppoPath; // return itemNew; } catch (IOException e) { throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); } } @Override public String uploadAvatar(String fileName, String postfix, byte[] bytes) { try{ // File destFile = new File(destPath.toString()); // OutputStream stream = new FileOutputStream(destFile,false); // org.apache.commons.io.IOUtils.write(bytes,stream); //按日期+随机数生成新文件名 String currDate = DateTime.now().toString(appPropertiesConfig.getAppShortDateFormat()); String newFileName = String.format("%s%d.%s",currDate, appPropertiesConfig.getRandomInt(),postfix); Path itemNew = getAvatarPath().resolve(newFileName); while (Files.exists(itemNew)) { newFileName = String.format("%s%d.%s",currDate, appPropertiesConfig.getRandomInt(),postfix); itemNew = getAvatarPath().resolve(newFileName); } OpenOption[] options = new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING}; Files.createFile(itemNew); Files.write(itemNew,bytes,options); return itemNew.toString(); }catch (IOException ex){ logger.error(String.format("%s Failed to store file:%s.%s", this.getClass().getName(),ex.getMessage(), System.lineSeparator()));//System.lineSeparator()换行符 } return null; } /* *解析文件名获取后缀名 */ @Override public String uploadAvatar(String fileName, byte[] bytes) { String pos = StringUtils.substringAfterLast(fileName,"."); return uploadAvatar(fileName,pos,bytes); } @Override public Resource downloadResource(String url) { if (!StringUtils.isEmpty(url) ) { Path path = Paths.get(url); if (Files.exists(path)) { Resource resource = applicationContext.getResource(url); return resource; } else { logger.warn(String.format("所要下载的文件%s不存在",url)); } } return null; } @Override public Path loadAvatar(T t) { return loadAvatar(t,null); } @Override public Path loadAvatar(T t, int width, int height, double scaling){ AvatorLoadFactor factor = new AvatorLoadFactor(); factor.setWidth(width); factor.setHeight(height); factor.setScaling(scaling); return loadAvatar(t,factor); } @Override public abstract Path loadAvatar(T t, AvatorLoadFactor factor) ; private Path loadAvatarInner(String url) { if (!StringUtils.isEmpty(url) ) { Path path = Paths.get(url); if (Files.exists(path)) { return path; } else { logger.warn(String.format("加载%s【%s】的图标被删除,使用默认头像。",getClass().getName(),url)); } } // logger.debug(String.format("加载%s,使用默认头像。",getClass().getName())); return getDefaultAvatar(); } protected Path loadAvatarInner(String url,AvatorLoadFactor factor) { if (factor == null) { return loadAvatarInner(url); } if (!StringUtils.isEmpty(url) ) { Path path = Paths.get(url); if (Files.exists(path)) { String fileName = path.getFileName().toString(); String currentDirectory = String.format("%s\\%s", path.getParent().toString(),StringUtils.substringBefore(fileName,"."));//toAbsolutePath(). Path upperPath = Paths.get(currentDirectory); try { if (!Files.exists(upperPath)) { upperPath = Files.createDirectories(upperPath); } String newFileName = String.format("%s_%d_%d.%s", StringUtils.substringBefore(fileName,"."),factor.getWidth(),factor.getHeight(), StringUtils.substringAfterLast(fileName,".")); Path newItem = upperPath.resolve(newFileName); File newFile; if (Files.exists(newItem) && newItem.toFile().length() > 0) { newFile = newItem.toFile(); }else{ if (Files.exists(newItem)) { Files.deleteIfExists(newItem);//异常:0字节文件 } newFile = Files.createFile(newItem).toFile(); Thumbnails.of(path.toUri().toURL()) .size(factor.getWidth(),factor.getHeight()) .outputQuality(factor.getScaling()) .useOriginalFormat() .toFile(newFile); } return newFile.toPath(); }catch (MalformedURLException ex) { logger.error(String.format("读取文件%s失败,异常:%s" ,fileName, ex.getMessage())); } catch (IOException ex) { logger.error(String.format("创建%s文件夹失败,异常:%s",upperPath.toString(),ex.getMessage())); } } else { logger.warn(String.format("加载%s【%s】的图标被删除,使用默认头像。",getClass().getName(),url)); } } // logger.debug(String.format("加载%s,使用默认头像。",getClass().getName())); return getDefaultAvatar(); } /** * 删除实体的附件。 * @param url */ @Override public void deleteInnertFile(String url) { if (url != null && !url.isEmpty() && !isBannedUrl(url)) { if (url.startsWith("file:/")) { url = url.replaceFirst("file:/", ""); } Path pathOld = Paths.get(StringUtils.join(getClassesPath(),url)); try{ Files.deleteIfExists(pathOld); }catch (IOException ex){ logger.error(String.format("%s 删除头像图标【%s】失败:%s.%s", this.getClass().getName(),pathOld.toAbsolutePath(),ex.getMessage(),System.lineSeparator()));//System.lineSeparator()换行符 } } } protected boolean isBannedUrl(String url) { return appPropertiesConfig.getBannedFiles().contains(url); } }
[ "13728199836@163.com" ]
13728199836@163.com
d0c4f861f429ed73f3d79a9dc702923cae2f0c12
96fdd0969806934251ab4320dcd2c24748124a26
/anyoujia-common/src/main/java/cn/anyoufang/utils/AesCBC.java
552774af0e16942459a28aee7f609b83e5ac3fef
[]
no_license
tinkinginGitHub/shequsuo
23d903e6207a9a5116622782e3c1af8185975380
dab42ff6c6b76eeee5479233499ad0ff119d6d6f
refs/heads/master
2020-03-27T15:43:26.748604
2019-01-21T06:32:12
2019-01-21T06:32:12
146,735,209
2
0
null
2018-12-14T03:37:12
2018-08-30T10:41:22
Java
UTF-8
Java
false
false
2,511
java
package cn.anyoufang.utils; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * AES 是一种可逆加密算法,对用户的敏感信息加密处理 * 对原始数据进行AES加密后,在进行Base64编码转化; * @author daping */ public class AesCBC { /** * 已确认加密用的Key 可以用26个字母和数字组成 * 此处使用AES-128-CBC加密模式,key需要为16位。 */ private static String sKey="u798y49H87BUii7g"; private static String ivParameter="28v6njy9ONIY9OBU"; private static String encodingFormat="utf-8"; private static AesCBC instance=null; private static final String salt = "575gh5rr556Dfhr67Ohrt8"; private AesCBC(){ } public static AesCBC getInstance(){ if (instance==null){ instance= new AesCBC(); } return instance; } /** * 加密 * @param sSrc * @return * @throws Exception */ public String encrypt(String sSrc) throws Exception { byte[] raw = sKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); //使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes("utf-8")); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(sSrc.getBytes(encodingFormat)); //此处使用BASE64做转码。 String result = org.apache.commons.codec.binary.Base64.encodeBase64String(encrypted).replaceAll("\r|\n", "");; return result; } /** * 解密 * @param sSrc * @return */ public String decrypt(String sSrc){ try { byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 =org.apache.commons.codec.binary.Base64.decodeBase64(sSrc); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original,encodingFormat); return originalString; } catch (Exception ex) { return null; } } }
[ "891130271@qq.com" ]
891130271@qq.com
d6828d0b481c369fd4ec908b9d9f73541ffceb6e
ce9340c5c202398f11dec6a9a066d32b5f151c3c
/tdmuteam.fhome/app/src/main/java/dcsteam/tdmuteamfhome/service/NotificationService.java
d7eb09b9d17383950307f24e120910f06161b681
[]
no_license
LeVinhit/tdmuteam.fhome
45187fa3721e3e2a1f1ad1a19a05e1cb52987de2
9595f7521cb1152b4a15046394dbe8b7723f73b8
refs/heads/master
2021-08-19T07:06:47.656207
2017-11-25T03:56:14
2017-11-25T03:56:14
111,975,029
0
0
null
null
null
null
UTF-8
Java
false
false
3,653
java
package dcsteam.tdmuteamfhome.service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.IBinder; import android.support.annotation.Nullable; import com.google.firebase.database.ChildEventListener; 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 khangit96.tdmuteamfhome.R; import khangit96.tdmuteamfhome.activity.MainActivity; /** * Created by Administrator on 12/9/2016. */ public class NotificationService extends Service { int count = 0; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("NhaTro"); mDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { count = (int) dataSnapshot.getChildrenCount(); } @Override public void onCancelled(DatabaseError databaseError) { } }); mDatabase.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { // if (Integer.parseInt(dataSnapshot.getKey()) + 1 > count && count != 0) { if ((Boolean)dataSnapshot.child("verified").getValue() == true) showNotification("Nhà trọ " + dataSnapshot.child("tenChuHo").getValue().toString()); // } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { if ((Boolean)dataSnapshot.child("verified").getValue() == true) showNotification("Nhà trọ " + dataSnapshot.child("tenChuHo").getValue().toString()); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); super.onStart(intent, startId); } /* * Show notification to user * */ public void showNotification(String houseName) { Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Intent intent = new Intent(getApplicationContext(), MainActivity.class); PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0); Notification mNotification = new Notification.Builder(getApplicationContext()) .setContentTitle("Có nhà trọ mới!") .setContentText(houseName) .setSmallIcon(R.mipmap.ic_launcher) .setContentIntent(pIntent) .setAutoCancel(true) .setSound(alarmSound) .build(); NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE); notificationManager.notify(0, mNotification); } }
[ "levinhit.tdm@gmail.com" ]
levinhit.tdm@gmail.com
fe96b392c9cf54125e3ebe2ffee3715758b16111
aa8085ea3aaf4cbbb938fac0ad95477d79c12e64
/subprojects/griffon-javafx/src/main/java/griffon/javafx/collections/DelegatingObservableSet.java
5ab7ae2525eebc35adc775bde56802d091890b39
[ "Apache-2.0" ]
permissive
griffon/griffon
3197c9ee3a5ee3bcb26418729f5c611f6f49c2d9
de3a5a7807478e750bfa7684f796ced42322f1aa
refs/heads/development
2023-09-04T16:34:08.308818
2021-11-06T23:19:37
2021-11-06T23:19:37
1,889,544
288
96
Apache-2.0
2020-04-30T19:14:02
2011-06-13T15:58:14
Java
UTF-8
Java
false
false
3,391
java
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2008-2021 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 griffon.javafx.collections; import griffon.annotations.core.Nonnull; import javafx.collections.ObservableSet; import javafx.collections.SetChangeListener; import javafx.collections.WeakSetChangeListener; import java.util.Collection; import java.util.Iterator; import static java.util.Objects.requireNonNull; /** * @author Andres Almiray * @since 2.9.0 */ public abstract class DelegatingObservableSet<E> extends ObservableSetBase<E> implements ObservableSet<E> { private final ObservableSet<E> delegate; private SetChangeListener<E> sourceListener; public DelegatingObservableSet(@Nonnull ObservableSet<E> delegate) { this.delegate = requireNonNull(delegate, "Argument 'delegate' must not be null"); this.delegate.addListener(new WeakSetChangeListener<>(getListener())); } @Nonnull protected ObservableSet<E> getDelegate() { return delegate; } private SetChangeListener<E> getListener() { if (sourceListener == null) { sourceListener = DelegatingObservableSet.this::sourceChanged; } return sourceListener; } protected abstract void sourceChanged(@Nonnull SetChangeListener.Change<? extends E> c); // --== Delegate methods ==-- @Override public int size() { return getDelegate().size(); } @Override public boolean isEmpty() { return getDelegate().isEmpty(); } @Override public boolean contains(Object o) { return getDelegate().contains(o); } @Override public Iterator<E> iterator() { return getDelegate().iterator(); } @Override public Object[] toArray() { return getDelegate().toArray(); } @Override public <T> T[] toArray(T[] a) { return getDelegate().toArray(a); } @Override public boolean add(E e) { return getDelegate().add(e); } @Override public boolean remove(Object o) { return getDelegate().remove(o); } @Override public boolean containsAll(Collection<?> c) { return getDelegate().containsAll(c); } @Override public boolean addAll(Collection<? extends E> c) { return getDelegate().addAll(c); } @Override public boolean retainAll(Collection<?> c) { return getDelegate().retainAll(c); } @Override public boolean removeAll(Collection<?> c) { return getDelegate().removeAll(c); } @Override public void clear() { getDelegate().clear(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @Override public int hashCode() { return getDelegate().hashCode(); } }
[ "aalmiray@gmail.com" ]
aalmiray@gmail.com
06f680c2ea4e1f9d62e8aa4bf761e17c3835eedc
8181b781903db3334ed7b483b3d7871c091ea72f
/test/CalculatorTest.java
cb3659641050c3fb00d8413fa045683748263b94
[]
no_license
CodeAmend/calculator
f643ab8c96bcb56c4fcb1fcf4c6f706487aab0ba
a506fe56975a350ff34c0f4af509d56eeaa3bfc9
refs/heads/master
2021-01-17T15:41:37.214470
2016-07-26T22:18:03
2016-07-26T22:18:03
43,619,862
0
2
null
null
null
null
UTF-8
Java
false
false
1,339
java
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by codeamend on 10/3/15. */ public class CalculatorTest { private final double TOLERANCE = 0.00001d; Calculator calc; @Before public void setUp() { calc = new Calculator(); } public void input(double... value) { for(double num : value) { calc.input(num); } } @Test public void accumulator_default_value() { assertEquals(0.0, calc.accumulator(), TOLERANCE); } @Test public void input_one_number() { input(4.0); assertEquals(4.0, calc.accumulator(), TOLERANCE); } @Test public void add_numbers_at_top_of_stack() { input(8.0, 4.0); calc.add(); assertEquals(12.0, calc.accumulator(), TOLERANCE); } @Test public void subtract_numbers_at_top_of_stack() { input(4.0, 8.0); calc.subtract(); assertEquals(-4.0, calc.accumulator(), TOLERANCE); } // refactor of operations should be an object @Test public void operation_object_add_top_of_stack() { input(3.0, 6.0); //calc.perform(new Addition()); //above method added to add() calc.add(); assertEquals(9.0, calc.accumulator(), TOLERANCE); } }
[ "CodeAmend@Gmail.Com" ]
CodeAmend@Gmail.Com
9b54e4577b75762452a530e26c487b6601289e32
fa38c4679be5651296dd0944cbc2beeed4699c33
/src/main/java/com/github/lyrric/ui/MainFrame.java
39baf5c748901d2c77263a230e60f534614ef5a4
[]
no_license
udeth/seckill
ead12c9c1cc94a65ea30626705fdf042537081cb
d7d3d3197411cc592d0602665d0d29bb4564bfd0
refs/heads/master
2022-11-29T11:15:05.246195
2020-08-11T12:09:16
2020-08-11T12:09:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,499
java
package com.github.lyrric.ui; import com.github.lyrric.conf.Config; import com.github.lyrric.model.BusinessException; import com.github.lyrric.model.TableModel; import com.github.lyrric.model.VaccineList; import com.github.lyrric.service.SecKillService; import org.apache.commons.lang3.StringUtils; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.io.IOException; import java.text.ParseException; import java.util.List; /** * Created on 2020-07-21. * * @author wangxiaodong */ public class MainFrame extends JFrame { SecKillService service = new SecKillService(); /** * 疫苗列表 */ private List<VaccineList> vaccines; JButton startBtn; JButton setCookieBtn; JButton setMemberBtn; JTable vaccinesTable; JButton refreshBtn; DefaultTableModel tableModel; JTextArea note; public MainFrame() { setLayout(null); setTitle("Just For Fun"); setBounds(500 , 500, 680, 340); init(); setLocationRelativeTo(null); setVisible(true); this.setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void init(){ startBtn = new JButton("开始"); startBtn.setEnabled(false); startBtn.addActionListener(e -> start()); setCookieBtn = new JButton("设置Cookie"); setCookieBtn.addActionListener((e)->{ ConfigDialog dialog = new ConfigDialog(this); dialog.setModal(true); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); if(dialog.success()){ setMemberBtn.setEnabled(true); startBtn.setEnabled(true); refreshBtn.setEnabled(true); appendMsg("设置cookie成功"); } }); setMemberBtn = new JButton("选择成员"); setMemberBtn.setEnabled(false); setMemberBtn.addActionListener((e)->{ MemberDialog dialog = new MemberDialog(this); dialog.setModal(true); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); if(dialog.success()){ appendMsg("已设置成员"); } }); refreshBtn = new JButton("刷新疫苗列表"); refreshBtn.setEnabled(false); refreshBtn.addActionListener((e)->{ refreshVaccines(); }); note = new JTextArea(); note.append("日记记录:\r\n"); note.setEditable(false); note.setAutoscrolls(true); note.setLineWrap(true); JScrollPane scroll = new JScrollPane(note); scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); String[] columnNames = { "id", "疫苗名称","医院名称","秒杀时间" }; tableModel = new TableModel(new String[0][], columnNames); vaccinesTable = new JTable(tableModel); JScrollPane scrollPane = new JScrollPane(vaccinesTable); scrollPane.setBounds(10,10,460,200); startBtn.setBounds(370, 230, 100, 30); setCookieBtn.setBounds(20, 230, 100, 30); setMemberBtn.setBounds(130, 230, 100, 30); refreshBtn.setBounds(240, 230,120, 30); scroll.setBounds(480, 10, 180, 280); add(scrollPane); add(scroll); add(startBtn); add(setCookieBtn); add(setMemberBtn); add(refreshBtn); } private void refreshVaccines(){ try { vaccines = service.getVaccines(); //清除表格数据 //通知模型更新 ((DefaultTableModel)vaccinesTable.getModel()).getDataVector().clear(); ((DefaultTableModel)vaccinesTable.getModel()).fireTableDataChanged(); vaccinesTable.updateUI();//刷新表 if(vaccines != null && !vaccines.isEmpty()){ for (VaccineList t : vaccines) { String[] item = { t.getId().toString(), t.getVaccineName(),t.getName() ,t.getStartTime()}; tableModel.addRow(item); } } } catch (IOException e) { e.printStackTrace(); appendMsg("未知错误"); } catch (BusinessException e) { appendMsg("错误:"+e.getErrMsg()+",errCode"+e.getCode()); } } private void start(){ if(StringUtils.isEmpty(Config.cookies)){ appendMsg("请配置cookie!!!"); return ; } if(vaccinesTable.getSelectedRow() < 0){ appendMsg("请选择要抢购的疫苗"); return ; } int selectedRow = vaccinesTable.getSelectedRow(); Integer id = vaccines.get(selectedRow).getId(); String startTime = vaccines.get(selectedRow).getStartTime(); new Thread(()->{ try { startBtn.setEnabled(false); service.startSecKill(id, startTime, this); } catch (ParseException | InterruptedException e) { appendMsg("解析开始时间失败"); startBtn.setEnabled(true); e.printStackTrace(); } }).start(); } public void appendMsg(String message){ note.append(message); note.append("\r\n"); } public void setStartBtnEnable(){ startBtn.setEnabled(true); } }
[ "xx20510@163.com" ]
xx20510@163.com
27a174b3a65522b743ef18b3c3226e79805a7fe6
b0b0c5512430c9ba47f193ddf7b9d9480d135ae5
/app/src/main/java/com/rackluxury/jaguar/reddit/fragments/ViewRedditGalleryVideoFragment.java
9b9eca7de03065242101ee0a060d1cee88589cf0
[]
no_license
HarshAProgrammer/Jaguar
87562150625387f2c954d32f705e0b704f7e5866
24239c652384aaff06882d818961cf462a08e373
refs/heads/master
2023-08-17T07:42:29.291799
2021-09-13T16:42:56
2021-09-13T16:42:56
405,972,038
0
0
null
null
null
null
UTF-8
Java
false
false
12,657
java
package com.rackluxury.jaguar.reddit.fragments; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.google.android.exoplayer2.ExoPlayerFactory; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.util.Util; import javax.inject.Inject; import javax.inject.Named; import butterknife.BindView; import butterknife.ButterKnife; import com.rackluxury.jaguar.reddit.Infinity; import com.rackluxury.jaguar.reddit.post.Post; import com.rackluxury.jaguar.R; import com.rackluxury.jaguar.reddit.services.RedditDownloadMediaService; import com.rackluxury.jaguar.reddit.utils.SharedPreferencesUtils; public class ViewRedditGalleryVideoFragment extends Fragment { public static final String EXTRA_REDDIT_GALLERY_VIDEO = "EIV"; public static final String EXTRA_SUBREDDIT_NAME = "ESN"; private static final String IS_MUTE_STATE = "IMS"; private static final String POSITION_STATE = "PS"; private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 0; @BindView(R.id.player_view_view_reddit_gallery_video_fragment) PlayerView videoPlayerView; @BindView(R.id.mute_exo_playback_control_view) ImageButton muteButton; private Activity activity; private Post.Gallery galleryVideo; private String subredditName; private SimpleExoPlayer player; private boolean wasPlaying = false; private boolean isMute = false; private boolean isDownloading = false; @Inject @Named("default") SharedPreferences mSharedPreferences; public ViewRedditGalleryVideoFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_view_reddit_gallery_video, container, false); ((Infinity) activity.getApplication()).getAppComponent().inject(this); ButterKnife.bind(this, rootView); setHasOptionsMenu(true); activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); galleryVideo = getArguments().getParcelable(EXTRA_REDDIT_GALLERY_VIDEO); subredditName = getArguments().getString(EXTRA_SUBREDDIT_NAME); if (!mSharedPreferences.getBoolean(SharedPreferencesUtils.VIDEO_PLAYER_IGNORE_NAV_BAR, false)) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || getResources().getBoolean(R.bool.isTabletReddit)) { //Set player controller bottom margin in order to display it above the navbar int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); LinearLayout controllerLinearLayout = rootView.findViewById(R.id.linear_layout_exo_playback_control_view); ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) controllerLinearLayout.getLayoutParams(); params.bottomMargin = getResources().getDimensionPixelSize(resourceId); } else { //Set player controller right margin in order to display it above the navbar int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); LinearLayout controllerLinearLayout = rootView.findViewById(R.id.linear_layout_exo_playback_control_view); ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) controllerLinearLayout.getLayoutParams(); params.rightMargin = getResources().getDimensionPixelSize(resourceId); } } videoPlayerView.setControllerVisibilityListener(visibility -> { switch (visibility) { case View.GONE: activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE); break; case View.VISIBLE: activity.getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } }); TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(); TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory); player = ExoPlayerFactory.newSimpleInstance(activity, trackSelector); videoPlayerView.setPlayer(player); DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(activity, Util.getUserAgent(activity, "Infinity")); player.prepare(new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(galleryVideo.url))); preparePlayer(savedInstanceState); return rootView; } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.view_reddit_gallery_video_fragment, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_download_view_reddit_gallery_video_fragment) { isDownloading = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // No explanation needed; request the permission requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE); } else { // Permission has already been granted download(); } } else { download(); } return true; } return false; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE && grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { Toast.makeText(activity, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); isDownloading = false; } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED && isDownloading) { download(); } } } private void download() { isDownloading = false; Intent intent = new Intent(activity, RedditDownloadMediaService.class); intent.putExtra(RedditDownloadMediaService.EXTRA_URL, galleryVideo.url); intent.putExtra(RedditDownloadMediaService.EXTRA_MEDIA_TYPE, RedditDownloadMediaService.EXTRA_MEDIA_TYPE_VIDEO); intent.putExtra(RedditDownloadMediaService.EXTRA_FILE_NAME, galleryVideo.fileName); intent.putExtra(RedditDownloadMediaService.EXTRA_SUBREDDIT_NAME, subredditName); ContextCompat.startForegroundService(activity, intent); Toast.makeText(activity, R.string.download_started, Toast.LENGTH_SHORT).show(); } private void preparePlayer(Bundle savedInstanceState) { player.setRepeatMode(Player.REPEAT_MODE_ALL); wasPlaying = true; boolean muteVideo = mSharedPreferences.getBoolean(SharedPreferencesUtils.MUTE_VIDEO, false); if (savedInstanceState != null) { long position = savedInstanceState.getLong(POSITION_STATE); if (position > 0) { player.seekTo(position); } isMute = savedInstanceState.getBoolean(IS_MUTE_STATE); if (isMute) { player.setVolume(0f); muteButton.setImageResource(R.drawable.ic_mute_24dp); } else { player.setVolume(1f); muteButton.setImageResource(R.drawable.ic_unmute_24dp); } } else if (muteVideo) { isMute = true; player.setVolume(0f); muteButton.setImageResource(R.drawable.ic_mute_24dp); } else { muteButton.setImageResource(R.drawable.ic_unmute_24dp); } player.addListener(new Player.EventListener() { @Override public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) { if (!trackGroups.isEmpty()) { for (int i = 0; i < trackGroups.length; i++) { String mimeType = trackGroups.get(i).getFormat(0).sampleMimeType; if (mimeType != null && mimeType.contains("audio")) { muteButton.setVisibility(View.VISIBLE); muteButton.setOnClickListener(view -> { if (isMute) { isMute = false; player.setVolume(1f); muteButton.setImageResource(R.drawable.ic_unmute_24dp); } else { isMute = true; player.setVolume(0f); muteButton.setImageResource(R.drawable.ic_mute_24dp); } }); break; } } } else { muteButton.setVisibility(View.GONE); } } }); } @Override public void onResume() { super.onResume(); if (wasPlaying) { player.setPlayWhenReady(true); } } @Override public void onPause() { super.onPause(); wasPlaying = player.getPlayWhenReady(); player.setPlayWhenReady(false); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(IS_MUTE_STATE, isMute); outState.putLong(POSITION_STATE, player.getCurrentPosition()); } @Override public void onDestroy() { super.onDestroy(); player.seekToDefaultPosition(); player.stop(true); player.release(); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); activity = (Activity) context; } }
[ "App.Lavishly@Gmail.com" ]
App.Lavishly@Gmail.com
ca59e58abcaa207aef9499d6eead8bc6b80f10f2
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/25/25_fac0c34f3cdcc0e6a5d85761d2efb7ecfd47a6d6/MainWindow/25_fac0c34f3cdcc0e6a5d85761d2efb7ecfd47a6d6_MainWindow_t.java
da83e6e507741cd6994d4b9bf292e47eb9867a37
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
73,977
java
/* Part of the ReplicatorG project - http://www.replicat.org Copyright (c) 2008 Zach Smith Forked from Arduino: http://www.arduino.cc Based on Processing http://www.processing.org Copyright (c) 2004-05 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: MainWindow.java 370 2008-01-19 16:37:19Z mellis $ */ package replicatorg.app.ui; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.Window; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.awt.print.PrinterJob; import java.io.File; import java.io.IOException; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.prefs.BackingStoreException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JSplitPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.filechooser.FileFilter; import javax.swing.text.BadLocationException; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.CompoundEdit; import javax.swing.undo.UndoManager; import net.miginfocom.swing.MigLayout; import org.w3c.dom.Document; import replicatorg.app.Base; import replicatorg.app.MRUList; import replicatorg.app.MachineController; import replicatorg.app.MachineFactory; import replicatorg.app.Serial; import replicatorg.app.Base.InitialOpenBehavior; import replicatorg.app.exceptions.SerialException; import replicatorg.app.syntax.JEditTextArea; import replicatorg.app.syntax.PdeKeywords; import replicatorg.app.syntax.PdeTextAreaDefaults; import replicatorg.app.syntax.SyntaxDocument; import replicatorg.app.syntax.TextAreaPainter; import replicatorg.app.ui.modeling.PreviewPanel; import replicatorg.app.util.PythonUtils; import replicatorg.app.util.SwingPythonSelector; import replicatorg.drivers.EstimationDriver; import replicatorg.drivers.MultiTool; import replicatorg.drivers.OnboardParameters; import replicatorg.drivers.SDCardCapture; import replicatorg.drivers.UsesSerial; import replicatorg.machine.MachineListener; import replicatorg.machine.MachineProgressEvent; import replicatorg.machine.MachineState; import replicatorg.machine.MachineStateChangeEvent; import replicatorg.machine.MachineToolStatusEvent; import replicatorg.model.Build; import replicatorg.model.BuildCode; import replicatorg.model.BuildElement; import replicatorg.model.BuildModel; import replicatorg.model.JEditTextAreaSource; import replicatorg.plugin.toolpath.ToolpathGenerator; import replicatorg.plugin.toolpath.ToolpathGeneratorFactory; import replicatorg.plugin.toolpath.ToolpathGeneratorThread; import replicatorg.plugin.toolpath.ToolpathGeneratorFactory.ToolpathGeneratorDescriptor; import replicatorg.uploader.FirmwareUploader; import com.apple.mrj.MRJAboutHandler; import com.apple.mrj.MRJApplicationUtils; import com.apple.mrj.MRJOpenDocumentHandler; import com.apple.mrj.MRJPrefsHandler; import com.apple.mrj.MRJQuitHandler; public class MainWindow extends JFrame implements MRJAboutHandler, MRJQuitHandler, MRJPrefsHandler, MRJOpenDocumentHandler, MachineListener, ChangeListener, ToolpathGenerator.GeneratorListener { /** * */ private static final long serialVersionUID = 4144538738677712284L; static final String WINDOW_TITLE = "ReplicatorG" + " - " + Base.VERSION_NAME; final static String MODEL_TAB_KEY = "MODEL"; final static String GCODE_TAB_KEY = "GCODE"; // p5 icon for the window Image icon; // our machines.xml document. public Document dom; MachineController machine; static public final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke .getKeyStroke('W', Toolkit.getDefaultToolkit() .getMenuShortcutKeyMask()); static final int HANDLE_NEW = 1; static final int HANDLE_OPEN = 2; static final int HANDLE_QUIT = 3; int checkModifiedMode; String handleOpenPath; boolean handleNewShift; PageFormat pageFormat; PrinterJob printerJob; MainButtonPanel buttons; CardLayout cardLayout = new CardLayout(); JPanel cardPanel = new JPanel(cardLayout); EditorHeader header = new EditorHeader(this); { header.setChangeListener(this); } MachineStatusPanel machineStatusPanel; MessagePanel console; JSplitPane splitPane; JLabel lineNumberComponent; // currently opened program public Build build; public JEditTextArea textarea; public PreviewPanel previewPanel; public SimulationThread simulationThread; public EstimationThread estimationThread; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; JMenuItem stopItem; JMenuItem pauseItem; JMenuItem controlPanelItem; JMenuItem buildMenuItem; JMenu machineMenu; MachineMenuListener machineMenuListener; public boolean building; public boolean simulating; public boolean debugging; // boolean presenting; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; public void updateUndo() { undoAction.updateUndoState(); redoAction.updateRedoState(); } // used internally, and only briefly CompoundEdit compoundEdit; FindReplace find; public Build getBuild() { return build; } private PreviewPanel getPreviewPanel() { if (previewPanel == null) { previewPanel = new PreviewPanel(this); cardPanel.add(previewPanel,MODEL_TAB_KEY); } return previewPanel; } private MRUList mruList; public MainWindow() { super(WINDOW_TITLE); setLocationByPlatform(true); MRJApplicationUtils.registerAboutHandler(this); MRJApplicationUtils.registerPrefsHandler(this); MRJApplicationUtils.registerQuitHandler(this); MRJApplicationUtils.registerOpenDocumentHandler(this); PythonUtils.setSelector(new SwingPythonSelector(this)); // load up the most recently used files list mruList = MRUList.getMRUList(); // set the window icon icon = Base.getImage("images/icon.gif", this); setIconImage(icon); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { handleQuitInternal(); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); JMenuBar menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildGCodeMenu()); menubar.add(buildMachineMenu()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); Container pane = getContentPane(); MigLayout layout = new MigLayout("nocache,fill,flowy,gap 0 0,ins 0"); pane.setLayout(layout); buttons = new MainButtonPanel(this); pane.add(buttons,"growx,dock north"); machineStatusPanel = new MachineStatusPanel(); pane.add(machineStatusPanel,"growx,dock north"); pane.add(header,"growx,dock north"); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); cardPanel.add(textarea,GCODE_TAB_KEY); console = new MessagePanel(this); console.setBorder(null); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, cardPanel, console); //splitPane.setOneTouchExpandable(true); // repaint child panes while resizing: a little heavyweight // splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(0.86); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. //splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Base.preferences.getInt("editor.divider.size",5); if (dividerSize < 5) dividerSize = 5; if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } splitPane.setPreferredSize(new Dimension(600,600)); pane.add(splitPane,"growx,growy,shrinkx,shrinky"); pack(); textarea.setTransferHandler(new TransferHandler() { private static final long serialVersionUID = 2093323078348794384L; public boolean canImport(JComponent dest, DataFlavor[] flavors) { // claim that we can import everything return true; } public boolean importData(JComponent src, Transferable transferable) { DataFlavor[] flavors = transferable.getTransferDataFlavors(); int successful = 0; for (int i = 0; i < flavors.length; i++) { try { // System.out.println(flavors[i]); // System.out.println(transferable.getTransferData(flavors[i])); Object stuff = transferable.getTransferData(flavors[i]); if (!(stuff instanceof java.util.List<?>)) continue; java.util.List<?> list = (java.util.List<?>) stuff; for (int j = 0; j < list.size(); j++) { Object item = list.get(j); if (item instanceof File) { File file = (File) item; // see if this is a .gcode file to be opened String filename = file.getName(); if (filename.endsWith(".gcode")) { handleOpenFile(file); return true; } } } } catch (Exception e) { e.printStackTrace(); return false; } } if (successful == 0) { error("No files were added to the sketch."); } else if (successful == 1) { message("One file added to the sketch."); } else { message(successful + " files added to the sketch."); } return true; } }); } // ................................................................... /** * Post-constructor setup for the editor area. Loads the last sketch that * was used (if any), and restores other MainWindow settings. The complement to * "storePreferences", this is called when the application is first * launched. */ public void restorePreferences() { if (Base.openedAtStartup != null) { handleOpen2(Base.openedAtStartup); } else { // last sketch that was in use, or used to launch the app final String prefName = "replicatorg.initialopenbehavior"; int ordinal = Base.preferences.getInt(prefName, InitialOpenBehavior.OPEN_LAST.ordinal()); final InitialOpenBehavior openBehavior = InitialOpenBehavior.values()[ordinal]; if (openBehavior == InitialOpenBehavior.OPEN_NEW) { handleNew2(true); } else { // Get last path opened; MRU keeps this. Iterator<String> i = mruList.iterator(); if (i.hasNext()) { String lastOpened = i.next(); if (new File(lastOpened).exists()) { handleOpen2(lastOpened); } else { handleNew2(true); } } else { handleNew2(true); } } } // read the preferences that are settable in the preferences window applyPreferences(); } /** * Read and apply new values from the preferences, either because the app is * just starting up, or the user just finished messing with things in the * Preferences window. */ public void applyPreferences() { // apply the setting for 'use external editor' boolean external = Base.preferences.getBoolean("editor.external",false); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); // beautifyMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Base.getColorPref("editor.external.bgcolor","#168299"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Base.getColorPref("editor.bgcolor","#ffffff"); painter.setBackground(color); boolean highlight = Base.preferences.getBoolean("editor.linehighlight",true); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor // TextAreaPainter painter = textarea.getPainter(); painter.setFont(Base.getFontPref("editor.font","Monospaced,plain,10")); // Font font = painter.getFont(); // textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case moved to a new location // For 0125, changing to async version (to be implemented later) // sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } /** * Store preferences about the editor's current state. Called when the * application is quitting. */ public void storePreferences() { // System.out.println("storing preferences"); // window location information Rectangle bounds = getBounds(); Base.preferences.putInt("last.window.x", bounds.x); Base.preferences.putInt("last.window.y", bounds.y); Base.preferences.putInt("last.window.width", bounds.width); Base.preferences.putInt("last.window.height", bounds.height); // last sketch that was in use // Preferences.set("last.sketch.name", sketchName); // Preferences.set("last.sketch.name", sketch.name); if (build != null) { String lastPath = build.getMainFilePath(); if (lastPath != null) { Base.preferences.put("last.sketch.path", build.getMainFilePath()); } } // location for the console/editor area divider int location = splitPane.getDividerLocation(); Base.preferences.putInt("last.divider.location", location); try { Base.preferences.flush(); } catch (BackingStoreException bse) { // Not much we can do about this, so let it go with a stack // trace. bse.printStackTrace(); } } public void runToolpathGenerator() { // Check for modified STL if (build.getModel().isModified()) { final String message = "<html>You have made changes to this model. Any unsaved changes will<br>" + "not be reflected in the generated toolpath.<br>" + "Save the model now?</html>"; int option = JOptionPane.showConfirmDialog(this, message, "Save model?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.CANCEL_OPTION) { return; } if (option == JOptionPane.YES_OPTION) { // save model handleSave(true); } } ToolpathGenerator generator = ToolpathGeneratorFactory.createSelectedGenerator(); ToolpathGeneratorThread tgt = new ToolpathGeneratorThread(this, generator, build); tgt.addListener(this); tgt.start(); } // ................................................................... private JMenu serialMenu = null; private void reloadSerialMenu() { if (serialMenu == null) return; serialMenu.removeAll(); if (machine == null) { JMenuItem item = new JMenuItem("No machine selected."); item.setEnabled(false); serialMenu.add(item); return; } else if (!(machine.driver instanceof UsesSerial)) { JMenuItem item = new JMenuItem("Currently selected machine does not use a serial port."); item.setEnabled(false); serialMenu.add(item); return; } String currentName = null; UsesSerial us = (UsesSerial)machine.driver; if (us.getSerial() != null) { currentName = us.getSerial().getName(); } else { currentName = Base.preferences.get("serial.last_selected", null); } Vector<Serial.Name> names = Serial.scanSerialNames(); Collections.sort(names); ButtonGroup radiogroup = new ButtonGroup(); for (Serial.Name name : names) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(name.toString()); item.setEnabled(name.isAvailable()); item.setSelected(name.getName().equals(currentName)); final String portName = name.getName(); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Thread t = new Thread() { public void run() { try { UsesSerial us = (UsesSerial)machine.driver; if (us != null) synchronized(us) { us.setSerial(new Serial(portName, us)); Base.preferences.put("serial.last_selected", portName); machine.reset(); } } catch (SerialException se) { se.printStackTrace(); } } }; t.start(); } }); radiogroup.add(item); serialMenu.add(item); } if (names.isEmpty()) { JMenuItem item = new JMenuItem("No serial ports detected"); item.setEnabled(false); serialMenu.add(item); } serialMenu.addSeparator(); JMenuItem item = new JMenuItem("Rescan serial ports"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reloadSerialMenu(); } }); serialMenu.add(item); } private JMenu mruMenu = null; private void reloadMruMenu() { if (mruMenu == null) { return; } mruMenu.removeAll(); class FileOpenActionListener implements ActionListener { public String path; FileOpenActionListener(String path) { this.path = path; } public void actionPerformed(ActionEvent e) { handleOpen(path); } } if (mruList != null) { int index = 0; for (String fileName : mruList) { String entry = Integer.toString(index) + ". " + fileName.substring(fileName.lastIndexOf('/') + 1); JMenuItem item = new JMenuItem(entry, KeyEvent.VK_0 + index); item.addActionListener(new FileOpenActionListener(fileName)); mruMenu.add(item); index = index + 1; if (index >= 9) { break; } } } } protected JMenu buildFileMenu() { JMenuItem item; JMenu menu = new JMenu("File"); item = newJMenuItem("New", 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleNew(false); } }); menu.add(item); item = newJMenuItem("Open...", 'O', false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleOpen(null); } }); menu.add(item); saveMenuItem = newJMenuItem("Save", 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); menu.add(saveMenuItem); saveAsMenuItem = newJMenuItem("Save As...", 'S', true); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); menu.add(saveAsMenuItem); menu.addSeparator(); mruMenu = new JMenu("Recent"); reloadMruMenu(); menu.add(mruMenu); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { menu.addSeparator(); item = newJMenuItem("Preferences", ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrefs(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Quit", 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleQuitInternal(); } }); menu.add(item); } return menu; } protected JMenu buildGCodeMenu() { JMenuItem item; JMenu menu = new JMenu("GCode"); item = newJMenuItem("Estimate", 'E'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleEstimate(); } }); menu.add(item); item = newJMenuItem("Simulate", 'L'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSimulate(); } }); menu.add(item); buildMenuItem = newJMenuItem("Build", 'B'); buildMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleBuild(); } }); menu.add(buildMenuItem); pauseItem = newJMenuItem("Pause", 'E'); pauseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePause(); } }); pauseItem.setEnabled(false); menu.add(pauseItem); stopItem = newJMenuItem("Stop", '.'); stopItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleStop(); } }); stopItem.setEnabled(false); menu.add(stopItem); // GENERATOR JMenu genMenu = new JMenu("Choose GCode generator"); Vector<ToolpathGeneratorDescriptor> generators = ToolpathGeneratorFactory.getGeneratorList(); String name = ToolpathGeneratorFactory.getSelectedName(); ButtonGroup group = new ButtonGroup(); for (ToolpathGeneratorDescriptor tgd : generators) { JRadioButtonMenuItem i = new JRadioButtonMenuItem(tgd.name); group.add(i); final String n = tgd.name; i.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ToolpathGeneratorFactory.setSelectedName(n); } }); if (name.equals(tgd.name)) { i.setSelected(true); } genMenu.add(i); } menu.add(genMenu); return menu; } JMenuItem onboardParamsItem = new JMenuItem("Motherboard Onboard Preferences..."); JMenuItem extruderParamsItem = new JMenuItem("Toolhead Onboard Preferences..."); JMenuItem toolheadIndexingItem = new JMenuItem("Set Toolhead Index..."); protected JMenu buildMachineMenu() { JMenuItem item; JMenu menu = new JMenu("Machine"); machineMenu = new JMenu("Driver"); populateMachineMenu(); menu.add(machineMenu); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) { } public void menuDeselected(MenuEvent e) { } public void menuSelected(MenuEvent e) { populateMachineMenu(); } }); machineMenuListener = new MachineMenuListener(); serialMenu = new JMenu("Serial Port"); reloadSerialMenu(); menu.add(serialMenu); controlPanelItem = new JMenuItem("Control Panel", 'C'); controlPanelItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J,ActionEvent.CTRL_MASK)); controlPanelItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleControlPanel(); } }); menu.add(controlPanelItem); onboardParamsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { handleOnboardPrefs(); } }); onboardParamsItem.setVisible(false); menu.add(onboardParamsItem); extruderParamsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { handleExtruderPrefs(); } }); extruderParamsItem.setVisible(false); menu.add(extruderParamsItem); toolheadIndexingItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { handleToolheadIndexing(); } }); toolheadIndexingItem.setVisible(false); menu.add(toolheadIndexingItem); item = new JMenuItem("Upload new firmware..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { FirmwareUploader.startUploader(MainWindow.this); } }); menu.add(item); return menu; } protected void handleToolheadIndexing() { if (machine == null || !(machine.driver instanceof MultiTool)) { JOptionPane.showMessageDialog( this, "ReplicatorG can't connect to your machine or toolhead index setting is not supported.\nTry checking your settings and resetting your machine.", "Can't run toolhead indexing", JOptionPane.ERROR_MESSAGE); } else { ToolheadIndexer indexer = new ToolheadIndexer(this,machine.driver); indexer.setVisible(true); } } class MachineMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (machineMenu == null) { System.out.println("machineMenu is null"); return; } int count = machineMenu.getItemCount(); for (int i = 0; i < count; i++) { ((JCheckBoxMenuItem) machineMenu.getItem(i)).setState(false); } JCheckBoxMenuItem item = (JCheckBoxMenuItem) e.getSource(); item.setState(true); final String name = item.getText(); Base.preferences.put("machine.name", name); // load it and set it. Thread t = new Thread() { public void run() { loadMachine(name, (machine != null) && machine.getMachineState().isConnected()); } }; t.start(); } } protected void populateMachineMenu() { machineMenu.removeAll(); boolean empty = true; try { for (String name : MachineFactory.getMachineNames() ) { JMenuItem rbMenuItem = new JCheckBoxMenuItem(name, name.equals(Base.preferences .get("machine.name",null))); rbMenuItem.addActionListener(machineMenuListener); machineMenu.add(rbMenuItem); empty = false; } if (!empty) { // System.out.println("enabling the machineMenu"); machineMenu.setEnabled(true); } } catch (Exception exception) { System.out.println("error retrieving machine list"); exception.printStackTrace(); } if (machineMenu.getItemCount() == 0) machineMenu.setEnabled(false); } protected JMenu buildHelpMenu() { JMenu menu = new JMenu("Help"); JMenuItem item; if (!Base.isLinux()) { item = newJMenuItem("Getting Started", '1'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/getting-started"); } }); menu.add(item); } item = newJMenuItem("Hardware Setup", '2'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/hardware"); } }); menu.add(item); item = newJMenuItem("Troubleshooting", '3'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/troubleshooting"); } }); menu.add(item); item = newJMenuItem("Reference", '4'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/reference"); } }); menu.add(item); item = newJMenuItem("Frequently Asked Questions", '5'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/faq"); } }); menu.add(item); item = newJMenuItem("Visit Replicat.orG", '6'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL("http://www.replicat.org/"); } }); menu.add(item); // macosx already has its own about menu menu.addSeparator(); JMenuItem aboutitem = new JMenuItem("About ReplicatorG"); aboutitem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleAbout(); } }); menu.add(aboutitem); return menu; } public JMenu buildEditMenu() { JMenu menu = new JMenu("Edit"); JMenuItem item; undoItem = newJMenuItem("Undo", 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); redoItem = newJMenuItem("Redo", 'Y'); redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem("Cut", 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); build.getCode().setModified(true); } }); menu.add(item); item = newJMenuItem("Copy", 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItem("Paste", 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); build.getCode().setModified(true); } }); menu.add(item); item = newJMenuItem("Select All", 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem("Find...", 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(MainWindow.this); } // new FindReplace(MainWindow.this).setVisible(true); find.setVisible(true); // find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem("Find Next", 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { // find.find(true); // FindReplace find = new FindReplace(MainWindow.this); // //.setVisible(true); find.find(true); } } }); menu.add(item); return menu; } /** * Convenience method, see below. */ static public JMenuItem newJMenuItem(String title, int what) { return newJMenuItem(title, what, false); } /** * A software engineer, somewhere, needs to have his abstraction taken away. * In some countries they jail or beat people for writing the sort of API * that would require a five line helper function just to set the command * key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what, boolean shift) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if (shift) modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } // ................................................................... class UndoAction extends AbstractAction { private static final long serialVersionUID = 7800704765553895387L; public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { if (currentElement == null) { return; } currentElement.getUndoManager().undo(); } catch (CannotUndoException ex) { // System.out.println("Unable to undo: " + ex); // ex.printStackTrace(); } updateUndo(); } protected void updateUndoState() { if (currentElement == null) { return; } UndoManager undo = currentElement.getUndoManager(); boolean canUndo = undo.canUndo(); this.setEnabled(canUndo); undoItem.setEnabled(canUndo); currentElement.setModified(canUndo); if (canUndo) { undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); } else { undoItem.setText("Undo"); putValue(Action.NAME, "Undo"); } } } class RedoAction extends AbstractAction { private static final long serialVersionUID = -2427139178653072745L; public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { currentElement.getUndoManager().redo(); } catch (CannotRedoException ex) { // System.out.println("Unable to redo: " + ex); // ex.printStackTrace(); } updateUndo(); } protected void updateRedoState() { if (currentElement == null) { return; } UndoManager undo = currentElement.getUndoManager(); if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText("Redo"); putValue(Action.NAME, "Redo"); } } } // ................................................................... // interfaces for MRJ Handlers, but naming is fine // so used internally for everything else public void handleAbout() { final Image image = Base.getImage("images/about.png", this); int w = image.getWidth(this); int h = image.getHeight(this); final Window window = new Window(this) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setFont(new Font("SansSerif", Font.PLAIN, 13)); g.setColor(Color.black); FontMetrics fm = g.getFontMetrics(); String version = Base.VERSION_NAME; Rectangle2D r = fm.getStringBounds(version,g); g.drawString(version, (int)(364-r.getWidth()), (int)(95-r.getMinY())); AttributedString text = new AttributedString("\u00a9 2008, 2009, 2010 by Zach Smith, Adam Mayer, and numerous contributors. " + "See Contributors.txt for a full list. \n\r" + "This program is free software; you can redistribute it and/or modify "+ "it under the terms of the GNU General Public License as published by "+ "the Free Software Foundation; either version 2 of the License, or "+ "(at your option) any later version."); AttributedCharacterIterator iterator = text.getIterator(); FontRenderContext frc = g2.getFontRenderContext(); LineBreakMeasurer measurer = new LineBreakMeasurer(text.getIterator(), frc); measurer.setPosition(iterator.getBeginIndex()); final int margins = 32; float wrappingWidth = image.getWidth(this) - (margins*2); float x = margins; float y = 140; while (measurer.getPosition() < iterator.getEndIndex()) { TextLayout layout = measurer.nextLayout(wrappingWidth); y += (layout.getAscent()); layout.draw(g2, x, y); y += layout.getDescent() + layout.getLeading(); } } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width - w) / 2, (screen.height - h) / 2, w, h); window.setVisible(true); } public void handleControlPanel() { if (machine == null) { JOptionPane.showMessageDialog( this, "ReplicatorG can't connect to your machine.\nTry checking your settings and resetting your machine.", "Can't find machine", JOptionPane.ERROR_MESSAGE); } else { ControlPanelWindow window = ControlPanelWindow.getControlPanel(machine); if (window != null) { window.pack(); window.setVisible(true); window.toFront(); } } } public void handleDisconnect() { if (machine == null) { // machine already disconnected } else { if (machine.driver instanceof UsesSerial) { UsesSerial us = (UsesSerial)machine.driver; us.setSerial(null); } machine.disconnect(); } } public void handleConnect() { if (machine != null && machine.getMachineState().getState() != MachineState.State.NOT_ATTACHED) { // Already connected, ignore } else { String name = Base.preferences.get("machine.name", null); if ( name != null ) { loadMachine(name, true); } } } public void handleOnboardPrefs() { if (machine == null || !(machine.driver instanceof OnboardParameters)) { JOptionPane.showMessageDialog( this, "ReplicatorG can't connect to your machine or onboard preferences are not supported.\nTry checking your settings and resetting your machine.", "Can't run onboard prefs", JOptionPane.ERROR_MESSAGE); } else { MachineOnboardParameters moo = new MachineOnboardParameters((OnboardParameters)machine.driver,machine.driver); moo.setVisible(true); } } public void handleExtruderPrefs() { if (machine == null || !(machine.driver instanceof OnboardParameters)) { JOptionPane.showMessageDialog( this, "ReplicatorG can't connect to your machine or onboard preferences are not supported.\nTry checking your settings and resetting your machine.", "Can't run onboard prefs", JOptionPane.ERROR_MESSAGE); } else { ExtruderOnboardParameters eop = new ExtruderOnboardParameters((OnboardParameters)machine.driver); eop.setVisible(true); } } /** * Show the preferences window. */ public void handlePrefs() { PreferencesWindow preferences = new PreferencesWindow(); preferences.showFrame(this); } // ................................................................... /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Called to update the text but not switch to a different set of code * (which would affect the undo manager). */ public void setText(String what, int selectionStart, int selectionEnd) { beginCompoundEdit(); textarea.setText(what); endCompoundEdit(); // make sure that a tool isn't asking for a bad location selectionStart = Math.max(0, Math.min(selectionStart, textarea .getDocumentLength())); selectionEnd = Math.max(0, Math.min(selectionStart, textarea .getDocumentLength())); textarea.select(selectionStart, selectionEnd); textarea.requestFocus(); // get the caret blinking } /** * Switch between tabs, this swaps out the Document object that's currently * being manipulated. */ public void setCode(BuildCode code) { if (code == null) return; if (code.document == null) { // this document not yet inited code.document = new SyntaxDocument(); // turn on syntax highlighting code.document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { code.document.insertString(0, code.program, null); } catch (BadLocationException bl) { bl.printStackTrace(); } final UndoManager undo = code.getUndoManager(); // connect the undo listener to the editor code.document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); updateUndo(); } } }); } // update the document object that's in use textarea.setDocument(code.document, code.selectionStart, code.selectionStop, code.scrollPosition); textarea.requestFocus(); // get the caret blinking } public void setModel(BuildModel model) { if (model != null) { getPreviewPanel().setModel(model); } } public void beginCompoundEdit() { compoundEdit = new CompoundEdit(); } public void endCompoundEdit() { compoundEdit.end(); currentElement.getUndoManager().addEdit(compoundEdit); updateUndo(); compoundEdit = null; } // ................................................................... public void handleEstimate() { if (building) return; if (simulating) return; // load our simulator machine // loadSimulator(); // fire off our thread. estimationThread = new EstimationThread(this); estimationThread.start(); } public void handleSimulate() { if (building) return; if (simulating) return; // buttons/status. simulating = true; //buttons.activate(MainButtonPanel.SIMULATE); // load our simulator machine // loadSimulator(); setEditorBusy(true); // fire off our thread. simulationThread = new SimulationThread(this); simulationThread.start(); } // synchronized public void simulationOver() public void simulationOver() { message("Done simulating."); simulating = false; setEditorBusy(false); } // synchronized public void handleBuild() public void handleBuild() { if (building) return; if (simulating) return; if (machine == null) { Base.logger.severe("Not ready to build yet."); } else { // build specific stuff building = true; //buttons.activate(MainButtonPanel.BUILD); setEditorBusy(true); // start our building thread. message("Building..."); buildStart = new Date(); machine.execute(); } } public void handleUpload() { if (building) return; if (simulating) return; if (machine == null || machine.driver == null || !(machine.driver instanceof SDCardCapture)) { Base.logger.severe("Not ready to build yet."); } else { BuildNamingDialog bsd = new BuildNamingDialog(this,build.getName()); bsd.setVisible(true); String path = bsd.getPath(); if (path != null) { // build specific stuff building = true; //buttons.activate(MainButtonPanel.BUILD); setEditorBusy(true); // start our building thread. message("Uploading..."); buildStart = new Date(); machine.upload(path); } } } // We can drop this in Java 6, which already has an equivalent private class ExtensionFilter extends FileFilter { private LinkedList<String> extensions = new LinkedList<String>(); private String description; public ExtensionFilter(String extension,String description) { this.extensions.add(extension); this.description = description; } public ExtensionFilter(String[] extensions,String description) { for (String e : extensions) { this.extensions.add(e); } this.description = description; } public boolean accept(File f) { if (f.isDirectory()) { return !f.isHidden(); } for (String extension : extensions) { if (f.getPath().toLowerCase().endsWith(extension)) { return true; } } return false; } public String getDescription() { return description; } }; private String selectOutputFile(String defaultName) { File directory = null; String loadDir = Base.preferences.get("ui.open_output_dir", null); if (loadDir != null) { directory = new File(loadDir); } JFileChooser fc = new JFileChooser(directory); fc.setFileFilter(new ExtensionFilter(".s3g","Makerbot build file")); fc.setDialogTitle("Save Makerbot build as..."); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setFileHidingEnabled(false); fc.setSelectedFile(new File(directory,defaultName)); int rv = fc.showSaveDialog(this); if (rv == JFileChooser.APPROVE_OPTION) { fc.getSelectedFile().getName(); Base.preferences.put("ui.open_output_dir",fc.getCurrentDirectory().getAbsolutePath()); return fc.getSelectedFile().getAbsolutePath(); } else { return null; } } public void handleBuildToFile() { if (building) return; if (simulating) return; if (machine == null || machine.driver == null || !(machine.driver instanceof SDCardCapture)) { Base.logger.severe("Not ready to build yet."); } else { String sourceName = build.getName() + ".s3g"; String path = selectOutputFile(sourceName); if (path != null) { // build specific stuff building = true; //buttons.activate(MainButtonPanel.BUILD); setEditorBusy(true); // start our building thread. buildStart = new Date(); machine.buildToFile(path); } } } public void handlePlayback() { if (building) return; if (simulating) return; if (machine == null || machine.driver == null || !(machine.driver instanceof SDCardCapture)) { Base.logger.severe("Not ready to build yet."); } else { SDCardCapture sdcc = (SDCardCapture)machine.driver; List<String> files = sdcc.getFileList(); //for (String filename : files) { System.out.println("File "+filename); } BuildSelectionDialog bsd = new BuildSelectionDialog(this,files); bsd.setVisible(true); String path = bsd.getSelectedPath(); Base.logger.info("Selected path is "+path); if (path != null) { // build specific stuff building = true; //buttons.activate(MainButtonPanel.BUILD); setEditorBusy(true); // start our building thread. message("Building..."); buildStart = new Date(); machine.buildRemote(path); } } } private Date buildStart = null; public void machineStateChanged(MachineStateChangeEvent evt) { boolean hasGcode = getBuild().getCode() != null; if (building) { if (evt.getState().isReady() || evt.getState().getState() == MachineState.State.STOPPING) { final MachineState endState = evt.getState(); building = false; SwingUtilities.invokeLater(new Runnable() { public void run() { if (endState.isReady()) { notifyBuildComplete(buildStart, new Date()); } else { notifyBuildAborted(buildStart, new Date()); } buildingOver(); } }); } else if (evt.getState().getState() == MachineState.State.NOT_ATTACHED) { building = false; // Don't keep the building state when disconnecting from the machine } } if (evt.getState().isReady()) { reloadSerialMenu(); } boolean showParams = evt.getState().isReady() && machine != null && machine.getDriver() instanceof OnboardParameters && ((OnboardParameters)machine.getDriver()).hasFeatureOnboardParameters(); // enable the control panel menu item when the machine is ready controlPanelItem.setEnabled(evt.getState().isReady()); // enable the build menu item when the machine is ready and there is gcode in the editor buildMenuItem.setEnabled(hasGcode && evt.getState().isReady()); onboardParamsItem.setVisible(showParams); extruderParamsItem.setVisible(showParams); boolean showIndexing = evt.getState().isReady() && machine != null && machine.getDriver() instanceof MultiTool && ((MultiTool)machine.getDriver()).toolsCanBeReindexed(); toolheadIndexingItem.setVisible(showIndexing); // Advertise machine name String name = "Not Connected"; if (evt.getState().isConnected() && machine != null) { name = machine.getName(); } if (name != null) { this.setTitle(name + " - " + WINDOW_TITLE); } else { this.setTitle(WINDOW_TITLE); } } public void setEditorBusy(boolean isBusy) { // variables and stuff. stopItem.setEnabled(isBusy); pauseItem.setEnabled(isBusy); // clear the console on each build, unless the user doesn't want to if (isBusy && Base.preferences.getBoolean("console.auto_clear",true)) { console.clear(); } // prepare editor window. setVisible(true); textarea.setEnabled(!isBusy); textarea.setEditable(!isBusy); if (isBusy) { textarea.selectNone(); textarea.scrollTo(0, 0); } else { //buttons.clear(); } } /** * give a prompt and stuff about the build being done with elapsed time, * etc. */ private void notifyBuildComplete(Date started, Date finished) { assert started != null; assert finished != null; long elapsed = finished.getTime() - started.getTime(); String message = "Build finished.\n\n"; message += "Completed in " + EstimationDriver.getBuildTimeString(elapsed); Base.showMessage("Build finished", message); } private void notifyBuildAborted(Date started, Date aborted) { assert started != null; assert aborted != null; long elapsed = aborted.getTime() - started.getTime(); String message = "Build aborted.\n\n"; message += "Stopped after " + EstimationDriver.getBuildTimeString(elapsed); Base.showMessage("Build aborted", message); } // synchronized public void buildingOver() public void buildingOver() { message("Done building."); // re-enable the gui and shit. textarea.setEnabled(true); building = false; if (machine != null) { if (machine.getSimulatorDriver() != null) machine.getSimulatorDriver().destroyWindow(); } else { } setEditorBusy(false); } class SimulationThread extends Thread { MainWindow editor; public SimulationThread(MainWindow edit) { super("Simulation Thread"); editor = edit; } public void run() { message("Simulating..."); machine.simulate(); EventQueue.invokeLater(new Runnable() { public void run() { simulationOver(); } }); } } public void handleStop() { // if (building || simulating) // can also be called during panel ops // called by menu or buttons doStop(); setEditorBusy(false); } class EstimationThread extends Thread { MainWindow editor; public EstimationThread(MainWindow edit) { super("Estimation Thread"); editor = edit; } public void run() { message("Estimating..."); machine.estimate(); editor.estimationOver(); } } public void estimationOver() { // stopItem.setEnabled(false); // pauseItem.setEnabled(false); //buttons.clear(); } /** * Stop the build. */ public void doStop() { if (machine != null) { machine.stop(); } building = false; simulating = false; } public void handleReset() { if (machine != null) { machine.reset(); } } public void handlePause() { // called by menu or buttons // if (building || simulating) // can also be used during control panel // ops doPause(); } /** * Pause the applet but don't kill its window. */ public void doPause() { if (machine.isPaused()) { machine.unpause(); if (simulating) { //buttons.activate(MainButtonPanel.SIMULATE); message("Simulating..."); } else if (building) { //buttons.activate(MainButtonPanel.BUILD); message("Building..."); } //buttons.inactivate(MainButtonPanel.PAUSE); } else { message("Paused."); machine.pause(); //buttons.clear(); //buttons.activate(MainButtonPanel.PAUSE); } } /** * Check to see if there have been changes. If so, prompt user whether or * not to save first. If the user cancels, just ignore. Otherwise, one of * the other methods will handle calling checkModified2() which will get on * with business. */ protected void checkModified(int checkModifiedMode) { this.checkModifiedMode = checkModifiedMode; if (build == null || !build.hasModifiedElements()) { checkModified2(); return; } String prompt = "Save changes to " + build.getName() + "? "; if (!Base.isMacOS() || Base.javaVersion < 1.5f) { int result = JOptionPane.showConfirmDialog(this, prompt, "Quit", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { handleSave(true); checkModified2(); } else if (result == JOptionPane.NO_OPTION) { checkModified2(); } // cancel is ignored altogether } else { // This code is disabled unless Java 1.5 is being used on Mac OS // X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude // about it! // adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">" + "b { font: 13pt \"Lucida Grande\" }" + "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }" + "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this // option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and quit) handleSave(true); checkModified2(); } else if (result == options[2]) { // don't save (still quit) checkModified2(); } } } protected boolean confirmBuildAbort() { if (machine != null && machine.getMachineState().getState() == MachineState.State.BUILDING) { final String message = "<html>You are currently printing from ReplicatorG! Your build will be stopped.<br>" + "Continue and abort print?</html>"; int option = JOptionPane.showConfirmDialog(this, message, "Abort print?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option == JOptionPane.CANCEL_OPTION) { return false; } } return true; } /** * Called by EditorStatus to complete the job and re-dispatch to handleNew, * handleOpen, handleQuit. */ public void checkModified2() { // This is as good a place as any to check that we don't have an in-progress manual build // that could be killed. if (!confirmBuildAbort()) return; switch (checkModifiedMode) { case HANDLE_NEW: handleNew2(false); break; case HANDLE_OPEN: handleOpen2(handleOpenPath); break; case HANDLE_QUIT: System.exit(0); break; } checkModifiedMode = 0; } /** * New was called (by buttons or by menu), first check modified and if * things work out ok, handleNew2() will be called. <p/> If shift is pressed * when clicking the toolbar button, then force the opposite behavior from * sketchbook.prompt's setting */ public void handleNew(final boolean shift) { //buttons.activate(MainButtonPanel.NEW); SwingUtilities.invokeLater(new Runnable() { public void run() { handleNewShift = shift; checkModified(HANDLE_NEW); } }); } /** * Extra public method so that Sketch can call this when a sketch is * selected to be deleted, and it won't call checkModified() to prompt for * save as. */ public void handleNewUnchecked() { handleNewShift = false; handleNew2(true); } /** * Does all the plumbing to create a new project then calls handleOpen to * load it up. * * @param noPrompt * true to disable prompting for the sketch name, used when the * app is starting (auto-create a sketch) */ protected void handleNew2(boolean noPrompt) { // try { //String pdePath = sketchbook.handleNew(noPrompt, handleNewShift); //if (pdePath != null) // handleOpen2(pdePath); // } catch (IOException e) { // // not sure why this would happen, but since there's no way to // // recover (outside of creating another new setkch, which might // // just cause more trouble), then they've gotta quit. // Base.showError("Problem creating a new sketch", // "An error occurred while creating\n" // + "a new sketch. ReplicatorG must now quit.", e); // } handleOpen2(null); //buttons.clear(); } /** * This is the implementation of the MRJ open document event, and the * Windows XP open document will be routed through this too. */ public void handleOpenFile(File file) { // System.out.println("handling open file: " + file); handleOpen(file.getAbsolutePath()); } private String selectFile() { File directory = null; String loadDir = Base.preferences.get("ui.open_dir", null); if (loadDir != null) { directory = new File(loadDir); } JFileChooser fc = new JFileChooser(directory); FileFilter defaultFilter; String[] extensions = {".gcode",".stl"}; fc.addChoosableFileFilter(defaultFilter = new ExtensionFilter(extensions,"GCode or STL files")); fc.addChoosableFileFilter(new ExtensionFilter(".gcode","GCode files")); fc.addChoosableFileFilter(new ExtensionFilter(".stl","STL files")); fc.addChoosableFileFilter(new ExtensionFilter(".obj","OBJ files (experimental)")); fc.addChoosableFileFilter(new ExtensionFilter(".dae","Collada files (experimental)")); fc.setAcceptAllFileFilterUsed(true); fc.setFileFilter(defaultFilter); fc.setDialogTitle("Open a gcode or model file..."); fc.setDialogType(JFileChooser.OPEN_DIALOG); fc.setFileHidingEnabled(false); int rv = fc.showOpenDialog(this); if (rv == JFileChooser.APPROVE_OPTION) { fc.getSelectedFile().getName(); Base.preferences.put("ui.open_dir",fc.getCurrentDirectory().getAbsolutePath()); return fc.getSelectedFile().getAbsolutePath(); } else { return null; } } /** * Open a sketch given the full path to the .gcode file. Pass in 'null' to * prompt the user for the name of the sketch. */ public void handleOpen(final String ipath) { // haven't run across a case where i can verify that this works // because open is usually very fast. // buttons.activate(MainButtonPanel.OPEN); SwingUtilities.invokeLater(new Runnable() { public void run() { String path = ipath; if (path == null) { // "open..." selected from the menu path = selectFile(); if (path == null) return; } Base.logger.info("Loading "+path); handleOpenPath = path; checkModified(HANDLE_OPEN); } }); } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ public void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { handleOpen2(path); setCode(build.getCode()); textarea.select(selStart, selStop); // textarea.updateScrollBars(); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected void handleOpen2(String path) { if (path != null && !new File(path).exists()) { JOptionPane.showMessageDialog(this, "The file "+path+" could not be found.", "File not found", JOptionPane.ERROR_MESSAGE); return; } try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // loading may take a few moments for large files build = new Build(this, path); setCode(build.getCode()); setModel(build.getModel()); updateBuild(); buttons.updateFromMachine(machine); if (null != path) { handleOpenPath = path; mruList.update(path); reloadMruMenu(); } if (Base.preferences.getBoolean("console.auto_clear",false)) { console.clear(); } } catch (Exception e) { error(e); } finally { this.setCursor(Cursor.getDefaultCursor()); } } /** * Actually handle the save command. If 'force' is set to false, this will * happen in another thread so that the message area will update and the * save button will stay highlighted while the save is happening. If 'force' * is true, then it will happen immediately. This is used during a quit, * because invokeLater() won't run properly while a quit is happening. */ public void handleSave(boolean force) { Runnable saveWork = new Runnable() { public void run() { Base.logger.info("Saving..."); try { if (build.save()) { Base.logger.info("Save operation complete."); } else { Base.logger.info("Save operation aborted."); } } catch (IOException e) { // show the error as a message in the window error(e); // zero out the current action, // so that checkModified2 will just do nothing checkModifiedMode = 0; // this is used when another operation calls a save } } }; if (force) { saveWork.run(); } else { SwingUtilities.invokeLater(saveWork); } } public void handleSaveAs() { SwingUtilities.invokeLater(new Runnable() { public void run() { // TODO: lock sketch? Base.logger.info("Saving..."); try { if (build.saveAs()) { updateBuild(); Base.logger.info("Save operation complete."); mruList.update(build.getMainFilePath()); // TODO: Add to MRU? } else { Base.logger.info("Save operation aborted."); } } catch (IOException e) { // show the error as a message in the window error(e); } } }); } /** * Quit, but first ask user if it's ok. Also store preferences to disk just * in case they want to quit. Final exit() happens in MainWindow since it has * the callback from EditorStatus. */ public void handleQuitInternal() { if (!confirmBuildAbort()) return; try { if (simulationThread != null) { simulationThread.interrupt(); simulationThread.join(); } if (estimationThread != null) { estimationThread.interrupt(); estimationThread.join(); } } catch (InterruptedException e) { assert (false); } // cleanup our machine/driver. if (machine != null) { machine.dispose(); machine = null; } checkModified(HANDLE_QUIT); } /** * Method for the MRJQuitHandler, needs to be dealt with differently than * the regular handler because OS X has an annoying implementation <A * HREF="http://developer.apple.com/qa/qa2001/qa1187.html">quirk</A> that * requires an exception to be thrown in order to properly cancel a quit * message. */ public void handleQuit() { SwingUtilities.invokeLater(new Runnable() { public void run() { handleQuitInternal(); } }); // Throw IllegalStateException so new thread can execute. // If showing dialog on this thread in 10.2, we would throw // upon JOptionPane.NO_OPTION throw new IllegalStateException("Quit Pending User Confirmation"); } /** * Clean up files and store UI preferences on shutdown. This is called by * the shutdown hook and will be run in virtually all shutdown scenarios. * Because it is used in a shutdown hook, there is no reason to call this * method explicit.y */ public void onShutdown() { storePreferences(); console.handleQuit(); } protected void handleReference() { String text = textarea.getSelectedText().trim(); if (text.length() == 0) { message("First select a word to find in the reference."); } else { String referenceFile = PdeKeywords.getReference(text); // System.out.println("reference file is " + referenceFile); if (referenceFile == null) { message("No reference available for \"" + text + "\""); } else { Base.showReference(referenceFile + ".html"); } } } public void highlightLine(int lnum) { if (lnum < 0) { textarea.select(0, 0); return; } // System.out.println(lnum); String s = textarea.getText(); int len = s.length(); int st = -1; int ii = 0; int end = -1; int lc = 0; if (lnum == 0) st = 0; for (int i = 0; i < len; i++) { ii++; // if ((s.charAt(i) == '\n') || (s.charAt(i) == '\r')) { boolean newline = false; if (s.charAt(i) == '\r') { if ((i != len - 1) && (s.charAt(i + 1) == '\n')) { i++; // ii--; } lc++; newline = true; } else if (s.charAt(i) == '\n') { lc++; newline = true; } if (newline) { if (lc == lnum) st = ii; else if (lc == lnum + 1) { // end = ii; // to avoid selecting entire, because doing so puts the // cursor on the next line [0090] end = ii - 1; break; } } } if (end == -1) end = len; // sometimes KJC claims that the line it found an error in is // the last line in the file + 1. Just highlight the last line // in this case. [dmose] if (st == -1) st = len; textarea.select(st, end); } // ................................................................... /** * Show an error int the status bar. */ public void error(String what) { Base.logger.severe(what); } public void error(Exception e) { if (e == null) { Base.logger.severe("MainWindow.error() was passed a null exception."); return; } // not sure if any RuntimeExceptions will actually arrive // through here, but gonna check for em just in case. String mess = e.getMessage(); if (mess != null) { String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } } Base.logger.log(Level.SEVERE,mess,e); } public void message(String msg) { Base.logger.info(msg); } // ................................................................... /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { // String currentDir = System.getProperty("user.dir"); String referenceFile = null; JMenuItem cutItem, copyItem; JMenuItem referenceItem; public TextAreaPopup() { JMenuItem item; cutItem = new JMenuItem("Cut"); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.cut(); build.getCode().setModified(true); } }); this.add(cutItem); copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); this.add(copyItem); item = new JMenuItem("Paste"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); build.getCode().setModified(true); } }); this.add(item); item = new JMenuItem("Select All"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); this.add(item); this.addSeparator(); referenceItem = new JMenuItem("Find in Reference"); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Base.showReference(referenceFile + ".html"); handleReference(); // textarea.getSelectedText()); } }); this.add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); String sel = textarea.getSelectedText().trim(); referenceFile = PdeKeywords.getReference(sel); referenceItem.setEnabled(referenceFile != null); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); referenceItem.setEnabled(false); } super.show(component, x, y); } } protected void setMachine(MachineController machine) { if (this.machine != machine) { if (this.machine != null) { this.machine.dispose(); } this.machine = machine; if (machine != null) { machine.setCodeSource(new JEditTextAreaSource(textarea)); machine.setMainWindow(this); machine.addMachineStateListener(this); machine.addMachineStateListener(machineStatusPanel); machine.addMachineStateListener(buttons); } } if (machine == null) { // Buttons will need an explicit null state notification buttons.machineStateChanged(new MachineStateChangeEvent(null, new MachineState())); } machineStatusPanel.setMachine(this.machine); // TODO: PreviewPanel: update with new machine } public MachineController getMachine(){ return this.machine; } /** * * @param name name of the machine * @param connect auto-connect on load. Usually true, but can be set to false to avoid talking on the serial port */ public void loadMachine(String name, Boolean connect) { setMachine(Base.loadMachine(name)); if (getMachine() == null) return; // abort on no selected machine reloadSerialMenu(); if(previewPanel != null) { /* FIXME: This is probably not the best place to do the reload. We need * the BuildVolume information (through MachineModel) which apparently * isn't initialized yet when this is called... */ Base.logger.fine("RELOADING the machine... removing previewPanel..."); getPreviewPanel().rebuildScene(); updateBuild(); } if (!connect) return; if (machine.driver instanceof UsesSerial) { UsesSerial us = (UsesSerial)machine.driver; String targetPort; if (Base.preferences.getBoolean("serial.use_machines",true) && us.isExplicit()) { targetPort = us.getPortName(); } else { targetPort = Base.preferences.get("serial.last_selected", null); } if (targetPort != null) { try { Serial current = us.getSerial(); System.err.println("Current serial port: "+((current==null)?"null":current.getName())+", specified "+targetPort); if (current == null || !current.getName().equals(targetPort)) { us.setSerial(new Serial(targetPort,us)); } machine.connect(); } catch (SerialException e) { String msg = e.getMessage(); if (msg == null) { msg = "."; } else { msg = ": "+msg; } Base.logger.log(Level.WARNING, "Could not use specified serial port ("+targetPort+")"+ msg); } } } } public void machineProgress(MachineProgressEvent event) { } public void toolStatusChanged(MachineToolStatusEvent event) { } BuildElement currentElement; public void setCurrentElement(BuildElement e) { currentElement = e; if (currentElement != null) { CardLayout cl = (CardLayout)cardPanel.getLayout(); if (currentElement.getType() == BuildElement.Type.MODEL ) { cl.show(cardPanel, MODEL_TAB_KEY); } else { cl.show(cardPanel, GCODE_TAB_KEY); } } updateUndo(); } private void updateBuild() { header.setBuild(build); header.repaint(); updateUndo(); } public void stateChanged(ChangeEvent e) { // We get a change event when another tab is selected. setCurrentElement(header.getSelectedElement()); } public void generationComplete(Completion completion, Object details) { // if success, update header and switch to code if (completion == Completion.SUCCESS) { if (build.getCode() != null) { setCode(build.getCode()); } buttons.updateFromMachine(machine); updateBuild(); } } public void updateGenerator(String message) { // ignore } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
747a29cceba1bee6bef80f9f704d7e7151d3f8a5
00d3b627c1dfd6ac7e613eedffe32f726e1564c7
/app/src/main/java/com/example/chronus/TomatoView.java
d7ae8ff55db9e5c237c1e7c4c15a730d29513239
[]
no_license
ShawnDiego/Chronus
02c3c9eb8cc9e89942d563eec043e855ed96e6ba
2c36cc3dd114c6954ab1903c02273d0eabc31e99
refs/heads/master
2022-03-23T10:06:57.351221
2019-12-25T06:35:41
2019-12-25T06:35:41
198,171,321
0
0
null
null
null
null
UTF-8
Java
false
false
7,892
java
package com.example.chronus; import android.animation.ValueAnimator; import android.app.NotificationManager; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.CountDownTimer; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.TextView; import android.widget.Toast; import com.example.chronus.AlarmNotification.Notify; public class TomatoView extends View { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint timePaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int mColor = Color.parseColor("#D1D1D1");//结束的灰色 private int centerX; private int centerY; private int radius; private RectF mRectF = new RectF(); public static final float START_ANGLE = -90; public static final int MAX_TIME = 60; private float sweepVelocity = 0; private String textTime = "25:00"; //分钟 private int time; //倒计时 private int countdownTime=25*60; private float touchX; private float touchY; private float offsetX; private float offsetY; public boolean isStarted = false; private NotificationManager mNM; private Context mContext; public TomatoView(Context context) { super(context); } public TomatoView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public TomatoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public static float dpToPixel(float dp) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); return dp * metrics.density; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); centerX = width / 2; centerY = height / 2; radius = (int) dpToPixel(120); setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mRectF.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius); //红圆 canvas.save(); mPaint.setColor(Color.parseColor("#AAE3170D")); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(dpToPixel(5)); canvas.drawCircle(centerX, centerY, radius, mPaint); canvas.restore(); //灰圆 canvas.save(); mPaint.setColor(mColor); canvas.drawArc(mRectF, START_ANGLE, 360 * sweepVelocity, false, mPaint); canvas.restore(); //时间 canvas.save(); timePaint.setColor(Color.parseColor("#AAE3170D")); timePaint.setStyle(Paint.Style.FILL); timePaint.setTextSize(dpToPixel(40)); canvas.drawText(textTime, centerX - timePaint.measureText(textTime) / 2, centerY - (timePaint.ascent() + timePaint.descent()) / 2, timePaint); canvas.restore(); } @Override public boolean onTouchEvent(MotionEvent event) { if (isStarted) { return true; } float x = event.getX(); float y = event.getY(); boolean isContained = isContained(x, y); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if (isContained) { touchX = x; touchY = y; } break; case MotionEvent.ACTION_MOVE: if (isContained) { offsetX = x - touchX; offsetY = y - touchY; time = (int) (offsetY / 2 / radius * MAX_TIME); if (time <= 0) { time = 0; } textTime = formatTime(time); countdownTime = time * 60; invalidate(); } break; } return true; } private boolean isContained(float x, float y) { if (Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY)) > radius) { return false; } else { return true; } } private String formatTime(int time) { StringBuilder sb = new StringBuilder(); if (time < 10) { sb.append("0" + time + ":00"); } else { sb.append(time + ":00"); } return sb.toString(); } private String formatCountdownTime(int countdownTime) { StringBuilder sb = new StringBuilder(); int minute = countdownTime / 60; int second = countdownTime - 60 * minute; if (minute < 10) { sb.append("0" + minute + ":"); } else { sb.append(minute + ":"); } if (second < 10) { sb.append("0" + second); } else { sb.append(second); } return sb.toString(); } CountDownTimer countDownTimer; int timeHistory; ValueAnimator valueAnimator; public void start() { if (countdownTime <= 0 || isStarted) { return; } isStarted = true; timeHistory = countdownTime; valueAnimator = ValueAnimator.ofFloat(0, 1.0f); valueAnimator.setDuration(countdownTime * 1000); valueAnimator.setInterpolator(new LinearInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { sweepVelocity = (float) animation.getAnimatedValue(); mColor = Color.parseColor("#D1D1D1"); invalidate(); } }); valueAnimator.start(); countDownTimer = new CountDownTimer(countdownTime * 1000, 1000) { @Override public void onTick(long millisUntilFinished) { countdownTime = (countdownTime * 1000 - 1000) / 1000; textTime = formatCountdownTime(countdownTime); invalidate(); } @Override public void onFinish() { valueAnimator.cancel(); mColor = Color.parseColor("#AAE3170D"); sweepVelocity = 0; isStarted = false; countdownTime = timeHistory; textTime = formatCountdownTime(countdownTime); invalidate(); TextView tx = getRootView().findViewById(R.id.tv_start); tx.setText("开始专注"); tx.setTextColor(Color.parseColor("#AAE3170D")); TextView tv_exp = getRootView().findViewById(R.id.tv_exp); tv_exp.setVisibility(View.VISIBLE); Toast.makeText(getContext(), "完成番茄钟!", Toast.LENGTH_SHORT).show(); mContext = getContext(); Notify nm = new Notify(getContext()); nm.setNotification("完成番茄钟!", "完成一个番茄,快去休息一下吧!"); } }.start(); } public void stop(){ countDownTimer.cancel(); valueAnimator.cancel(); countdownTime=timeHistory; textTime = formatCountdownTime(countdownTime); mColor = Color.parseColor("#AAE3170D"); sweepVelocity = 0; isStarted = false; invalidate(); } }
[ "miqi111111@126.com" ]
miqi111111@126.com
84a9830ab3426ceb49491bef2ea238df078c44f5
bd928d717511f33857bfe8210de321830b75c5fc
/src/main/java/com/bowlink/rr/jobs/ProcessUploadFilesJob.java
f86b1398f72f7b8eeebce274a75a57c6244b5c7c
[]
no_license
bowlinktech/rapidregistry
73f06879b41ffe31b53bdbf24a8bf4db1d7b7c32
a48c0a0af992b048185c674f7e963b41fe088142
refs/heads/master
2023-08-18T03:18:16.251210
2023-08-09T20:10:47
2023-08-09T20:10:47
22,726,288
0
0
null
2021-12-15T01:49:32
2014-08-07T15:26:33
Java
UTF-8
Java
false
false
1,290
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.bowlink.rr.jobs; import com.bowlink.rr.service.importManager; import java.util.logging.Level; import java.util.logging.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.context.support.SpringBeanAutowiringSupport; /** * * @author gchan */ public class ProcessUploadFilesJob implements Job { @Autowired private importManager importmanager; @Override public void execute(JobExecutionContext context) throws JobExecutionException { try { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); importmanager.processUploadedFiles(); } catch (Exception ex) { try { throw new Exception("Error occurred processing uploaded file schedule task",ex); } catch (Exception ex1) { Logger.getLogger(ProcessUploadFilesJob.class.getName()).log(Level.SEVERE, null, ex1); } } } }
[ "gchan123@yahoo.com" ]
gchan123@yahoo.com
52d3c17bccc5e54f782d5912b8c5e7960db836e3
cc13305700d14af74e6576cc462be8adbe0dcd33
/12-02-2015/elearning/src/main/java/org/lztvn/elearning/service/IMessageService.java
77dad094af020b2f6a63cee4783953f5ada45377
[]
no_license
sivarajankumar/lzt-elearning
6854b6a4c7c10a26398ce4e45536384b0e5e15f8
cd91e80ad4c438154dc18d68aca051bbf8e733a8
refs/heads/master
2021-01-10T03:19:13.872113
2015-03-04T09:55:32
2015-03-04T09:55:32
48,041,186
0
0
null
null
null
null
UTF-8
Java
false
false
151
java
package org.lztvn.elearning.service; import org.lztvn.elearning.dao.IMessageDAO; public interface IMessageService extends IMessageDAO { }
[ "duanvuminh@gmail.com" ]
duanvuminh@gmail.com
04e034c30121ffcaaa3e611865b5b45bc23084b8
afaf5c898380ef0576b816143bb7df9923108019
/app/src/main/java/com/example/sederhana/MainActivity.java
299184006ded2783bbd0a828b690502c84f69903
[]
no_license
rahmaalia/rahmaXIRPLA_login
ef9c85887af89d15e9be74f234fa56ce27c2d774
f5c43da314cb168c004a517aefe18a79f4c2f6bb
refs/heads/master
2020-07-17T11:42:04.225026
2019-09-03T07:18:00
2019-09-03T07:18:00
206,013,551
0
0
null
null
null
null
UTF-8
Java
false
false
2,943
java
package com.example.sederhana; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; public class MainActivity extends AppCompatActivity { String Username,Password; TextInputEditText username,password; TextInputLayout layoutusername,layoutpassword; Button login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layoutpassword = findViewById(R.id.layoutpassword); layoutusername = findViewById(R.id.layoutuser); username = findViewById(R.id.username); password = findViewById(R.id.password); login = findViewById(R.id.btnLogin); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Username = username.getText().toString(); Password = password.getText().toString(); if (Username.length()==0){ layoutusername.setError("field tidak boleh kosong"); }else if (Username != "admin"){ layoutusername.setError("Masukkan username yang valid"); if (Username.equals("admin") || Username.equals("user")){ layoutusername.setError(null); layoutusername.setErrorEnabled(false); } } if (Password.length()==0){ layoutpassword.setError("Password tidak boleh kosong"); }else if (Password != "admin"){ layoutpassword.setError("Masukkan password yang valid"); if(Password.equals("admin") || Password.equals("user")){ layoutpassword.setError(null); layoutpassword.setErrorEnabled(false); } } if (Username.equals("admin") && Password.equals("user")){ layoutpassword.setError("Masukkan password yang valid"); }else if (Username.equals("user") && Password.equals("admin")){ layoutpassword.setError("Masukkan password yang valid"); } if (Username.equals("admin") && Password.equals("admin")){ Intent admin = new Intent(MainActivity.this,LamanAdmin.class); startActivity(admin); } if (Username.equals("user") && Password.equals("user")){ Intent user = new Intent(MainActivity.this,LamanUser.class); startActivity(user); } } }); } }
[ "rahmaaliaputri27@gmail.com" ]
rahmaaliaputri27@gmail.com
db69d9122d651e25dffd6fec99b124d82d01a810
0bf8a01ba1c90bd0783018232bd3a83c8fdedf4e
/gtk-devops-algorithm/src/main/java/com/gqs/algorithm/class005_count_sort/T001_PrefixTreeArray.java
c5c074b7e9b87dcfaf2a401bf9e0ba556a433d31
[]
no_license
gaoqisen/gtk-devops-scd
738aa8891a44dbedfd0c5158653e59f48105e7e8
c4df46016402d99902c6a6f58dc958eb2fd963bb
refs/heads/master
2023-06-23T00:58:34.068071
2023-06-19T14:59:43
2023-06-19T14:59:43
238,143,223
0
1
null
2023-03-08T17:31:56
2020-02-04T06:57:36
Java
UTF-8
Java
false
false
2,775
java
package com.gqs.algorithm.class005_count_sort; public class T001_PrefixTreeArray { public static class Tire{ public Node root; public Tire() { this.root = new Node(); } // 插入字符串 public void insert(String str) { if(str == null || str.isEmpty()) { return; } char[] chars = str.toCharArray(); Node node = root; for (int i = 0; i < chars.length; i++) { int index = chars[i] - 'a'; if(node.nexts[index] == null) { node.nexts[index] = new Node(); } node = node.nexts[index]; node.pass++; } node.end++; } // 删除字符串 public void del(String str) { if(str == null || str.isEmpty() || findCount(str) == 0) { return; } char[] chars = str.toCharArray(); Node node = root; node.pass--; for (int i = 0; i < chars.length; i++) { int index = chars[i] - 'a'; if(--node.nexts[index].pass == 0) { node.nexts[index] = null; return; } node = node.nexts[index]; } node.end--; } // 获取字符串出现了几次 public int findCount(String str) { if(str == null || str.isEmpty()) { return 0; } char[] chars = str.toCharArray(); Node node = root; for (int i = 0; i < chars.length; i++) { int index = chars[i] - 'a'; if(node.nexts[index] == null) { return 0; } node = node.nexts[index]; } return node.end; } // 获取有多少个符合str的前缀字符串 public int prefixCount(String str) { if(str == null || str.isEmpty()) { return 0; } char[] chars = str.toCharArray(); Node node = root; for (int i = 0; i < chars.length; i++) { int index = chars[i] - 'a'; if(node.nexts[index] == null) { return 0; } node = node.nexts[index]; } return node.pass; } } public static class Node{ public int pass; public int end; public Node[] nexts; public Node() { this.pass = 0; this.end = 0; // 按照26个字母作为路径 this.nexts = new Node[26]; } } }
[ "1073825890@qq.com" ]
1073825890@qq.com
b80b8e7246dcfa0457c766d86185ae98c85f83b7
2587b4daf81190246e930e2da12df30b28469c58
/src/com/challenge63/Solver63.java
b3cf73c2e68df28eb83fdddfcd504177587bc825
[]
no_license
gaborweisz/Euler79
353539522c74da3ab5a36efcc05564a9c8f607ff
d9deba5008f6820a285513ee0ea1ebcbf67e6e41
refs/heads/master
2021-09-24T00:41:16.512858
2021-09-17T13:18:57
2021-09-17T13:18:57
150,324,555
0
0
null
null
null
null
UTF-8
Java
false
false
765
java
package com.challenge63; import java.math.BigDecimal; /** * Created by gabor on 2019.04.15.. */ public class Solver63 { public void solve() { int max_num = 100; int max_pow = 100; int counter = 0; for (Integer n = 1; n <= max_num; n++) { for (int p = 1; p <= max_pow; p++) { BigDecimal num = new BigDecimal(n); BigDecimal result = num.pow(p); if (result.toString().length() == p) { counter++; System.out.printf("Found : n = %d; p = %d; num = %s; length = %d\n", n, p, result.toString(), result.toString().length()); } } } System.out.println("Soluton = " + counter); } }
[ "43587299+gaborweisz@users.noreply.github.com" ]
43587299+gaborweisz@users.noreply.github.com
db211ea6775b9eedb4362ca91b7f64d3f70dc9bb
93c67d54e516ca02e4de482c70aad4fd25847352
/src/test/java/com/lee/you/mongodb/TestMain.java
fb65e8552a458001ee54d52c6918ea94521c7974
[]
no_license
youzhibing/mongodb
a1910419eebbbcc3d6882edf4e6a44ea782f7493
3b885df227d70e29566d33c6db166215b9067777
refs/heads/master
2021-01-21T18:34:31.557589
2017-05-23T11:17:04
2017-05-23T11:17:04
92,061,959
0
1
null
null
null
null
UTF-8
Java
false
false
469
java
package com.lee.you.mongodb; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lee.you.mongodb.dao.IMongoDao; public class TestMain { public static void main(String[] args) { ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext-mongo.xml"); IMongoDao dao = (IMongoDao)context.getBean("mongoDao"); System.out.println(dao.listAll()); } }
[ "997914490@qq.com" ]
997914490@qq.com
7495b7d60b4073cd2cc0b08dd6caf84c657d856b
ee5d3f5b62ea5c5f3e4674c1821b3f1275656cdf
/05.04-Records/src/Quadrado.java
1dda6a045ec1383da143dee95718463c1471726c
[]
no_license
JuniorPlantier/JavaSe-Fundamentos
b6997acc2bfa88f042e934dd3900fba8710d2e84
28ec4ea28e7aae61634336d1fb37d9f150e0a582
refs/heads/master
2022-12-07T10:07:11.639200
2020-09-02T13:24:32
2020-09-02T13:24:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
102
java
public record Quadrado(double lado) { public double calcularArea() { return lado * lado; } }
[ "junior.plantier@gmail.com" ]
junior.plantier@gmail.com
b728dea32ed8a6d5c6149fcf6ec2d6197273f559
ab99e077ea0f501d81fabb9101ed6fc9bd733874
/src/FortuneTeller.java
8ae43c406341ac71acf57b3358df15b458b1c5ce
[]
no_license
camman00/Level-1
c0324fc9d8613db5cc8cb275a5a7839e4cba21f8
4f88bf372ddd1b203bb0f7e174bb15a573324da5
refs/heads/master
2020-04-06T04:53:15.311418
2017-04-02T19:40:21
2017-04-02T19:40:21
73,642,595
0
0
null
null
null
null
UTF-8
Java
false
false
3,405
java
import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; @SuppressWarnings("serial") public class FortuneTeller extends JPanel implements Runnable, MouseListener { static JFrame frame = new JFrame(); int frameWidth = 500; int frameHeight = 400; FortuneTeller() throws Exception { // 1. Choose an image for your fortune teller and put it in your default package fortuneTellerImage = ImageIO.read(getClass().getResource("fortune_teller.jpeg")); // 2. Adjust the frameWidth and frameHeight variables to fit your image nicely (doesn’t need a new line of code) // 4. add a mouse listener to the frame frame.addMouseListener(this); } static void begin() { JOptionPane.showMessageDialog(frame, "HOLA COMO ESTAS, El targeto esta debajo de la primero photographio y es un poco al la derechalo"); } @Override public void mousePressed(MouseEvent e) { int mouseX = e.getX(); int mouseY = e.getY(); System.out.println(mouseX + " " + mouseY); // 6. Add the mouseY variable to the previous line so that it prints out too (no new line) // 7. Adjust your secret location co-ordinates here: int secretLocationX = 399; int secretLocationY = 499; /** If the mouse co-ordinates and secret location are close, we'll let them ask a question. */ if (areClose(mouseX, secretLocationX) && areClose(mouseY, secretLocationY)) { // 8. Get the user to enter a question for the fortune teller // 9. Find a spooky sound and put it in your default package (freesound.org) // AudioClip sound = JApplet.newAudioClip(getClass().getResource("spooky.aif")); // 10. Play the sound // 11. Use the pause() method below to wait until your music has finished // 12. Insert your completed Magic 8 ball recipe (http://bit.ly/Zdrf6d) here } } private boolean areClose(int mouseX, int secretLocationX) { return mouseX < secretLocationX + 15 && mouseX > secretLocationX - 15; } private void pause(int seconds) { try { Thread.sleep(1000 * seconds); } catch (InterruptedException e) { e.printStackTrace(); } } /**************** don't worry about the stuff under here *******************/ BufferedImage fortuneTellerImage; public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new FortuneTeller()); begin(); } @Override public void run() { frame.add(this); setPreferredSize(new Dimension(frameWidth, frameHeight)); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } private void showAnotherImage(String imageName) { try { fortuneTellerImage = ImageIO.read(getClass().getResource(imageName)); } catch (Exception e) { System.err.println("Couldn't find this image: " + imageName); } repaint(); } @Override public void paintComponent(Graphics g) { g.drawImage(fortuneTellerImage, 0, 0, null); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } // Copyright The League, 2016
[ "skyswims@yahoo.com" ]
skyswims@yahoo.com
b432c71484b329d0fd1572a500076f08be7ffd5b
962494be5b297050796531d2381cdc1715a9c22a
/httpVerbs/src/main/java/br/com/microservices/taha/config/exception/handler/GlobalResponseEntityExceptionHandler.java
24904490b44c2a8047b06e43630ade5671f9f5f0
[]
no_license
antoniotaha/basic-spring-boot
975f38439b976dcbb6f418f167a8e2c9a5faf55f
475da4514bf92b57f2d83c95e92279e709c1c73f
refs/heads/main
2023-08-05T11:35:37.125094
2021-09-24T21:59:25
2021-09-24T21:59:25
410,061,481
0
0
null
null
null
null
UTF-8
Java
false
false
1,514
java
package br.com.microservices.taha.config.exception.handler; import java.time.LocalDateTime; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import br.com.microservices.taha.config.exception.ExceptionResponse; import br.com.microservices.taha.config.exception.UnsupportedMathOperationException; @RestController @ControllerAdvice public class GlobalResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler({Exception.class}) public final ResponseEntity<ExceptionResponse> handleAllException(Exception ex, WebRequest request) { ExceptionResponse exceptionResponse = new ExceptionResponse(LocalDateTime.now(), ex.getMessage(), request.getDescription(false)); return ResponseEntity.internalServerError().body(exceptionResponse); } @ExceptionHandler({ UnsupportedMathOperationException.class}) public final ResponseEntity<ExceptionResponse> handleBadRequestException(UnsupportedMathOperationException ex, WebRequest request) { ExceptionResponse exceptionResponse = new ExceptionResponse(LocalDateTime.now(), ex.getMessage(), request.getDescription(false)); return ResponseEntity.badRequest().body(exceptionResponse); } }
[ "antoniotahasc@gmail.com" ]
antoniotahasc@gmail.com
88490152f6b64340cb90ddd9a5a769a930b51710
0834c0c4e4e488e58ec3aeef939a1ad5149a9185
/src/test/java/org/openapitools/client/api/GroupUsersApiTest.java
a5ccb5f64e1c05f04a4f0d4a1aeb11e5454b4138
[]
no_license
caleeli/spark-sdk-java
f90fdf581e973e78f300928faf5d79cd7cb5549f
5186824f8c6bdb5301f3f3faad7f378ea84a298c
refs/heads/master
2020-05-17T11:03:43.071597
2019-04-26T18:19:11
2019-04-26T18:19:11
183,674,934
1
0
null
null
null
null
UTF-8
Java
false
false
1,323
java
/* * ProcessMaker API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 1.0.0 * Contact: info@processmaker.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.api; import ProcessMaker_Client.ApiException; import org.openapitools.client.model.InlineResponse2006; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for GroupUsersApi */ @Ignore public class GroupUsersApiTest { private final GroupUsersApi api = new GroupUsersApi(); /** * Returns all users of a group * * * * @throws ApiException * if the Api call fails */ @Test public void getMembersTest() throws ApiException { String filter = null; String orderBy = null; String orderDirection = null; Integer perPage = null; String include = null; InlineResponse2006 response = api.getMembers(filter, orderBy, orderDirection, perPage, include); // TODO: test validations } }
[ "davidcallizaya@gmail.com" ]
davidcallizaya@gmail.com
58c86765990cc779d384b17460848744d3682435
1db6a9775f3a6d1e05d9897cc3f24bd193a42bbc
/src/main/java/ext/RandomUniqueValue.java
7bf5e2b12816fc4ec73e918de8e26762d79a3d35
[]
no_license
lyoumi/RPG
943d6a888c62c47e550fbd2d1933af890d58d6d6
022f22ebb74d990fa4526ca1cbb1b98660af8f36
refs/heads/master
2021-01-18T12:04:27.098386
2017-09-10T10:22:06
2017-09-10T10:22:06
97,833,216
0
0
null
null
null
null
UTF-8
Java
false
false
1,369
java
package ext; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Класс с методом возвращающим кникальное значение типа int. */ public class RandomUniqueValue { private Random random = new Random(); private List<Integer> list = new ArrayList<>(); /** * Этот метод описывает генерацию уникального значения типа int. * Возвращает случайное значение типа int и заносит в массив. * При следующем вызове метода значение будет генироваться и будет выполняться првоерка на наличие его в массиве * и в случае его отсутствия он будет добавляться в массив, в противном случае значение будет сгенерировано заново. * * @return * unique int. */ public int nextUniqueInt(){ int value = random.nextInt(10000); if (list.isEmpty()) { list.add(value); return value; } else { if (list.contains(value)) nextUniqueInt(); else list.add(value); return value; } } }
[ "newframework@protonmail.com" ]
newframework@protonmail.com
300fe5641ca426e0f516f68b7b5f7da0f7a9a927
1c0fa98cfa725e6f0bbb29792a2ebaeb955bde6b
/fanyi/src/main/java/com/fypool/component/ScheduleComponent.java
90ce58ea19349d7656e1f13340496c63d674e62e
[]
no_license
mack-wang/project
043a17d97b747352d2d20ab8143188a26872cfaf
c7eec8ba9b87d24272511abb519754067e6e65e3
refs/heads/master
2021-09-01T06:59:51.084085
2017-12-25T14:34:40
2017-12-25T14:34:40
115,329,425
0
0
null
null
null
null
UTF-8
Java
false
false
2,674
java
package com.fypool.component; import com.fypool.controller.web.FileCleanController; import com.fypool.model.SmsNotify; import com.fypool.repository.AttributeRepository; import com.fypool.repository.FileCleanRepository; import com.fypool.repository.SmsNotifyRepository; import com.fypool.repository.TaskRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component public class ScheduleComponent { @Autowired TaskRepository taskRepository; @Autowired SmsNotifyRepository smsNotifyRepository; @Autowired AttributeRepository attributeRepository; //这个类,可以用来读取/* /** /*/* 匹配型的目录和文件 @Autowired ResourcePatternResolver resourcePatternResolver; @Autowired FileCleanController fileCleanController; //每半小时执行一次,并且每次重新部署都会执行一次 //置顶到期后,半小时之间把置顶的1变回0 @Scheduled(fixedDelay = 30 * 60 * 1000) public void fixedDelayJob() { // System.out.println("定时任务正在执行"); taskRepository.updateTop(new Date()); } //每天0点整,将提醒短信的数量重置为0 @Scheduled(cron = "0 0 0 * * ?") public void cronJob() { smsNotifyRepository.updateUsed(); } //每周日早上4点整,清理每周文件,若出现问题大家加班解决,以便周一工作日不影响用户使用 @Scheduled(cron = "0 0 4 ? * 1") public void cleanEveryWeek() { fileCleanController.cleanAdvice(); fileCleanController.cleanAttachment(); fileCleanController.cleanAvatar(); fileCleanController.cleanCertificate(); fileCleanController.cleanIdCard(); fileCleanController.cleanLicense(); fileCleanController.cleanQrcode(); fileCleanController.cleanVipAttachment(); fileCleanController.cleanVipTask(); } // @Scheduled(fixedDelay=ONE_Minute) // public void fixedDelayJob(){ // System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>fixedDelay执行...."); // } // // @Scheduled(fixedRate=ONE_Minute) // public void fixedRateJob(){ // System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>fixedRate执行...."); // } // // @Scheduled(cron="0 15 3 * * ?") // public void cronJob(){ // System.out.println(Dates.format_yyyyMMddHHmmss(new Date())+" >>cron执行...."); // } //文件清理 }
[ "641212003@qq.com" ]
641212003@qq.com
512381a11111cd8f6a237772ab18789971b67e51
40dc49503632d51583e88add9009599e74f5ac46
/any-vblog/src/com/ilovn/app/anyvblog/model/sina/UserInfo4Sina.java
e1f97509dd21ec3b917ac7f54c0bb50592ae7532
[]
no_license
hongyunxp/any-vblog
c301d9a2200f62f75c20867618ef3a8d12958ca5
122b2d83f7f749e9a0626d4c2fa1f9a280206556
refs/heads/master
2020-06-06T17:18:55.547671
2012-04-29T04:26:32
2012-04-29T04:26:32
41,403,224
0
0
null
null
null
null
UTF-8
Java
false
false
5,902
java
package com.ilovn.app.anyvblog.model.sina; import java.util.Map; import com.ilovn.app.anyvblog.model.User; import com.ilovn.app.anyvblog.model.UserAdapter; import com.ilovn.app.anyvblog.utils.Constants; public class UserInfo4Sina implements User { private String id; // int64 用户UID private String screen_name; // string 用户昵称 private String name; // string 友好显示名称 private int province; // int 用户所在地区ID private int city; // int 用户所在城市ID private String location; // string 用户所在地 private String description; // string 用户描述 private String url; // string 用户博客地址 private String profile_image_url; // string 用户头像地址 private String domain; // string 用户的个性化域名 private String gender; //string 性别,m:男、f:女、n:未知 private int followers_count; // int 粉丝数 private int friends_count; // int 关注数 private int statuses_count; // int 微博数 private int favourites_count; // int 收藏数 private String created_at; // string 创建时间 private boolean following; // boolean 当前登录用户是否已关注该用户 private boolean verified; // boolean 是否是微博认证用户,即带V用户 private Status4Sina status; // object 用户的最近一条微博信息字段 private boolean geo_enabled; @Override public UserAdapter conver2User() { UserAdapter adapter = new UserAdapter(); adapter.setSp(Constants.SP_SINA); adapter.setUser_id(id); adapter.setName(name); adapter.setNick(screen_name); //adapter.setHead(null); adapter.setHead_url(profile_image_url); adapter.setCount_followers(followers_count); adapter.setCount_friends(friends_count); adapter.setCount_status(statuses_count); if ("m".equals(gender)) { adapter.setSex("男"); } else if("f".equals(gender)) { adapter.setSex("女"); } else { adapter.setSex("未知"); } adapter.setDescription(description); adapter.setLocation(location); adapter.setIsvip(verified); adapter.setFriend(following); if (status != null) { adapter.setStatus(status.conver2Data()); } return adapter; } @Override public Map<String, Object> conver() { // TODO Auto-generated method stub return null; } @Override public String toString() { return "UserInfo4Sina [id=" + id + ", screen_name=" + screen_name + ", name=" + name + ", province=" + province + ", city=" + city + ", location=" + location + ", description=" + description + ", url=" + url + ", profile_image_url=" + profile_image_url + ", domain=" + domain + ", gender=" + gender + ", followers_count=" + followers_count + ", friends_count=" + friends_count + ", statuses_count=" + statuses_count + ", favourites_count=" + favourites_count + ", created_at=" + created_at + ", following=" + following + ", verified=" + verified + ", status=" + status + ", geo_enabled=" + geo_enabled + "]"; } public boolean isGeo_enabled() { return geo_enabled; } public void setGeo_enabled(boolean geo_enabled) { this.geo_enabled = geo_enabled; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getScreen_name() { return screen_name; } public void setScreen_name(String screen_name) { this.screen_name = screen_name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProvince() { return province; } public void setProvince(int province) { this.province = province; } public int getCity() { return city; } public void setCity(int city) { this.city = city; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getFollowers_count() { return followers_count; } public void setFollowers_count(int followers_count) { this.followers_count = followers_count; } public int getFriends_count() { return friends_count; } public void setFriends_count(int friends_count) { this.friends_count = friends_count; } public int getStatuses_count() { return statuses_count; } public void setStatuses_count(int statuses_count) { this.statuses_count = statuses_count; } public int getFavourites_count() { return favourites_count; } public void setFavourites_count(int favourites_count) { this.favourites_count = favourites_count; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public boolean isFollowing() { return following; } public void setFollowing(boolean following) { this.following = following; } public boolean isVerified() { return verified; } public void setVerified(boolean verified) { this.verified = verified; } public Status4Sina getStatus() { return status; } public void setStatus(Status4Sina status) { this.status = status; } }
[ "zhaoyong1990@gmail.com" ]
zhaoyong1990@gmail.com
e5d11a7de14f22ed798f2d41ca86bece79ad0ff8
e0cb36c94a00f960bfb710d29c9ee09ec03cea34
/app/src/main/java/com/example/generify/viewModel/DashboardViewModel.java
14eacab95819033b6e1ab1bd0e782ef813e2ceca
[]
no_license
erdemduman/Generify_Mobile
5b2798dc674cce115ee1a4be6ec7a35305bcf9d2
7d59c9adc2c9be284164e829658dfbd27bdacee9
refs/heads/master
2021-07-17T10:53:52.785738
2020-09-17T17:14:26
2020-09-17T17:14:26
214,883,754
1
0
null
null
null
null
UTF-8
Java
false
false
835
java
package com.example.generify.viewModel; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.example.generify.service.SpotifyAuth; import com.spotify.sdk.android.authentication.AuthenticationRequest; public class DashboardViewModel extends BaseViewModel { private MutableLiveData<AuthenticationRequest> spotifyAuthRequestProp; public DashboardViewModel(@NonNull Application application) { super(application); spotifyAuthRequestProp = new MutableLiveData<>(); } public void runSpotifyAuthRequest(){ spotifyAuthRequestProp.setValue(SpotifyAuth.getAuthRequest()); } public LiveData<AuthenticationRequest> getSpotifyAuthRequest(){ return spotifyAuthRequestProp; } }
[ "erdemduman23@gmail.com" ]
erdemduman23@gmail.com
750a8e8b798a2d1a75f61a17b1bb95356aa4620a
76365e99485d9889cf348554a6d8196eb477cfb0
/mini project/build/app/generated/not_namespaced_r_class_sources/debug/r/androidx/transition/R.java
efd4a2baf0a44745c5d4d78dfd9517b201a35702
[]
no_license
ShubhamModi999/Automated-Food-Ordering-System
f9abf5058b4fde692ba8d2946661af803219cdf5
145d5b925f6071afc8d52748a7dd3d1c7a08d85a
refs/heads/main
2023-06-14T14:47:48.316205
2021-07-08T11:34:59
2021-07-08T11:34:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,116
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.transition; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f030027; public static final int font = 0x7f0300d9; public static final int fontProviderAuthority = 0x7f0300db; public static final int fontProviderCerts = 0x7f0300dc; public static final int fontProviderFetchStrategy = 0x7f0300dd; public static final int fontProviderFetchTimeout = 0x7f0300de; public static final int fontProviderPackage = 0x7f0300df; public static final int fontProviderQuery = 0x7f0300e0; public static final int fontStyle = 0x7f0300e1; public static final int fontVariationSettings = 0x7f0300e2; public static final int fontWeight = 0x7f0300e3; public static final int ttcIndex = 0x7f0301e6; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050072; public static final int notification_icon_bg_color = 0x7f050073; public static final int ripple_material_light = 0x7f050083; public static final int secondary_text_default_material_light = 0x7f05008d; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f060053; public static final int compat_button_inset_vertical_material = 0x7f060054; public static final int compat_button_padding_horizontal_material = 0x7f060055; public static final int compat_button_padding_vertical_material = 0x7f060056; public static final int compat_control_corner_material = 0x7f060057; public static final int compat_notification_large_icon_max_height = 0x7f060058; public static final int compat_notification_large_icon_max_width = 0x7f060059; public static final int notification_action_icon_size = 0x7f0600c6; public static final int notification_action_text_size = 0x7f0600c7; public static final int notification_big_circle_margin = 0x7f0600c8; public static final int notification_content_margin_start = 0x7f0600c9; public static final int notification_large_icon_height = 0x7f0600ca; public static final int notification_large_icon_width = 0x7f0600cb; public static final int notification_main_column_padding_top = 0x7f0600cc; public static final int notification_media_narrow_margin = 0x7f0600cd; public static final int notification_right_icon_size = 0x7f0600ce; public static final int notification_right_side_padding_top = 0x7f0600cf; public static final int notification_small_icon_background_padding = 0x7f0600d0; public static final int notification_small_icon_size_as_large = 0x7f0600d1; public static final int notification_subtext_size = 0x7f0600d2; public static final int notification_top_pad = 0x7f0600d3; public static final int notification_top_pad_large_text = 0x7f0600d4; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070073; public static final int notification_bg = 0x7f070074; public static final int notification_bg_low = 0x7f070075; public static final int notification_bg_low_normal = 0x7f070076; public static final int notification_bg_low_pressed = 0x7f070077; public static final int notification_bg_normal = 0x7f070078; public static final int notification_bg_normal_pressed = 0x7f070079; public static final int notification_icon_background = 0x7f07007a; public static final int notification_template_icon_bg = 0x7f07007b; public static final int notification_template_icon_low_bg = 0x7f07007c; public static final int notification_tile_bg = 0x7f07007d; public static final int notify_panel_notification_icon_bg = 0x7f07007e; } public static final class id { private id() {} public static final int action_container = 0x7f08002e; public static final int action_divider = 0x7f080030; public static final int action_image = 0x7f080031; public static final int action_text = 0x7f080037; public static final int actions = 0x7f080038; public static final int async = 0x7f08003f; public static final int blocking = 0x7f080043; public static final int chronometer = 0x7f08004c; public static final int forever = 0x7f080072; public static final int ghost_view = 0x7f080073; public static final int icon = 0x7f080077; public static final int icon_group = 0x7f080078; public static final int info = 0x7f08007b; public static final int italic = 0x7f08007c; public static final int line1 = 0x7f080082; public static final int line3 = 0x7f080083; public static final int normal = 0x7f080090; public static final int notification_background = 0x7f080091; public static final int notification_main_column = 0x7f080092; public static final int notification_main_column_container = 0x7f080093; public static final int parent_matrix = 0x7f080099; public static final int right_icon = 0x7f0800a3; public static final int right_side = 0x7f0800a4; public static final int save_image_matrix = 0x7f0800a5; public static final int save_non_transition_alpha = 0x7f0800a6; public static final int save_scale_type = 0x7f0800a7; public static final int tag_transition_group = 0x7f0800d6; public static final int tag_unhandled_key_event_manager = 0x7f0800d7; public static final int tag_unhandled_key_listeners = 0x7f0800d8; public static final int text = 0x7f0800d9; public static final int text2 = 0x7f0800da; public static final int time = 0x7f0800e2; public static final int title = 0x7f0800e3; public static final int transition_current_scene = 0x7f0800e9; public static final int transition_layout_save = 0x7f0800ea; public static final int transition_position = 0x7f0800eb; public static final int transition_scene_layoutid_cache = 0x7f0800ec; public static final int transition_transform = 0x7f0800ed; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f09000e; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b0031; public static final int notification_action_tombstone = 0x7f0b0032; public static final int notification_template_custom_big = 0x7f0b0033; public static final int notification_template_icon_group = 0x7f0b0034; public static final int notification_template_part_chronometer = 0x7f0b0035; public static final int notification_template_part_time = 0x7f0b0036; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e002b; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f011b; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f011c; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f011d; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f011e; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f011f; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01c8; public static final int Widget_Compat_NotificationActionText = 0x7f0f01c9; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f0300db, 0x7f0300dc, 0x7f0300dd, 0x7f0300de, 0x7f0300df, 0x7f0300e0 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300d9, 0x7f0300e1, 0x7f0300e2, 0x7f0300e3, 0x7f0301e6 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "87000385+ShubhamModi999@users.noreply.github.com" ]
87000385+ShubhamModi999@users.noreply.github.com
d1ca8466deb982901d0e079ab24f553ef8c263f2
620de2e6a5581846ee02da6494c29d8567b173b2
/app/src/main/java/com/dainavahood/workoutlogger/exercises/ExercisesActivity.java
c390f4ff526a791a26201f566093d7f7562033ef
[]
no_license
Dainiulis/WorkoutLogger
bc887e0afcdf139f6bd8587b4656aeba027fbd87
584bb629f1905fbcac27a0ce72441444addc5f71
refs/heads/master
2021-01-11T15:53:10.452036
2017-07-02T09:14:41
2017-07-02T09:14:41
53,480,484
0
0
null
2016-03-09T08:32:23
2016-03-09T08:20:28
null
UTF-8
Java
false
false
9,003
java
package com.dainavahood.workoutlogger.exercises; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.dainavahood.workoutlogger.MainActivity; import com.dainavahood.workoutlogger.R; import com.dainavahood.workoutlogger.extras.Constants; import com.dainavahood.workoutlogger.db.ExercisesDataSource; import com.dainavahood.workoutlogger.history.WorkoutsHistoryListActivity; import com.dainavahood.workoutlogger.model.Exercise; import com.dainavahood.workoutlogger.workouts.CreateSetGroupActivity; import com.dainavahood.workoutlogger.workouts.SetDetailsActivity; import com.dainavahood.workoutlogger.workouts.WorkoutLOGActivity; import com.dainavahood.workoutlogger.workouts.WorkoutsActivity; import java.util.ArrayList; import java.util.List; public class ExercisesActivity extends AppCompatActivity { public static final String MUSCLE_GROUP = "MUSCLE_GROUP"; ExercisesDataSource exercisesDataSource; private ArrayAdapter<Exercise> adapter; private String filteredText; private ListView lv; private List<Exercise> exercisesToRemove = new ArrayList<>(); private List<Exercise> exercises = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercises); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Helper inicijavimas ir duombazes sukurimas/paleidimas exercisesDataSource = new ExercisesDataSource(this); exercisesDataSource.open(); lv = (ListView) findViewById(R.id.exercisesListView); //Koki muscleGroup pasirinko final String muscleGroup = getIntent().getStringExtra(ExerciseGroupActivity.MUSCLE_GROUP); //pakeiciu title setTitle(muscleGroup); //Muscle group is kurio gauti duomenis is duomenubazes exercises = exercisesDataSource.findByMuscleGroup(muscleGroup); lv = refreshListView(exercises); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (getIntent().getIntExtra(CreateSetGroupActivity.CALLING_ACTIVITY, 0) == Constants.CREATE_SET_GROUP_ACTIVITY || getIntent().getIntExtra(WorkoutLOGActivity.WORKOUT_LOG_CALLING_ACTIVITY, 0 ) == Constants.WORKOUT_LOG_ACTIVITY) { Exercise exercise = (Exercise) parent.getItemAtPosition(position); Intent intent = new Intent(ExercisesActivity.this, SetDetailsActivity.class); if (getIntent().getIntExtra(CreateSetGroupActivity.CALLING_ACTIVITY, 0) == Constants.CREATE_SET_GROUP_ACTIVITY) { intent.putExtra(CreateSetGroupActivity.CALLING_ACTIVITY, Constants.CREATE_SET_GROUP_ACTIVITY); } else { intent.putExtra(WorkoutLOGActivity.WORKOUT_LOG_CALLING_ACTIVITY, Constants.WORKOUT_LOG_ACTIVITY); } intent.putExtra(Constants.EXERCISE_PACKAGE_NAME, exercise); intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); finish(); } } }); lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL); lv.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { final int checkedCount = lv.getCheckedItemCount(); switch (checkedCount) { case 1: mode.setTitle(checkedCount + " exercise selected"); break; default: mode.setTitle(checkedCount + " exercises selected"); break; } Exercise exercise = (Exercise) lv.getItemAtPosition(position); if (!checked) { exercisesToRemove.remove(exercise); } else { exercisesToRemove.add(exercise); } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { if (lv.getAdapter().getItem(0).getClass().equals(String.class)) { return false; } mode.getMenuInflater().inflate(R.menu.delete_multiple, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()){ case R.id.delete: for (Exercise exercise : exercisesToRemove) { exercisesDataSource.removeExercise(exercise); adapter.remove(exercise); } mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { exercises = exercisesDataSource.findAll(); exercisesToRemove.clear(); adapter.notifyDataSetChanged(); adapter.getFilter().filter(filteredText); } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ExercisesActivity.this, CreateExerciseActivity.class); intent.putExtra(MUSCLE_GROUP, muscleGroup); if (getIntent().getIntExtra(CreateSetGroupActivity.CALLING_ACTIVITY, 0) == Constants.CREATE_SET_GROUP_ACTIVITY){ intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); intent.putExtra(CreateSetGroupActivity.CALLING_ACTIVITY, Constants.CREATE_SET_GROUP_ACTIVITY); } else if (getIntent().getIntExtra(WorkoutLOGActivity.WORKOUT_LOG_CALLING_ACTIVITY, 0) == Constants.WORKOUT_LOG_ACTIVITY) { intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); intent.putExtra(WorkoutLOGActivity.WORKOUT_LOG_CALLING_ACTIVITY, Constants.WORKOUT_LOG_ACTIVITY); } startActivity(intent); finish(); } }); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @NonNull private ListView refreshListView(List<Exercise> exercises) { adapter = new ArrayAdapter<Exercise>(this, android.R.layout.simple_list_item_activated_1, android.R.id.text1, exercises); lv.setAdapter(adapter); android.widget.SearchView sv = (android.widget.SearchView) findViewById(R.id.searchView1); sv.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { filteredText = newText; adapter.getFilter().filter(newText); return false; } }); return lv; } @Override protected void onResume() { super.onResume(); exercisesDataSource.open(); } @Override protected void onPause() { super.onPause(); exercisesDataSource.close(); } }
[ "dainiusmie@gmail.com" ]
dainiusmie@gmail.com
4b09c2ff7c64c4910eabe4a2189b81d66c80bc27
91091cc7597135ee3c5af10046979fd62c5db16d
/ReflectionExam/gen/com/example/reflectionexam/R.java
932f96651f53a8c3fe31c1652270c4be436b59df
[]
no_license
stickto1/android_animation
23e82928ee5948da67eae1cdbb9bfbf69d241368
10eab3684c2279f984aec3c498d14e4ee42f8c95
refs/heads/master
2021-01-19T14:07:12.045413
2013-01-30T02:06:30
2013-01-30T02:06:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,095
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.reflectionexam; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; public static final int p2=0x7f020001; } public static final class id { public static final int layout=0x7f070000; public static final int menu_settings=0x7f070001; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int activity_main=0x7f060000; } public static final class string { public static final int app_name=0x7f040000; public static final int hello_world=0x7f040001; public static final int menu_settings=0x7f040002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
[ "ksfaly@clbee.com" ]
ksfaly@clbee.com
b8b77c8a4a51256662ae2a3d08967cd899576f11
f5427d82a994b7b05a3564abcb93a8a4bb6141cf
/src/com/cn/saint/ssh/spring/SpringAOPDemo.java
b7175ca38eaa4c23b502d8adf0b9daa4e3d33fae
[]
no_license
saintliu/I-love-code
2417a94555e38424fbe358f7ef3e50868efb6c49
52357638f12795c625da363ae2f8b220ee6bb6b7
refs/heads/master
2021-08-15T03:42:31.881191
2017-11-17T07:47:09
2017-11-17T07:47:09
111,076,229
1
0
null
null
null
null
UTF-8
Java
false
false
387
java
package com.cn.saint.ssh.spring; /** * @author saint * @version 创建时间:2017年8月30日 下午2:00:33 * 类说明 */ /** * 可以理解为:对业务功能进行前入/后入的的功能插入 * 是的业务功能可以专心业务的实施。 * * */ public class SpringAOPDemo { public static void main(String[] args) { // TODO Auto-generated method stub } }
[ "liuyusheng86@163.com" ]
liuyusheng86@163.com
81a6168e2b27c0f28328fee727e74cb383e68e26
a460c94f6965bc77a836b5b479081b0fd36ad685
/DP_&_ Greedy/Intermediate/Russian Doll Envelopes/Main.java
c976ce2eadc85ed51e02467db72c2c6a66f35df7
[]
no_license
immahesh1/DSA
e06799da11860a5f5b3041ac74f8d064aa061199
591c1fecee525670b152918afaf25df06843e8bc
refs/heads/master
2023-08-11T22:19:02.826045
2021-09-07T20:26:22
2021-09-07T20:26:22
295,623,373
0
0
null
null
null
null
UTF-8
Java
false
false
1,195
java
import java.util.*; import java.io.*; class Main{ public static class Envelope implements Comparable<Envelope>{ int w,h; public int compareTo(Envelope o){ return this.w - o.w; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); Envelope env[] = new Envelope[n]; for(int i=0; i<n; i++){ String str = br.readLine(); env[i] = new Envelope(); env[i].w = Integer.parseInt(str.split(" ")[0]); env[i].h = Integer.parseInt(str.split(" ")[1]); } Arrays.sort(env); int dp[] = new int[n]; int omax = 0; for(int i=0; i<n; i++){ int max = 0; for(int j=0; j<i; j++){ if(env[j].h <= env[i].h){ if(dp[j] > max){ max = dp[j]; } } } dp[i] = max + 1; if(dp[i] > omax){ omax = dp[i]; } } System.out.println(omax); } }
[ "mahesh_kumar1019@yahoo.in" ]
mahesh_kumar1019@yahoo.in
c0de1582a4ebe8f2ac7aba248c708cb09b7d6b70
b40458b5b81fda474d03f593b801eafb21b2897b
/library-net/src/main/java/com/young/library/net/cookie/CookieJarImpl.java
c2af222a824121e65d3a484d32640fa380ea7626
[]
no_license
Deep20160607/young_people
dc26c53f04fda8969cbc372f9588d275607e890c
7f9a2b3941290cfd6aa637544e3c0f8e86033610
refs/heads/master
2022-03-18T23:02:19.354772
2022-03-14T12:37:08
2022-03-14T12:37:08
469,724,978
0
1
null
null
null
null
UTF-8
Java
false
false
1,041
java
package com.young.library.net.cookie; import com.young.library.net.cookie.store.CookieStore; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; /** * CookieJar的实现类,默认管理了用户自己维护的Cookie * * @author dupeng * @version 2.6.0, 2019/3/26 10:32 PM * @since android 17MiddleTeacher */ public class CookieJarImpl implements CookieJar { private CookieStore cookieStore; public CookieJarImpl(CookieStore cookieStore) { if (cookieStore == null) { throw new IllegalArgumentException("cookieStore can not be null!"); } this.cookieStore = cookieStore; } @Override public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.saveCookie(url, cookies); } @Override public synchronized List<Cookie> loadForRequest(HttpUrl url) { return cookieStore.loadCookie(url); } public CookieStore getCookieStore() { return cookieStore; } }
[ "dupeng@qiyi.com" ]
dupeng@qiyi.com
7b1704dad41fc93bba526ade894bdc35b0122ba7
20d235f5ece12fa64093b8d0a49bd0f42761eb10
/src/test/java/io/github/miareko/test/concurrency/ProducerAndConsumerTest.java
4d616cb40663032cd3e1e36835aa17430594cba2
[]
no_license
miareko/java-practice
6d301b795e2843d9ead8d6200f6afb8d544f7712
d927c7de111306d089f216b70313051fa854abb7
refs/heads/master
2020-03-16T23:24:32.494600
2018-08-13T16:32:13
2018-08-13T16:32:13
133,076,033
0
0
null
null
null
null
UTF-8
Java
false
false
1,020
java
package io.github.miareko.test.concurrency; import io.github.miareko.samples.concurrency.producerandconsumer.LockCondition; import io.github.miareko.samples.concurrency.producerandconsumer.WaitNotify; import org.junit.Test; /** * Created by miareko on 2018/5/12. */ public class ProducerAndConsumerTest { @Test public void testWaitNotify() { Thread p = new Thread(new WaitNotify.Producer()); Thread c = new Thread(new WaitNotify.Consumer()); p.start(); c.start(); try { p.join(); c.join(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testLockCondition() { Thread p = new Thread(new LockCondition.Producer()); Thread c = new Thread(new LockCondition.Consumer()); p.start(); c.start(); try { p.join(); c.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
[ "teamfanlu@gmail.com" ]
teamfanlu@gmail.com
6f1fd8adfb1fcb15bc2575d0b3a8f18ab0c099b4
d4c6b053382a13aac151b47480be09492108c64e
/src/main/java/com/zyr/demo/exception/AuthorizationException.java
a366ecbdeb0a7fef06a9690e6914d158ced676f3
[]
no_license
zhanyr/mGameDemo
e27178bd7a2650e9eeb980ffee31239a3a8dea8f
63064eb507a1bb6b257f3f099fa48e326ec17e0d
refs/heads/master
2021-01-10T01:45:58.297006
2015-11-06T02:54:00
2015-11-06T02:54:00
45,168,745
0
0
null
null
null
null
UTF-8
Java
false
false
202
java
package com.zyr.demo.exception; /** * AuthorizationException * 自定义异常类:没有登录 * * @author zhanyr * @date 2015/11/1 */ public class AuthorizationException extends Exception { }
[ "zhanyr111@163.com" ]
zhanyr111@163.com
f281a7e0efb258b514c2ed5680f578c466ca0438
3394ed29aa46a88979d42376554ecb230f8b90e7
/src/pl/bartflor/Dao/FileDao.java
a903cdda68f3efaf0cc107faf3d304b136c04db8
[]
no_license
bartflor/FileUploadServlet
ab9028f627b0176af70934783eac3586b6dc4934
bb18eed0671acf3170b867b9b6bdbde9563161ac
refs/heads/master
2021-05-18T20:23:08.765270
2020-03-30T19:00:54
2020-03-30T19:00:54
251,401,917
0
0
null
null
null
null
UTF-8
Java
false
false
3,408
java
package pl.bartflor.Dao; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; public class FileDao { private DatabaseAcces dbAcces; private DaoFactory daoFactory; private ServletContext sContext; public FileDao(ServletContext sContext) { this.sContext = sContext; this.daoFactory = new DaoFactory(sContext); this.dbAcces = daoFactory.createDaoObject(); } public boolean setNewUpload(FileItem item, String owner, String path) { dbAcces = daoFactory.createDaoObject(); String sqlInsert = "INSERT INTO files_tbl(file_name, type, size, upload_date, owner, path) " + "VALUES (?, ?, ?, ?, ?, ?)"; dbAcces.executeStatement(sqlInsert, item.getName(), item.getContentType(), "" + item.getSize(), LocalDateTime.now().toString(), owner, path); return true; } public List<UploadFile> getFilesList(HttpSession userSession) { List<UploadFile> fileList = new LinkedList<>(); User user = (User) userSession.getAttribute("user"); String sqlQuerry = "SELECT file_id, file_name, type, size, upload_date FROM files_tbl WHERE owner=?;"; ResultSet result = dbAcces.getQuerryResult(sqlQuerry, user.getName()); try { while (result.next()) { UploadFile file = new UploadFile(result.getString("file_id"), result.getString("file_name"), result.getString("type"), result.getString("size"), result.getString("upload_date")); fileList.add(file); } } catch (SQLException e) { e.printStackTrace(); return null; } finally { dbAcces.close(); } return fileList; } public String getFilePath(String fileId, HttpSession userSession) { User user = (User) userSession.getAttribute("user"); String sqlQuerry = "SELECT path FROM files_tbl WHERE owner=? AND file_id=?;"; ResultSet result = dbAcces.getQuerryResult(sqlQuerry, user.getName(), fileId); try { while (result.next()) { return result.getString("path"); } } catch (SQLException e) { e.printStackTrace(); return null; } finally { dbAcces.close(); } return null; } public boolean deleteFile(String fileId, HttpSession userSession) { User user = (User) userSession.getAttribute("user"); String sqlQuerry = "DELETE FROM files_tbl WHERE owner=? AND file_id=?;"; return dbAcces.executeStatement(sqlQuerry, user.getName(), fileId); } public double getFilesSize(HttpSession userSession) { User user = (User) userSession.getAttribute("user"); String sqlQuerry = "SELECT SUM(size) FROM files_tbl WHERE owner=?;"; ResultSet result = dbAcces.getQuerryResult(sqlQuerry, user.getName()); try { while (result.next()) { String totalFilesSize = result.getString("SUM(size)"); if (totalFilesSize != null) { return Double.parseDouble(result.getString("SUM(size)")); } else { return 0.0; } } } catch (SQLException e) { e.printStackTrace(); return 0; } finally { dbAcces.close(); } return 0; } public StorageInfo getStorageInfo(HttpSession userSession) { int totalStorage = Integer.parseInt(sContext.getInitParameter("totalStorageSpace")); int filesSize = (int) getFilesSize(userSession); int spaceLeft = totalStorage - filesSize; return new StorageInfo(totalStorage, filesSize, spaceLeft); } }
[ "bartflor@wp.pl" ]
bartflor@wp.pl
01c305e5102b34f929b2bffcd0814461807c025b
1f5d09d699164e7f89cd004a3570c61529133e17
/java/Aula 12/Atividade3.java
db6eb7fad80c2f7592e0eb19c70a87aba26ca329
[]
no_license
J-H-N-Campos/Algoritmos
71392bf05d47cfebf702fea88fa441ff059e3b1f
5c448703a81a3797de652e25eef61d04b53e4675
refs/heads/master
2022-11-16T17:16:45.494637
2020-07-16T23:37:44
2020-07-16T23:37:44
280,280,148
0
0
null
null
null
null
UTF-8
Java
false
false
2,464
java
public class Atividade3{ public static void main (String args[]){ int [][] A = new int [10][10]; int [][] B = new int [10][10]; int i,j,contador,aux,aux2; for (i=0;i<10; i++){ for (j=0;j<10; j++){ A[i][j] = (int)(Math.random()*10); B[i][j] = A[i][j]; } } System.out.println("MATRIZ PRIM?RIA"); //MOSTRAR A MATRIZ for (i=0;i<10; i++){ for (j=0;j<10; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } //-------TROCA A LINHA------- for (j=0;j<10; j++){ A[1][j] = B[7][j]; A[7][j] = B[1][j]; } System.out.println(); System.out.println("MATRIZ COM A TROCA DA LINHA"); //MOSTRAR A MATRIZ for (i=0;i<10; i++){ for (j=0;j<10; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } // TRANSFORMA A "B" NA PRINCIPAL for (i=0;i<10; i++){ for (j=0;j<10; j++){ B[i][j]=A[i][j]; } } //------TROCA COLUNA-------- for (i=0;i<10; i++){ A[i][3] = B[i][9]; A[i][9] = B[i][3]; } System.out.println(); System.out.println("MATRIZ COM A TROCA DA COLUNA"); //MOSTRAR A MATRIZ for (i=0;i<10; i++){ for (j=0;j<10; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } System.out.println(); // TRANSFORMA A "B" NA PRINCIPAL for (i=0;i<10; i++){ for (j=0;j<10; j++){ B[i][j]=A[i][j]; } } System.out.println("TROCA DE POSI??ES DA DIAGONAL PRIMARIA COM SECUND?RIA"); //TROCA DE POSI??ES DA DIAGONAL PRIMARIA COM SECUND?RIA contador = 10 - 1; for (i = 0; i < 10; i++){ aux = A[i][i]; A[i][i] = A[i][contador]; A[i][contador] = aux; contador--; } //MOSTRA MATRIZ for (i=0;i<10; i++){ for (j=0;j<10; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } // TRANSFORMA A "B" NA PRINCIPAL for (i=0;i<10; i++){ for (j=0;j<10; j++){ B[i][j]=A[i][j]; } } System.out.println(); System.out.println("TROCA LINHA 5 COM COLUNA 10"); for(i = 0; i < 10; i++){ aux2 = A[4][i]; A[4][i] = A[10 - i -1][10 - 1]; A[10 - i -1][10 - 1] = aux2; } //MOSTRA MATRIZ for (i=0;i<10; i++){ for (j=0;j<10; j++){ System.out.print(A[i][j]+" "); } System.out.println(); } } }
[ "joao.campos@universo.univates.br" ]
joao.campos@universo.univates.br
ff50a7cac2f2eefe9633034e9975dda0ebcb10ee
f1f2a8f45aef50de8a369940470ed07655086fc6
/week-03/Day-04/test/count_letters/CountLettersTest.java
efb1fdd761c100c0736995c240a3c78bbf6b7b64
[]
no_license
green-fox-academy/ah-mady
b0ce72fae21fec505a15c9335845c88c6b9b76b2
82bfb38fdb20100205edcdc7ef7484bd0c412090
refs/heads/master
2021-01-15T01:57:42.405534
2020-04-01T12:06:20
2020-04-01T12:06:20
242,840,193
0
0
null
null
null
null
UTF-8
Java
false
false
518
java
package count_letters; import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import org.junit.jupiter.api.Test; class CountLettersTest { @Test public void countCharsInString() { CountLetters countString = new CountLetters(); String inputWord = "Ahmed"; HashMap<Character,Integer> map = new HashMap<>(); map.put('A', 1); map.put('h',2); map.put('m',3); map.put('e',4); map.put('d',5); assertEquals(map, countString.countCharsInString(inputWord)); } }
[ "ahmad_bhai28@yahoo.com" ]
ahmad_bhai28@yahoo.com
c8166250137d33dcfce3244e8672105283601b37
c58bb8db16dca4eb104d60104a5f1551f4129092
/net.certware.sacm.edit/bin/src-gen/net/certware/sacm/SACM/Evidence/parts/ObjectPropertiesEditionPart.java
f38ffe433db864eac00222daa22614adee78c470
[ "Apache-2.0" ]
permissive
johnsteele/CertWare
361537d76a76e8c7eb55cc652da5b3beb5b26b66
f63ff91edaaf2b0718b51a34cda0136f3cdbb085
refs/heads/master
2021-01-16T19:16:08.546554
2014-07-03T16:49:40
2014-07-03T16:49:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,573
java
// Copyright (c) 2013 United States Government as represented by the National Aeronautics and Space Administration. All rights reserved. package net.certware.sacm.SACM.Evidence.parts; // Start of user code for imports import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.eef.runtime.ui.widgets.ButtonsModeEnum; import org.eclipse.emf.eef.runtime.ui.widgets.eobjflatcombo.EObjectFlatComboSettings; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings; import org.eclipse.jface.viewers.ViewerFilter; // End of user code /** * @author Kestrel Technology LLC * */ public interface ObjectPropertiesEditionPart { /** * @return the id * */ public String getId(); /** * Defines a new id * @param newValue the new id to set * */ public void setId(String newValue); /** * Init the timing * @param current the current value * @param containgFeature the feature where to navigate if necessary * @param feature the feature to manage */ public void initTiming(ReferencesTableSettings settings); /** * Update the timing * @param newValue the timing to update * */ public void updateTiming(); /** * Adds the given filter to the timing edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addFilterToTiming(ViewerFilter filter); /** * Adds the given filter to the timing edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addBusinessFilterToTiming(ViewerFilter filter); /** * @return true if the given element is contained inside the timing table * */ public boolean isContainedInTimingTable(EObject element); /** * Init the custody * @param current the current value * @param containgFeature the feature where to navigate if necessary * @param feature the feature to manage */ public void initCustody(ReferencesTableSettings settings); /** * Update the custody * @param newValue the custody to update * */ public void updateCustody(); /** * Adds the given filter to the custody edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addFilterToCustody(ViewerFilter filter); /** * Adds the given filter to the custody edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addBusinessFilterToCustody(ViewerFilter filter); /** * @return true if the given element is contained inside the custody table * */ public boolean isContainedInCustodyTable(EObject element); /** * Init the provenance * @param current the current value * @param containgFeature the feature where to navigate if necessary * @param feature the feature to manage */ public void initProvenance(ReferencesTableSettings settings); /** * Update the provenance * @param newValue the provenance to update * */ public void updateProvenance(); /** * Adds the given filter to the provenance edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addFilterToProvenance(ViewerFilter filter); /** * Adds the given filter to the provenance edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addBusinessFilterToProvenance(ViewerFilter filter); /** * @return true if the given element is contained inside the provenance table * */ public boolean isContainedInProvenanceTable(EObject element); /** * Init the event * @param current the current value * @param containgFeature the feature where to navigate if necessary * @param feature the feature to manage */ public void initEvent(ReferencesTableSettings settings); /** * Update the event * @param newValue the event to update * */ public void updateEvent(); /** * Adds the given filter to the event edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addFilterToEvent(ViewerFilter filter); /** * Adds the given filter to the event edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addBusinessFilterToEvent(ViewerFilter filter); /** * @return true if the given element is contained inside the event table * */ public boolean isContainedInEventTable(EObject element); /** * @return the name * */ public String getName(); /** * Defines a new name * @param newValue the new name to set * */ public void setName(String newValue); /** * @return the concept * */ public String getConcept(); /** * Defines a new concept * @param newValue the new concept to set * */ public void setConcept(String newValue); /** * @return the definition * */ public EObject getDefinition(); /** * Init the definition * @param settings the combo setting */ public void initDefinition(EObjectFlatComboSettings settings); /** * Defines a new definition * @param newValue the new definition to set * */ public void setDefinition(EObject newValue); /** * Defines the button mode * @param newValue the new mode to set * */ public void setDefinitionButtonMode(ButtonsModeEnum newValue); /** * Adds the given filter to the definition edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addFilterToDefinition(ViewerFilter filter); /** * Adds the given filter to the definition edition editor. * * @param filter * a viewer filter * @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter) * */ public void addBusinessFilterToDefinition(ViewerFilter filter); /** * Returns the internationalized title text. * * @return the internationalized title text. * */ public String getTitle(); // Start of user code for additional methods // End of user code }
[ "mrbcuda@mac.com" ]
mrbcuda@mac.com
88d3429fa89ee38809c8ad226218c3dda950cafa
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2018/4/BatchOperationService.java
bd01ee7aa0c2cb0b41a5a0e5d7d0c113d1cbe62b
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
6,720
java
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server.rest.web; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriInfo; import org.neo4j.server.rest.batch.BatchOperationResults; import org.neo4j.server.rest.batch.NonStreamingBatchOperations; import org.neo4j.server.rest.repr.OutputFormat; import org.neo4j.server.rest.repr.RepresentationWriteHandler; import org.neo4j.server.rest.repr.StreamingFormat; import org.neo4j.server.web.HttpHeaderUtils; import org.neo4j.server.web.WebServer; import org.neo4j.udc.UsageData; import static org.neo4j.udc.UsageDataKeys.Features.http_batch_endpoint; import static org.neo4j.udc.UsageDataKeys.features; @Path( "/batch" ) public class BatchOperationService { private static final Logger LOGGER = Log.getLogger(BatchOperationService.class); private final OutputFormat output; private final WebServer webServer; private final UsageData usage; private RepresentationWriteHandler representationWriteHandler = RepresentationWriteHandler.DO_NOTHING; public BatchOperationService( @Context WebServer webServer, @Context OutputFormat output, @Context UsageData usage ) { this.output = output; this.webServer = webServer; this.usage = usage; } public void setRepresentationWriteHandler( RepresentationWriteHandler representationWriteHandler ) { this.representationWriteHandler = representationWriteHandler; } @POST public Response performBatchOperations( @Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @Context HttpServletRequest req, InputStream body ) { usage.get( features ).flag( http_batch_endpoint ); if ( isStreaming( httpHeaders ) ) { return batchProcessAndStream( uriInfo, httpHeaders, req, body ); } return batchProcess( uriInfo, httpHeaders, req, body ); } private Response batchProcessAndStream( final UriInfo uriInfo, final HttpHeaders httpHeaders, final HttpServletRequest req, final InputStream body ) { try { final StreamingOutput stream = output -> { try { final ServletOutputStream servletOutputStream = new ServletOutputStream() { @Override public void write( int i ) throws IOException { output.write( i ); } @Override public boolean isReady() { return true; } @Override public void setWriteListener( WriteListener writeListener ) { try { writeListener.onWritePossible(); } catch ( IOException e ) { // Ignore } } }; new StreamingBatchOperations( webServer ).readAndExecuteOperations( uriInfo, httpHeaders, req, body, servletOutputStream ); representationWriteHandler.onRepresentationWritten(); } catch ( Exception e ) { LOGGER.warn( "Error executing batch request ", e ); } finally { representationWriteHandler.onRepresentationFinal(); } }; return Response.ok(stream) .type( HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE) ).build(); } catch ( Exception e ) { return output.serverError( e ); } } private Response batchProcess( UriInfo uriInfo, HttpHeaders httpHeaders, HttpServletRequest req, InputStream body ) { try { NonStreamingBatchOperations batchOperations = new NonStreamingBatchOperations( webServer ); BatchOperationResults results = batchOperations.performBatchJobs( uriInfo, httpHeaders, req, body ); Response res = Response.ok().entity(results.toJSON()) .type(HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE)).build(); representationWriteHandler.onRepresentationWritten(); return res; } catch ( Exception e ) { return output.serverError( e ); } finally { representationWriteHandler.onRepresentationFinal(); } } private boolean isStreaming( HttpHeaders httpHeaders ) { if ( "true".equalsIgnoreCase( httpHeaders.getRequestHeaders().getFirst( StreamingFormat.STREAM_HEADER ) ) ) { return true; } for ( MediaType mediaType : httpHeaders.getAcceptableMediaTypes() ) { Map<String, String> parameters = mediaType.getParameters(); if ( parameters.containsKey( "stream" ) && "true".equalsIgnoreCase( parameters.get( "stream" ) ) ) { return true; } } return false; } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
c41d8aed97d194cfcbb84b16cc397db85d1a704e
71ce7a31684ac1130eeb12afa1effce17b52a7c0
/osmosis-geojson/src/main/java/org/openstreetmap/osmosis/geojson/common/CompressionMethod.java
dc9ab18d78eaff06791a34046fbeea4f8d1ef63c
[]
no_license
RatomicLab/osmosis
e2e0b4284ed2d9fe30abf3385d7b97f9928427af
5cbae10fca84b6d5e7ebd831e282509c4f133e5f
refs/heads/master
2020-12-30T17:50:31.565141
2015-02-26T21:17:23
2015-02-26T21:17:23
31,125,205
0
0
null
2015-02-21T12:39:16
2015-02-21T12:39:16
null
UTF-8
Java
false
false
483
java
// This software is released into the Public Domain. See copying.txt for details. package org.openstreetmap.osmosis.geojson.common; /** * Defines the various compression methods supported by xml tasks. * * @author Brett Henderson */ public enum CompressionMethod { /** * Specifies that no compression be performed. */ None, /** * Specifies that GZip compression should be used. */ GZip, /** * Specifies that BZip2 compression should be used. */ BZip2 }
[ "olicarbo@gmail.com" ]
olicarbo@gmail.com
bd92d7c22a9dea583f6fdaeac342c44a6a9abe55
ec3d38beb8b58093c4b69902e23094aa9c44ab08
/src/main/java/com/mall/dao/ProductMapper.java
45d6351fc2fdc7e702fc1fa776f2b06ebf7712ae
[]
no_license
chuckma/mall_learn
75987ea70c826f72fb85b52585d3f6e0dfd923ea
d9b119677461cae8ab6197f533de6c85fc707a74
refs/heads/master
2021-01-19T22:49:04.770003
2018-06-13T13:05:36
2018-06-13T13:05:36
88,873,908
2
0
null
2018-06-13T13:05:37
2017-04-20T14:18:27
Java
UTF-8
Java
false
false
870
java
package com.mall.dao; import com.mall.pojo.Product; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ProductMapper { int deleteByPrimaryKey(Integer id); int insert(Product record); int insertSelective(Product record); Product selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Product record); int updateByPrimaryKey(Product record); List<Product> selectList(); List<Product> selectByNameAndProductId(@Param("productName") String productName, @Param("productId") Integer productId); List<Product> selectByNameAndCategoryIds(@Param("productName") String productName, @Param("categoryIdList") List<Integer> categoryIdList); // 此处一定要用Integer ,因为int 无法为null,考虑到很多商品已经删除的情况. Integer selectStockByProductId(Integer id); }
[ "robbincen@163.com" ]
robbincen@163.com
082bf3fbc11e74caef9b97bb3d580f8001c31bfc
a551aeba9c94bd262ff1741b5994b451c307aa12
/MainWindowM.java
14e527aa6acf8e75a4863c156a77e2c98c5925bf
[]
no_license
dimax0505/git-geek-java2
36fd6ab22da0ad8c0cd0a74c2a2df8f24d86f4ef
e2ace1747be267ebaf89ac92a5ee0948a2913cc7
refs/heads/master
2020-03-24T03:52:31.585041
2018-07-29T12:48:14
2018-07-29T12:48:14
142,435,351
0
0
null
2018-07-29T12:48:15
2018-07-26T12:04:10
Java
UTF-8
Java
false
false
2,748
java
package ru.geekbrains.maksimov.geek; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class MainWindowM extends JFrame { private static final int POS_X = 600; private static final int POS_Y = 200; private static final int WINDOW_WIDTH = 800; private static final int WINDOW_HEIGHT = 600; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new MainWindowM(); } }); } MainWindowM() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(POS_X,POS_Y,WINDOW_WIDTH,WINDOW_HEIGHT); setTitle("Пузырики"); GameCanvas gameCanvas = new GameCanvas(this); add(gameCanvas, BorderLayout.CENTER); addMouseListener(new MouseAdapter() { @Override public void mouseClicked (MouseEvent e) { super.mouseClicked(e); if (e.getButton()==MouseEvent.BUTTON3) { sprites[currentBalls]=new OneBall(); currentBalls++; if (currentBalls==sprites.length-5){ Sprites[] spritestemp = new Sprites[currentBalls*2]; for (int i=0; i<sprites.length; i++) { spritestemp[i]=sprites[i]; } sprites = spritestemp; } } if (e.getButton()==MouseEvent.BUTTON1) { if (currentBalls>0) { sprites[currentBalls] = null; currentBalls--; } } } }); repaint(); initGame(); setVisible(true); } int currentBalls = 5; int maxBalls = 20; Sprites[] sprites = new Sprites[maxBalls]; Backgrounds backgrounds; private void initGame() { for (int i = 0; i < currentBalls; i++) { sprites[i] = new OneBall(); } backgrounds = new Backgrounds(); } public void onDrawFrame(GameCanvas canvas, Graphics g, float deltaTime) { update(canvas, deltaTime); render(canvas, g); } private void update(GameCanvas canvas, float deltaTime) { backgrounds.update(); for (int i = 0; i < currentBalls; i++) { sprites[i].update(canvas, deltaTime); } } private void render(GameCanvas canvas, Graphics g) { backgrounds.render(canvas,g); for (int i = 0; i < currentBalls; i++) { sprites[i].render(canvas, g); } } }
[ "dimax0505@gmail.com" ]
dimax0505@gmail.com
0614c5bf4266234e8b731b8f8b8176c77c26a557
3773967acf16d57d5e698eda539e024c5ee941e2
/app/src/main/java/swasolutions/com/wdpos/adaptadores/FacturaAdapter.java
365d70b7dfe5c9223694aa84c49e0dd98bb530eb
[]
no_license
sebasorozco101596/swaventas
deb8206d93561709681742cf36f438211ddbc19c
1a8d698e7b120e131d187b6582bffa65908cc198
refs/heads/master
2021-05-14T04:00:12.443610
2018-06-19T20:23:54
2018-06-19T20:23:54
116,632,132
0
0
null
null
null
null
UTF-8
Java
false
false
2,793
java
package swasolutions.com.wdpos.adaptadores; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import swasolutions.com.wdpos.R; import swasolutions.com.wdpos.vo.clases_objeto.ProductoCarrito; /** * Created by sebas on 24/06/2017. */ public class FacturaAdapter extends RecyclerView.Adapter<FacturaAdapter.FacturaViewHolder>{ private List<ProductoCarrito> productos; private String tipo; /** * Builder class * @param productos */ public FacturaAdapter(List<ProductoCarrito> productos,String tipo){ this.productos=productos; this.tipo=tipo; } @Override public FacturaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_productos_factura, parent,false); return new FacturaViewHolder(view); } @Override public void onBindViewHolder(final FacturaViewHolder holder, int position) { holder.nombre.setText(productos.get(position).getNombre().toLowerCase()); holder.total.setText(""+(verificarPrecio(productos.get(position).getPrecio(), productos.get(position).getPrecio2(),tipo)*productos.get(position).getCantidad())); holder.cantidad.setText(""+productos.get(position).getCantidad()); holder.cardView.getBackground().setAlpha(0); } private int verificarPrecio(int precio, int precio2,String tipo) { int numero=0; if("Contado".equals(tipo)){ if(precio>=precio2){ numero=precio2; }else{ numero=precio; } }else if("Credito".equals(tipo)){ if(precio>=precio2){ numero=precio; }else{ numero=precio2; } } return numero; } @Override public int getItemCount() { return productos.size(); } static class FacturaViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; private TextView nombre; private TextView total; private TextView cantidad; public FacturaViewHolder(View itemView) { super(itemView); cardView= (CardView) itemView.findViewById(R.id.cardViewProductosFactura); nombre= (TextView) itemView.findViewById(R.id.txtNombre_CardViewProductosFactura); cantidad= (TextView) itemView.findViewById(R.id.txtCantidad_CardViewProductosFactura); total = (TextView) itemView.findViewById(R.id.txtPrecio_CardViewFactura); } } }
[ "sebasorozcob@gmail.com" ]
sebasorozcob@gmail.com
0c4aaebff038a5ef1abd3e92d2f386c7a41c0934
550a1fe08a7149f9b5d939b6ce156a103155f7ba
/app/src/androidTest/java/com/example/android/courtcounteraf/ExampleInstrumentedTest.java
06fda7ad6aae4c2f678f7146b088ae9ca0dea0ab
[]
no_license
AhmadTalat111/CourtCounterAF
6e735e57a0adf4dcbaef2d63c5454dbed27d487f
d615369a69e0a11ef74217d263b4ff48db151ea9
refs/heads/master
2020-03-21T08:34:24.825851
2018-10-06T21:15:53
2018-10-06T21:15:53
102,913,413
0
0
null
null
null
null
UTF-8
Java
false
false
772
java
package com.example.android.courtcounteraf; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.android.courtcounteraf", appContext.getPackageName()); } }
[ "ahmadtalat111@gmail.com" ]
ahmadtalat111@gmail.com
7db75cd1ebf877d6abb2c65088a25eeba9343d7c
91ff4289911ef135a34a2e3e6ae54377f7e00705
/nowcoder/chap07_BinaryTree/Tree_7_13_LongestDistance.java
c4b186ffe18a5885d7fd02c993ddef9f1ced6c4e
[]
no_license
liufengyuqing/Code_Practice
29971ef91b9969bf0589bae71cfe402ad334fc93
dce8cf254f99253d3b26def6fc0626d95b508998
refs/heads/master
2021-05-15T18:51:39.979984
2017-05-25T08:56:03
2017-05-25T08:56:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,203
java
package chap07_BinaryTree; /** * Created by xing on 5/1/17. * 从二叉树的节点A出发,可以向上或者向下走,但沿途的节点只能经过一次,当到达节点B时,路径上的节点数叫作A到B的距离。对于给定的一棵二叉树,求整棵树上节点间的最大距离。 给定一个二叉树的头结点root,请返回最大距离。保证点数大于等于2小于等于500. */ import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ // 递归解法,比递归解法简洁很多 public class LongestDistance { private int longest = 0; // save the longest distance; public int findLongest(TreeNode root) { // write code here int depth = findDist(root); return longest; } public int findDist(TreeNode root) { if (root == null) { return 0; } int left = findDist(root.left); int right = findDist(root.right); longest = Math.max(left + right + 1, longest); return Math.max(left, right) + 1; } } // 非递归解法,用后序遍历
[ "phoebe800@gmail.com" ]
phoebe800@gmail.com
7ab12acbd24d79a7e14124409a1880459e35f857
d81f128a33dd66a11b74e929cb6637b4d73b1c09
/Saffron_OSGI/.svn/pristine/5d/5d66c8422f50c629e3ea5753357d4aa2f37793ab.svn-base
8792cf57ac4375adcf79c48d413287c4e7c064bb
[]
no_license
deepakdinakaran86/poc
f56e146f01b66fd5231b3e16d1e5bf55ae4405c6
9aa4f845d3355f6ce8c5e205d42d66a369f671bb
refs/heads/master
2020-04-03T10:05:08.550330
2016-08-11T06:57:57
2016-08-11T06:57:57
65,439,459
0
1
null
null
null
null
UTF-8
Java
false
false
4,442
/** * */ package com.pcs.device.gateway.ruptela.config; /** * @author pcseg310 * */ public interface PropertyKeys { static final String CACHE_PROVIDER = "ruptela.devicemanager.cacheprovider"; static final String CACHE_PROVIDER_CONFIG_PATH = "ruptela.devicemanager.cacheprovider.config.path"; static final String DEVICE_COMMAND_CACHE = "ruptela.command.cache"; static final String DEVICE_SESSION_CACHE = "ruptela.devicemanager.cache.session"; static final String DEVICE_SESSION_CACHE_TIMEOUT = "ruptela.devicemanager.cache.session.timeout"; static final String DEVICE_CONFIGURATION_CACHE = "ruptela.devicemanager.cache.configuration"; static final String DEVICE_KEYS_CACHE = "ruptela.devicemanager.cache.keys"; static final String DEVICE_POINTS_PROTOCOL_CACHE = "ruptela.devicemanager.cache.points.protocol"; static final String REMOTE_PLATFORM_IP = "ruptela.devicemanager.remote.platform.hostIp"; static final String REMOTE_PLATFORM_PORT = "ruptela.devicemanager.remote.platform.port"; static final String REMOTE_PLATFORM_SCHEME = "ruptela.devicemanager.remote.platform.scheme"; static final String AUTHENTICATION_URL = "ruptela.devicemanager.remote.authentication.url"; static final String CONFIGURATION_URL = "ruptela.devicemanager.remote.configuration.url"; static final String DATASOURCE_REGISTER_URL = "ruptela.devicemanager.datasource.register.url"; static final String DATASOURCE_UPDATE_URL = "ruptela.devicemanager.datasource.update.url"; static final String DATASOURCE_PUBLISH_URL = "ruptela.devicemanager.datasource.publish.url"; static final String DATASOURCE_PLATFORM_IP ="ruptela.devicemanager.datasource.platform.hostIp"; static final String DATASOURCE_PLATFORM_PORT="ruptela.devicemanager.datasource.platform.port"; static final String ENTITY_PLATFORM_IP ="ruptela.devicemanager.entity.platform.hostIp"; static final String ENTITY_PLATFORM_PORT="ruptela.devicemanager.entity.platform.port"; static final String DEVICE_DATASOURCE_UPDATE_URL = "ruptela.devicemanager.device.datasource.update.url"; static final String DATADISTRIBUTOR_IP="ruptela.devicemanager.datadistributor.ip"; static final String DATADISTRIBUTOR_REGISTRY_NAME = "ruptela.devicemanager.datadistributor.registryname"; static final String ANALYZED_MESSAGE_STREAM= "ruptela.devicemanager.datadistributor.analyzedmessagestream"; static final String DECODED_MESSAGE_STREAM = "ruptela.devicemanager.datadistributor.decodedmessagestream"; static final String DATADISTRIBUTOR_PORT = "ruptela.devicemanager.datadistributor.port"; static final String DEVICE_PROTOCOL_POINTS_URL = "ruptela.devicemanager.datasource.device.points"; //Gateway configurations static final String START_MODE = "ruptela.devicegateway.startmode"; static final String START_WITH_DELAY = "ruptela.devicegateway.startwithdelay"; static final String TCP_DATA_SERVER_DOMAIN = "ruptela.devicegateway.tcp.dataserverdomain"; static final String TCP_DATA_SERVER_IP = "ruptela.devicegateway.tcp.dataserverip"; static final String TCP_DATA_SERVER_PORT = "ruptela.devicegateway.tcp.dataserverport"; static final String TCP_CONTROL_SERVER_PORT = "ruptela.devicegateway.tcp.controlserverport"; static final String TCP_DATA_COMMAND_PORT = "ruptela.devicegateway.tcp.commandport"; static final String UDP_DATA_SERVER_DOMAIN = "ruptela.devicegateway.udp.dataserverdomain"; static final String UDP_DATA_SERVER_IP = "ruptela.devicegateway.udp.dataserverip"; static final String UDP_DATA_SERVER_PORT = "ruptela.devicegateway.udp.dataserverport"; static final String UDP_CONTROL_SERVER_PORT = "ruptela.devicegateway.udp.controlserverport"; static final String UDP_DATA_COMMAND_PORT = "ruptela.devicegateway.udp.commandport"; static final String DATA_DISTRIBUTOR_IP = "ruptela.devicegateway.datadistributor.ip"; static final String DATA_DISTRIBUTOR_PORT = "ruptela.devicegateway.datadistributor.port"; static final String REALTIME_DATA_PERSIST_TOPIC ="ruptela.devicegateway.realtime.persist.topic"; static final String COMMAND_REGISTER_URL = "ruptela.devicegateway.command.register.url"; static final String COMMAND_REGISTER = "ruptela.devicegateway.command.register"; static final String FMXXX_MODEL = "FMS"; static final String FMXXX_PROTOCOL = "FMPRO"; static final String FMXXX_TYPE = "Telematics"; static final String FMXXX_VENDOR = "Ruptela"; static final String FMXXX_VERSION = "1.02"; static final String DIAG_ENABLE="diag.enable"; }
[ "PCSEG288@pcs.com" ]
PCSEG288@pcs.com
fb8fc540c76c3ae036230ac977109754613ccb22
0e14cb23b50a559a791a3a3fad1619528c40608f
/gen/com/islamic/monabihalzakren/BuildConfig.java
9cfb68efed1283b30122deb1fbfd1c26db477eae
[]
no_license
Shehab-Muhammad/Monabih-AlZakren
66ed11a7233b92eb63cca1a85020ed29c1194bb7
c22bf3b48271b74531e160194bdd13a8fd5ecfd8
refs/heads/master
2021-01-13T08:03:02.156321
2016-10-24T00:05:14
2016-10-24T00:06:26
71,682,203
0
0
null
null
null
null
UTF-8
Java
false
false
169
java
/** Automatically generated file. DO NOT MODIFY */ package com.islamic.monabihalzakren; public final class BuildConfig { public final static boolean DEBUG = true; }
[ "shhab7@gmail.com" ]
shhab7@gmail.com
1a25945799d6e58763197da929d9a9c1a1a81e79
6a0c6f63e8f8cd6dafe8bfeab44a8f59fd75d24b
/androidapp/app/src/main/java/com/cantech/cannect/fragment/MAF_Fragment.java
20450a8831e815b60ce4eac3633d8814d473bbe1
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
yazicienes/capstone
d40c733bc44b111dcba522ce6d255815a88bbd7d
df2652471b58efdbdce9c00ece3c3c01f34aef07
refs/heads/master
2023-02-04T22:27:48.660474
2020-12-23T00:57:52
2020-12-23T00:57:52
323,765,832
1
0
null
null
null
null
UTF-8
Java
false
false
5,071
java
package com.cantech.cannect.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.cantech.cannect.DataParsing; import com.cantech.cannect.R; import com.cantech.cannect.SharedPref; /** * A simple {@link Fragment} subclass. * Use the {@link MAF_Fragment#newInstance} factory method to * create an instance of this fragment. */ public class MAF_Fragment extends Fragment { private static final String TAG = "MAF Fragment"; TextView mafsenosr; SharedPref sharedPref; private Context mContext; private DataParsing dataParsing; private StringBuilder data_message; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public MAF_Fragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MAF_Fragment. */ // TODO: Rename and change types and number of parameters public static MAF_Fragment newInstance(String param1, String param2) { MAF_Fragment fragment = new MAF_Fragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onAttach(@NonNull Context context) { super.onAttach(mContext); mContext = context; LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, new IntentFilter("incomingMessage")); } @Override public void onCreate(Bundle savedInstanceState) { sharedPref = new SharedPref(mContext); //set theme if(sharedPref.loadDarkModeState()==true){ mContext.getTheme().applyStyle(R.style.darkTheme, true); }else{ mContext.getTheme().applyStyle(R.style.AppTheme, true); } super.onCreate(savedInstanceState); data_message = new StringBuilder(); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_maf, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mafsenosr = view.findViewById(R.id.MAF_TextView); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, new IntentFilter("incomingMessage")); super.onResume(); } @Override public void onPause() { LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver); super.onPause(); } @Override public void onDetach() { super.onDetach(); mContext = null; } @Override public void onDestroyView() { super.onDestroyView(); } BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String text = intent.getStringExtra("theMessage"); Log.d(TAG, text); data_message.append(text + "\n"); String[] parsed = dataParsing.convertOBD2FrameToUserFormat(data_message.toString()); try { switch (parsed[0]) { case "MAF SENSOR": //changing string to float. mafsenosr.setText(parsed[1]); break; default: break; } }catch (Exception e){ e.printStackTrace(); } if (data_message.length()>=32){ data_message.setLength(0); } } }; }
[ "raung@sfu.ca" ]
raung@sfu.ca
fdf2eb4144ad02a87de01306679a1edb4ebe7838
667728b86381407d7e775403a06a3ea4b3404d7f
/src/main/java/com/myself/wechatfileupload/util/HttpServletRequestUtil.java
08a8e443c33ece6c32b72cae54d7f5c699b4f63b
[]
no_license
gotheworld/SBToWxFileUpload
1d89b5130ee525105ee9218e9855b02d5d1f992e
107874a8b66a130132922e52485a508e089bc83b
refs/heads/master
2021-09-20T16:15:18.116297
2018-08-12T08:45:07
2018-08-12T08:45:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,312
java
package com.myself.wechatfileupload.util; import javax.servlet.http.HttpServletRequest; /** * @Author:UncleCatMySelf * @Email:zhupeijie_java@126.com * @QQ:1341933031 * @Date:Created in 11:14 2018\8\11 0011 */ public class HttpServletRequestUtil { public static int getInt(HttpServletRequest request, String key) { try { return Integer.decode(request.getParameter(key)); } catch (Exception e) { return -1; } } public static long getLong(HttpServletRequest request, String key) { try { return Long.valueOf(request.getParameter(key)); } catch (Exception e) { return -1; } } public static Double getDouble(HttpServletRequest request, String key) { try { return Double.valueOf(request.getParameter(key)); } catch (Exception e) { return -1d; } } public static boolean getBoolean(HttpServletRequest request, String key) { try { return Boolean.valueOf(request.getParameter(key)); } catch (Exception e) { return false; } } public static String getString(HttpServletRequest request, String key) { try { String result = request.getParameter(key); if (result != null) { result = result.trim(); } if ("".equals(result)) { result = null; } return result; } catch (Exception e) { return null; } } public static String getObjectArray(HttpServletRequest request, String key){ try { String newResult = ""; String[] arrays = request.getParameterValues(key); System.err.println("arrays.toString(): " + arrays.toString()); if (arrays != null){ StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < arrays.length; i++){ stringBuffer.append(arrays[i]); } newResult = stringBuffer.toString(); } return newResult; } catch (Exception e) { return null; } } }
[ "awakeningcode@126.com" ]
awakeningcode@126.com
fef8c1a3a6aef03e71d940431fb17a628a00ac31
f2063d493bd6a034da4106376d6ad6dc4acda66e
/chapter_001/src/test/java/ru/job4j/condition/DummyBotTest.java
2d0ee8659fa5a68334279a6945663951e495e9e2
[ "Apache-2.0" ]
permissive
ahorn80/job4j
98d249271c5dc0990af52d289b36a39705675d16
2a98d0d449b50bf6ec2746a2d78d715a27b56ebd
refs/heads/master
2020-03-10T08:45:29.808226
2018-06-12T16:51:42
2018-06-12T16:51:42
129,293,371
1
0
null
null
null
null
UTF-8
Java
false
false
978
java
package ru.job4j.condition; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * @author Andreas Horn (ahorn80@yandex.ru) * @version $Id$ * @since 0.1 */ public class DummyBotTest { @Test public void whenGreetBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Привет, Бот."), is("Привет, умник.") ); } @Test public void whenByuBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Пока."), is("До скорой встречи.") ); } @Test public void whenUnknownBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Сколько будет 2 + 2?"), is("Это ставит меня в тупик. Спросите другой вопрос.") ); } }
[ "ahorn80@gmx.de" ]
ahorn80@gmx.de
0c2903a7e30d5a51d2c3429d39a6173a0c27c90c
6b59d73858048da73cdb544d8d0875fbcf11ca6d
/dts-server/src/main/java/com/le/dts/server/store/hbase/ClientGroupAccess4Hbase.java
0fbcde0a93ec70236bff4e01ed416d300edac646
[]
no_license
suzuizui/dts-all
e63c2a901ca8c473faa9c490fe014089fb39d018
605b51b6ad53bc05871ee4755af4f19052eadea1
refs/heads/master
2021-01-01T19:50:20.484429
2017-07-29T03:20:59
2017-07-29T03:21:01
98,704,868
2
1
null
null
null
null
UTF-8
Java
false
false
1,316
java
package com.le.dts.server.store.hbase; import java.util.List; import com.le.dts.common.domain.store.ClientGroup; import com.le.dts.common.exception.AccessException; import com.le.dts.server.store.ClientGroupAccess; /** * 客户端集群信息访问接口 * Hbase实现 * @author tianyao.myc * */ public class ClientGroupAccess4Hbase implements ClientGroupAccess { /** * 插入 */ public long insert(ClientGroup clientGroup) throws AccessException { // TODO Auto-generated method stub return 0; } /** * 查询 */ public List<ClientGroup> query(ClientGroup query) throws AccessException { // TODO Auto-generated method stub return null; } /** * 更新 */ public int update(ClientGroup clientGroup) throws AccessException { // TODO Auto-generated method stub return 0; } /** * 删除 */ public int delete(ClientGroup clientGroup) throws AccessException { // TODO Auto-generated method stub return 0; } @Override public List<ClientGroup> queryUser(ClientGroup query) throws AccessException { // TODO Auto-generated method stub return null; } @Override public String checkUser(ClientGroup clientGroup) throws AccessException { // TODO Auto-generated method stub return null; } }
[ "shangqiit@foxmail.com" ]
shangqiit@foxmail.com
171d778d0b74c63f311129356d74e62dc2aa5883
6c2324d4a5871bca4e0eddb8873e4907d27f6f65
/knowledgebase-ui/src/main/java/com/gokrokve/knowledgebase/samples/crud/NumberField.java
46e761b388346ee67a8cb08202ea1ccc45027add
[]
no_license
gokrokvertskhov/knowledgebase
5be819633d97c818831f59ca19865bb75f76c2c0
674186d3608ced1187446dc7594a4a19138fda70
refs/heads/master
2021-01-25T04:02:07.457748
2015-03-27T05:08:23
2015-03-27T05:08:23
32,564,314
0
0
null
null
null
null
UTF-8
Java
false
false
1,563
java
package com.gokrokve.knowledgebase.samples.crud; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; import com.gokrokve.knowledgebase.samples.AttributeExtension; import com.vaadin.data.util.converter.StringToIntegerConverter; import com.vaadin.ui.TextField; /** * A field for entering numbers. On touch devices, a numeric keyboard is shown * instead of the normal one. */ public class NumberField extends TextField { public NumberField() { // Mark the field as numeric. // This affects the virtual keyboard shown on mobile devices. AttributeExtension ae = new AttributeExtension(); ae.extend(this); ae.setAttribute("type", "number"); setConverter(new StringToIntegerConverter() { @Override protected NumberFormat getFormat(Locale locale) { // do not use a thousands separator, as HTML5 input type // number expects a fixed wire/DOM number format regardless // of how the browser presents it to the user (which could // depend on the browser locale) DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); format.setGroupingUsed(false); return format; } }); } public NumberField(String caption) { this(); setCaption(caption); } }
[ "gokrokvertskhov@mirantis.com" ]
gokrokvertskhov@mirantis.com
7f3acb8b94978012d032c751f6e7f9b67036ef51
be20eb253ca388f55ab96282737cae2316f001c1
/src/main/java/com/course/work/buy_and_sale_house/service/RequestToBuyService.java
e212c0bb30f3f78604e3f19842c09572759b9c40
[]
no_license
bkovalevych/real_estate
3a343c1912785924d5d50ed6b9f2c8b7db7f8028
a501f4895ff9dd3f47c34f82944463341b545633
refs/heads/master
2023-04-26T21:17:45.023919
2021-05-18T02:11:16
2021-05-18T02:11:16
368,356,325
0
0
null
null
null
null
UTF-8
Java
false
false
1,209
java
package com.course.work.buy_and_sale_house.service; import com.course.work.buy_and_sale_house.entity.District; import com.course.work.buy_and_sale_house.entity.PropertyForSale; import com.course.work.buy_and_sale_house.entity.RequestToBuy; import com.course.work.buy_and_sale_house.entity.User; import java.util.List; public interface RequestToBuyService { static final String STATUS_SOLD = "Продано"; static final String STATUS_HIDDEN = "Приховано"; static final String STATUS_OK = "Відкрито"; static final String TYPE_APARTMENT = "Квартира"; static final String TYPE_HOUSE = "Будинок"; RequestToBuy findById(Long id); List<RequestToBuy> findAllByUserAndStatusIs(User user, String status); List<RequestToBuy> findAppropriate(PropertyForSale propertyForSale, boolean isOwn); void addPropertyForSale(PropertyForSale propertyForSale, RequestToBuy requestToBuy); void deleteById(Long id); void save(RequestToBuy requestToBuy); List<RequestToBuy> loadTestData(List<District> districts, User user, int count); void deleteAll(Iterable<? extends RequestToBuy> iterable); List<RequestToBuy> findAllByUser(User user); }
[ "32486313+bkovalevych@users.noreply.github.com" ]
32486313+bkovalevych@users.noreply.github.com
1b89ccca45858e467a06728b2d148ea820e27a11
d8b6e7dde4bcf8353983a1a619f9e561ebf870a9
/SensorData.java
2a9fea501c8df790d3cd30bf2aff659380226afb
[]
no_license
wsgan001/Real-Time-IoT-Event-Detection-Using-Apache-Storm
b79fc6d6b0fd5b98c704dd05df6f94a0a663a444
14e9fe8621aca4e955e3ab14e37fbb2c2a8a3510
refs/heads/master
2020-03-26T03:58:04.371642
2017-03-07T21:22:59
2017-03-07T21:22:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,602
java
/* Class for representing sensor data Created by: Umuralp Kaytaz */ package udacity.storm; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.Map; import java.util.ArrayList; import java.lang.*; import java.util.Arrays; import udacity.storm.Moments; public class SensorData { private double arrivalTime; private double sensorID; private Moments rawDataMoments; private int numOfPossibleIds=100; public SensorData(Moments rawDataMoments, double sensorID, double dataTime) { this.setMoments(rawDataMoments); this.setID(sensorID); this.setTime(dataTime); } public SensorData(Moments rawDataMoments, double sensorID) { this.setMoments(rawDataMoments); this.setID(sensorID); this.setTime(); } public SensorData(Moments rawDataMoments) { this.setMoments(rawDataMoments); this.setID((double)ThreadLocalRandom.current().nextInt(0,numOfPossibleIds)); this.setTime(); } public SensorData(){ Moments randMoments=new Moments(); this.setMoments(randMoments); this.setID((double)ThreadLocalRandom.current().nextInt(0,numOfPossibleIds)); this.setTime(); } public void setMoments(Moments rawDataMoments) { this.rawDataMoments = rawDataMoments; } public Moments getMoments(){ return this.rawDataMoments; } public void setID(double sensorID) { this.sensorID = sensorID; } public double getID() { return this.sensorID; } public void setTime(double dataTime) { this.arrivalTime = dataTime; } public void setTime() { this.arrivalTime = (double)System.currentTimeMillis(); } protected static SensorData generateRandomData(){ Moments newMoments=Moments.generateRandomMoments(); //System.out.println("new moments are generated"); //System.out.println(newMoments.toString()); SensorData newData=new SensorData(newMoments); return newData; } public static List generateMultipleData(int size){ List multipleSensorData=new ArrayList<SensorData>(size); for(int i = 0; i < size; i++) { SensorData aNewData=generateRandomData(); //System.out.println("new sensor data is generated"); //System.out.println(aNewData.toString()); multipleSensorData.add(aNewData); } return multipleSensorData; } public String toString(){ return "("+rawDataMoments+","+sensorID+","+arrivalTime+")"; } }
[ "ukaytaz@ku.edu.tr" ]
ukaytaz@ku.edu.tr
ee11ae4d662618ba0666af00508470300924fdb4
88e4f484e8b7c8b280f0da5384f71d51b4335b9f
/src/utility/Struts2Filter.java
b98496234898112737ab1ef39b523576f66469d1
[]
no_license
farhadhossain/hms
55371d7484f4802c1313e22ca3a2c4ffa5ff383c
10b1158c75cf0aba25b8ac1d71238548a59b4cb5
refs/heads/master
2020-04-06T06:56:35.808347
2016-08-21T03:23:59
2016-08-21T03:23:59
49,805,980
0
1
null
2016-02-22T11:56:56
2016-01-17T06:29:43
Java
UTF-8
Java
false
false
792
java
package utility; import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Created by macintosh on 4/17/16. */ public class Struts2Filter extends StrutsPrepareAndExecuteFilter{ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { String path = ((HttpServletRequest) req).getServletPath(); if (path.endsWith(".jsp")) { chain.doFilter(req, res); } else { super.doFilter(req, res, chain); } } }
[ "fhossain@icancerhelp.com" ]
fhossain@icancerhelp.com
e10042ea5fd73f8f1094636406d5e04b8613d0d6
d27a3ddb7d5574a01f344cc29014e3868389f4da
/src/main/java/org/sitenv/ccdaaggregator/model/CCDAOrganization.java
d617d98d88f5169d736470e694bc680f649d6637
[]
no_license
monikadrajer/ccdaaggregator
ee3feec293b271d55bed7f061d2c7f8acf39f15c
9e2ba0fefae00b1b5a8bb780e7e94132890c68b1
refs/heads/master
2021-08-22T23:23:24.007582
2017-12-01T16:46:56
2017-12-01T16:46:56
112,762,254
0
0
null
null
null
null
UTF-8
Java
false
false
1,388
java
package org.sitenv.ccdaaggregator.model; import org.apache.log4j.Logger; import java.util.ArrayList; public class CCDAOrganization { private static Logger log = Logger.getLogger(CCDAOrganization.class.getName()); private ArrayList<CCDADataElement> names; private ArrayList<CCDADataElement> telecom; private ArrayList<CCDAAddress> address; public void log() { for(int j = 0; j < telecom.size(); j++) { log.info(" Telecom [" + j + "] = " + telecom.get(j).getValue()); } for(int j = 0; j < names.size(); j++) { log.info(" Name [" + j + "] = " + names.get(j).getValue()); } for(int k = 0; k < address.size(); k++) { address.get(k).log(); } } public CCDAOrganization() { names = new ArrayList<CCDADataElement>(); address = new ArrayList<CCDAAddress>(); telecom = new ArrayList<CCDADataElement>(); } public ArrayList<CCDADataElement> getNames() { return names; } public void setNames(ArrayList<CCDADataElement> n) { if(n != null) this.names = n; } public ArrayList<CCDADataElement> getTelecom() { return telecom; } public void setTelecom(ArrayList<CCDADataElement> tels) { if(tels != null) this.telecom = tels; } public ArrayList<CCDAAddress> getAddress() { return address; } public void setAddress(ArrayList<CCDAAddress> ads) { if(ads != null) this.address = ads; } }
[ "mounika.narne@drajer.com" ]
mounika.narne@drajer.com
01af5f5f9cc13fd79d682434914e89fe262ef420
b1fef061d7791a8a266ea7454f570a22a9b71ff8
/src/main/java/com/rongdong/dao/fiveDataSource/FiveLoanRecordMapper.java
32d94acb4791bdd3f01f4af86485e3ce385a993f
[]
no_license
elementaryApe/wait
23a7c5025563aedff5ef5f8a60e514050a25c593
b622323356b79c6176c083cdb671428cbf41fa93
refs/heads/master
2022-07-07T20:43:33.704969
2019-08-31T14:56:07
2019-08-31T14:56:07
205,556,616
0
0
null
2022-06-17T02:27:33
2019-08-31T14:44:01
Java
UTF-8
Java
false
false
572
java
package com.rongdong.dao.fiveDataSource; import com.rongdong.model.fiveDataSource.FiveLoanRecord; import com.rongdong.model.priDataSource.LoanRecord; import java.util.List; public interface FiveLoanRecordMapper { int deleteByPrimaryKey(String id); int insert(FiveLoanRecord record); int insertSelective(FiveLoanRecord record); FiveLoanRecord selectByPrimaryKey(String id); int updateByPrimaryKeySelective(FiveLoanRecord record); int updateByPrimaryKey(FiveLoanRecord record); List<LoanRecord> findLoanRecords(LoanRecord loanRecord); }
[ "hsh@wdtianxia.com" ]
hsh@wdtianxia.com
a00f6597a8cbb2eeadd8accb6e805e37c9058d40
c408fa7394c0512ae862904e06db0acb29049d51
/AlgorithmsAndDataStructure/LeetCode/map_and_set/V_LeetCode1.java
5c44bad0577c27cfd81c3013d56b00cfe6ee6f30
[]
no_license
huangweikuna/AlgorithmsAndDataStructure
49c711a3382394cc8302fde548fae5ae4d8110f2
9667222c118b1f55fa824c6207c7f0eaff7190fa
refs/heads/master
2020-04-26T03:35:21.679805
2019-06-11T09:19:27
2019-06-11T09:19:27
null
0
0
null
null
null
null
GB18030
Java
false
false
580
java
package map_and_set; import java.util.HashMap; import java.util.Map; //查找数组中是否含有两个相加为target的两个数 返回两个数的下标(重0开始) 数组不排序 public class V_LeetCode1 { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int[] result = { 0, 0 }; for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { result[0] = map.get(target - nums[i]); result[1] = i; return result; } else map.put(nums[i], i); } return null; } }
[ "986004722@qq.com" ]
986004722@qq.com
22cff5662e9ba7f6c40d9e9fddc97c4db866fefa
e41bb2cc629f9a1659fd28aefe9a54ad583422a3
/EXTRA/ArtOfMultiprocessorProgramming/src/com/company/workStealingSharing/WorkStealingThread.java
90efada80581c9ad13d585cf36d1443a141bab53
[ "MIT" ]
permissive
bozhnyukAlex/SPBU_hometasks
f78dd8ccdacc0d1ede839afe6ab0cc08a908b0eb
bf7a5368cfa4845739da27beaa848dbbfe3c51ee
refs/heads/master
2023-03-29T18:37:41.769339
2021-04-12T09:27:39
2021-04-12T09:27:39
209,381,605
0
0
null
null
null
null
UTF-8
Java
false
false
1,046
java
package com.company.workStealingSharing; import java.util.Dictionary; import java.util.Random; import java.util.concurrent.RecursiveAction; import java.util.concurrent.ThreadLocalRandom; public class WorkStealingThread extends Thread{ Dictionary<Integer, IDEQueue<RecursiveAction>> queue; Random random; public WorkStealingThread(Dictionary<Integer, IDEQueue<RecursiveAction>> myQueue) { this.queue = myQueue; } @Override public void run() { int me = (int) Thread.currentThread().getId(); RecursiveAction task = queue.get(me).popBottom(); while (true) { while (task != null) { task.invoke(); task = queue.get(me).popBottom(); } while (task == null) { Thread.yield(); int victim = ThreadLocalRandom.current().nextInt(queue.size()); if (!queue.get(victim).isEmpty()) { task = queue.get(victim).popTop(); } } } } }
[ "bozhnyuks@mail.ru" ]
bozhnyuks@mail.ru
e59a0c16553859c42353b72393a5b898987a90e4
7e1511cdceeec0c0aad2b9b916431fc39bc71d9b
/flakiness-predicter/input_data/original_tests/doanduyhai-Achilles/nonFlakyMethods/info.archinnov.achilles.test.integration.tests.ClusteredEntityIT-should_iterate_over_clusterings_components.java
72256f475e1d481e3dfda85d7e73796e4e5778bd
[ "BSD-3-Clause" ]
permissive
Taher-Ghaleb/FlakeFlagger
6fd7c95d2710632fd093346ce787fd70923a1435
45f3d4bc5b790a80daeb4d28ec84f5e46433e060
refs/heads/main
2023-07-14T16:57:24.507743
2021-08-26T14:50:16
2021-08-26T14:50:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,399
java
@Test public void should_iterate_over_clusterings_components() throws Exception { long partitionKey=RandomUtils.nextLong(); insertClusteredEntity(partitionKey,1,"name11","val11"); insertClusteredEntity(partitionKey,1,"name12","val12"); insertClusteredEntity(partitionKey,1,"name13","val13"); insertClusteredEntity(partitionKey,2,"name21","val21"); insertClusteredEntity(partitionKey,2,"name22","val22"); insertClusteredEntity(partitionKey,3,"name31","val31"); insertClusteredEntity(partitionKey,4,"name41","val41"); final Iterator<ClusteredEntity> iterator=manager.sliceQuery(ClusteredEntity.class).partitionComponents(partitionKey).fromClusterings(1).bounding(INCLUSIVE_START_BOUND_ONLY).limit(6).iterator(2); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val11"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val12"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val13"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val21"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val22"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.next().getValue()).isEqualTo("val31"); assertThat(iterator.hasNext()).isFalse(); }
[ "aalsha2@masonlive.gmu.edu" ]
aalsha2@masonlive.gmu.edu
2df7e4adf9105fdd577cd7a8bcba4d24fa312e4a
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/druid-io--druid/145e08682cba02fdbaf9ad71763542f3ee8174da/after/ServerManagerTest.java
c6d6a9a0bceb474f801bf5e56a48cb18ffa83129
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
23,279
java
/* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.coordination; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.metamx.common.IAE; import com.metamx.common.MapUtils; import com.metamx.common.Pair; import com.metamx.common.guava.ConcatSequence; import com.metamx.common.guava.Sequence; import com.metamx.common.guava.Sequences; import com.metamx.common.guava.Yielder; import com.metamx.common.guava.YieldingAccumulator; import com.metamx.common.guava.YieldingSequenceBase; import com.metamx.druid.Druids; import com.metamx.druid.Query; import com.metamx.druid.QueryGranularity; import com.metamx.druid.StorageAdapter; import com.metamx.druid.client.DataSegment; import com.metamx.druid.index.QueryableIndex; import com.metamx.druid.index.ReferenceCountingSegment; import com.metamx.druid.index.Segment; import com.metamx.druid.index.v1.IndexIO; import com.metamx.druid.loading.SegmentLoader; import com.metamx.druid.loading.SegmentLoadingException; import com.metamx.druid.metrics.NoopServiceEmitter; import com.metamx.druid.query.ConcatQueryRunner; import com.metamx.druid.query.MetricManipulationFn; import com.metamx.druid.query.NoopQueryRunner; import com.metamx.druid.query.QueryRunner; import com.metamx.druid.query.QueryRunnerFactory; import com.metamx.druid.query.QueryRunnerFactoryConglomerate; import com.metamx.druid.query.QueryToolChest; import com.metamx.druid.query.search.SearchQuery; import com.metamx.druid.result.Result; import com.metamx.druid.result.SearchResultValue; import com.metamx.druid.shard.NoneShardSpec; import com.metamx.emitter.EmittingLogger; import com.metamx.emitter.service.ServiceMetricEvent; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** */ public class ServerManagerTest { private ServerManager serverManager; private MyQueryRunnerFactory factory; private CountDownLatch queryWaitLatch; private CountDownLatch queryWaitYieldLatch; private CountDownLatch queryNotifyLatch; private ExecutorService serverManagerExec; @Before public void setUp() throws IOException { EmittingLogger.registerEmitter(new NoopServiceEmitter()); queryWaitLatch = new CountDownLatch(1); queryWaitYieldLatch = new CountDownLatch(1); queryNotifyLatch = new CountDownLatch(1); factory = new MyQueryRunnerFactory(queryWaitLatch, queryWaitYieldLatch, queryNotifyLatch); serverManagerExec = Executors.newFixedThreadPool(2); serverManager = new ServerManager( new SegmentLoader() { @Override public boolean isSegmentLoaded(DataSegment segment) throws SegmentLoadingException { return false; } @Override public Segment getSegment(final DataSegment segment) { return new SegmentForTesting( MapUtils.getString(segment.getLoadSpec(), "version"), (Interval) segment.getLoadSpec().get("interval") ); } @Override public void cleanup(DataSegment segment) throws SegmentLoadingException { } }, new QueryRunnerFactoryConglomerate() { @Override public <T, QueryType extends Query<T>> QueryRunnerFactory<T, QueryType> findFactory(QueryType query) { return (QueryRunnerFactory) factory; } }, new NoopServiceEmitter(), serverManagerExec ); loadQueryable("test", "1", new Interval("P1d/2011-04-01")); loadQueryable("test", "1", new Interval("P1d/2011-04-02")); loadQueryable("test", "2", new Interval("P1d/2011-04-02")); loadQueryable("test", "1", new Interval("P1d/2011-04-03")); loadQueryable("test", "1", new Interval("P1d/2011-04-04")); loadQueryable("test", "1", new Interval("P1d/2011-04-05")); loadQueryable("test", "2", new Interval("PT1h/2011-04-04T01")); loadQueryable("test", "2", new Interval("PT1h/2011-04-04T02")); loadQueryable("test", "2", new Interval("PT1h/2011-04-04T03")); loadQueryable("test", "2", new Interval("PT1h/2011-04-04T05")); loadQueryable("test", "2", new Interval("PT1h/2011-04-04T06")); loadQueryable("test2", "1", new Interval("P1d/2011-04-01")); loadQueryable("test2", "1", new Interval("P1d/2011-04-02")); } @Test public void testSimpleGet() { Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("P1d/2011-04-01"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("1", new Interval("P1d/2011-04-01")) ) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( QueryGranularity.DAY, "test", new Interval("P2d/2011-04-02"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("1", new Interval("P1d/2011-04-01")), new Pair<String, Interval>("2", new Interval("P1d/2011-04-02")) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testDelete1() throws Exception { final String dataSouce = "test"; final Interval interval = new Interval("2011-04-01/2011-04-02"); Future future = assertQueryable( QueryGranularity.DAY, dataSouce, interval, ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("2", interval) ) ); waitForTestVerificationAndCleanup(future); dropQueryable(dataSouce, "2", interval); future = assertQueryable( QueryGranularity.DAY, dataSouce, interval, ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("1", interval) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testDelete2() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); waitForTestVerificationAndCleanup(future); dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); dropQueryable("test", "1", new Interval("2011-04-04/2011-04-05")); future = assertQueryable( QueryGranularity.HOUR, "test", new Interval("2011-04-04/2011-04-04T06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("2", new Interval("2011-04-04T00/2011-04-04T01")), new Pair<String, Interval>("2", new Interval("2011-04-04T01/2011-04-04T02")), new Pair<String, Interval>("2", new Interval("2011-04-04T02/2011-04-04T03")), new Pair<String, Interval>("2", new Interval("2011-04-04T04/2011-04-04T05")), new Pair<String, Interval>("2", new Interval("2011-04-04T05/2011-04-04T06")) ) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( QueryGranularity.HOUR, "test", new Interval("2011-04-04/2011-04-04T03"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("2", new Interval("2011-04-04T00/2011-04-04T01")), new Pair<String, Interval>("2", new Interval("2011-04-04T01/2011-04-04T02")), new Pair<String, Interval>("2", new Interval("2011-04-04T02/2011-04-04T03")) ) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( QueryGranularity.HOUR, "test", new Interval("2011-04-04T04/2011-04-04T06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("2", new Interval("2011-04-04T04/2011-04-04T05")), new Pair<String, Interval>("2", new Interval("2011-04-04T05/2011-04-04T06")) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testReferenceCounting() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); queryNotifyLatch.await(25, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getSegmentReferences().size()); for (ReferenceCountingSegment referenceCountingSegment : factory.getSegmentReferences()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } queryWaitYieldLatch.countDown(); Assert.assertTrue(factory.getAdapters().size() == 1); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } queryWaitLatch.countDown(); future.get(); dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertTrue(segmentForTesting.isClosed()); } } @Test public void testReferenceCountingWhileQueryExecuting() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); queryNotifyLatch.await(25, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getSegmentReferences().size()); for (ReferenceCountingSegment referenceCountingSegment : factory.getSegmentReferences()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } queryWaitYieldLatch.countDown(); Assert.assertEquals(1, factory.getAdapters().size()); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } queryWaitLatch.countDown(); future.get(); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertTrue(segmentForTesting.isClosed()); } } @Test public void testMultipleDrops() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); queryNotifyLatch.await(25, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getSegmentReferences().size()); for (ReferenceCountingSegment referenceCountingSegment : factory.getSegmentReferences()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } queryWaitYieldLatch.countDown(); Assert.assertEquals(1, factory.getAdapters().size()); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } queryWaitLatch.countDown(); future.get(); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertTrue(segmentForTesting.isClosed()); } } private void waitForTestVerificationAndCleanup(Future future) { try { queryNotifyLatch.await(25, TimeUnit.MILLISECONDS); queryWaitYieldLatch.countDown(); queryWaitLatch.countDown(); future.get(); factory.clearAdapters(); } catch (Exception e) { throw Throwables.propagate(e); } } private <T> Future assertQueryable( QueryGranularity granularity, String dataSource, Interval interval, List<Pair<String, Interval>> expected ) { final Iterator<Pair<String, Interval>> expectedIter = expected.iterator(); final List<Interval> intervals = Arrays.asList(interval); final SearchQuery query = Druids.newSearchQueryBuilder() .dataSource(dataSource) .intervals(intervals) .granularity(granularity) .limit(10000) .query("wow") .build(); final QueryRunner<Result<SearchResultValue>> runner = serverManager.getQueryRunnerForIntervals( query, intervals ); return serverManagerExec.submit( new Runnable() { @Override public void run() { Sequence<Result<SearchResultValue>> seq = runner.run(query); Sequences.toList(seq, Lists.<Result<SearchResultValue>>newArrayList()); Iterator<SegmentForTesting> adaptersIter = factory.getAdapters().iterator(); while (expectedIter.hasNext() && adaptersIter.hasNext()) { Pair<String, Interval> expectedVals = expectedIter.next(); SegmentForTesting value = adaptersIter.next(); Assert.assertEquals(expectedVals.lhs, value.getVersion()); Assert.assertEquals(expectedVals.rhs, value.getInterval()); } Assert.assertFalse(expectedIter.hasNext()); Assert.assertFalse(adaptersIter.hasNext()); } } ); } public void loadQueryable(String dataSource, String version, Interval interval) throws IOException { try { serverManager.loadSegment( new DataSegment( dataSource, interval, version, ImmutableMap.<String, Object>of("version", version, "interval", interval), Arrays.asList("dim1", "dim2", "dim3"), Arrays.asList("metric1", "metric2"), new NoneShardSpec(), IndexIO.CURRENT_VERSION_ID, 123l ) ); } catch (SegmentLoadingException e) { throw new RuntimeException(e); } } public void dropQueryable(String dataSource, String version, Interval interval) { try { serverManager.dropSegment( new DataSegment( dataSource, interval, version, ImmutableMap.<String, Object>of("version", version, "interval", interval), Arrays.asList("dim1", "dim2", "dim3"), Arrays.asList("metric1", "metric2"), new NoneShardSpec(), IndexIO.CURRENT_VERSION_ID, 123l ) ); } catch (SegmentLoadingException e) { throw new RuntimeException(e); } } public static class MyQueryRunnerFactory implements QueryRunnerFactory<Result<SearchResultValue>, SearchQuery> { private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; private List<SegmentForTesting> adapters = Lists.newArrayList(); private List<ReferenceCountingSegment> segmentReferences = Lists.newArrayList(); public MyQueryRunnerFactory( CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public QueryRunner<Result<SearchResultValue>> createRunner(Segment adapter) { if (!(adapter instanceof ReferenceCountingSegment)) { throw new IAE("Expected instance of ReferenceCountingSegment, got %s", adapter.getClass()); } final ReferenceCountingSegment segment = (ReferenceCountingSegment) adapter; Assert.assertTrue(segment.getNumReferences() > 0); segmentReferences.add(segment); adapters.add((SegmentForTesting) segment.getBaseSegment()); return new BlockingQueryRunner<Result<SearchResultValue>>( new NoopQueryRunner<Result<SearchResultValue>>(), waitLatch, waitYieldLatch, notifyLatch ); } @Override public QueryRunner<Result<SearchResultValue>> mergeRunners( ExecutorService queryExecutor, Iterable<QueryRunner<Result<SearchResultValue>>> queryRunners ) { return new ConcatQueryRunner<Result<SearchResultValue>>(Sequences.simple(queryRunners)); } @Override public QueryToolChest<Result<SearchResultValue>, SearchQuery> getToolchest() { return new NoopQueryToolChest<Result<SearchResultValue>, SearchQuery>(); } public List<SegmentForTesting> getAdapters() { return adapters; } public List<ReferenceCountingSegment> getSegmentReferences() { return segmentReferences; } public void clearAdapters() { adapters.clear(); } } public static class NoopQueryToolChest<T, QueryType extends Query<T>> extends QueryToolChest<T, QueryType> { @Override public QueryRunner<T> mergeResults(QueryRunner<T> runner) { return runner; } @Override public Sequence<T> mergeSequences(Sequence<Sequence<T>> seqOfSequences) { return new ConcatSequence<T>(seqOfSequences); } @Override public ServiceMetricEvent.Builder makeMetricBuilder(QueryType query) { return new ServiceMetricEvent.Builder(); } @Override public Function<T, T> makeMetricManipulatorFn(QueryType query, MetricManipulationFn fn) { return Functions.identity(); } @Override public TypeReference<T> getResultTypeReference() { return new TypeReference<T>() { }; } } private static class SegmentForTesting implements Segment { private final String version; private final Interval interval; private final Object lock = new Object(); private volatile boolean closed = false; SegmentForTesting( String version, Interval interval ) { this.version = version; this.interval = interval; } public String getVersion() { return version; } public Interval getInterval() { return interval; } @Override public String getIdentifier() { return version; } public boolean isClosed() { return closed; } @Override public Interval getDataInterval() { return interval; } @Override public QueryableIndex asQueryableIndex() { throw new UnsupportedOperationException(); } @Override public StorageAdapter asStorageAdapter() { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { synchronized (lock) { closed = true; } } } private static class BlockingQueryRunner<T> implements QueryRunner<T> { private final QueryRunner<T> runner; private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; public BlockingQueryRunner( QueryRunner<T> runner, CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.runner = runner; this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public Sequence<T> run(Query<T> query) { return new BlockingSequence<T>(runner.run(query), waitLatch, waitYieldLatch, notifyLatch); } } private static class BlockingSequence<T> extends YieldingSequenceBase<T> { private final Sequence<T> baseSequence; private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; private BlockingSequence( Sequence<T> baseSequence, CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.baseSequence = baseSequence; this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public <OutType> Yielder<OutType> toYielder( final OutType initValue, final YieldingAccumulator<OutType, T> accumulator ) { notifyLatch.countDown(); try { waitYieldLatch.await(25, TimeUnit.MILLISECONDS); } catch (Exception e) { throw Throwables.propagate(e); } final Yielder<OutType> baseYielder = baseSequence.toYielder(initValue, accumulator); return new Yielder<OutType>() { @Override public OutType get() { try { waitLatch.await(25, TimeUnit.MILLISECONDS); } catch (Exception e) { throw Throwables.propagate(e); } return baseYielder.get(); } @Override public Yielder<OutType> next(OutType initValue) { return baseYielder.next(initValue); } @Override public boolean isDone() { return baseYielder.isDone(); } @Override public void close() throws IOException { baseYielder.close(); } }; } } }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
1349edbd10c44fe34a19553167ed8658b17c51c1
f974edb986f8e81e8224ae01a49e1dbffa979155
/springboot_cfigMapper/src/main/java/com/dyq/config/CfigurationPro.java
3b13254bd04ebe67c67f2cd16aa24baab824a3de
[]
no_license
1515925040/testGit
af98f095d9df553c5022d8b2ab5d417c59d19708
405ecc1c9c6a345fff7de5c65569c09e2b536a9a
refs/heads/master
2020-04-18T10:22:40.407449
2019-02-23T07:26:12
2019-02-23T07:26:12
167,465,913
0
0
null
null
null
null
UTF-8
Java
false
false
924
java
package com.dyq.config; /** * @author 丁艳青 * @site www.dyq.com * @company xxx * @create 2019-01-21 21:10 */ /* @Configuration @Data @AllArgsConstructor @NoArgsConstructor //@ConfigurationProperties(value = "classpath:db.properties") @PropertySource(value = "classpath:db.properties") public class CfigurationPro { @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DruidDataSource druidDataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } } */
[ "1512650658@qq.com" ]
1512650658@qq.com
993fb28cd808e7325a07e9def22d624426e43c9c
9a3aefbd2e8e846690de473adeefad3376b47171
/src/main/java/com/payment/entity/CustomerBillingInformationPK.java
018494fc49ecfa6fca519b0f6ceb7c619cbaf49b
[]
no_license
PravatKumarPradhan/Spring-Boot-REST-JPA-Hibernate-MySQL-Example
9c4ad4adf93496d00663c54689142061a8e61c8d
ad8b4915f11490ffcc5cf3faf7116a998fead8b7
refs/heads/master
2020-03-23T20:18:46.757399
2017-08-13T20:56:18
2017-08-13T20:56:18
142,034,415
2
2
null
2018-07-23T15:35:12
2018-07-23T15:35:11
null
UTF-8
Java
false
false
2,612
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.payment.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author mustafa */ @Embeddable public class CustomerBillingInformationPK implements Serializable { @Basic(optional = false) @Column(name = "Customer_Id") private String customerId; @Basic(optional = false) @Column(name = "Customer_Billing_Date") @Temporal(TemporalType.DATE) private Date customerBillingDate; public CustomerBillingInformationPK() { } public CustomerBillingInformationPK(String customerId, Date customerBillingDate) { this.customerId = customerId; this.customerBillingDate = customerBillingDate; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public Date getCustomerBillingDate() { return customerBillingDate; } public void setCustomerBillingDate(Date customerBillingDate) { this.customerBillingDate = customerBillingDate; } @Override public int hashCode() { int hash = 0; hash += (customerId != null ? customerId.hashCode() : 0); hash += (customerBillingDate != null ? customerBillingDate.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CustomerBillingInformationPK)) { return false; } CustomerBillingInformationPK other = (CustomerBillingInformationPK) object; if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) { return false; } if ((this.customerBillingDate == null && other.customerBillingDate != null) || (this.customerBillingDate != null && !this.customerBillingDate.equals(other.customerBillingDate))) { return false; } return true; } @Override public String toString() { return "com.jpa.CustomerBillingInformationPK[ customerId=" + customerId + ", customerBillingDate=" + customerBillingDate + " ]"; } }
[ "mustafa@Linux-PC" ]
mustafa@Linux-PC
6cca9ba8bc84493f5d8089658fb645ac6f9e34d2
c113f4e2b8c371bd3904fe9bdcfd345c8074a17e
/src/main/java/com/bhatta/config/RestExceptionHandler.java
e2253da77c5c5b43645eae6098cc45748ea6dd51
[]
no_license
Pooja-Gulshetty/Bhatta-Backend-Api
8d69c61aa0c260b399300cea776b4f13c420c4e5
e4093b1c7fe2f1dadb9070c2e68cf18996b4c14a
refs/heads/main
2023-01-15T04:49:46.787119
2020-11-21T15:56:34
2020-11-21T15:56:34
303,110,714
0
0
null
2020-10-22T20:40:38
2020-10-11T11:59:17
Java
UTF-8
Java
false
false
904
java
package com.bhatta.config; import com.bhatta.dto.ErrorDto; import com.bhatta.exceptions.ConflictException; import com.bhatta.exceptions.InvalidRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class RestExceptionHandler { @ExceptionHandler(value = InvalidRequest.class) public ResponseEntity<ErrorDto> handleInvalidRequest(InvalidRequest exception) { return new ResponseEntity<>(new ErrorDto(exception.getMessage()), HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = ConflictException.class) public ResponseEntity<ErrorDto> handleConflictException(ConflictException exception) { return new ResponseEntity<>(new ErrorDto(exception.getMessage()), HttpStatus.CONFLICT); } }
[ "iranna.patil@irdeto.com" ]
iranna.patil@irdeto.com
d589122b4d61ceff38eee07d38075569d244fc8d
c8ddd003d3b8784db51cbd55921d20987d55cfd0
/idlealarm-demo/src/main/java/org/vaadin/alump/idlealarm/DemoUI.java
d415bd07b036fd93311a1e25277d260e23a6e2a0
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jonathanjt/IdleAlarm
a884be182789ec8c075f7d46e58e5d18ff974ad2
578efa49cf8c38bf54a8cc2e7bc0757ed4b7c7a1
refs/heads/master
2021-01-20T21:59:35.135747
2015-07-16T14:47:51
2015-07-16T14:47:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,503
java
package org.vaadin.alump.idlealarm; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.server.*; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.*; import org.vaadin.alump.idlealarm.client.shared.IdleAlarmFormatting; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; /** * Demo UI of IdleAlarm addon */ @Theme("demo") @Title("IdleAlarm Add-on Demo") @SuppressWarnings("serial") public class DemoUI extends UI { private static final String STYLED_FORMATTING = "Lennät muuten ulos <b>" + IdleAlarmFormatting.SECS_TO_TIMEOUT + "</b> sekunnin kuluttua, ellet tee mitään."; private static final int IDLE_TIMEOUT_SECONDS = 60; private static final String GUIDE = "IdleAlarm add-on is designed to be used with Vaadin's idle timeout feature. " + "Add-on adds option to show alarm to user when sessions is about to expire because of long idle period."; private static final String NOTICE = "<b>Please notice</b> that there is always some extra delay (from seconds to " + "few minutes) before session really gets expired. As the idle time out in this application is set to very " + " short (60 seconds), you can easily see this extra time here."; // This add-on old works when closeIdleSessions init parameter is true @WebServlet(value = "/*", asyncSupported = true, initParams = { @WebInitParam(name="closeIdleSessions", value="true") }) @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.idlealarm.DemoWidgetSet") public static class Servlet extends VaadinServlet implements SessionInitListener { protected void servletInitialized() throws ServletException { super.servletInitialized(); getService().addSessionInitListener(this); } @Override public void sessionInit(SessionInitEvent event) throws ServiceException { event.getSession().getSession().setMaxInactiveInterval(IDLE_TIMEOUT_SECONDS); } } @Override protected void init(VaadinRequest request) { VerticalLayout layout = new VerticalLayout(); layout.setWidth(100, Unit.PERCENTAGE); layout.setMargin(true); layout.setSpacing(true); setContent(layout); layout.addComponent(new Label(GUIDE)); layout.addComponent(new Label(NOTICE, ContentMode.HTML)); // -- Inputs to modify IdleAlarm -- HorizontalLayout row = createRow(layout); row.setWidth(100, Unit.PERCENTAGE); row.setCaption("Setup warning message (values can be modified only in disabled state)"); final TextField secondsBefore = new TextField("Seconds"); secondsBefore.setValue("40"); secondsBefore.setWidth(60, Unit.PIXELS); row.addComponent(secondsBefore); final TextArea warningMessage = new TextArea("Message"); warningMessage.setValue(IdleAlarm.DEFAULT_FORMATTING); warningMessage.setWidth(100, Unit.PERCENTAGE); row.addComponent(warningMessage); row.setExpandRatio(warningMessage, 1f); final ComboBox contentMode = new ComboBox("Content mode"); contentMode.addItem(ContentMode.TEXT); contentMode.addItem(ContentMode.PREFORMATTED); contentMode.addItem(ContentMode.HTML); contentMode.setValue(ContentMode.TEXT); contentMode.setNullSelectionAllowed(false); row.addComponent(contentMode); final Button enableButton = new Button("Enable"); row.addComponent(enableButton); row.setComponentAlignment(enableButton, Alignment.TOP_RIGHT); final Button disableButton = new Button("Disable"); disableButton.setEnabled(false); row.addComponent(disableButton); row.setComponentAlignment(disableButton, Alignment.TOP_LEFT); enableButton.addClickListener(event -> { enableButton.setEnabled(false); disableButton.setEnabled(true); secondsBefore.setEnabled(false); warningMessage.setEnabled(false); contentMode.setEnabled(false); IdleAlarm.get().setSecondsBefore(Integer.valueOf(secondsBefore.getValue())) .setMessage(warningMessage.getValue()) .setContentMode((ContentMode) contentMode.getValue()); }); disableButton.addClickListener(event -> { enableButton.setEnabled(true); disableButton.setEnabled(false); secondsBefore.setEnabled(true); warningMessage.setEnabled(true); contentMode.setEnabled(true); IdleAlarm.unload(); }); final String START_BLOCK = "<span class=\"keyword\">"; final String END_BLOCK = "</span>"; Label keywords = new Label("Keywords you can use in message are " + START_BLOCK + IdleAlarmFormatting.SECS_TO_TIMEOUT + END_BLOCK + ", " + START_BLOCK + IdleAlarmFormatting.SECS_MAX_IDLE_TIMEOUT + END_BLOCK + " " + " and " + START_BLOCK + IdleAlarmFormatting.SECS_SINCE_RESET + END_BLOCK + ".", ContentMode.HTML); layout.addComponent(keywords); // -- Labels for debugging -- row = createRow(layout); IdleCountdownLabel label = new IdleCountdownLabel(); label.setCaption("IdleCountdownLabel (mainly for debugging):"); row.addComponent(label); IdleCountdownLabel styledLabel = new IdleCountdownLabel(STYLED_FORMATTING); styledLabel.setContentMode(ContentMode.HTML); styledLabel.setCaption("IdleCountdownLabel (formatting & styling)"); row.addComponent(styledLabel); Button resetTimeout = new Button("Reset timeout by calling server", event -> { Notification.show("Idle time reset"); }); layout.addComponent(resetTimeout); Link gitHub = new Link("IdleAlarm in GitHub (source code, issue tracker...)", new ExternalResource("https://github.com/alump/IdleAlarm")); layout.addComponent(gitHub); } private HorizontalLayout createRow(ComponentContainer parent) { HorizontalLayout row = new HorizontalLayout(); row.setSpacing(true); parent.addComponent(row); return row; } }
[ "sami.viitanen@vaadin.com" ]
sami.viitanen@vaadin.com
433609ec44446508cb695141de075d68a5cac96e
cdecaeb705a05592a31d1258ee4646635b1803b4
/src/main/java/edu/warbot/scriptcore/wrapper/PyWrapper.java
f541359d6f11515fdbb0f85cc2af7820d8f02715
[]
no_license
geoffrey0170/Warbot
70d7f1b4eebfc6319dfb86501e0e89e88aeb04f8
bf859c8ddac08c66d58a298487366bcec7ad98ab
refs/heads/master
2020-05-29T12:27:51.784506
2015-03-30T14:15:15
2015-03-30T14:15:15
33,596,852
0
0
null
2015-04-30T06:42:07
2015-04-08T09:15:54
Java
UTF-8
Java
false
false
750
java
package edu.warbot.scriptcore.wrapper; import org.python.core.PyObject; /** * @author jlopez02 * * @param <T> Une classe java que l'on souhaite accessible dans du code python */ public class PyWrapper <T extends Object> extends PyObject{ /** * L'objet accessible */ private T object; /** * Contructeur * @param object l'objet à rendre accessible */ public PyWrapper(T object) { this.object = object; } /** * Contructeur par recopie * @param copy */ public PyWrapper(PyWrapper<T> copy) { this.object = copy.get(); } /** * Getter * @return l'objet java */ public T get() { return object; } /** * Setter * @param object */ public void set(T object) { this.object = object; } }
[ "sebastien.beugnon@etud.univ-montp2.fr" ]
sebastien.beugnon@etud.univ-montp2.fr
a068db6b51d3a6ddeebdf0e89672c9a4cbfe0506
15bb99e84620116c93817206526bc924c81df4b8
/JAVA Essential/Chapter8/src/MyFrame.java
2cf30be513d104e13faa3eeffc91e9f4a6efc0cd
[]
no_license
Komudi/YuraKim
b842c78fe7a58aad2bac5e0668c778b0b132b012
1b1623479ac44e1a0a9fedc29fac66a86b3d585c
refs/heads/master
2022-12-28T13:42:52.635502
2020-07-07T12:38:06
2020-07-07T12:38:06
257,009,508
0
0
null
2020-10-13T23:22:33
2020-04-19T13:42:45
Java
UHC
Java
false
false
248
java
import javax.swing.*; public class MyFrame extends JFrame { MyFrame() { setTitle("300x300 스윙 프레임 만들기"); setSize(300,300); setVisible(true); } public static void main(String[] args) { MyFrame frame = new MyFrame(); } }
[ "35290028+yura1518@users.noreply.github.com" ]
35290028+yura1518@users.noreply.github.com
2ab70bbb4109f37bface4017e20ceb5442d68707
cbbd05b152eacc7be1ee686426129f38409d39d6
/src/main/java/edu/eci/pdsw/persistence/PacienteDAO.java
5f4da2795adba7ad534b515964ac720a632a5811
[]
no_license
JuanMorenoS/Laboratorio5
245c3e43e9f2ee0704149513bd6b8844df8f0c62
8de9e64163785ae578e3dbe01d2839069a2bca72
refs/heads/master
2021-07-10T10:36:53.989419
2017-10-12T18:00:41
2017-10-12T18:00:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
639
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.eci.pdsw.persistence; import edu.eci.pdsw.samples.entities.Paciente; import java.util.List; /** * * @author blackphantom */ public interface PacienteDAO { public List<Paciente> load() throws PersistenceException; public Paciente loadById(int id,String tipoId) throws PersistenceException; public void save(Paciente p) throws PersistenceException ; public void update(Paciente p) throws PersistenceException; }
[ "=" ]
=
f0a863fa9565456fd0b81a182396fd0f462e8d0d
aaa6f5315a25a820b01d06f6869389e5cb4157e6
/src/main/java/com/dirtracker/task_scheduler/Task.java
41c701382045d52ecf63c5df3298c06c638ea4ab
[]
no_license
ihechukwudere/dirtracker
634efc46166db185b2ad019b817669d8d9a57720
2c2fe2188dc186d870cee89074a0b5bb0330728b
refs/heads/master
2020-06-13T22:27:58.721954
2019-08-04T18:33:43
2019-08-04T18:33:43
194,045,281
0
0
null
null
null
null
UTF-8
Java
false
false
660
java
package com.dirtracker.task_scheduler; import java.math.BigDecimal; /** * An interface that can be implemented by classes * and interfaces for creating task scheduler objects. * @author Ihechukwudere Okoroego * */ public interface Task { /** * Schedule a repeatable or one-time task * @param timeInterval * @param delay */ public void scheduleTask(long timeInterval, long delay) throws NumberFormatException; public void stop(); public Task start(); public void setTimeInterval(BigDecimal time); public BigDecimal getTimeInterval(); public void setDelay(BigDecimal delayTime); public BigDecimal getDelay(); }
[ "ihechukwudere@yahoo.com" ]
ihechukwudere@yahoo.com
01c192818400e00085a48cee1ba08f68330bc870
8c0bad2bd85b8b6a038ca6fb2b205ffe5d77917f
/app/src/main/java/com/trade/bluehole/trad/widget/HackyViewPager.java
f651eba37faff2be3583d7976fe21b52d02745d0
[]
no_license
baoxituo1/testWork2
ef5b4e37a6a68199910250c14694fa0f82a86e5e
3145674e747639df3ccff1d7c6d283a620b85025
refs/heads/master
2020-12-24T18:04:12.027193
2015-06-14T04:53:10
2015-06-14T04:53:10
32,718,956
2
0
null
2015-06-14T18:10:41
2015-03-23T08:12:40
Java
UTF-8
Java
false
false
1,436
java
package com.trade.bluehole.trad.widget; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; /** * Found at http://stackoverflow.com/questions/7814017/is-it-possible-to-disable-scrolling-on-a-viewpager. * Convenient way to temporarily disable ViewPager navigation while interacting with ImageView. * * Julia Zudikova */ /** * Hacky fix for Issue #4 and * http://code.google.com/p/android/issues/detail?id=18990 * <p/> * ScaleGestureDetector seems to mess up the touch events, which means that * ViewGroups which make use of onInterceptTouchEvent throw a lot of * IllegalArgumentException: pointerIndex out of range. * <p/> * There's not much I can do in my code for now, but we can mask the result by * just catching the problem and ignoring it. * * @author Chris Banes */ public class HackyViewPager extends ViewPager { public HackyViewPager(Context context) { super(context); } public HackyViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (IllegalArgumentException e) { Log.e("Log_", null, e); return false; } } }
[ "zheng@gmail.com" ]
zheng@gmail.com
917386175036097910e02cf2fe0f9f1432c0d3f7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/6/6_afd78e3e9259653ff8a7fa7265537a96b5cc2e54/InputEventProvider/6_afd78e3e9259653ff8a7fa7265537a96b5cc2e54_InputEventProvider_s.java
621ab0a667251f30e119c0477426ca169547004b
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
4,014
java
/******************************************************************************* * Copyright (c) 2008, 2009 Bug Labs, Inc. * 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 Bug Labs, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package com.buglabs.bug.input.pub; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import org.osgi.service.log.LogService; import com.buglabs.bug.jni.common.FCNTL_H; import com.buglabs.bug.jni.input.InputDevice; import com.buglabs.bug.jni.input.InputEvent; import com.buglabs.device.ButtonEvent; import com.buglabs.device.IButtonEventListener; import com.buglabs.device.IButtonEventProvider; public class InputEventProvider extends Thread implements IButtonEventProvider { private ArrayList listeners; private final LogService log; private String inputDevice; public InputEventProvider(String inputDevice, LogService log) { this.log = log; listeners = new ArrayList(); this.inputDevice = inputDevice; } public void addListener(IButtonEventListener listener) { synchronized (listeners) { if (!listeners.contains(listener)) { listeners.add(listener); } } } public void removeListener(IButtonEventListener listener) { synchronized (listeners) { listeners.remove(listener); } } public void run() { InputDevice dev = new InputDevice(); if (dev.open(inputDevice, FCNTL_H.O_RDWR) < 0) { log.log(LogService.LOG_ERROR, "Unable to open input device: " + inputDevice); } while (!isInterrupted()) { try { InputEvent[] inputEvents = dev.readEvents(); synchronized (listeners) { Iterator iter = listeners.iterator(); for (int i = 0; i < inputEvents.length; ++i) { ButtonEvent b = new ButtonEvent(inputEvents[i].code, 0, inputEvents[i].code, convertButtonAction(inputEvents[i].value), this.getClass().toString()); while (iter.hasNext()) { IButtonEventListener l = (IButtonEventListener) iter.next(); l.buttonEvent(b); } } } } catch (ConcurrentModificationException e) { log.log(LogService.LOG_ERROR, "Concurrency issue", e); } } dev.close(); } private long convertButtonAction(long value) { if (value == 1) { return ButtonEvent.KEY_DOWN; } if (value == 0) { return ButtonEvent.KEY_UP; } return value; } public void tearDown() { interrupt(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
6b60ea99adaad9d974685327677ad9da0e8c407d
ab05dd1cf6678de2ee9ff01ab241de2ec3b77db7
/app/src/main/java/com/example/navigationdrawerfragments/activity/movies/AliveActivity.java
2799a1ca873592e3eb4275720824bef7b91c4647
[]
no_license
ainanadia/movie-app
a7788c61fc7cacb611a08b3e8cefae5647a2153e
1ac19ebb68fb9153136b7e434c19175c90fc2ef6
refs/heads/master
2023-02-05T10:24:21.755635
2020-12-22T05:16:53
2020-12-22T05:16:53
303,917,128
0
1
null
null
null
null
UTF-8
Java
false
false
5,555
java
package com.example.navigationdrawerfragments.activity.movies; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.example.navigationdrawerfragments.R; import com.example.navigationdrawerfragments.activity.playtrailer.PlayTrailerActivity; import com.google.android.material.floatingactionbutton.FloatingActionButton; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class AliveActivity extends AppCompatActivity { private static final String TAG = "buttonPlayTheRing"; Button backBtn; FloatingActionButton floatingEditButton, floatingDelete, floatingEdit ; Button playTrailerAlive; boolean isFABOpen = false; int movieid; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alive); backBtn = findViewById(R.id.btnBackAlive); floatingEditButton = findViewById(R.id.floatingEditButton); floatingEdit = findViewById(R.id.floatingEdit); floatingDelete = findViewById(R.id.floatingDelete); playTrailerAlive = findViewById(R.id.btnPlayAlive); Intent intent=getIntent(); movieid =intent.getIntExtra("alive", 2); playTrailerAlive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(AliveActivity.this, PlayTrailerActivity.class); intent.putExtra("alive", 2); startActivity(intent); return; } }); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); floatingEditButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!isFABOpen){ showFABMenu(); }else{ closeFABMenu(); } } }); } private void showFABMenu(){ isFABOpen=true; floatingEdit.animate().translationY(-getResources().getDimension(R.dimen.standard_65)); floatingDelete.animate().translationY(-getResources().getDimension(R.dimen.standard_125)); } private void closeFABMenu(){ isFABOpen=false; floatingEdit.animate().translationY(0); floatingDelete.animate().translationY(0); } public void openDeleteDialog (View v){ AlertDialog.Builder dialog=new AlertDialog.Builder(this, R.style.MyDialogTheme); dialog.setTitle("Confirm Delete"); dialog.setMessage("Do you want to delete this movie? "); dialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { // Database_TT db = new Database_TT(DeleteTT.this); public void onClick(DialogInterface dialog, int which) { // continue with delete delete_data_from_server(movieid); System.out.println("TENGOK ID BERAPA" + movieid); } }); dialog.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // close dialog dialog.cancel(); } }); AlertDialog alertDialog = dialog.create(); alertDialog.show(); } private void delete_data_from_server(final int itemid) { AsyncTask<String, Void, Void> task = new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { HashMap<String, Integer> nameValuePairs = new HashMap<>(); nameValuePairs.put("movieid", itemid); JSONObject jsonObject = new JSONObject(nameValuePairs); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject)); Log.d(TAG, "doInBackground: request" + jsonObject); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .header("Content-Type", "application/json; charset=utf-8") .url("http://192.168.0.190:8080/movie-restful/rest/MovieService/deletemovie") .delete(body) .build(); Log.d(TAG, "doInBackground: request"); try { Response response = client.newCall(request).execute(); Log.d(TAG, "doInBackground: response"); Log.d(TAG, "response: " + response.body().string()); //String accept = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return null; } }; task.execute(); } }
[ "ainanadiarahmat@gmail.com" ]
ainanadiarahmat@gmail.com
45bc1388a671ac1ccba0ac8c3c9c715bf0a25bb9
c7bf1d96eb434a74648b1072d8f6960089120983
/src/java/es/uma/ecplusproject/ejb/ECPlusBusinessException.java
8cc76e9f9f917177509a731a9f99f2b3eb820091
[]
no_license
jfrchicanog/ECPlusAcademicPortal
d999e44bb190bcceadd61a6c5011550f03df0a8e
eefc6eb88a82eb4a97e25296583f154db3190a48
refs/heads/master
2022-07-01T23:22:18.738837
2018-05-17T00:24:39
2018-05-17T00:24:39
143,293,118
0
0
null
null
null
null
UTF-8
Java
false
false
464
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package es.uma.ecplusproject.ejb; /** * * @author francis */ public class ECPlusBusinessException extends Exception { public ECPlusBusinessException(String message) { super(message); } public ECPlusBusinessException() { super(); } }
[ "chicano@lcc.uma.es" ]
chicano@lcc.uma.es
8173ba344a7267d6887b6258e9c760bc052df928
b9a14875c2c2983bf940a63c66d46e9580b8eabe
/modules/framework/src/main/java/io/cattle/platform/async/retry/Retry.java
1b5ea57b5d4f3e81fab5787da4538f5b6b972b65
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
bartoszcisek/cattle
a341d93dc4feb010c9b1efe07b4ddb665f952391
f59058d70fdb139f9259c2e3d697c0f57b615862
refs/heads/master
2020-03-21T17:37:16.010693
2017-10-17T19:01:18
2017-10-17T19:01:18
138,843,076
0
0
Apache-2.0
2018-06-27T07:05:59
2018-06-27T07:05:58
null
UTF-8
Java
false
false
1,082
java
package io.cattle.platform.async.retry; import java.util.concurrent.Future; public class Retry { int retryCount; int retries; Long timeoutMillis; Runnable runnable; Future<?> future; boolean keepalive = false; public Retry(int retries, Long timeoutMillis, Future<?> future, Runnable runnable) { super(); this.retryCount = 0; this.retries = retries; this.timeoutMillis = timeoutMillis; this.runnable = runnable; this.future = future; } public int getRetryCount() { return retryCount; } public int getRetries() { return retries; } public Long getTimeoutMillis() { return timeoutMillis; } public Runnable getRunnable() { return runnable; } public Future<?> getFuture() { return future; } public int increment() { return ++retryCount; } public void setKeepalive(boolean keepalive) { this.keepalive = keepalive; } public boolean isKeepalive() { return keepalive; } }
[ "darren.s.shepherd@gmail.com" ]
darren.s.shepherd@gmail.com
df9f104eade699877af780ac060179ecca7e6cc7
13bf6827d443182fa3abbd07fa833ac6075bbf84
/app/src/main/java/com/example/projectswd/presenters/WaterActivityPresenter.java
16a74c58f3481f3efd31c9cd80c720bd62efcaab
[]
no_license
k12SWDproject/apartment_citizen_android
2d44a43add1f5657f85ce35dc510fbe5d3e88f71
e92a15171fa550feed6a7f2ac7772d10c4b2bd27
refs/heads/master
2020-09-14T01:52:54.683330
2019-12-08T10:54:33
2019-12-08T10:54:33
222,975,039
0
0
null
2019-12-15T13:18:42
2019-11-20T16:00:07
Java
UTF-8
Java
false
false
1,119
java
package com.example.projectswd.presenters; import com.example.projectswd.contract.WaterActivityContract; import com.example.projectswd.model.HouseRecipt; import com.example.projectswd.repositories.ReciptRepository; import com.example.projectswd.repositories.ReciptRepositoryImp; import com.example.projectswd.utils.CallBackData; public class WaterActivityPresenter implements WaterActivityContract.presenter { WaterActivityContract.view view; ReciptRepository reciptRepository; public WaterActivityPresenter(WaterActivityContract.view view) { this.view = view; reciptRepository = new ReciptRepositoryImp(); } @Override public void getListWaterReceipt(String token, String type) { reciptRepository.getListRecipt(token, type, new CallBackData<HouseRecipt>() { @Override public void success(HouseRecipt houseRecipt) { view.getListWaterReceiptSuccess(houseRecipt); } @Override public void fail(String msg) { view.getListWaterReceiptFail(msg); } }); } }
[ "57663703+NguyenLuongVan@users.noreply.github.com" ]
57663703+NguyenLuongVan@users.noreply.github.com
4f51e118370a5f5ac7b08940e50c113f67cd71f0
72ea639c4bfdca216d8a5d4f4242755e7df773ce
/ssm-shop/src/main/java/com/mapper/ProductInfoMapper.java
4891408ee936bfd5c4002c5a97e9e0d9857206a8
[]
no_license
1045728150/2021GIT
877ab18a5718e499f055a72150b5386fb3852837
80ae9423c9c62d9ed6f6ee6590842dbbaf714b1f
refs/heads/master
2023-07-18T05:58:12.579471
2021-09-08T09:34:52
2021-09-08T09:34:52
403,494,847
0
0
null
null
null
null
UTF-8
Java
false
false
1,210
java
package com.mapper; import com.pojo.ProductInfo; import com.pojo.ProductInfoExample; import com.pojo.vo.ProductInfoVo; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ProductInfoMapper { int countByExample(ProductInfoExample example); int deleteByExample(ProductInfoExample example); int deleteByPrimaryKey(Integer pId); int insert(ProductInfo record); int insertSelective(ProductInfo record); List<ProductInfo> selectByExample(ProductInfoExample example); ProductInfo selectByPrimaryKey(Integer pId); int updateByExampleSelective(@Param("record") ProductInfo record, @Param("example") ProductInfoExample example); int updateByExample(@Param("record") ProductInfo record, @Param("example") ProductInfoExample example); int updateByPrimaryKeySelective(ProductInfo record); int updateByPrimaryKey(ProductInfo record); //批量删除商品,传一个String数组,用来做sql语句的条件拼接 int deleteBatch(String []ids); /** * * @param infoVo 封装条件查询参数的对象 * @return 符合条件的商品集合 */ List<ProductInfo> selectCondition(ProductInfoVo infoVo); }
[ "1045728150@qq.com" ]
1045728150@qq.com