blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
689M
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
131 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
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
37018c40d5a0150913ea93ed95721dd0697f65d7
34a32b8c47d23d213c0ade8c389c4651b4f0747e
/src/ru/rks/multiplication/Multiplication.java
acbc5705dadcd3ba2f2d2687dfa0632c5ebed7de
[]
no_license
RiazanovKS/MultiplicationWithoutMultiply
01582d42a65980a15a11de67d0942d6deb24a211
30ca0bd03cd45935ea4feb4cdd0bd0fe38414aa1
refs/heads/master
2020-03-27T23:17:48.898297
2018-09-04T09:54:22
2018-09-04T09:54:22
147,307,392
0
0
null
null
null
null
UTF-8
Java
false
false
2,803
java
package ru.rks.multiplication; import java.util.Scanner; public class Multiplication { public static void main(String[] args) { int firstFactor = input(); int secondFactor = input(); System.out.println("Произведение чисел " + firstFactor + " и " + secondFactor + "= " + calculate(firstFactor, secondFactor)); } /** * Метод, возвращающий целочисленное значение, введенное с клавиатуры. * @return - целочисленное значение, введенное с клавиатуры. */ private static int input() { Scanner scanner = new Scanner(System.in); System.out.println("Введите число"); return scanner.nextInt(); } /** * Метод, возвращающий результат произведения двух целочисленных значений. * @param firstFactor - первый множитель * @param secondFactor - второй множитель * @return - целочисленное произведение первого и второго множителя. */ private static int calculate(int firstFactor, int secondFactor) { int result = 0; if(firstFactor>secondFactor&&secondFactor>0) { int tmp; tmp = secondFactor; secondFactor = firstFactor; firstFactor = tmp; } if(firstFactor>secondFactor&&firstFactor<0){ int tmp; tmp = secondFactor; secondFactor = firstFactor; firstFactor = tmp; } if (firstFactor < 0 && secondFactor > 0) { firstFactor = -firstFactor; secondFactor = - secondFactor; } if (firstFactor < 0 && secondFactor < 0) { firstFactor = -firstFactor; secondFactor = -secondFactor; } result = sum(firstFactor,secondFactor); if (firstFactor == 0 || secondFactor == 0) { result = 0; } return result; } /** * Цикл с параметром реализующий вычисление произведения двух множителей. * @param firstFactor - первый множитель. * @param secondFactor - второй множитель. * @return - результат вычисления произведения первого и второго множителя. */ private static int sum(int firstFactor, int secondFactor) { int resultOfSum = 0; for (int i = 0; i < firstFactor; i++) { resultOfSum += secondFactor; } return resultOfSum; } }
e1a962b8512c2d726897805a6e0c19746e925bde
84e064c973c0cc0d23ce7d491d5b047314fa53e5
/latest9.4/hej/net/sf/saxon/trans/RuleTarget.java
880655221ad3df20ef6b8cb4fcff3f1520195c47
[]
no_license
orbeon/saxon-he
83fedc08151405b5226839115df609375a183446
250c5839e31eec97c90c5c942ee2753117d5aa02
refs/heads/master
2022-12-30T03:30:31.383330
2020-10-16T15:21:05
2020-10-16T15:21:05
304,712,257
1
1
null
null
null
null
UTF-8
Java
false
false
1,073
java
package net.sf.saxon.trans; import net.sf.saxon.trace.ExpressionPresenter; import java.io.Serializable; /** * The target of a rule, typically a Template. */ public interface RuleTarget extends Serializable { /** * Output diagnostic explanation to an ExpressionPresenter */ public void explain(ExpressionPresenter presenter); } // // The contents of this file are subject to the Mozilla Public License Version 1.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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is: all this file // // The Initial Developer of the Original Code is Saxonica Limited. // Portions created by ___ are Copyright (C) ___. All rights reserved. // // Contributor(s): //
d631513eaef568bc9f2c2997222f982d5c8304f5
08fbb0f523b2e868278c5e3a75f0e7134b74f710
/app/src/main/java/com/readboy/wearlauncher/utils/Utils.java
67e7582382af847c6e587449d372633d638ea8ad
[]
no_license
sengeiou/WearLauncherA2
515af1f9c34e56112f9c7a26427a067254226d95
05c711e0fe297c8f7433ec67c3f08ffb07d4ef09
refs/heads/master
2021-10-11T13:20:53.427361
2019-01-26T12:26:41
2019-01-26T12:27:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,828
java
package com.readboy.wearlauncher.utils; import android.annotation.TargetApi; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Build; import android.provider.Settings; import android.renderscript.Allocation; import android.renderscript.Element; import android.renderscript.RenderScript; import android.renderscript.ScriptIntrinsicBlur; import android.text.TextUtils; import android.util.Log; import android.view.WindowManager; import android.widget.ImageView; import android.widget.Toast; import com.readboy.wearlauncher.Launcher; import com.readboy.wearlauncher.LauncherApplication; import com.readboy.wearlauncher.R; import com.readboy.wearlauncher.dialog.ClassDisableDialog; import com.readboy.wearlauncher.view.DialBaseLayout; import java.util.Arrays; import java.util.Calendar; import java.util.List; import android.app.readboy.PersonalInfo; import android.app.readboy.ReadboyWearManager; import android.app.readboy.IReadboyWearListener; public class Utils { //Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS public static final String AIRPLANE_MODE_TOGGLEABLE_RADIOS = "airplane_mode_toggleable_radios"; public static boolean isAirplaneModeOn(Context context) { return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } public static void checkAndDealWithAirPlanMode(Context context){ if (!isAirplaneModeOn(context)) return; Intent intent = new Intent("com.readboy.settings.AirplaneModeReset"); context.startActivity(intent); } public static boolean isRadioAllowed(Context context, String type) { if (!Utils.isAirplaneModeOn(context)) { return true; } // Here we use the same logic in onCreate(). String toggleable = Settings.Global.getString(context.getContentResolver(), AIRPLANE_MODE_TOGGLEABLE_RADIOS); return toggleable != null && toggleable.contains(type); } public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) { // Retrieve all services that can match the given intent PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0); // Make sure only one match was found if (resolveInfo == null || resolveInfo.size() != 1) { return null; } // Get component info and create ComponentName ResolveInfo serviceInfo = resolveInfo.get(0); String packageName = serviceInfo.serviceInfo.packageName; String className = serviceInfo.serviceInfo.name; ComponentName component = new ComponentName(packageName, className); // Create a new intent. Use the old one for extras and such reuse Intent explicitIntent = new Intent(implicitIntent); // Set the component to be explicit explicitIntent.setComponent(component); return explicitIntent; } public static int getScreenWidth(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point p = new Point(); wm.getDefaultDisplay().getSize(p); return p.x; } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static int getScreenHeight(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Point p = new Point(); wm.getDefaultDisplay().getSize(p); return p.y; } public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } public static void startActivity(Context context, String pkg, String cls){ List<String> ableEnterList = Arrays.asList(context.getResources().getStringArray( R.array.ableEnterList)); /*boolean isEnable = ((LauncherApplication)LauncherApplication.getApplication()).getWatchController().isNowEnable();*/ ReadboyWearManager rwm = (ReadboyWearManager)context.getSystemService(Context.RBW_SERVICE); boolean isEnable = rwm.isClassForbidOpen(); if(isEnable && !ableEnterList.contains(pkg)){ ClassDisableDialog.showClassDisableDialog(context); checkAndDealWithAirPlanMode(context); return; } try { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); if(TextUtils.equals(DialBaseLayout.DIALER_PACKAGE_NAME,pkg) && ((LauncherApplication) LauncherApplication.getApplication()).getWatchController().getMissCallCountImmediately() > 0){ intent.setType(android.provider.CallLog.Calls.CONTENT_TYPE); intent.putExtra("index",2); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.setClassName(pkg, cls); context.startActivity(intent); LauncherApplication.setTouchEnable(false); Log.d("TEST","start activity pkg:"+pkg+", cls:"+cls); }catch (Exception e){ e.printStackTrace(); Log.e("TEST","Can not find pkg:"+pkg+", cls:"+cls); Toast.makeText(context,"Can not find pkg:"+pkg+",\ncls:"+cls,Toast.LENGTH_SHORT).show(); } } private static Activity getActivity(Context context) { while (!(context instanceof Activity) && context instanceof ContextWrapper) { context = ((ContextWrapper) context).getBaseContext(); } if (context instanceof Activity) { return (Activity) context; }else { return null; } } public static boolean isFirstBoot(Context context){ if(Settings.System.getInt(context.getContentResolver(),"readboy_first_open",0) != 1){ return true; } return false; } public static void setFirstBoot(Context context, boolean firstBoot){ if(firstBoot){ Settings.System.putInt(context.getContentResolver(),"readboy_first_open",0); }else { Settings.System.putInt(context.getContentResolver(),"readboy_first_open",1); } } /** * 建议模糊度(在0.0到25.0之间) */ private static final int BLUR_RADIUS = 20; private static final int SCALED_WIDTH = 100; private static final int SCALED_HEIGHT = 100; /** * 得到模糊后的bitmap * thanks http://wl9739.github.io/2016/07/14/教你一分钟实现模糊效果/ * * @param context * @param bitmap * @param radius * @return */ public static Bitmap getBlurBitmap(Context context, Bitmap bitmap, int radius) { // 将缩小后的图片做为预渲染的图片。 Bitmap inputBitmap = Bitmap.createScaledBitmap(bitmap, SCALED_WIDTH, SCALED_HEIGHT, false); // 创建一张渲染后的输出图片。 Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap); // 创建RenderScript内核对象 RenderScript rs = RenderScript.create(context); // 创建一个模糊效果的RenderScript的工具对象 ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间。 // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去。 Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap); Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap); // 设置渲染的模糊程度, 25f是最大模糊度 blurScript.setRadius(radius); // 设置blurScript对象的输入内存 blurScript.setInput(tmpIn); // 将输出数据保存到输出内存中 blurScript.forEach(tmpOut); // 将数据填充到Allocation中 tmpOut.copyTo(outputBitmap); return outputBitmap; } public static void startSwitchBackgroundAnim(ImageView view, Bitmap bitmap) { Drawable oldDrawable = view.getDrawable(); Drawable oldBitmapDrawable ; TransitionDrawable oldTransitionDrawable = null; if (oldDrawable instanceof TransitionDrawable) { oldTransitionDrawable = (TransitionDrawable) oldDrawable; oldBitmapDrawable = oldTransitionDrawable.findDrawableByLayerId(oldTransitionDrawable.getId(1)); } else if (oldDrawable instanceof BitmapDrawable) { oldBitmapDrawable = oldDrawable; } else { oldBitmapDrawable = new ColorDrawable(0xffc2c2c2); } if (oldTransitionDrawable == null) { oldTransitionDrawable = new TransitionDrawable(new Drawable[]{oldBitmapDrawable, new BitmapDrawable(bitmap)}); oldTransitionDrawable.setId(0, 0); oldTransitionDrawable.setId(1, 1); oldTransitionDrawable.setCrossFadeEnabled(true); view.setImageDrawable(oldTransitionDrawable); } else { oldTransitionDrawable.setDrawableByLayerId(oldTransitionDrawable.getId(0), oldBitmapDrawable); oldTransitionDrawable.setDrawableByLayerId(oldTransitionDrawable.getId(1), new BitmapDrawable(bitmap)); } oldTransitionDrawable.startTransition(1000); } /** 获取今天零时时间戳*/ public static long getTodayStartTime(){ Calendar calendar = Calendar.getInstance(); calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0); long dayStartTime = calendar.getTimeInMillis(); dayStartTime = dayStartTime - dayStartTime % 1000; return dayStartTime; } public static Drawable addShadow(Context context,Drawable src) { if (src == null ) { return src; } Bitmap b = drawableToBitmap(src); return new BitmapDrawable(context.getResources(), addShadow(b)); } public static Bitmap addShadow(Bitmap bitmap) { int shadowWidth = 10; int shadowHeight = 10; int width = bitmap.getWidth() + shadowWidth; int height = bitmap.getHeight() + shadowHeight; Rect dst = new Rect(0, 0, width, height); Rect src = new Rect(0, 0, width - shadowWidth, height - shadowHeight); Canvas canvas = new Canvas(); Paint paint = new Paint(); Paint blurPaint = new Paint(); BlurMaskFilter bf = new BlurMaskFilter(20, BlurMaskFilter.Blur.INNER); blurPaint.setColor(0xff000000); blurPaint.setMaskFilter(bf); Bitmap result = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888); canvas.setBitmap(result); canvas.drawBitmap(bitmap.extractAlpha(blurPaint, null), src, dst, blurPaint); canvas.drawBitmap(bitmap, shadowWidth / 2, shadowHeight / 2, paint); canvas.setBitmap(null); return result; } private static Bitmap drawableToBitmap(Drawable d) { if (d == null) return null; int width = d.getIntrinsicWidth(); int height = d.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Rect rect = new Rect(0, 0, width, height); Rect oldBound = d.copyBounds(); d.setBounds(rect); d.draw(canvas); d.setBounds(oldBound); canvas.setBitmap(null); return bitmap; } public static boolean isEmpty(CharSequence str){ if (str == null || str.length() == 0 || str.equals("null") || str.equals("NULL")) return true; else return false; } }
ab2349df474f2ef01815faaae6755dc0ca96b927
7b13d893c1d27cbf2130219e894c009f54f5a761
/app/src/main/java/org/mixare/MixMap.java
6df30a80d70c4e30e346ae7570d1f7eda1571191
[]
no_license
radinaldn/arlacak-frontend
b0c79cfbea035642ab7fc784485a6531cbff4ecc
5806fa1e157d9e9e506daa5961e28ceeaa19853e
refs/heads/master
2021-09-17T22:15:02.692070
2018-07-05T23:04:34
2018-07-05T23:04:34
107,045,186
0
0
null
null
null
null
UTF-8
Java
false
false
9,279
java
package org.mixare; import java.util.ArrayList; import java.util.List; import org.inkubator.radinaldn.R; import org.mixare.data.DataHandler; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.location.Location; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class MixMap extends MapActivity implements OnTouchListener{ private static List<Overlay> mapOverlays; private Drawable drawable; private static ArrayList<Marker> markerList; private static DataView dataView; private static GeoPoint startPoint; private MixContext ctx; private MapView mapView; static MixMap map; private static Context thisContext; private static TextView searchNotificationTxt; public static ArrayList<Marker> originalMarkerList; @Override protected boolean isRouteDisplayed() { return false; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dataView = MixView.dataView; ctx = dataView.getContext(); setMarkerList(dataView.getDataHandler().getMarkerList()); map = this; setMapContext(this); mapView= new MapView(this, "05j7Agbwq2a0NWfYkP_L15iXlOkhinUeIGEVwrA"); mapView.setBuiltInZoomControls(true); mapView.setClickable(true); mapView.setSatellite(true); mapView.setEnabled(true); this.setContentView(mapView); setStartPoint(); createOverlay(); if (dataView.isFrozen()){ searchNotificationTxt = new TextView(this); searchNotificationTxt.setWidth(MixView.dWindow.getWidth()); searchNotificationTxt.setPadding(10, 2, 0, 0); searchNotificationTxt.setText(getString(DataView.SEARCH_ACTIVE_1)+" "+ MixListView.getDataSource()+ getString(DataView.SEARCH_ACTIVE_2)); searchNotificationTxt.setBackgroundColor(Color.DKGRAY); searchNotificationTxt.setTextColor(Color.WHITE); searchNotificationTxt.setOnTouchListener(this); addContentView(searchNotificationTxt, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } } public void setStartPoint() { Location location = ctx.getCurrentLocation(); MapController controller; double latitude = location.getLatitude()*1E6; double longitude = location.getLongitude()*1E6; controller = mapView.getController(); startPoint = new GeoPoint((int)latitude, (int)longitude); controller.setCenter(startPoint); controller.setZoom(14); } public void createOverlay(){ mapOverlays=mapView.getOverlays(); OverlayItem item; drawable = this.getResources().getDrawable(R.drawable.icon_map); MixOverlay mixOverlay = new MixOverlay(this, drawable); for (int i = 0; i < markerList.size(); i++) { GeoPoint point = new GeoPoint((int)(markerList.get(i).getLatitude()*1E6), (int)(markerList.get(i).getLongitude()*1E6)); item = new OverlayItem(point, "", ""); mixOverlay.addOverlay(item); mapOverlays.add(mixOverlay); } MixOverlay myOverlay; drawable = this.getResources().getDrawable(R.drawable.loc_icon); myOverlay = new MixOverlay(this, drawable); item = new OverlayItem(startPoint, "Your Position", ""); myOverlay.addOverlay(item); mapOverlays.add(myOverlay); } @Override public boolean onCreateOptionsMenu(Menu menu) { int base = Menu.FIRST; /*define the first*/ MenuItem item1 =menu.add(base, base, base, getString(DataView.MAP_MENU_NORMAL_MODE)); MenuItem item2 =menu.add(base, base+1, base+1, getString(DataView.MAP_MENU_SATELLITE_MODE)); MenuItem item3 =menu.add(base, base+2, base+2, getString(DataView.MAP_MY_LOCATION)); MenuItem item4 =menu.add(base, base+3, base+3, getString(DataView.MENU_ITEM_2)); MenuItem item5 =menu.add(base, base+4, base+4, getString(DataView.MENU_CAM_MODE)); /*assign icons to the menu items*/ item1.setIcon(android.R.drawable.ic_menu_gallery); item2.setIcon(android.R.drawable.ic_menu_mapmode); item3.setIcon(android.R.drawable.ic_menu_mylocation); item4.setIcon(android.R.drawable.ic_menu_view); item5.setIcon(android.R.drawable.ic_menu_camera); //adhastar added item1.setVisible(true); item2.setVisible(true); item3.setVisible(true); item4.setVisible(false); item5.setVisible(true); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ /*Satellite View*/ case 1: mapView.setSatellite(false); break; /*street View*/ case 2: mapView.setSatellite(true); break; /*go to users location*/ case 3: setStartPoint(); break; /*List View*/ case 4: createListView(); finish(); break; /*back to Camera View*/ case 5: finish(); break; } return true; } public void createListView(){ MixListView.setList(2); if (dataView.getDataHandler().getMarkerCount() > 0) { Intent intent1 = new Intent(MixMap.this, MixListView.class); startActivityForResult(intent1, 42); } /*if the list is empty*/ else{ Toast.makeText( this, DataView.EMPTY_LIST_STRING_ID, Toast.LENGTH_LONG ).show(); } } // public static ArrayList<Marker> getMarkerList(){ // return markerList; // } public void setMarkerList(ArrayList<Marker> maList){ markerList = maList; } public DataView getDataView(){ return dataView; } // public static void setDataView(DataView view){ // dataView= view; // } // public static void setMixContext(MixContext context){ // ctx= context; // } // // public static MixContext getMixContext(){ // return ctx; // } public List<Overlay> getMapOverlayList(){ return mapOverlays; } public void setMapContext(Context context){ thisContext= context; } public Context getMapContext(){ return thisContext; } public void startPointMsg(){ Toast.makeText(getMapContext(), DataView.MAP_CURRENT_LOCATION_CLICK, Toast.LENGTH_LONG).show(); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); doMixSearch(query); } } @Override public void onNewIntent(Intent intent) { setIntent(intent); handleIntent(intent); } private void doMixSearch(String query) { DataHandler jLayer = dataView.getDataHandler(); if (!dataView.isFrozen()) { originalMarkerList = jLayer.getMarkerList(); MixListView.originalMarkerList = jLayer.getMarkerList(); } markerList = new ArrayList<Marker>(); for(int i = 0; i < jLayer.getMarkerCount(); i++) { Marker ma = jLayer.getMarker(i); if (ma.getTitle().toLowerCase().indexOf(query.toLowerCase())!=-1){ markerList.add(ma); } } if(markerList.size()==0){ Toast.makeText( this, getString(DataView.SEARCH_FAILED_NOTIFICATION), Toast.LENGTH_LONG ).show(); } else{ jLayer.setMarkerList(markerList); dataView.setFrozen(true); finish(); Intent intent1 = new Intent(this, MixMap.class); startActivityForResult(intent1, 42); } } @Override public boolean onTouch(View v, MotionEvent event) { dataView.setFrozen(false); dataView.getDataHandler().setMarkerList(originalMarkerList); searchNotificationTxt.setVisibility(View.INVISIBLE); searchNotificationTxt = null; finish(); Intent intent1 = new Intent(this, MixMap.class); startActivityForResult(intent1, 42); return false; } } class MixOverlay extends ItemizedOverlay<OverlayItem> { private ArrayList<OverlayItem> overlayItems = new ArrayList<OverlayItem>(); private MixMap mixMap; public MixOverlay(MixMap mixMap, Drawable marker){ super (boundCenterBottom(marker)); this.mixMap = mixMap; } @Override protected OverlayItem createItem(int i) { return overlayItems.get(i); } @Override public int size() { return overlayItems.size(); } @Override protected boolean onTap(int index){ if (size() == 1) mixMap.startPointMsg(); else if (mixMap.getDataView().getDataHandler().getMarker(index).getURL() != null) { String url = mixMap.getDataView().getDataHandler().getMarker(index).getURL(); //Log.d("MapView", "opern url: "+url); try { if (url != null && url.startsWith("webpage")) { String newUrl = MixUtils.parseAction(url); mixMap.getDataView().getContext().loadWebPage(newUrl, mixMap.getMapContext()); } } catch (Exception e) { e.printStackTrace(); } } return true; } public void addOverlay(OverlayItem overlay) { overlayItems.add(overlay); populate(); } }
c7d849128392863f78b35abdf77f73cb6eb87be5
7a459958a02a3fc005af3cc493d3e7a4aac756e0
/src/test/java/tests/bankmanager/BankManagerLoginTest.java
f360e133a108bc4e85e30ed002e8e747b33461f4
[]
no_license
hothicam/Project_Thao_Cam
72d4511fcd7f3d54e6784c900d456d2e1d1d73bb
0fbdeaf57a54ed22267454e0726dc15db6b7284c
refs/heads/master
2023-05-10T02:12:12.407252
2020-01-15T01:57:18
2020-01-15T01:57:18
233,975,367
0
0
null
2023-05-09T18:18:12
2020-01-15T01:55:19
JavaScript
UTF-8
Java
false
false
709
java
package tests.bankmanager; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import static tests.PageProvider.getBankManagerLoginPage; public class BankManagerLoginTest { @When("^I click bank manager login$") public void clickBankManagerLoginButtton() throws InterruptedException { Thread.sleep(1000); getBankManagerLoginPage().clickBankManagerLoginButton(); Thread.sleep(1000); } @Then("^I verify login into bank management successfully$") public void verifyLoginSuccessfully() throws InterruptedException { Thread.sleep(1000); getBankManagerLoginPage().verifyLoginManagerSuccessfully(); Thread.sleep(1000); } }
bd169c9284f8a6b745f76d8f3820ec81f4437c28
0a91e3ba61c210f929da28ecd2e12503a5d1a00e
/src/main/java/net/atos/start/student/entity/Student.java
2500e62aa6931d5a0ab7a8c7b7888528896f3c13
[]
no_license
Vertig00/Spring-project
f9a7877b7faaf2664c60c54ad7a0f1b9d634473c
b9852230e9ef9dd6770821f3272973027bc1d4b8
refs/heads/master
2020-09-24T20:45:56.875013
2016-10-03T14:00:36
2016-10-03T14:00:36
67,441,138
0
0
null
null
null
null
UTF-8
Java
false
false
4,239
java
package net.atos.start.student.entity; import org.hibernate.annotations.Type; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by lukasz on 25.07.16. */ @Entity(name = "Student") @Table(name = "student") @SequenceGenerator(name = "student_sequence", sequenceName = "student_sequence", allocationSize = 1) public class Student { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "student_sequence") @Column(name = "id", nullable = false, updatable = false, unique = true) private int id; @NotNull @Column(name = "name") private String name; @NotNull @Column(name = "surname") private String surname; @NotNull @Type(type = "date") @DateTimeFormat(pattern = "dd-MM-yyyy") @Column(name = "date") private Date date; @NotNull @Size(max = 11, min = 11) @Column(name = "pesel", unique = true) private String pesel; @NotNull @Column(name = "email") private String email; @NotNull @Size(max = 1) @Column(name = "sex") private String sex; @ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL) @JoinTable(name = "student_subject", joinColumns = @JoinColumn( name = "student_id", referencedColumnName = "id" ), inverseJoinColumns = @JoinColumn( name = "subject_id", referencedColumnName = "subject_id" ) ) private List<SubjectEntity> subjects = new ArrayList<SubjectEntity>(); // TODO: zrobic buildera public Student(){} public Student(int id, String name, String surname, Date date, String sex, String pesel, String email) { this.id = id; this.name = name; this.surname = surname; this.date = date; this.sex = sex; this.pesel = pesel; this.email = email; } public Student(int id, String name, String surname, String sex, String pesel, String email) { this.id = id; this.name = name; this.surname = surname; this.sex = sex; this.pesel = pesel; this.email = email; } public Student(String name, String surname, Date date, String sex, String pesel, String email) { this.name = name; this.surname = surname; this.sex = sex; this.pesel = pesel; this.date = date; this.email = email; } public Student(int id, String name, String surname) { this.id = id; this.name = name; this.surname = surname; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPesel() { return pesel; } public void setPesel(String pesel) { this.pesel = pesel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public StudentForm getForm(){ StudentForm form = new StudentForm(); form.setId(this.getId()); form.setName(this.getName()); form.setSurname(this.getSurname()); form.setSex(this.getSex()); form.setPesel(this.getPesel()); form.setEmail(this.getEmail()); return form; } public List<SubjectEntity> getSubjects() { return subjects; } public void setSubjects(List<SubjectEntity> subjects) { this.subjects = subjects; } }
af3fed7e039dba67efda90dc1cb8970d7bfc288a
ce975af2263d2dd8312e68c5456445a669be2e28
/src/main/java/valandur/webapi/security/SecurityFilter.java
bc1b099025ca0e7bf5399b34187c0a9c88587b76
[ "MIT" ]
permissive
ancgate/Web-API
0939efd61840a0b5ceb3e14ab6e02e5311b85f90
c45445ea61079d5f1d9519e597409e9a82d15a28
refs/heads/master
2020-04-18T08:37:10.142593
2018-08-23T10:33:19
2018-08-23T10:33:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,198
java
package valandur.webapi.security; import com.google.common.net.HttpHeaders; import org.eclipse.jetty.http.HttpMethod; import valandur.webapi.WebAPI; import valandur.webapi.servlet.base.ExplicitDetails; import valandur.webapi.servlet.base.Permission; import valandur.webapi.util.TreeNode; import javax.annotation.Priority; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ResourceInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import static valandur.webapi.security.SecurityService.*; @Provider @Priority(Priorities.AUTHENTICATION) public class SecurityFilter implements ContainerRequestFilter { private SecurityService srv; private Map<String, Double> lastCall = new ConcurrentHashMap<>(); private AtomicLong calls = new AtomicLong(0); @Context private ResourceInfo resourceInfo; @Context private HttpServletRequest request; @Context private HttpServletResponse response; public SecurityFilter() { this.srv = WebAPI.getSecurityService(); } @Override public void filter(ContainerRequestContext context) { String addr = getRealAddr(request); String target = context.getUriInfo().getPath(); request.setAttribute("ip", addr); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ORIGIN); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_METHODS); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_HEADERS); // Exit early on options requests if (HttpMethod.OPTIONS.asString().equalsIgnoreCase(context.getMethod())) { context.abortWith(Response.ok().build()); return; } if (!srv.whitelistContains(addr)) { WebAPI.getLogger().warn(addr + " is not on whitelist: " + target); throw new ForbiddenException(); } else if (srv.blacklistContains(addr)) { WebAPI.getLogger().warn(addr + " is on blacklist: " + target); throw new ForbiddenException(); } String key = context.getHeaderString(API_KEY_HEADER); if (key == null || key.isEmpty()) { key = context.getUriInfo().getQueryParameters().getFirst("key"); } if (key == null || key.isEmpty()) { key = context.getHeaderString(HttpHeaders.AUTHORIZATION); if (key != null) key = key.substring(key.indexOf(" ") + 1); } PermissionStruct permStruct; if (key != null) { permStruct = srv.getPermissions(key); } else { key = DEFAULT_KEY; permStruct = srv.getDefaultPermissions(); } // Add new security context SecurityContext securityContext = new SecurityContext(permStruct); context.setSecurityContext(securityContext); request.setAttribute("security", securityContext); // Do rate limiting calls.incrementAndGet(); if (permStruct.getRateLimit() > 0) { double time = System.nanoTime() / 1000000000d; if (lastCall.containsKey(key) && time - lastCall.get(key) < 1d / permStruct.getRateLimit()) { WebAPI.getLogger().warn(addr + " has exceeded the rate limit when requesting " + request.getRequestURI()); throw new ClientErrorException("Rate limit exceeded", Response.Status.TOO_MANY_REQUESTS); } lastCall.put(key, time); } boolean details = true; Method method = resourceInfo.getResourceMethod(); if (method.isAnnotationPresent(ExplicitDetails.class)) { ExplicitDetails dets = method.getAnnotation(ExplicitDetails.class); if (dets.value()) { details = false; } } request.setAttribute("details", details); String basePath = resourceInfo.getResourceClass().getAnnotation(Path.class).value(); TreeNode perms = permStruct.getPermissions(); Permission[] reqPerms = method.getAnnotationsByType(Permission.class); if (reqPerms.length == 0) { return; } // Calculate the sub-perms that apply for our endpoint for (Permission reqPerm : reqPerms) { if (!reqPerm.autoCheck()) { continue; } List<String> reqPermList = new ArrayList<>(Arrays.asList(reqPerm.value())); reqPermList.add(0, basePath); TreeNode methodPerms = SecurityService.subPermissions(perms, reqPermList); if (!methodPerms.getValue()) { WebAPI.getLogger().warn(addr + " does not have permisson to access " + target); if (key.equalsIgnoreCase(DEFAULT_KEY)) { throw new NotAuthorizedException("Bearer realm=\"Web-API Access\""); } else { throw new ForbiddenException(); } } // Set the endpoint permissions to the first permissions listed if (securityContext.getEndpointPerms() == null) securityContext.setEndpointPerms(methodPerms); } } private String getRealAddr(HttpServletRequest request) { final String addr = request.getRemoteAddr(); String forwardedFor = request.getHeader(HttpHeaders.X_FORWARDED_FOR); if (forwardedFor == null) return addr; // First check the actual IP that we got. If that is not a trusted proxy we're done. if (!srv.containsProxyIP(addr)) { WebAPI.getLogger().warn(addr + " sent " + HttpHeaders.X_FORWARDED_FOR + " header, but is not a proxy. Header will be ignored!"); return addr; } String[] ips = forwardedFor.split(","); // Traverse the X-Forwarded-For header backwards and take the first IP that we don't trust. for (int i = ips.length - 1; i >= 0; i--) { String ip = ips[i].trim(); if (srv.containsProxyIP(ip)) { continue; } if (i > 0) { WebAPI.getLogger().warn(ips[i].trim() + " sent " + HttpHeaders.X_FORWARDED_FOR + " header, but is not a proxy. Header will be ignored!"); } return ips[i]; } // We usually shouldn't get here, but if we don't it means we trusted all proxy ips, so just // return the last one of those. return ips[ips.length - 1]; } }
2d0c841664f9a1c2eb7d86e5b22bef8c6193aa75
9695fd84717c5df8c77599c119db8554ebbeaccd
/src/main/java/com/emusicstore/controller/LoginController.java
88330ad5077a685ed7c83a972811655eb5179ad5
[]
no_license
kssraju/eMusicStore
6c0397072e47ab393211f0cf985a372c3b5db934
352f4dd121b78e462574009a8fa3b444b40df50e
refs/heads/master
2021-01-18T15:42:28.317990
2017-02-28T23:37:19
2017-02-28T23:37:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
800
java
package com.emusicstore.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class LoginController { @RequestMapping("/login") public String login(@RequestParam (value="error", required=false) String error, @RequestParam (value="logout", required=false) String logout, Model model) { if (error != null) { model.addAttribute("error", "Invalid username or password"); } if (logout != null) { model.addAttribute("msg", "You have been logged out successfully"); } return "login"; } }
fd626d8106c6b1fd7d575424106e5736dda4e2f0
68c73e7f6ee097ef8d6d34d4683eae6ffc5f8f46
/plat-app/plat-service/src/main/java/com/jyh/app/plat/service/dao/ServiceMapper.java
eba81bba093c1b44f29f1948a00153781c88486d
[]
no_license
bounce5733/jyh-app
0d4eadb89479afced0222dbf3cfc239c428817ff
577211d9620fd5cf5893236067a43c71d16e0e3c
refs/heads/master
2020-03-24T12:02:40.220829
2018-08-22T15:31:12
2018-08-22T15:31:12
142,698,208
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package com.jyh.app.plat.service.dao; import com.jyh.app.plat.service.Mapper; import com.jyh.entity.plat.service.ServiceEntity; public interface ServiceMapper extends Mapper<ServiceEntity> { }
8b582ab9fcc4f458e57446403345b88b8bb000bd
dea92fc41db6a97d8cb32b266c399edd3a61989f
/source/org.strategoxt.imp.spoofax.generator/src-gen/org/strategoxt/imp/spoofax/generator/lifted9438.java
59f668ba5db73b3c8c6ee2b842182ada2c801422
[]
no_license
adilakhter/spoofaxlang
19170765e690477a79069e05fd473f521d1d1ddc
27515280879cc108a3cf2108df00760b6d39e15e
refs/heads/master
2020-03-17T01:15:18.833754
2015-01-22T07:12:05
2015-01-22T07:12:05
133,145,594
1
0
null
null
null
null
UTF-8
Java
false
false
1,105
java
package org.strategoxt.imp.spoofax.generator; import org.strategoxt.stratego_lib.*; import org.strategoxt.stratego_lib.*; import org.strategoxt.stratego_sglr.*; import org.strategoxt.stratego_gpp.*; import org.strategoxt.stratego_xtc.*; import org.strategoxt.stratego_aterm.*; import org.strategoxt.stratego_rtg.*; import org.strategoxt.stratego_sdf.*; import org.strategoxt.stratego_tool_doc.*; import org.strategoxt.java_front.*; import org.strategoxt.lang.*; import org.spoofax.interpreter.terms.*; import static org.strategoxt.lang.Term.*; import org.spoofax.interpreter.library.AbstractPrimitive; import java.util.ArrayList; import java.lang.ref.WeakReference; @SuppressWarnings("all") final class lifted9438 extends Strategy { TermReference w_4320; @Override public IStrategoTerm invoke(Context context, IStrategoTerm term) { Fail28641: { if(w_4320.value == null) break Fail28641; term = set_verbosity_0_0.instance.invoke(context, w_4320.value); if(term == null) break Fail28641; if(true) return term; } return null; } }
6c0bf02639a4015d41c6d80c9051e84073ec98bb
dcf0489d6ee91750d1d7696fc2cf2a049b524161
/nutella/src/main/java/endereco/Endereco.java
35826ceef8a517425a71853133cc9fdaeeaa35df
[]
no_license
biafernandesmaia/bia
5ff5c567e9a05cbff07502dfd7da14ebf7beb5a1
1076165680d642d9789e8c8eb620f81559a147c5
refs/heads/master
2021-06-20T11:43:59.194895
2017-08-04T12:18:41
2017-08-04T12:18:41
98,647,671
0
0
null
null
null
null
UTF-8
Java
false
false
398
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 endereco; /** * * @author aluno */ public class Endereco { private String Pais; private String Estado; private String Cidade; private String Rua; private String Complemento; }
e8c318a01622ae8600d6f03420ab2d0d69c0848a
e4a947cd69068150f736e18b2fc1c608ab55080f
/Students/Sabau M. Andrei/Zoowsome/src/javasmmr/zoowsome/services/factories/AquaticFactory.java
17fa3eac906180fe7d62363f74795479c4e2f56c
[]
no_license
bareeka/30425
6ce764b0c23848d3a25074beef473efd5c6a64c5
4e204cd2a89d79faacb0dee5694fcbf2f63b874d
refs/heads/master
2021-01-11T01:23:20.892520
2016-12-07T18:52:09
2016-12-07T18:52:09
70,613,243
0
0
null
2016-10-11T16:28:55
2016-10-11T16:28:54
null
UTF-8
Java
false
false
510
java
package javasmmr.zoowsome.services.factories; import javasmmr.zoowsome.models.animals.*; public class AquaticFactory extends SpeciesFactory{ public Animal getAnimal(String type) { if(Constants.Animals.Aquatics.SHARK.equals(type)) { return new Shark(); } else if(Constants.Animals.Aquatics.OCTOPUS.equals(type)) { return new Octopus(); } else if(Constants.Animals.Aquatics.FISH.equals(type)) { return new Fish(); } else throw new Exception("Invalid animal exception"); } }
fee43d0011c5a96114cd7f7576a91e497423a055
650c04cb1e0ae7ea21e0c0e0eab04ce551572949
/app/src/main/java/com/sg/moviesindex/model/tmdb/MovieDBResponse.java
5d5320e2498701c0b424519a456039b4f2b6599d
[]
no_license
shubh-dubey/Movies-Index
f097c9bcf4be1ff348845a27fdd168401cb7a4a4
0d6666b5582ffdd6a954997880f29310cfe6624b
refs/heads/master
2022-11-14T08:11:34.254447
2020-07-07T17:14:18
2020-07-07T17:14:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,294
java
package com.sg.moviesindex.model.tmdb; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class MovieDBResponse implements Parcelable { @SerializedName("page") @Expose private Integer page; @SerializedName("total_results") @Expose private Integer totalResults; @SerializedName("total_pages") @Expose private Integer totalPages; @SerializedName("results") @Expose private List<Movie> movies = null; public final static Parcelable.Creator<MovieDBResponse> CREATOR = new Creator<MovieDBResponse>() { @SuppressWarnings({ "unchecked" }) public MovieDBResponse createFromParcel(Parcel in) { return new MovieDBResponse(in); } public MovieDBResponse[] newArray(int size) { return (new MovieDBResponse[size]); } }; protected MovieDBResponse(Parcel in) { this.page = ((Integer) in.readValue((Integer.class.getClassLoader()))); this.totalResults = ((Integer) in.readValue((Integer.class.getClassLoader()))); this.totalPages = ((Integer) in.readValue((Integer.class.getClassLoader()))); in.readList(this.movies, (Movie.class.getClassLoader())); } public MovieDBResponse() { } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getTotalResults() { return totalResults; } public void setTotalResults(Integer totalResults) { this.totalResults = totalResults; } public Integer getTotalPages() { return totalPages; } public void setTotalPages(Integer totalPages) { this.totalPages = totalPages; } public List<Movie> getMovies() { return movies; } public void setMovies(List<Movie> movies) { this.movies = movies; } public void writeToParcel(Parcel dest, int flags) { dest.writeValue(page); dest.writeValue(totalResults); dest.writeValue(totalPages); dest.writeList(movies); } public int describeContents() { return 0; } }
1a8b9f2e5cdc5c7efa04eea5159ae8cd53118492
f97cecacb401daed67f32e11757d172afb7c3635
/mall-member/src/main/java/com/wff/mall/member/service/impl/MemberReceiveAddressServiceImpl.java
8c6b4f10ca329cdcdba81c7bd646c4003ff6eea4
[ "Apache-2.0" ]
permissive
wff0/mall
d21cae6aeed93e2eaab3d0ea4b77052593fa3e9a
297137e344c98e543b330f0e4eb0b7e60be5b054
refs/heads/master
2023-05-09T22:45:16.727916
2021-06-03T13:33:36
2021-06-03T13:33:36
363,636,858
0
0
null
null
null
null
UTF-8
Java
false
false
1,303
java
package com.wff.mall.member.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.wff.common.utils.PageUtils; import com.wff.common.utils.Query; import com.wff.mall.member.dao.MemberReceiveAddressDao; import com.wff.mall.member.entity.MemberReceiveAddressEntity; import com.wff.mall.member.service.MemberReceiveAddressService; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service("memberReceiveAddressService") public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressDao, MemberReceiveAddressEntity> implements MemberReceiveAddressService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<MemberReceiveAddressEntity> page = this.page( new Query<MemberReceiveAddressEntity>().getPage(params), new QueryWrapper<MemberReceiveAddressEntity>() ); return new PageUtils(page); } @Override public List<MemberReceiveAddressEntity> getAddress(Long memberId) { return this.list(new QueryWrapper<MemberReceiveAddressEntity>().eq("member_id", memberId)); } }
dd262b8aece4a70946206eb43c19ba05f13d7b85
98e53f3932ecce2a232d0c314527efe49f62e827
/org.rcfaces.core/src/org/rcfaces/core/internal/tools/GridServerSort.java
cf25fdd30627176768ad9797bae81d7367aaabab
[]
no_license
Vedana/rcfaces-2
f053a4ebb8bbadd02455d89a5f1cb870deade6da
4112cfe1117c4bfcaf42f67fe5af32a84cf52d41
refs/heads/master
2020-04-02T15:03:08.653984
2014-04-18T09:36:54
2014-04-18T09:36:54
11,175,963
1
0
null
null
null
null
UTF-8
Java
false
false
14,847
java
/* * $Id: GridServerSort.java,v 1.4 2013/11/13 12:53:22 jbmeslin Exp $ * */ package org.rcfaces.core.internal.tools; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.FacesException; import javax.faces.component.UIColumn; import javax.faces.component.UIComponent; import javax.faces.component.ValueHolder; import javax.faces.context.FacesContext; import javax.faces.event.FacesListener; import javax.faces.model.DataModel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.rcfaces.core.component.capability.ISortEventCapability; import org.rcfaces.core.event.SortEvent; import org.rcfaces.core.internal.capability.IGridComponent; import org.rcfaces.core.internal.listener.IScriptListener; import org.rcfaces.core.internal.listener.SortActionListener; import org.rcfaces.core.model.IRangeDataModel; import org.rcfaces.core.model.ISortedComponent; /** * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ public final class GridServerSort { private static final Log LOG = LogFactory.getLog(GridServerSort.class); private static final Long LONG_0 = new Long(0l); private static final Double DOUBLE_0 = new Double(0.0); private static final Map<String, ISortMethod> SORT_ALIASES = new HashMap<String, ISortMethod>( 8); static { SORT_ALIASES.put(ISortEventCapability.SORT_INTEGER, new SortLong()); SORT_ALIASES.put(ISortEventCapability.SORT_NUMBER, new SortDouble()); SORT_ALIASES.put(ISortEventCapability.SORT_ALPHA, new SortAlpha()); SORT_ALIASES.put(ISortEventCapability.SORT_ALPHA_IGNORE_CASE, new SortAlphaIgnoreCase()); SORT_ALIASES.put(ISortEventCapability.SORT_TIME, new SortDate()); SORT_ALIASES.put(ISortEventCapability.SORT_DATE, new SortDate()); } public static int[] computeSortedTranslation(FacesContext facesContext, IGridComponent data, DataModel dataModel, ISortedComponent sortedComponents[]) { ISortMethod< ? > sortMethods[] = new ISortMethod[sortedComponents.length]; for (int i = 0; i < sortMethods.length; i++) { UIColumn columnComponent = (UIColumn) sortedComponents[i] .getComponent(); if ((columnComponent instanceof ISortEventCapability) == false) { continue; } sortMethods[i] = getSortMethod( (ISortEventCapability) columnComponent, data); } int rowCount = data.getRowCount(); List<Object> datas[] = new List[sortedComponents.length]; for (int i = 0; i < datas.length; i++) { if (rowCount > 0) { datas[i] = new ArrayList<Object>(rowCount); } else { datas[i] = new ArrayList<Object>(); } } if (dataModel instanceof IRangeDataModel) { // Charge tout ! ((IRangeDataModel) dataModel).setRowRange(0, rowCount); } try { for (int rowIndex = 0;; rowIndex++) { data.setRowIndex(rowIndex); if (data.isRowAvailable() == false) { break; } Object rowData = null; boolean rowDataInitialized = false; for (int i = 0; i < datas.length; i++) { UIComponent column = sortedComponents[i].getComponent(); Object value = null; if (column instanceof ValueHolder) { value = ValuesTools.getValue(column); } ISortMethod< ? > sortMethod = sortMethods[i]; if (sortMethod == null) { throw new FacesException( "Can not get sort method for column #" + i + " id=" + column.getId()); } value = sortMethod .convertValue(facesContext, column, value); if (value == null) { if (rowDataInitialized == false) { rowDataInitialized = true; rowData = data.getRowData(); } // Avoid crahes when compare // then WHY get the full row Data when the column value // is null ? if (rowData instanceof Comparable) { value = rowData; } } datas[i].add(value); } } } finally { data.setRowIndex(-1); } int translations[] = new int[datas[0].size()]; for (int i = 0; i < translations.length; i++) { translations[i] = i; } if (translations.length < 2) { return translations; } Object ds[][] = new Object[datas.length][]; Comparator<Object> comparators[] = new Comparator[datas.length]; boolean sortOrders[] = new boolean[datas.length]; for (int i = 0; i < ds.length; i++) { ds[i] = datas[i].toArray(); ISortMethod sortMethod = sortMethods[i]; if (sortMethod == null) { throw new FacesException("No sort method #" + i + " for grid '" + ((UIComponent) data).getId() + "' of view '" + facesContext.getViewRoot().getViewId() + "'"); } comparators[i] = sortMethod.getComparator(); sortOrders[i] = sortedComponents[i].isAscending(); } for (int i = 0; i < translations.length; i++) { next_element: for (int j = i; j > 0; j--) { int j0 = translations[j - 1]; int j1 = translations[j]; for (int k = 0; k < sortMethods.length; k++) { Object o1 = ds[k][j0]; Object o2 = ds[k][j1]; if (comparators[k] == null) { continue; } int order = comparators[k].compare(o1, o2); if (order == 0) { continue; } if (sortOrders[k]) { if (order < 0) { break next_element; } } else if (order > 0) { break next_element; } translations[j] = j0; translations[j - 1] = j1; continue next_element; } } } if (LOG.isDebugEnabled()) { Set set2 = new HashSet(translations.length); LOG.debug("Valid SORT translation ..."); for (int i = 0; i < translations.length; i++) { if (set2.add(new Integer(translations[i])) == false) { LOG.debug("*** INVALID TRANSLATION ***"); continue; } } } return translations; } private static ISortMethod< ? > getSortMethod( ISortEventCapability columnComponent, IGridComponent gridComponent) { FacesListener facesListeners[] = columnComponent.listSortListeners(); for (int j = 0; j < facesListeners.length; j++) { FacesListener facesListener = facesListeners[j]; // Priorité coté JAVASCRIPT, on verra le serveur dans un // deuxieme temps ... if (facesListener instanceof SortActionListener) { return new SortAction((SortActionListener) facesListener, (UIComponent) columnComponent, gridComponent); } if ((facesListener instanceof IScriptListener) == false) { continue; } IScriptListener scriptListener = (IScriptListener) facesListener; ISortMethod< ? > sortMethod = (ISortMethod< ? >) SORT_ALIASES .get(scriptListener.getCommand()); if (sortMethod == null) { continue; } return sortMethod; } return null; } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private interface ISortMethod<T> { Comparator<T> getComparator(); Object convertValue(FacesContext facesContext, UIComponent component, Object value); } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static abstract class AbstractSortMethod<T> implements ISortMethod<T>, Comparator<T> { public Comparator<T> getComparator() { return this; } public int compare(T o1, T o2) { if (o1 == null) { return (o2 == null) ? 0 : -1; } else if (o2 == null) { return 1; } return ((Comparable<T>) o1).compareTo(o2); } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortLong extends AbstractSortMethod { public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return LONG_0; } if (value instanceof Number) { return value; } if (value instanceof String) { String s = (String) value; if (s.length() < 1) { return LONG_0; } long l = Long.parseLong(s); if (l == 0l) { return LONG_0; } return new Long(l); } return LONG_0; } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortDouble extends AbstractSortMethod { public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return DOUBLE_0; } if (value instanceof Number) { return value; } if (value instanceof String) { String s = (String) value; if (s.length() < 1) { return DOUBLE_0; } double d = Double.parseDouble(s); if (d == 0.0) { return DOUBLE_0; } return new Double(d); } return DOUBLE_0; } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortAlpha extends AbstractSortMethod { public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return ""; } if (value instanceof String) { return value; } value = ValuesTools.valueToString(value, component, facesContext); if (value == null) { return ""; } return value; } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortAlphaIgnoreCase extends AbstractSortMethod { public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return ""; } if (value instanceof String) { return ((String) value).toLowerCase(); } value = ValuesTools.valueToString(value, component, facesContext); if (value == null) { return ""; } return ((String) value).toLowerCase(); } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortDate extends AbstractSortMethod { public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return null; } if (value instanceof Date) { return value; } throw new FacesException( "Invalid Date for \"date\" sort method ! (class=" + value.getClass() + " object=" + value + ")"); } } /** * * @author Olivier Oeuillot (latest modification by $Author: jbmeslin $) * @version $Revision: 1.4 $ $Date: 2013/11/13 12:53:22 $ */ private static class SortAction extends AbstractSortMethod { private final Comparator comparator; private final SortEvent.ISortConverter converter; public SortAction(SortActionListener listener, UIComponent dataColumnComponent, IGridComponent dataModel) { SortEvent sortEvent = new SortEvent(dataColumnComponent, dataModel); listener.processSort(sortEvent); comparator = sortEvent.getSortComparator(); if (comparator == null) { throw new FacesException("Comparator of sortEvent is NULL !"); } converter = sortEvent.getSortConverter(); } public Object convertValue(FacesContext facesContext, UIComponent component, Object value) { if (converter == null) { return value; } return converter.convertValue(facesContext, component, value); } public Comparator getComparator() { return comparator; } } }
1d37044b9f10cd19dc0b131f5fae99b813f6e3be
ad2bea6dbc9519552af2d5ef3f73c16e5ebf32d4
/src/com/cloverstudio/spika/couchdb/SpikaAsyncTask.java
c0990452f7b1ae82a49a0ffed98b923ed7cfeb0e
[ "MIT" ]
permissive
TTMTT/Spika-Android
abb15893e9d61815c0c7aea12cf37e73dff2ed8c
7b7b8e307c3c29b418b3faa82db4565a831252ed
refs/heads/master
2021-01-17T18:15:11.310209
2014-03-04T10:32:09
2014-03-04T10:32:09
17,983,947
2
0
null
null
null
null
UTF-8
Java
false
false
4,065
java
package com.cloverstudio.spika.couchdb; import java.io.IOException; import org.json.JSONException; import com.cloverstudio.spika.R; import com.cloverstudio.spika.SpikaApp; import com.cloverstudio.spika.dialog.HookUpDialog; import com.cloverstudio.spika.dialog.HookUpProgressDialog; import com.cloverstudio.spika.utils.Const; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.util.Log; public class SpikaAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>{ protected Command<Result> command; protected Context context; protected ResultListener<Result> resultListener; protected Exception exception; protected HookUpProgressDialog progressDialog; protected boolean showProgressBar = false; public SpikaAsyncTask(Command<Result> command, ResultListener<Result> resultListener, Context context, boolean showProgressBar) { super(); this.command = command; this.resultListener = resultListener; this.context = context; this.showProgressBar = showProgressBar; } // public SpikaAsyncTask(Command<Result> command, Context context, boolean showProgressBar) { // super(); // this.command = command; // this.context = context; // this.showProgressBar = showProgressBar; // } // // protected SpikaAsyncTask(Context context){ // super(); // this.context = context; // } @Override protected void onPreExecute() { if (SpikaApp.hasNetworkConnection()) { super.onPreExecute(); if (showProgressBar) { progressDialog = new HookUpProgressDialog(context); if (!((Activity)context).isFinishing()) progressDialog.show(); } } else { this.cancel(false); Log.e(Const.ERROR, Const.OFFLINE); final HookUpDialog dialog = new HookUpDialog(context); dialog.showOnlyOK(context.getString(R.string.no_internet_connection)); } } @Override protected Result doInBackground(Params... params) { Result result = null; try { result = (Result) command.execute(); } catch (JSONException e) { exception = e; e.printStackTrace(); } catch (IOException e) { exception = e; e.printStackTrace(); } catch (SpikaException e) { exception = e; e.printStackTrace(); } catch (NullPointerException e) { exception = e; e.printStackTrace(); } return result; } @Override protected void onPostExecute(Result result) { super.onPostExecute(result); // final HookUpDialog _dialog = new HookUpDialog(context); // Log.e("is this the way", "active:" + _dialog.getWindow().isActive()); if (showProgressBar) { if (!((Activity)context).isFinishing()) { if (progressDialog.isShowing()) progressDialog.dismiss(); } } if (exception != null) { String error = (exception.getMessage() != null) ? exception.getMessage() : context.getString(R.string.an_internal_error_has_occurred); Log.e(Const.ERROR, error); final HookUpDialog dialog = new HookUpDialog(context); String errorMessage = null; if (exception instanceof IOException){ errorMessage = context.getString(R.string.can_not_connect_to_server) + "\n" + exception.getClass().getName() + " " + error; }else if(exception instanceof JSONException){ errorMessage = context.getString(R.string.an_internal_error_has_occurred) + "\n" + exception.getClass().getName() + " " + error; }else if(exception instanceof NullPointerException){ errorMessage = context.getString(R.string.an_internal_error_has_occurred) + "\n" + exception.getClass().getName() + " " + error; }else if(exception instanceof SpikaException){ errorMessage = error; }else{ errorMessage = context.getString(R.string.an_internal_error_has_occurred) + "\n" + exception.getClass().getName() + " " + error; } if (context instanceof Activity) { if (!((Activity)context).isFinishing()) { dialog.showOnlyOK(errorMessage); } } if (resultListener != null) resultListener.onResultsFail(); } else { if (resultListener != null) resultListener.onResultsSucceded(result); } } }
8146c2e087484e8f115fb7a3fc9899ef28f42cf2
e4065132860a9d1c9f35aa2e2b778af99ae33e39
/src/main/java/com/info/dao/InfoDao.java
a81b905300bd0226f49ea6fcf9e34c0e1f865695
[]
no_license
yount/project
1ea1cac96a77416fe9ac3401a8a415a5bfcf4c7b
ea4d460239f769a51a70a6b5eef0b0dfa6226c2e
refs/heads/master
2021-01-12T15:24:04.287331
2016-10-24T09:13:35
2016-10-24T09:13:35
71,771,619
0
0
null
null
null
null
UTF-8
Java
false
false
124
java
package com.info.dao; import com.info.model.Info; public interface InfoDao { public Info getInfoByUUID(String uuid); }
1e06c35214a4525c25c0a1b5408d15b114a95424
2320eb33351c4b26064beda8ab1ace25b338e433
/app/src/main/java/com/example/carwash/carwash/activities/NewClientActivity.java
010654f7e5c4c0e9a79ab11df01567c9f90035ba
[]
no_license
Monageng/carwash-app-ui
c5d3cb44f1ae41273385113a064bb6dbae8e391b
35b044312bcd8e9d85d2b83433db2e3541826a05
refs/heads/master
2021-01-01T20:43:50.081877
2017-07-31T19:03:02
2017-07-31T19:03:02
98,919,943
0
0
null
null
null
null
UTF-8
Java
false
false
3,699
java
package com.example.carwash.carwash.activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.example.carwash.carwash.R; import com.example.carwash.carwash.dao.CarwashDAO; import com.example.carwash.carwash.dto.CustomerDto; import com.example.carwash.carwash.impl.CarwashImpl; import com.example.carwash.carwash.utils.DateUtils; import java.text.SimpleDateFormat; import java.util.Date; public class NewClientActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private String errorMessage = ""; /** Called when the user taps the Send button */ public void home(View view) { Intent intent = new Intent(this, Home.class); startActivity(intent); } public void sendMessage(View view) { Intent intent = new Intent(this, SearchClientsActivity.class); errorMessage = ""; validateView(view); EditText editName = (EditText) findViewById(R.id.editName); String name = editName.getText().toString(); EditText editSurname = (EditText) findViewById(R.id.editSurname); String surname = editSurname.getText().toString(); EditText editCellNo = (EditText) findViewById(R.id.editCellNo); String cellNo = editCellNo.getText().toString(); EditText editRegNo = (EditText) findViewById(R.id.editRegNo); String regNo = editRegNo.getText().toString(); EditText editDateOfBirth = (EditText) findViewById(R.id.editDateOfBirth); String dateOfBirth = editDateOfBirth.getText().toString(); if (errorMessage != null && errorMessage.length() > 0) { TextView errTxt = (TextView) findViewById(R.id.errorMessageTxt); errTxt.setText(errorMessage); } else { Date currentDate = new Date(); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyy-MM-dd"); //CarwashDAO dao = new CarwashDAO(this); CustomerDto dto = new CustomerDto(name,surname,regNo,cellNo,dateOfBirth, dateFormatter.format(currentDate)); //dao.insertCustomer(dto); CarwashImpl carwashImpl = new CarwashImpl(); carwashImpl.createClient(dto); startActivity(intent); } } private void validateView(View view) { EditText editName = (EditText) findViewById(R.id.editName); if (editName.getText().length() < 1) { errorMessage = errorMessage + " Name is mandatory, \r\n"; } EditText editSurname = (EditText) findViewById(R.id.editSurname); if (editSurname.getText().length() < 1) { errorMessage = errorMessage + " Surname is mandatory, \r\n"; } EditText editRegNo = (EditText) findViewById(R.id.editRegNo); if (editRegNo.getText().length() < 1) { errorMessage = errorMessage + " Registration no is mandatory, \r\n"; } EditText editDateOfBirth = (EditText) findViewById(R.id.editDateOfBirth); if (editDateOfBirth.getText().length() < 1) { errorMessage = errorMessage + " DateOfBirth is mandatory, \r\n"; } String dateInput = editDateOfBirth.getText().toString(); try { Date date = DateUtils.parseToDate(dateInput, DateUtils.PATTERN_YYYY_MM_DD ); } catch (Exception e) { errorMessage = errorMessage + " , " + e.getMessage() + ", \r\n"; } } }
c818907a15284e9628d88b1477e6343580165e18
9ccf99159f3bbd0789a0de9e518955f33ff05efd
/easycode-auth-core/src/main/java/com/easycodebox/auth/core/util/CodeMsgExt.java
6d882817c797ce8e879e0ad0b7717e69a35b02ec
[ "Apache-2.0" ]
permissive
swyl/easycode
71aa824cd82e0a08eabe0da6e3f1961778b0e12d
1d514796668d96ed1ec71203f7c4e4098e284641
refs/heads/master
2021-01-23T22:31:10.777845
2017-03-09T09:24:43
2017-03-09T09:24:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,338
java
package com.easycodebox.auth.core.util; import com.easycodebox.common.error.CodeMsg; import com.easycodebox.common.file.PropertiesPool; import com.easycodebox.common.lang.Symbol; import java.io.File; /** * @author WangXiaoJin * */ public class CodeMsgExt extends CodeMsg { public static CodeMsg PARAM_ERR = new CodeMsgExt("1002", "{0}参数错误"); public static CodeMsg PARAM_BLANK = new CodeMsgExt("1003", "{0}参数不能为空"); public static CodeMsg EXISTS = new CodeMsgExt("2001", "{0}已存在"); private static final String FILE_PATH = "/code-msg.properties"; static { PropertiesPool.loadPropertiesFile(FILE_PATH); } protected CodeMsgExt(String code, String msg) { super(code, msg); } public static void main(String[] args) throws Exception { /* ------------ 生成properties文件 BEGIN -------------- */ File file = new File("src/main/resources" + (FILE_PATH.startsWith(Symbol.SLASH) ? "" : Symbol.SLASH) + FILE_PATH); CodeMsgs.storePropertiesFile(CodeMsgExt.class, file); /* ------------ 生成properties文件 END ---------------- */ CodeMsg code = CodeMsgExt.NONE; System.out.println(code.getMsg()); CodeMsg xx = code.msg("XXXXXXXXXXx"); System.out.println(code.getMsg()); System.out.println(xx.getMsg()); System.out.println(CodeMsgExt.NONE.getMsg()); } }
5207e2ac5075f0eb5bc25091f1bcd43f2ea5e0bc
95d20c83d8aff34e314c56a3ecb2b87c9fa9fc86
/Ghidra/Features/FunctionGraph/src/main/java/ghidra/app/plugin/core/functiongraph/mvc/LazySaveableXML.java
5ce69a6fa983f71c8a7f8e29c28b56af46a19dab
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
NationalSecurityAgency/ghidra
969fe0d2ca25cb8ac72f66f0f90fc7fb2dbfa68d
7cc135eb6bfabd166cbc23f7951dae09a7e03c39
refs/heads/master
2023-08-31T21:20:23.376055
2023-08-29T23:08:54
2023-08-29T23:08:54
173,228,436
45,212
6,204
Apache-2.0
2023-09-14T18:00:39
2019-03-01T03:27:48
Java
UTF-8
Java
false
false
736
java
/* ### * IP: GHIDRA * * 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 ghidra.app.plugin.core.functiongraph.mvc; public abstract class LazySaveableXML extends SaveableXML { public abstract boolean isEmpty(); }
de84c07c03af3a166ee47c165478f77f5e359dcf
a6f634f2b55ee46f98d39a0620b9ae70cc3da382
/chapter5/src/main/java/com/zzuduoduo/chapter5/connector/ResponseBase.java
7e40d2d4f07d225f781ac78f1dad7855202fb1e0
[]
no_license
zzuduoduo/how-tomcat-works
cb3016af338f1ccfbb1ff3b091e9bc4834b3b6c5
456ed28831f0a424705f6c91ba78abef1e81f113
refs/heads/master
2021-02-14T16:56:37.259729
2020-04-11T15:37:09
2020-04-11T15:37:09
244,820,788
1
0
null
2020-10-13T20:44:59
2020-03-04T06:04:04
Java
UTF-8
Java
false
false
5,197
java
package com.zzuduoduo.chapter5.connector; import com.zzuduoduo.chapter5.Connector; import com.zzuduoduo.chapter5.Request; import com.zzuduoduo.chapter5.Response; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; public abstract class ResponseBase implements ServletResponse, Response { protected Connector connector = null; protected OutputStream output; protected Request request; protected PrintWriter writer = null; protected ServletOutputStream stream = null; protected int bufferCount = 0; protected byte[] buffer = new byte[1024]; protected boolean committed = false; protected int contentCount = 0; protected String encoding = null; protected int contentLength = -1; protected boolean included = false; protected String contentType; public boolean isCommitted() { return committed; } public String getContentType() { return contentType; } @Override public Connector getConnector() { return connector; } @Override public void setConnector(Connector connector) { this.connector = connector; } public OutputStream getOutput() { return output; } public void setOutput(OutputStream output) { this.output = output; } public Request getRequest() { return request; } public void setRequest(Request request) { this.request = request; } @Override public void finishResponse() throws IOException { if(this.stream == null){ return; } if (((ResponseStream) stream).isClosed()){ return; } if (writer!=null){ System.out.println("writer flush"); writer.flush(); writer.close(); }else{ stream.flush(); stream.close(); } } @Override public void recycle(){ // todo recycle bufferCount = 0; committed = false; contentCount = 0; encoding = null; output = null; request = null; stream = null; writer = null; } @Override public PrintWriter getWriter() throws IOException { if (writer != null){ return writer; } if (stream != null){ throw new IOException("stream error"); } ResponseStream newStream = (ResponseStream)createOutputStream(); newStream.setCommit(false); OutputStreamWriter osw = new OutputStreamWriter(newStream, getCharacterEncoding()); writer = new ResponseWriter(osw, newStream); this.stream = newStream; return writer; } @Override public String getCharacterEncoding(){ if(encoding == null){ return "UTF-8"; } return encoding; } public ServletOutputStream createOutputStream() throws IOException { return new ResponseStream(this); } public void write(int b) throws IOException { if (bufferCount >= buffer.length){ flushBuffer(); } buffer[bufferCount++] = (byte)b; contentCount++; } public void write(byte[] b, int off, int len) throws IOException{ if (len == 0){ return; } if (len <= (buffer.length - bufferCount)){ System.arraycopy(b, off, buffer, bufferCount, len); bufferCount += len; contentCount += len; return; } flushBuffer(); int iterations = len / buffer.length; int leftoverStart = iterations * buffer.length; int leftoverLen = len - leftoverStart; for (int i = 0; i<iterations;i++){ write(b,off + i*buffer.length,buffer.length); } if (leftoverLen > 0) write(b,off+leftoverStart, leftoverLen); } public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void flushBuffer() throws IOException{ committed = true; if (bufferCount > 0){ try{ output.write(buffer, 0, bufferCount); }finally { bufferCount = 0; } } } @Override public ServletOutputStream getOutputStream() throws IOException{ if (writer != null){ throw new IOException("response write"); } if (stream == null){ stream = createOutputStream(); } ((ResponseStream)stream).setCommit(true); return stream; } public int getContentLength() { return contentLength; } @Override public void setContentLength(int contentLength) { if(isCommitted()) return; if (included) return; this.contentLength = contentLength; } @Override public void setContentType(String type) { if (isCommitted()) return; if (included) return; this.contentType = type; //todo } }
a38479afadc188444782dc08df27799da2fde246
e2506a7748c75a55780bf1e2c168795322eb0810
/app/src/main/java/com/example/planner/LoginActivity.java
6efe11fe75958827e73cf5e5b898b13f6b12e58f
[]
no_license
Moldoveanu-Florin-George/PPA
c2b60b9139ca05d88d2fc347939a6ed8737e3838
0ef30702f7e1b29f2513c4c8e0909bb2dfae838d
refs/heads/main
2023-04-18T18:14:49.932711
2021-04-19T17:20:42
2021-04-19T17:20:42
359,536,354
0
0
null
null
null
null
UTF-8
Java
false
false
2,043
java
package com.example.planner; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class LoginActivity extends AppCompatActivity { String password,username; public boolean checkPasswordConstraints(String proposedPass){ return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); password = ""; username = ""; Button signin; EditText user,pass,copass; signin = findViewById(R.id.signup); user = findViewById(R.id.username); pass= findViewById(R.id.password); copass = findViewById(R.id.password_confirm); signin.setOnClickListener(v -> { String inuser = user.getText().toString(); String inpass = pass.getText().toString(); String incopass = copass.getText().toString(); if(incopass.equals(inpass)) { if(checkPasswordConstraints(password) && (inpass.equals("")==false) && (inuser.equals("")==false)){ SharedPreferences pref = getSharedPreferences("preference", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("firststart", false); editor.commit(); SharedPreferences data = getSharedPreferences("user_data",MODE_PRIVATE); SharedPreferences.Editor datasaver = data.edit(); datasaver.putString("pass/user",inpass + "/" +inuser); datasaver.commit(); finish(); } } }); } @Override public void onBackPressed(){}//don't go back if the back button is pressed public void SaveData(){} } //SharedPreferences.Editor editor = pref.edit(); // editor.putBoolean("firststart", false); //editor.commit();
5866ca0622cc1f595cdab31f81de94b8d799070a
2c08db50b793af9ba1a308f8cd6f39160af62f2c
/src/java/JsfClasses/ImagesclientController.java
59ec6adf2c5a3d14e3cdf9364d2ee694f399c25f
[]
no_license
gassen77/cabinet
6a638d167af945cd626870b4fc6267de2e77e8f7
342728ecff61b0f6b70bf7bded675b2e36366fd9
refs/heads/master
2021-04-26T01:04:29.685259
2017-10-18T08:46:01
2017-10-18T08:46:01
107,382,914
0
0
null
null
null
null
UTF-8
Java
false
false
18,511
java
package JsfClasses; import entities.Imagesclient; import JsfClasses.util.JsfUtil; import JsfClasses.util.PaginationHelper; import SessionBeans.ClientFacade; import SessionBeans.ImagesclientFacade; import entities.Client; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.StringTokenizer; import java.util.concurrent.Semaphore; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.component.UIPanel; import javax.faces.component.UIViewRoot; import javax.faces.component.html.HtmlInputText; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.faces.model.SelectItem; import org.primefaces.event.FileUploadEvent; @ManagedBean(name = "imagesclientController") @ViewScoped public class ImagesclientController implements Serializable { private Imagesclient current; private DataModel items = null; @EJB private SessionBeans.ImagesclientFacade ejbFacade; private PaginationHelper pagination; private int selectedItemIndex; private String page; private Integer pageDestination; private Map<String,Object>mapRechercheList; @EJB private ClientFacade ejbclient; public ImagesclientController() { FacesContext fc = FacesContext.getCurrentInstance(); ejbclient = (ClientFacade) fc.getApplication().getELResolver().getValue(fc.getELContext(), null, "ClientJpa"); } public Map<String, Object> getMapRechercheList() { return mapRechercheList; } public void setMapRechercheList(Map<String, Object> mapRechercheList) { this.mapRechercheList = mapRechercheList; } public Integer getPageDestination() { return pageDestination; } public void setPageDestination(Integer pageDestination) { this.pageDestination = pageDestination; } @PostConstruct public void init() { FacesContext fc=FacesContext.getCurrentInstance(); Map<String,Object>map=fc.getExternalContext().getRequestMap(); try { page = (String) map.get("page"); } catch (Exception e) { } try { current = (Imagesclient) map.get("current"); } catch (Exception e) { current = null; } try{ items=(DataModel) map.get("items"); }catch(Exception e){} try{ mapRechercheList= (Map<String, Object>) map.get("mapRechercheList"); }catch(Exception e){ mapRechercheList=null; } if ((page != null)) { if ((page.equalsIgnoreCase("Create"))) { initPrepareCreate(); } if (page.equalsIgnoreCase("List")) { initRechercheList(); } if ((page.equalsIgnoreCase("Edit")) && (current != null)) { initPrepareEdit(); } } } public void initPrepareCreate() { current = new Imagesclient(); selectedItemIndex = -1; } public void initRechercheList() { recreateModel(); } public void initPrepareEdit() { } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public Imagesclient getSelected() { if (current == null) { current = new Imagesclient(); selectedItemIndex = -1; } return current; } private ImagesclientFacade getFacade() { return ejbFacade; } public PaginationHelper getPagination() { if (pagination == null) { List<String>s=new ArrayList<String>(); List<Object>o=new ArrayList<Object>(); pagination = new PaginationHelper(10,"Select o from Imagesclient o",s,o) { @Override public int getItemsCount() { return getFacade().countMultipleCritiria(getRequetteJpql(),getArrayNames(),getArrayValues()); } @Override public DataModel createPageDataModel() { return new ListDataModel(getFacade().findByParameterMultipleCreteria(getRequetteJpql(),getArrayNames(),getArrayValues(),getPageFirstItem(),getPageSize())); } }; } return pagination; } public String premierePage() { getPagination().setPage(0); recreateModel(); return null; } public String dernierePage() { getPagination().setPage(getPagination().totalPages()-1); recreateModel(); return null; } public String previous() { this.pageDestination=getPagination().getPage(); return goPageDestination(); } public String next() { this.pageDestination=getPagination().getPage(); this.pageDestination=this.pageDestination+2; return goPageDestination(); } public String goPageDestination() { items=null; if(pageDestination!=null){ if(pageDestination>0){ if(pageDestination<=getPagination().totalPages()){ getPagination().setPage(pageDestination.intValue()-1); recreateModel(); } } } pageDestination=null; return null; } public void setMettreJourAttributeRecherche(String mettreJourAttributeRecherche){ FacesContext fc=FacesContext.getCurrentInstance(); UIComponent component = UIViewRoot.getCurrentComponent(fc); UIPanel panel=(UIPanel)component; Iterator it=panel.getChildren().iterator(); while(it.hasNext()){ UIComponent u=(UIComponent)it.next(); if(u.getClass().equals(HtmlInputText.class)){ this.mapRechercheList.put(u.getId(),mettreJourAttributeRecherche); } } } public String getMettreJourAttributeRecherche(){ FacesContext fc=FacesContext.getCurrentInstance(); HtmlInputText component = (HtmlInputText) UIViewRoot.getCurrentComponent(fc); return (String) this.mapRechercheList.get(component.getId()); } public String rechercherListItems(){ String requette="Select o from Imagesclient o where "; String order="order by "; Iterator it=this.mapRechercheList.entrySet().iterator(); List<String>ss=new ArrayList<String>(); List<Object>oo=new ArrayList<Object>(); while(it.hasNext()){ Object o=it.next(); Entry<String,Object> e=(Entry<String,Object>)o; String nomComponent=e.getKey(); String valueComponent=e.getValue().toString(); if(valueComponent!=null){ if(valueComponent.isEmpty()==false){ StringTokenizer st=new StringTokenizer(nomComponent,"_"); if(st.countTokens()==1){ requette=requette+"o."+nomComponent+" like :"+nomComponent+" and "; ss.add(nomComponent); oo.add("%"+valueComponent+"%"); order=order+"o."+nomComponent+","; }else{ String nomCompletColonne="o."; String lastSuffixColumn=""; while(st.hasMoreTokens()){ String stt=st.nextToken(); nomCompletColonne=nomCompletColonne+stt+"."; lastSuffixColumn=stt; } if(nomCompletColonne.endsWith(".")){ nomCompletColonne=nomCompletColonne.substring(0,nomCompletColonne.lastIndexOf(".")); } requette=requette+nomCompletColonne+" like :"+lastSuffixColumn+" and "; ss.add(lastSuffixColumn); oo.add("%"+valueComponent+"%"); order=order+nomCompletColonne+","; } } } } if(order.endsWith(",")){ order=order.substring(0,order.lastIndexOf(",")); } if(order.endsWith("order by ")){ order=order.substring(0,order.lastIndexOf("order by ")); } if(requette.endsWith(" and ")){ requette=requette.substring(0,requette.lastIndexOf(" and ")); } if(requette.endsWith(" where ")){ requette=requette.substring(0,requette.lastIndexOf(" where ")); } requette=requette.trim(); requette=requette+" "+order; try{ getPagination().setRequetteJpql(requette); getPagination().setArrayNames(ss); getPagination().setArrayValues(oo); getPagination().setPage(0); items=null; }catch(Exception ex){ } return null; } public String prepareList() { recreateModel(); FacesContext fc=FacesContext.getCurrentInstance(); Map<String,Object>map=fc.getExternalContext().getRequestMap(); this.mapRechercheList=new HashMap<String, Object>(); page = "List"; map.put("page", page); map.put("current", current); map.put("items", items); map.put("mapRechercheList",mapRechercheList); return "List_Imagesclient"; } public String prepareView() { current = (Imagesclient) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); return "View"; } public String prepareCreate() { current = new Imagesclient(); current.setDatecreation(new Date()); selectedItemIndex = -1; FacesContext fc=FacesContext.getCurrentInstance(); Map<String,Object>map=fc.getExternalContext().getRequestMap(); map.put("page", page); map.put("current", current); return "Create_Imagesclient"; } public String create() { try { Long l = new Long(1); try { l = getFacade().findByParameterSingleResultCountsansparam("Select max(c.id) from Imagesclient c"); if (l==null) { l = new Long(1); } } catch(Exception e) { e.printStackTrace(); } current.setId(l+1); current.setDatecreation(new Date()); getFacade().create(current); JsfUtil.addSuccessMessage("Transaction reussi"); return prepareCreate(); } catch (Exception e) { JsfUtil.addErrorMessage("Transaction echouee"); return null; } } public String prepareEdit() { current = (Imagesclient) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); page = "Edit"; FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("page", page); FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("current", current); return "Edit_Imagesclient"; } public String update() { try { getFacade().edit(current); JsfUtil.addSuccessMessage("Transaction reussi"); return prepareList(); } catch (Exception e) { JsfUtil.addErrorMessage("Transaction echouee"); return null; } } public String destroy() { current = (Imagesclient) getItems().getRowData(); selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex(); performDestroy(); recreateModel(); return "List"; } public String destroyAndView() { performDestroy(); recreateModel(); updateCurrentItem(); if (selectedItemIndex >= 0) { return "View"; } else { // all items were removed - go back to list recreateModel(); return "List"; } } private void performDestroy() { try { getFacade().remove(current); JsfUtil.addSuccessMessage("Transaction reussi"); } catch (Exception e) { JsfUtil.addErrorMessage("Transaction echouee"); } } private void updateCurrentItem() { int count = getFacade().count(); if (selectedItemIndex >= count) { // selected index cannot be bigger than number of items: selectedItemIndex = count - 1; // go to previous page if last page disappeared: if (pagination.getPageFirstItem() >= count) { pagination.previousPage(); } } if (selectedItemIndex >= 0) { current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0); } } public DataModel getItems() { if (items == null) { items = getPagination().createPageDataModel(); } return items; } private void recreateModel() { items = null; } public SelectItem[] getItemsAvailableSelectMany() { return JsfUtil.getSelectItems(ejbFacade.findAll(), false); } public SelectItem[] getItemsAvailableSelectOne() { return JsfUtil.getSelectItems(ejbFacade.findAll(), true); } @FacesConverter(forClass = Imagesclient.class) public static class ImagesclientControllerConverter implements Converter { public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } try{ ImagesclientController controller = (ImagesclientController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "imagesclientController"); return controller.ejbFacade.find(getKey(value));}catch(Exception e){return null;} } java.lang.Long getKey(String value) { java.lang.Long key; key = Long.valueOf(value); return key; } String getStringKey(java.lang.Long value) { StringBuffer sb = new StringBuffer(); sb.append(value); return sb.toString(); } public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof Imagesclient) { Imagesclient o = (Imagesclient) object; return getStringKey(o.getId()); } else { throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ImagesclientController.class.getName()); } } } public List<Client> autocompleteClient(String code) { List<Client> result = new ArrayList<Client>(); try { result = (List<Client>) requeteClient(code); return result; } catch (Exception d) { result = new ArrayList<Client>(); return result; } } public List<Client> requeteClient(String code) { String q = "Select b from Client b where b.code like :code or b.nom like :code"; List<Client> l = this.ejbclient.findByParameterAutocomplete(q, "code", code + "%", 50); return l; } public void handleFileUpload(FileUploadEvent event) { System.out.println("handleFileUpload"); try { InputStream input = event.getFile().getInputstream(); // String nomImage = this.nomImage(event.getFile().getFileName()); String nomImage="photo"+current.getClient().getNom()+current.getDatecreation().getDay()+current.getDatecreation().getMonth()+current.getDatecreation().getYear(); File directory = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pages/images/imagespatients")); directory.mkdirs(); // System.out.println("nomImage "+nomImage); OutputStream output = new FileOutputStream(new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pages/images/imagespatients") + "/" + nomImage + ".jpg")); int data = input.read(); while (data != -1) { output.write(data); data = input.read(); } input.close(); output.close(); JsfUtil.addSuccessMessage("Le Fichier :" + event.getFile().getFileName() + " est telecharge."); this.getSelected().setPhoto("/pages/images/imagespatients/" + nomImage + ".jpg"); } catch (Exception e) { e.printStackTrace(); JsfUtil.addErrorMessage("echec " + event.getFile().getFileName() + " n'est pas telecharger."); } } protected static Semaphore semaphoreImage = new Semaphore(1, true); public String nomImage(String s) { try { String s3 = ""; DateFormat f = new SimpleDateFormat("ddMMyyyyHHmmssSSS"); semaphoreImage.acquire(); Date date = new Date(); s3 = current.getPhoto(); System.out.println("s3 "+s3); semaphoreImage.release(); return s3; } catch (Exception r) { r.printStackTrace(); try { semaphoreImage.release(); } catch (Exception releaseExcp) { System.out.println("releaseExcp"); releaseExcp.printStackTrace(); } } return ""; } }
e92fd49b6cbcc8690b8af6a1da38da5cbd3145bc
184981dd7f122b0df83c00049bfc302b41673c05
/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderRecode.java
42a0da94a90876963fda7d14dc16dab550b898e4
[ "Apache-2.0" ]
permissive
winggyn/incubator-systemml
907deed5970a85b5ba7d353f690daed8ac1ff5a9
996ba79fae3cf8c0da63f09d90f44771f0e55e75
refs/heads/master
2020-05-29T08:53:30.148093
2016-10-04T21:12:39
2016-10-05T00:31:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,737
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.sysml.runtime.transform.decode; import java.util.HashMap; import java.util.List; import org.apache.sysml.lops.Lop; import org.apache.sysml.parser.Expression.ValueType; import org.apache.sysml.runtime.matrix.data.FrameBlock; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.Pair; import org.apache.sysml.runtime.transform.TfUtils; import org.apache.sysml.runtime.util.UtilFunctions; /** * Simple atomic decoder for recoded columns. This decoder builds internally * inverted recode maps from the given frame meta data. * */ public class DecoderRecode extends Decoder { private static final long serialVersionUID = -3784249774608228805L; private HashMap<Long, Object>[] _rcMaps = null; private boolean _onOut = false; protected DecoderRecode(List<ValueType> schema, boolean onOut, int[] rcCols) { super(schema, rcCols); _onOut = onOut; } @Override public FrameBlock decode(MatrixBlock in, FrameBlock out) { if( _onOut ) { //recode on output (after dummy) for( int i=0; i<in.getNumRows(); i++ ) { for( int j=0; j<_colList.length; j++ ) { int colID = _colList[j]; double val = UtilFunctions.objectToDouble( out.getSchema()[colID-1], out.get(i, colID-1)); long key = UtilFunctions.toLong(val); out.set(i, colID-1, _rcMaps[j].get(key)); } } } else { //recode on input (no dummy) out.ensureAllocatedColumns(in.getNumRows()); for( int i=0; i<in.getNumRows(); i++ ) { for( int j=0; j<_colList.length; j++ ) { double val = in.quickGetValue(i, _colList[j]-1); long key = UtilFunctions.toLong(val); out.set(i, _colList[j]-1, _rcMaps[j].get(key)); } } } return out; } @Override @SuppressWarnings("unchecked") public void initMetaData(FrameBlock meta) { //initialize recode maps according to schema _rcMaps = new HashMap[_colList.length]; for( int j=0; j<_colList.length; j++ ) { HashMap<Long, Object> map = new HashMap<Long, Object>(); for( int i=0; i<meta.getNumRows(); i++ ) { if( meta.get(i, _colList[j]-1)==null ) break; //reached end of recode map String[] tmp = meta.get(i, _colList[j]-1).toString().split(Lop.DATATYPE_PREFIX); Object obj = UtilFunctions.stringToObject(_schema.get(_colList[j]-1), tmp[0]); map.put(Long.parseLong(tmp[1]), obj); } _rcMaps[j] = map; } } /** * Parses a line of <token, ID, count> into <token, ID> pairs, where * quoted tokens (potentially including separators) are supported. * * @param entry * @param pair */ public static void parseRecodeMapEntry(String entry, Pair<String,String> pair) { int ixq = entry.lastIndexOf('"'); String token = UtilFunctions.unquote(entry.substring(0,ixq+1)); int idx = ixq+2; while(entry.charAt(idx) != TfUtils.TXMTD_SEP.charAt(0)) idx++; String id = entry.substring(ixq+2,idx); pair.set(token, id); } }
d047eb49d5f0b0c0835482f82755526efd80efe8
5ae0937ba000377673dc701adbed8f211b493c12
/src/main/java/me/charlesj/apu/DividerListener.java
d0458312dc3aa34171df5c9cf4f97ef9cf5d7079
[]
no_license
serach24/NES-Emulator
00e333fdece8f9a5feaafb2c2de77a09366bc687
a9102bdb5fbb56c98cbcdc58b03d58d22ab91415
refs/heads/master
2022-12-27T14:42:28.439891
2020-05-11T23:19:30
2020-05-11T23:19:30
262,898,014
6
1
null
2020-10-13T21:55:08
2020-05-11T00:00:49
Java
UTF-8
Java
false
false
127
java
package me.charlesj.apu; /** * 2020/2/3. */ public interface DividerListener { void onClock(Divider divider); }
41fcec09fc54b8cebf4e0f22cb72b7488b371f27
03d61086047f041168f9a77b02a63a9af83f0f3f
/newrelic/src/main/java/com/newrelic/agent/deps/org/yaml/snakeyaml/reader/UnicodeReader.java
039372946e558bbda0f012ccac624c70836f839b
[]
no_license
masonmei/mx2
fa53a0b237c9e2b5a7c151999732270b4f9c4f78
5a4adc268ac1e52af1adf07db7a761fac4c83fbf
refs/heads/master
2021-01-25T10:16:14.807472
2015-07-30T21:49:33
2015-07-30T21:49:35
39,944,476
1
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
// // Decompiled by Procyon v0.5.29 // package com.newrelic.agent.deps.org.yaml.snakeyaml.reader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PushbackInputStream; import java.io.Reader; public class UnicodeReader extends Reader { PushbackInputStream internalIn; InputStreamReader internalIn2; private static final int BOM_SIZE = 3; public UnicodeReader(final InputStream in) { this.internalIn2 = null; this.internalIn = new PushbackInputStream(in, 3); } public String getEncoding() { return this.internalIn2.getEncoding(); } protected void init() throws IOException { if (this.internalIn2 != null) { return; } final byte[] bom = new byte[3]; final int n = this.internalIn.read(bom, 0, bom.length); String encoding; int unread; if (bom[0] == -17 && bom[1] == -69 && bom[2] == -65) { encoding = "UTF-8"; unread = n - 3; } else if (bom[0] == -2 && bom[1] == -1) { encoding = "UTF-16BE"; unread = n - 2; } else if (bom[0] == -1 && bom[1] == -2) { encoding = "UTF-16LE"; unread = n - 2; } else { encoding = "UTF-8"; unread = n; } if (unread > 0) { this.internalIn.unread(bom, n - unread, unread); } this.internalIn2 = new InputStreamReader(this.internalIn, encoding); } public void close() throws IOException { this.init(); this.internalIn2.close(); } public int read(final char[] cbuf, final int off, final int len) throws IOException { this.init(); return this.internalIn2.read(cbuf, off, len); } }
ea51d8005018a1e83b532167c27b8b2a545fb7d0
2c9003f3c4f3b5182ec1e8dbe7e707eb7fac0031
/src/main/java/com/example/suduko/entity/AlienAddress.java
ea7081f5a87079832ad98d8d00e34c5c6a8354fb
[]
no_license
TamtePrathamesh/sb_mapping
208d5c13a0bec0d2c83ba4057cc80ffa65c00576
34a109a5ded2d173c5b1ef75176be13d9f92ad5c
refs/heads/main
2023-04-04T02:51:17.088554
2021-04-04T05:45:09
2021-04-04T05:45:09
354,465,954
0
0
null
null
null
null
UTF-8
Java
false
false
580
java
package com.example.suduko.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; @Entity @Builder @Table(name = "alien_address") @Data @AllArgsConstructor @NoArgsConstructor public class AlienAddress implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "planet") private String planet; @OneToOne(mappedBy = "alienAddress") private Alien alien; }
ca42bf499a9f404d331db452b2556600c9a5ea65
b2f6bedc4776aab918210fe60d5bd84cc8411562
/src/org/pathvisio/core/model/GpmlFormat.java
094b3e4a02c231839474dd3a795068fb8b3e7afd
[ "Apache-2.0" ]
permissive
nrnb/gsoc2017saurabh_kumar
d70c477f7da6a309c23aac86bd0d92cff8e6f48c
fec80ae4b470fb20668ac3297446451691eace2b
refs/heads/master
2021-01-22T17:40:01.467928
2017-08-24T15:24:42
2017-08-24T15:24:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,452
java
// PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2011 BiGCaT Bioinformatics // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.pathvisio.core.model; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import org.bridgedb.bio.DataSourceTxt; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.JDOMParseException; import org.jdom.input.SAXBuilder; import org.pathvisio.core.debug.Logger; import org.pathvisio.core.util.RootElementFinder; import org.xml.sax.InputSource; /** * class responsible for interaction with Gpml format. * Contains all gpml-specific constants, * and should be the only class (apart from svgFormat) * that needs to import jdom */ public class GpmlFormat extends AbstractPathwayFormat { static private final GpmlFormat2017 CURRENT = GpmlFormat2017.GPML_2017; public static final Namespace RDF = Namespace.getNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); public static final Namespace RDFS = Namespace.getNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); public static final Namespace BIOPAX = Namespace.getNamespace("bp", "http://www.biopax.org/release/biopax-level3.owl#"); public static final Namespace OWL = Namespace.getNamespace("owl", "http://www.w3.org/2002/07/owl#"); static { DataSourceTxt.init(); } public Pathway doImport(File file) throws ConverterException { Pathway pathway = new Pathway(); readFromXml(pathway, file, true); pathway.clearChangedFlag(); return pathway; } public void doExport(File file, Pathway pathway) throws ConverterException { writeToXml(pathway, file, true); } public String[] getExtensions() { return new String[] { "gpml", "xml" }; } public String getName() { return "GPML file"; } public static Document createJdom(Pathway data) throws ConverterException { return CURRENT.createJdom(data); } static public Element createJdomElement(PathwayElement o) throws ConverterException { return CURRENT.createJdomElement(o); } public static PathwayElement mapElement(Element e) throws ConverterException { return CURRENT.mapElement(e); } /** * Writes the JDOM document to the file specified * @param file the file to which the JDOM document should be saved * @param validate if true, validate the dom structure before writing to file. If there is a validation error, * or the xsd is not in the classpath, an exception will be thrown. */ static public void writeToXml(Pathway pwy, File file, boolean validate) throws ConverterException { CURRENT.writeToXml(pwy, file, validate); } static public void writeToXml(Pathway pwy, OutputStream out, boolean validate) throws ConverterException { CURRENT.writeToXml(pwy, out, validate); } static public void readFromXml(Pathway pwy, File file, boolean validate) throws ConverterException { InputStream inf; try { inf = new FileInputStream (file); } catch (FileNotFoundException e) { throw new ConverterException (e); } readFromXmlImpl (pwy, new InputSource(inf), validate); } static public void readFromXml(Pathway pwy, InputStream in, boolean validate) throws ConverterException { readFromXmlImpl (pwy, new InputSource(in), validate); } static public void readFromXml(Pathway pwy, Reader in, boolean validate) throws ConverterException { readFromXmlImpl (pwy, new InputSource(in), validate); } public static GpmlFormatReader getReaderForNamespace (Namespace ns) { GpmlFormatReader[] formats = new GpmlFormatReader[] { GpmlFormat200X.GPML_2007, GpmlFormat200X.GPML_2008A, GpmlFormat2010a.GPML_2010A , GpmlFormat2013a.GPML_2013A, GpmlFormat2017.GPML_2017 }; for (GpmlFormatReader format : formats) { if (ns.equals(format.getGpmlNamespace())) { return format; } } return null; } private static void readFromXmlImpl(Pathway pwy, InputSource in, boolean validate) throws ConverterException { // Start XML processing SAXBuilder builder = new SAXBuilder(false); // no validation when reading the xml file // try to read the file; if an error occurs, catch the exception and print feedback try { Logger.log.trace ("Build JDOM tree"); // build JDOM tree Document doc = builder.build(in); // Copy the pathway information to a VPathway Element root = doc.getRootElement(); if (!root.getName().equals("Pathway")) { throw new ConverterException ("Not a Pathway file"); } Namespace ns = root.getNamespace(); GpmlFormatReader format = getReaderForNamespace (ns); if (format == null) { throw new ConverterException ("This file looks like a pathway, " + "but the namespace " + ns + " was not recognized. This application might be out of date."); } Logger.log.info ("Recognized format " + ns); Logger.log.trace ("Start Validation"); if (validate) format.validateDocument(doc); Logger.log.trace ("Copy map elements"); format.readFromRoot (root, pwy); } catch(JDOMParseException pe) { throw new ConverterException (pe); } catch(JDOMException e) { throw new ConverterException (e); } catch(IOException e) { throw new ConverterException (e); } catch(NullPointerException e) { throw new ConverterException (e); } catch(IllegalArgumentException e) { throw new ConverterException (e); } catch(Exception e) { //Make all types of exceptions a ConverterException throw new ConverterException (e); } } @Override public boolean isCorrectType(File f) { String uri; try { uri = "" + RootElementFinder.getRootUri(f); return uri.startsWith ("http://genmapp.org/"); } catch (Exception e) { e.printStackTrace(); return false; } } }
5f6c3d6cb98f3c32d30cd744b37be48bfeff09af
9574ef260fe351f5cdfed8753a1a4fb919517c15
/src/main/java/org/teachmeskills/project/application/utils/Input.java
757823e9bd146b2e9299e796b5393dffb38475f7
[]
no_license
VilchinskiOleg/transport-company-app
cf67a2784647787c905d65d5e4660e248a0106a4
3c038f4dec218ed1cbb6b02305cbf258365d4f04
refs/heads/master
2023-01-29T22:09:24.989283
2020-12-10T21:23:06
2020-12-10T21:23:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,565
java
package org.teachmeskills.project.application.utils; import org.teachmeskills.project.entitiy.TypeTransport; import java.util.Scanner; public class Input { private static Scanner scanner = new Scanner(System.in); public static int getInt() { if (scanner.hasNextInt()) { int number = scanner.nextInt(); scanner.nextLine(); return number; } System.out.println(scanner.nextLine() + " - это не целое число. Поаторите ввод."); return getInt(); } public static int getInt(String massage) { System.out.println(massage); return getInt(); } public static double getDouble() { if (scanner.hasNextDouble()) { double number = scanner.nextDouble(); scanner.nextLine(); return number; } System.out.println(scanner.nextLine() + " - это не число с плавающей точкой. Поаторите ввод."); return getDouble(); } public static double getDouble(String massage) { System.out.println(massage); return getDouble(); } public static String getString() { return scanner.nextLine(); } public static String getString(String massage) { System.out.println(massage); return getString(); } public static boolean getBoolean() { String answer = scanner.nextLine().trim(); if (!(answer.equals("Yes") || answer.equals("No"))) { System.out.println("Не корректный ответ. Повторите ввод."); return getBoolean(); } return answer.equals("Yes"); } public static boolean getBoolean(String massage) { System.out.println(massage + "Yes/No"); return getBoolean(); } public static TypeTransport getTypeTransport() { System.out.println("Выберите тип транспорта:"); showTypes(); return getType(); } private static void showTypes() { for (TypeTransport type : TypeTransport.values()) System.out.println(type.getIdType() + " - " + type.getType()); } private static TypeTransport getType() { int result = getInt(); if (result <= 0 || result > TypeTransport.values().length) { System.out.println("Не корректный ответ. Повторите ввод."); return getType(); } return TypeTransport.values()[result - 1]; } }
875b0e4072418106920a3143a2a6a4365840c198
018adaf5f1e17065845e1b8fcad32e7c3eab74c6
/paascloud-provider/paascloud-provider-uac/src/main/java/com/paascloud/provider/mapper/UacGroupUserMapper.java
f9674552845a002f60998cefd22da15ab5eb83d3
[]
no_license
wangwuuw/surpermarket
e367f4daf9581acb48abf9c415ce718fb6b3e5ef
5f0a1b7643d6bbfe276937eafbb99c5bc887100d
refs/heads/master
2020-04-28T15:12:43.642801
2019-03-13T07:54:43
2019-03-13T07:54:43
175,364,625
0
0
null
null
null
null
UTF-8
Java
false
false
1,916
java
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:UacGroupUserMapper.java * 创建人:刘兆明 * 联系方式:[email protected] * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.paascloud.provider.mapper; import com.paascloud.core.mybatis.MyMapper; import com.paascloud.provider.model.domain.UacGroup; import com.paascloud.provider.model.domain.UacGroupUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import java.util.List; /** * The interface Uac group user mapper. * * @author [email protected] */ @Mapper @Component public interface UacGroupUserMapper extends MyMapper<UacGroupUser> { /** * Query by user id uac group user. * * @param userId the user id * * @return the uac group user */ UacGroupUser getByUserId(Long userId); /** * Update by user id int. * * @param uacGroupUser the uac group user * * @return the int */ int updateByUserId(UacGroupUser uacGroupUser); /** * Select group list by user id list. * * @param userId the user id * * @return the list */ List<UacGroup> selectGroupListByUserId(Long userId); /** * List by group id list. * * @param groupId the group id * * @return the list */ List<UacGroupUser> listByGroupId(@Param("groupId") Long groupId); /** * Delete exclude super mng int. * * @param groupId the group id * @param superManagerRoleId the super manager role id * * @return the int */ int deleteExcludeSuperMng(@Param("currentGroupId") Long groupId, @Param("superManagerRoleId") Long superManagerRoleId); }
5c8dc93dfdb99b2b97a986231ab2cbf3ac4c5008
7082c3df0fcec950e1930740140bcc66d810b065
/Part2/chapter5/SamplePager/app/src/main/java/com/example/samplepager/Fragment3.java
88c80010462eef04954ad563f72c5eb4285d6cbb
[]
no_license
limjh0513/Doit_Android
af8c818c9f6a8a8f032c5099910ab671e306b7d7
aca0730727ac560e3f04d0e40cc52d2593ccd537
refs/heads/main
2023-04-04T01:27:09.289508
2021-03-26T13:29:00
2021-03-26T13:29:00
332,646,063
0
0
null
null
null
null
UTF-8
Java
false
false
511
java
package com.example.samplepager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; public class Fragment3 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment3, container, false); } }
75642f03667447aedab7fc5084fd8416a87a23d2
8b695fc59af9228837d798fd8eb900fa09f21db5
/src/org/mjsip/sdp/field/KeyParam.java
feccd3e72461e1b17b66102d72e830418886be78
[]
no_license
k1995/mjsipME
08e1b5e96f962201bb2cd53f58582991daff02db
557318304bc01114621b9977b0fa747de656c87b
refs/heads/main
2023-08-15T00:13:06.939618
2021-09-19T14:56:24
2021-09-19T14:56:24
408,155,865
0
0
null
null
null
null
UTF-8
Java
false
false
1,749
java
/* * Copyright (C) 2010 Luca Veltri - University of Parma - Italy * * This file is part of MjSip (http://www.mjsip.org) * * MjSip 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. * * MjSip 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 MjSip; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Luca Veltri ([email protected]) */ package org.mjsip.sdp.field; import org.zoolu.util.Parser; /** Key-param of a crypto attribute field. */ public class KeyParam { /** Key-param value */ String value; /** Creates a new KeyParam. */ public KeyParam(String key_method, String key_info) { value=key_method+":"+key_info; } /** Creates a new KeyParam. */ public KeyParam(String key_param) { value=key_param; } /** Creates a new KeyParam. */ public KeyParam(KeyParam kp) { value=kp.value; } /** Gets the key-method. */ public String getKeyMethod() { Parser par=new Parser(value); char[] delim={':'}; return par.getWord(delim); } /** Gets the key-info. */ public String getKeyInfo() { Parser par=new Parser(value); return par.goTo(':').skipChar().getString(); } /** Converts this object to String. */ public String toString() { return value; } }
52613698385b5cc9f32431364af116149e8ad244
2354eb072ad00d8d11eb037901cb92f40ea1733b
/upload-service/src/main/java/org/upload/model/RequestInfo.java
2e135b20c69ae4ddd02a80b9bcf51c6cb6c3042b
[]
no_license
mcubillos/sample-spring-microservice-file-reader
830f2c6b09573940e93a8746b399fd4c4141e3e9
fc48f728c45515952d6a6b4d1c63fb5583a8e41d
refs/heads/master
2020-03-19T02:03:11.555805
2018-06-12T20:28:38
2018-06-12T20:28:38
135,594,285
0
0
null
null
null
null
UTF-8
Java
false
false
212
java
package org.upload.model; public class RequestInfo { private String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }
493580d39e956048327df3d2714301fd536ad058
e6228437bbbb7c190f7d8e07523089993e35f53d
/src/org/delft/naward07/MapReduce/hdfs/Clustering.java
d1a0e0e7a92b61323328b2d17c7a0ec3ca3c2669
[]
no_license
norvigaward/naward07
5bc5603325fe41f85ff36f5169441ca45907d12e
121874c3531d9471d78fa708fd7d145468b97c0e
refs/heads/master
2021-01-01T10:40:02.332187
2014-08-31T22:10:14
2014-08-31T22:10:14
19,768,867
3
0
null
null
null
null
UTF-8
Java
false
false
1,668
java
package org.delft.naward07.MapReduce.hdfs; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; /** * @author Feng Wang */ public class Clustering implements Runnable { private String path; private String outPath; public Clustering(String path, String outPath) { this.path = path; this.outPath = outPath; } @Override public void run() { System.out.println("test3"); // PropertyConfigurator.configure("log4jconfig.properties"); final Configuration conf = new Configuration(); // The core-site.xml and hdfs-site.xml are cluster specific. If you wish to use this on other clusters adapt the files as needed. conf.addResource(Clustering.class.getResourceAsStream("/nl/surfsara/warcexamples/hdfs/resources/core-site.xml")); conf.addResource(Clustering.class.getResourceAsStream("/nl/surfsara/warcexamples/hdfs/resources/hdfs-site.xml")); System.out.println("test4"); conf.set("hadoop.security.authentication", "kerberos"); conf.set("hadoop.security.authorization", "true"); System.setProperty("java.security.krb5.realm", "CUA.SURFSARA.NL"); System.setProperty("java.security.krb5.kdc", "kdc.hathi.surfsara.nl"); UserGroupInformation.setConfiguration(conf); UserGroupInformation loginUser; try { loginUser = UserGroupInformation.getLoginUser(); System.out.println("Logged in as: " + loginUser.getUserName()); RunClustering runClustering = new RunClustering(conf, path, outPath); loginUser.doAs(runClustering); } catch (IOException e) { // Just dump the error.. e.printStackTrace(); } } }
bbc5bc68bb38532f2ac31a58bb83b25a8a8d963e
fb40408fe856a4dc6b158abacdfe9572de7557cc
/src/com/service/AreasServiceImpl.java
07ef2018df628c5d24a7cae6de2ae7ecd43205af
[]
no_license
duxingluochen/stussh
c7df748d1db917d70bb13f87f24b0410667b8e2e
76020b4ee1a9e86cee13a8f98916d21650859a28
refs/heads/master
2021-05-02T02:53:46.040580
2018-02-09T10:04:45
2018-02-09T10:04:45
120,888,746
0
0
null
null
null
null
GB18030
Java
false
false
1,291
java
package com.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.beans.AreasCustom; import com.beans.AreasQueryVo; import com.mapper.AreasMapper; @Transactional @Service(value="areasService") public class AreasServiceImpl implements AreasService { @Resource(name="areasMapper") private AreasMapper areasMapper; @Override public List<AreasCustom> queryareas() { return areasMapper.queryareas(); } @Override public boolean deleteareas(int id) { return areasMapper.deleteareas(id); } /** * 根据id查找 */ @Override public AreasCustom queryareasup(int id) { return areasMapper.queryareasup(id); } /** * 去重查询上级 */ @Override public List<AreasCustom> queryprovince() { return areasMapper.queryprovince(); } /** * 去掉重复的地区类型 */ @Override public List<AreasCustom> queryareatype() { return areasMapper.queryareatype(); } /** * 根据id修改地区 */ @Override public boolean updatareas(AreasQueryVo areasQueryVo) { return areasMapper.updatareas(areasQueryVo); } }
a8b5ea366b4b9c41cd7ca7d6dabb108a830f081a
741c50a0da38f213060ff37052c66934bce918eb
/src/main/java/AutomationFramework/SeleniumGrid/App.java
15cec4a6e0e8e09c211e922ba0c883d76cc289c0
[]
no_license
avietlobo/SeleniumGridProject
17c0fffe6696a6519ae19521c22d114d78a9939c
6d460d26ff027f9acf967ed3aae22fb5477dc95b
refs/heads/master
2023-05-15T03:19:11.047155
2020-06-04T10:10:48
2020-06-04T10:10:48
269,289,230
0
0
null
2023-05-09T18:46:42
2020-06-04T07:24:38
HTML
UTF-8
Java
false
false
195
java
package AutomationFramework.SeleniumGrid; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
570a5dcc0a025772af19b77ad18a8fbcc806960d
cabbf8d0bd891ef3ffb257e481f417388f887033
/jack-compiler/src/test/java/com/akwabasystems/ExpressionTests.java
c85ea627e264ef33ba78769f3597235664f98030
[]
no_license
akwabasystems/nand2tetris
8b2b453a528c6ebc22059ddf1f7b7784fc04ac41
503e4f97a4ba16957cd418faae04195d419ddbce
refs/heads/develop
2021-06-24T22:16:39.693378
2020-10-13T23:11:32
2020-10-13T23:11:32
135,829,149
0
1
null
2020-10-13T23:11:33
2018-06-02T15:25:20
Java
UTF-8
Java
false
false
27,105
java
package com.akwabasystems; import com.akwabasystems.parsing.XMLCompilationEngine; import com.akwabasystems.parsing.JackTokenizer; import com.akwabasystems.parsing.Tokenizer; import junit.framework.TestCase; public class ExpressionTests extends TestCase { public void testTerminalOrKeywordConstants() { StringBuilder input = new StringBuilder(); input.append("class Main {\n") .append(" function void test() { // Added to test Jack syntax that is not use in\n") .append(" var String s; // the Square files.\n") .append(" var Array a;\n") .append("\n") .append(" if (false) {\n") .append(" let s = \"string constant\";\n") .append(" let s = null;\n") .append(" }\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Main </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> test </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<varDec>\n") .append("<keyword> var </keyword>\n") .append("<identifier> String </identifier>\n") .append("<identifier> s </identifier>\n") .append("<symbol> ; </symbol>\n") .append("</varDec>\n") .append("<varDec>\n") .append("<keyword> var </keyword>\n") .append("<identifier> Array </identifier>\n") .append("<identifier> a </identifier>\n") .append("<symbol> ; </symbol>\n") .append("</varDec>\n") .append("<statements>\n") .append("<ifStatement>\n") .append("<keyword> if </keyword>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<keyword> false </keyword>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> s </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<stringConstant> string constant </stringConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> s </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<keyword> null </keyword>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</ifStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testUnaryOperatorTerm() { StringBuilder input = new StringBuilder(); input.append("class Main {\n") .append(" function void test() {\n") .append(" let i = -j;\n") .append(" let j = j + 1;\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Main </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> test </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> i </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> - </symbol>\n") .append("<term>\n") .append("<identifier> j </identifier>\n") .append("</term>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> j </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> j </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<integerConstant> 1 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testOperatorTerms() { StringBuilder input = new StringBuilder(); input.append("class Main {\n") .append(" function void test() {\n") .append(" let i = i * (-j);\n") .append(" let j = j / (-2); // note: unary negate constant 2\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Main </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> test </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> i </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> i </identifier>\n") .append("</term>\n") .append("<symbol> * </symbol>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> - </symbol>\n") .append("<term>\n") .append("<identifier> j </identifier>\n") .append("</term>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> j </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> j </identifier>\n") .append("</term>\n") .append("<symbol> / </symbol>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> - </symbol>\n") .append("<term>\n") .append("<integerConstant> 2 </integerConstant>\n") .append("</term>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testParenthesizedExpression() { StringBuilder input = new StringBuilder(); input.append("class Square {\n") .append(" function void moveRight() {\n") .append(" let x = (x + size) + 1;\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Square </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> moveRight </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> x </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> x </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<integerConstant> 1 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testIfWithParenthesizedExpression() { StringBuilder input = new StringBuilder(); input.append("class Square {\n") .append(" function void incSize() {\n") .append(" if ((y + size) < 254) {\n") .append(" let size = size + 2;\n") .append(" }\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Square </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> incSize </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<ifStatement>\n") .append("<keyword> if </keyword>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> y </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("<symbol> &lt; </symbol>\n") .append("<term>\n") .append("<integerConstant> 254 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> size </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<integerConstant> 2 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</ifStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testIfWithParenthesizedExpressions() { StringBuilder input = new StringBuilder(); input.append("class Square {\n") .append(" function void incSize() {\n") .append(" if (((y + size) < 254) & ((x + size) < 510)) {\n") .append(" let size = size + 2;\n") .append(" }\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Square </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> incSize </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<ifStatement>\n") .append("<keyword> if </keyword>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> y </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("<symbol> &lt; </symbol>\n") .append("<term>\n") .append("<integerConstant> 254 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("<symbol> &amp; </symbol>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<symbol> ( </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> x </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("<symbol> &lt; </symbol>\n") .append("<term>\n") .append("<integerConstant> 510 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ) </symbol>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> size </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> size </identifier>\n") .append("</term>\n") .append("<symbol> + </symbol>\n") .append("<term>\n") .append("<integerConstant> 2 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</ifStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testPropertyAccessTerm() { StringBuilder input = new StringBuilder(); input.append("class Main {\n") .append(" function void test() {\n") .append(" let a = a[2];\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Main </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> test </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> a </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> a </identifier>\n") .append("<symbol> [ </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<integerConstant> 2 </integerConstant>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ] </symbol>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } public void testSubroutineTerm() { StringBuilder input = new StringBuilder(); input.append("class Main {\n") .append(" function void test() {\n") .append(" let game = SquareGame.new();\n") .append(" }\n") .append("}\n"); Tokenizer tokenizer = new JackTokenizer(input.toString()); XMLCompilationEngine compiler = new XMLCompilationEngine(tokenizer); compiler.compileClass(); StringBuilder output = new StringBuilder(); output.append("<class>\n") .append("<keyword> class </keyword>\n") .append("<identifier> Main </identifier>\n") .append("<symbol> { </symbol>\n") .append("<subroutineDec>\n") .append("<keyword> function </keyword>\n") .append("<keyword> void </keyword>\n") .append("<identifier> test </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<parameterList>\n") .append("</parameterList>\n") .append("<symbol> ) </symbol>\n") .append("<subroutineBody>\n") .append("<symbol> { </symbol>\n") .append("<statements>\n") .append("<letStatement>\n") .append("<keyword> let </keyword>\n") .append("<identifier> game </identifier>\n") .append("<symbol> = </symbol>\n") .append("<expression>\n") .append("<term>\n") .append("<identifier> SquareGame </identifier>\n") .append("<symbol> . </symbol>\n") .append("<identifier> new </identifier>\n") .append("<symbol> ( </symbol>\n") .append("<expressionList>\n") .append("</expressionList>\n") .append("<symbol> ) </symbol>\n") .append("</term>\n") .append("</expression>\n") .append("<symbol> ; </symbol>\n") .append("</letStatement>\n") .append("</statements>\n") .append("<symbol> } </symbol>\n") .append("</subroutineBody>\n") .append("</subroutineDec>\n") .append("<symbol> } </symbol>\n") .append("</class>"); assertEquals(compiler.toXML(), output.toString()); } }
cd8b7a380490624ff17fcefd3f0baa58b1753af5
dbe59da45f4cee95debb721141aeab16f44b4cac
/src/main/java/com/syuesoft/sell/model/XsSuppliertraderAccount.java
802a995df33a398d4cd8a25f80022d7aa1fb7157
[]
no_license
tonyliu830204/UESoft
5a8a546107f2093ee920facf6d93eedd1affd248
9dd48ff19f40556d1892688f6426e4bfe68c7d10
refs/heads/master
2021-01-23T15:51:00.782632
2014-03-26T15:56:46
2014-03-26T15:56:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,303
java
package com.syuesoft.sell.model; import java.sql.Timestamp; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * XsSuppliertraderAccount entity. @author MyEclipse Persistence Tools */ public class XsSuppliertraderAccount implements java.io.Serializable { // Fields private Integer enterpriseId; private Integer accountId; private String accountCode; private String remark; private Integer instorehouseId; private Integer accountPerson; private Date accountDate; private Double accountSun; private Double accountBalance; private Double accountMoney; private Integer accountType; private Set xsSupplierAccountlogs = new HashSet(0); // Constructors /** default constructor */ public XsSuppliertraderAccount() { } /** full constructor */ public XsSuppliertraderAccount(String accountCode, Integer instorehouseId, Integer accountPerson, Timestamp accountDate, Double accountSun, Double accountBalance, Double accountMoney, Integer accountType, Set xsSupplierAccountlogs) { this.accountCode = accountCode; this.instorehouseId = instorehouseId; this.accountPerson = accountPerson; this.accountDate = accountDate; this.accountSun = accountSun; this.accountBalance = accountBalance; this.accountMoney = accountMoney; this.accountType = accountType; this.xsSupplierAccountlogs = xsSupplierAccountlogs; } // Property accessors public Integer getAccountId() { return this.accountId; } public Integer getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(Integer enterpriseId) { this.enterpriseId = enterpriseId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public void setAccountId(Integer accountId) { this.accountId = accountId; } public String getAccountCode() { return this.accountCode; } public void setAccountCode(String accountCode) { this.accountCode = accountCode; } public Integer getInstorehouseId() { return this.instorehouseId; } public void setInstorehouseId(Integer instorehouseId) { this.instorehouseId = instorehouseId; } public Integer getAccountPerson() { return this.accountPerson; } public void setAccountPerson(Integer accountPerson) { this.accountPerson = accountPerson; } public Date getAccountDate() { return this.accountDate; } public void setAccountDate(Date accountDate) { this.accountDate = accountDate; } public Double getAccountSun() { return this.accountSun; } public void setAccountSun(Double accountSun) { this.accountSun = accountSun; } public Double getAccountBalance() { return this.accountBalance; } public void setAccountBalance(Double accountBalance) { this.accountBalance = accountBalance; } public Double getAccountMoney() { return this.accountMoney; } public void setAccountMoney(Double accountMoney) { this.accountMoney = accountMoney; } public Integer getAccountType() { return this.accountType; } public void setAccountType(Integer accountType) { this.accountType = accountType; } public Set getXsSupplierAccountlogs() { return this.xsSupplierAccountlogs; } public void setXsSupplierAccountlogs(Set xsSupplierAccountlogs) { this.xsSupplierAccountlogs = xsSupplierAccountlogs; } }
3b15789de07217b06374c059174fe3fea77fc0c1
071a0709ba083c8248d7606b8fcbc88352738fe5
/src/timeflow/data/db/filter/StringMatchFilter.java
6b9d6500b4afa1b30668b9f2231a615f8ab9ebd4
[]
no_license
mmistretta/TimeFlow
bfc601d5b439b452846e76eeb18bdab2b13bbf3c
0bdd6dfb53b78bcd9d5dd1070df2740e19975f2a
refs/heads/master
2021-01-17T08:09:23.558039
2013-10-13T20:44:42
2013-10-13T20:44:42
13,530,927
0
1
null
null
null
null
UTF-8
Java
false
false
1,539
java
package timeflow.data.db.filter; import timeflow.data.db.*; import timeflow.data.time.*; import java.util.regex.*; public class StringMatchFilter extends ActFilter { private Field[] textFields; private Field[] listFields; private String query=""; private boolean isRegex=false; private Pattern pattern; public StringMatchFilter(ActDB db, boolean isRegex) { this(db,"", isRegex); } public StringMatchFilter(ActDB db, String query, boolean isRegex) { textFields=(Field[])db.getFields(String.class).toArray(new Field[0]); listFields=(Field[])db.getFields(String[].class).toArray(new Field[0]); this.isRegex=isRegex; setQuery(query); } public String getQuery() { return query; } public void setQuery(String query) { this.query=query; if (isRegex) { pattern=Pattern.compile(query, Pattern.CASE_INSENSITIVE+Pattern.MULTILINE+Pattern.DOTALL); } else this.query=query.toLowerCase(); } @Override public boolean accept(Act act) { // check text fields for (int i=0; i<textFields.length; i++) { String s=act.getString(textFields[i]); if (s==null) continue; if (isRegex ? pattern.matcher(s).find() : s.toLowerCase().contains(query)) return true; } // check list fields for (int j=0; j<listFields.length; j++) { String[] m=act.getTextList(listFields[j]); if (m!=null) for (int i=0; i<m.length; i++) { String s=m[i]; if (isRegex ? pattern.matcher(s).find() : s.toLowerCase().contains(query)) return true; } } return false; } }
cea76151e65bde265836af0e2881ddca6cd07117
bd882b28a7b644896d2e80b1528fca26693360ad
/src/com/javaex/io/FileStreamEx.java
17d24cb670a4e49ba96523b59eae9cb9ef956feb
[]
no_license
yoonchaiyoung/javaex
3e2f5e13aeac9e0d6c407df48b25f3c92cf79a99
00303847f5e8e4d45d252cf5af9c5a6f57b2b65f
refs/heads/master
2022-12-14T23:28:05.468136
2020-09-21T06:42:45
2020-09-21T06:42:45
295,352,540
0
0
null
null
null
null
UTF-8
Java
false
false
993
java
package com.javaex.io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileStreamEx { private static String rootPath = System.getProperty("user.dir") + "\\files\\"; private static String src = rootPath + "img.jpg"; private static String tgt = rootPath + "img_copy.jpg"; public static void main(String[] args) { // files\img.jpg를 입력 // files\img_copy.jpg로 출력 try { InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(tgt); int data = 0; while((data = is.read()) != -1) { os.write(data); } os.close(); is.close(); System.out.println("파일을 복사했어요."); } catch (FileNotFoundException e) { System.err.println("파일을 찾을 수 없어요."); } catch (IOException e) { System.err.println(e.getMessage()); } } }
d864bf468ebdf0b8c64a5f2129018cce4cb4000f
7de78e79de0879a91386adcfeb07a51596a13f01
/liuyq-business-common/src/main/java/com/liuyq/Pages/Page.java
08a1e503d434fd6c13d30a81e02ebc8928532d81
[]
no_license
liuyq913/liuyq-businessNew
6f3a172540926e6997de61f9e0a15f7b2c6721a0
588b3025edfb1e8862d36d7042a22e031a6b6ce9
refs/heads/master
2022-12-22T06:36:06.118805
2019-08-22T01:50:45
2019-08-22T01:50:45
123,286,910
0
0
null
2022-12-16T08:25:52
2018-02-28T13:12:52
Java
UTF-8
Java
false
false
4,020
java
package com.liuyq.Pages; import com.github.pagehelper.PageInfo; import java.io.Serializable; import java.util.List; /** * 通用Page组件 * @param <T> */ public class Page<T> implements Serializable{ /** * */ private static final long serialVersionUID = 1L; // 每页条数 private int rp = 10; // 当前第几页 private int page = 1; // 查询集合 private List<T> rows; // 总记录数 private long total; private int firstPage; private int prePage; private int nextPage; private int lastPage; private boolean isFirstPage; private boolean isLastPage; private boolean hasPreviousPage; private boolean hasNextPage; public Page() { } /** * 基本构造 * @param rp 每页行数 * @param page 页码 */ public Page(int rp, int page){ //分页参数的传递,全部统一为Page对象,行数最大允许100行 this.rp = rp > 100 ? 100 : rp; this.page = page; } public Page(PageInfo<T> pageInfo){ this.rp = pageInfo.getPageSize(); this.rows = pageInfo.getList(); this.page = pageInfo.getPageNum(); this.total = pageInfo.getTotal(); this.firstPage = pageInfo.getFirstPage(); this.prePage = pageInfo.getPrePage(); this.nextPage = pageInfo.getNextPage(); this.lastPage = pageInfo.getLastPage(); this.isFirstPage = pageInfo.isIsFirstPage(); this.isLastPage = pageInfo.isIsLastPage(); this.hasPreviousPage = pageInfo.isHasPreviousPage(); this.hasNextPage = pageInfo.isHasNextPage(); } public Page(Integer rp, Integer page, List<T> rows, Long total, Integer firstPage, Integer prePage, Integer nextPage, Integer lastPage, boolean isFirstPage, boolean isLastPage, boolean hasPreviousPage, boolean hasNextPage) { this.rp = rp == null ? 0 : rp; this.page = page == null ? 0 : page; this.rows = rows; this.total = total == null ? 0 : total; this.firstPage = firstPage == null ? 0 : firstPage; this.prePage = prePage == null ? 0 : prePage; this.nextPage = nextPage == null ? 0 : nextPage; this.lastPage = lastPage == null ? 0 : lastPage; this.isFirstPage = isFirstPage; this.isLastPage = isLastPage; this.hasPreviousPage = hasPreviousPage; this.hasNextPage = hasNextPage; } public Page(int rp, int page, List<T> rows, long total){ this.rp = rp; this.rows = rows; this.page = page; this.total = total; } public Page(Page<T> page) { this.rp = page.rp; this.rows = page.rows; this.page = page.page; this.total = page.total; } public int getRp() { return rp; } public void setRp(int rp) { this.rp = rp; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public int getFirstResult() { return ((page - 1) * rp); } public boolean isHasNextPage() { return hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } public boolean isHasPreviousPage() { return hasPreviousPage; } public void setHasPreviousPage(boolean hasPreviousPage) { this.hasPreviousPage = hasPreviousPage; } public boolean isLastPage() { return isLastPage; } public void setIsLastPage(boolean isLastPage) { this.isLastPage = isLastPage; } public boolean isFirstPage() { return isFirstPage; } public void setIsFirstPage(boolean isFirstPage) { this.isFirstPage = isFirstPage; } public int getLastPage() { return lastPage; } public void setLastPage(int lastPage) { this.lastPage = lastPage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getFirstPage() { return firstPage; } public void setFirstPage(int firstPage) { this.firstPage = firstPage; } }
47c5ed2a31f06ca535a9defe163a1a5eccd3bde5
a6cf573d5d5c4fa12d8ba78b3379c0e41740b06d
/src/com/Java8/demo/StaticMethods/MyDataImpl.java
207e28fd9e8853c347cdf1380bdc65fd22f76b28
[]
no_license
ardianalok/java-8-features
510c0fbf4ceacd2aa66bb8518343e0ed59942761
8be27e78fb594dbfd9b034cd6bd60318d1218dd1
refs/heads/master
2021-08-30T13:52:39.794412
2017-12-18T07:01:47
2017-12-18T07:01:47
null
0
0
null
null
null
null
MacCentralEurope
Java
false
false
643
java
package com.Java8.demo.StaticMethods; //letís see an implementation class that is having isNull() method with poor implementation. public class MyDataImpl implements MyData { public boolean isNull(String str) { System.out.println("Impl Null Check"); return str == null ? true : false; } public static void main(String args[]){ MyDataImpl obj = new MyDataImpl(); obj.print(""); obj.isNull("abc"); /* Note that isNull(String str) is a simple class method, itís not overriding the interface method. For example, if we will add @Override annotation to the isNull() method, it will result in compiler error.*/ } }
66188b2c7fc697ff052c45ed746b80013695f4ac
b6ba1bea35dcaa6b72a8df96f51dfeb20c2fe14a
/src/study/笔试/Main.java
f8b1d1f5935455a492dd26925228c891cd4de7cb
[]
no_license
YinWangPing/algorithm-study
31896d7f488e261c18448f080fa3849d2ec94df8
4843b972fad06b5232836769e33e924520b69c94
refs/heads/master
2021-01-03T04:35:50.491579
2020-06-29T01:32:19
2020-06-29T01:32:19
239,924,456
0
0
null
null
null
null
UTF-8
Java
false
false
13,815
java
package study.笔试; //import java.io.InputStreamReader; //import java.util.Scanner; // //public class Main { // public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // while (sc.hasNextLine()) { // int n = Integer.parseInt(sc.nextLine().trim()); // for (int i = 0; i < n; i++) { // String[] strings = sc.nextLine().trim().split(" "); // String indexi = Integer.toBinaryString(Integer.parseInt(strings[0])); // int indexj = -1; // for (int j = 0; j < indexi.length(); j++) { // if (indexi.charAt(j) == '1') { // indexj = j; // break; // } // } // int level = indexi.length() - indexj; // long res = -1; // long nums = Long.parseLong(strings[0]); // for (int p = 0; p < level - Integer.parseInt(strings[1]); p++) { // res = nums / 2; // nums = res; // } // System.out.println(res); // } // } // } //} // import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args) { int [][]people=new int[][]{{0,2},{1,3},{2,4}}; List<int[]> list=new ArrayList<>(); for (int []p:people) { list.add(p[0],p); } int [][]res=list.toArray(new int[people.length][2]); Queue queue=new LinkedList(); System.out.println(queue.add(1)); System.out.println(queue.add(2)); System.out.println(queue.add(3)); System.out.println(queue.offer(4)); System.out.println("---------------"); System.out.println(); System.out.println(queue.peek()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.element()); System.out.println(queue.peek()); // Scanner sc = new Scanner(System.in); // while (sc.hasNextInt()) { // int n = sc.nextInt(); // int []res=new int[3]; // for (int i = 0; i < n ; i++) { // res[i]=sc.nextInt(); // } // int []res1=new int[3]; // for (int i = 0; i < n ; i++) { // res1[i]=sc.nextInt(); // } // int count=0; // for (int i = 1; i <n ; i++) { // if(res[i]<res[i-1]){ // count++; // } // } // System.out.println(count); // } } } //public class Main { // private Stack<Integer> push; // private Stack<Integer> pop; // // public Main() { // this.pop = new Stack<Integer>(); // this.push = new Stack<Integer>(); // } // // public void add(int newNum) { // this.push.push(newNum); // if (this.pop.empty()) { // while (!this.push.empty()) { // this.pop.push(this.push.pop()); // } // } // } // // public int poll() { // if (this.pop.empty() && this.push.empty()) { // throw new RuntimeException("Queue is empty!"); // } else if (this.pop.empty()) { // while (!this.push.empty()) { // this.pop.push(this.push.pop()); // } // } // return this.pop.pop(); // } // // public int peek() { // if (this.pop.empty() && this.push.empty()) { // throw new RuntimeException("Queue is empty!"); // } else if (this.pop.empty()) { // while (!this.push.empty()) { // this.pop.push(this.push.pop()); // } // } // return this.pop.peek(); // } // // public static void main(String[] args) throws Exception { // Main q = new Main(); // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // int n = Integer.parseInt(br.readLine()); // for (int i = 0; i < n; i++) { // String[] opr = br.readLine().split(" "); // if (opr.length == 2) { // q.add(Integer.parseInt(opr[1])); // } else { // if (opr[0].equals("peek")) { // System.out.println(q.peek()); // } else q.poll(); // } // // } // } // //} // // public static String [] calculate(String [] str){ //// HashMap<String,String>map=new HashMap<>(); //// for (int i = 0; i <str.length ; i++) { //// if(str[i].contains("##")){ //// String []strings=str[i].split("##"); //// if(strings.length>1) { //// map.put(strings[0], map.getOrDefault(strings[0], "") + strings[1]); //// }else { //// map.put(strings[0], map.getOrDefault(strings[0], "")+"*"); //// } //// }else { //// map.put(str[i],map.getOrDefault(str[i],"")+"$$"); //// } //// } //// HashMap<String,String>res=new HashMap<>(); //// for (Map.Entry entry:map.entrySet()) { //// map.put((String) entry.getValue(),map.getOrDefault(entry.getValue(), "")+entry.getKey()); //// } //// Collections.sort(res); //// int i=0; ////// for (int i = 0; i <map.size() ; i++) { ////// visited[i]=true; ////// for (int j = 1; j <map.size() ; j++) { ////// if(map.get()) ////// } ////// } //// return null; //// } //// public static void main(String[] args) { //// Scanner sc=new Scanner(System.in); //// while (sc.hasNextInt()){ //// int r =sc.nextInt(); //// int c=sc.nextInt(); //// int [][]nums=new int[r][c]; //// for (int i = 0; i <r ; i++) { //// for (int j = 0; j <c ; j++) { //// nums[i][j]=sc.nextInt(); //// } //// } //// System.out.println(numIslands(nums)); //// } ////// Scanner sc = new Scanner(System.in); ////// while (sc.hasNextLine()) { ////// int k= Integer.parseInt(sc.nextLine().trim()); ////// HashMap<String,String>map=new HashMap<>(); ////// for (int i = 0; i <k ; i++) { ////// String line=sc.nextLine().trim(); ////// String []str=line.split("//"); ////// if(str[1].contains("/")){ ////// String []strings=str[1].split("/"); ////// map.put() ////// } ////// } ////// } //// } // public static int numIslands(int[][] grid) { // int nums = 0; // for (int i = 0; i < grid.length; i++) { // replace(grid, i, 0); // replace(grid, i, grid[0].length - 1); // } // for (int i = 0; i < grid[0].length; i++) { // replace(grid, 0, i); // replace(grid, grid.length - 1, i); // } // for (int i = 0; i < grid.length; i++) { // for (int j = 0; j < grid[0].length; j++) { // if (grid[i][j] == 1) { // calculate(grid, i, j); // nums++; // } // } // } // return nums; // } // // private static int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; // // public static int calculate(int[][] grid, int r, int c) { // if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) { // return 0; // } // grid[r][c] = 0; // int res = 1; // for (int[] d : directions) { // res += calculate(grid, r + d[0], c + d[1]); // } // return res; // } // // public static void replace(int[][] grid, int r, int c) { // if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == 0) { // return; // } // grid[r][c] = 0; // for (int[] d : directions) { // calculate(grid, r + d[0], c + d[1]); // } // } //} // // //// //// int left = 0, right = 0, max = 0; //// for (int i = 0; i < m; i++) { //// a[i] = sc.nextInt(); //// left = Math.max(left, a[i]); //// right += a[i]; //// } //// if (m == k) { //// for (int i = 0; i < m - 1; i++) { //// System.out.print(a[i]+" " +"/"+" "); //// } //// System.out.print(a[m - 1]); //// }else if(k==1){ //// for (int i = 0; i < m - 1; i++) { //// System.out.print(a[i] + " "); //// } //// System.out.print(a[m - 1]); //// }else //// calculate(a, m, k, left, right); //// public static void calculate(int[] a, int m, int k, int left, int right) { //// int max = right; //// int mid; //// while (left < right) { //// mid = (left + right) >> 1; //// int t = 1, sum = a[0]; //// for (int i = 1; i < m; i++) { //// if (sum + a[i] <= mid) { //// sum += a[i]; //// } else { //// t++; //// if (t > k) break; //// sum = a[i]; //// } //// } //// if (t > k) { //// left = mid + 1; //// } else { //// right = mid; //// } //// } //// } //// if (right != max) { //// int sum = 0; //// for (int i = 0; i < m; i++) { //// if (sum + a[i] <= right) { //// System.out.print(a[i] + " "); //// sum += a[i]; //// } else { //// sum = 0; //// System.out.print("/" + " "); //// i--; //// } //// } //// } else { //// for (int i = 0; i < m - 1; i++) { //// System.out.print(a[i] + " "); //// } //// System.out.print(a[m - 1]); //// } //// } ////} ////https://exam.nowcoder.com/cts/17073371/summary?id=CE8DF681247E5C46 //// 5a 12 5b ba 34 5b bb 88 05 5a 75 cd bb 62 5a 34 cd 78 cc da fb 06 5a ////public class Main { //// public static void main(String[] args) { //// Scanner sc = new Scanner(System.in); //// while (sc.hasNextLine()) { //// String str = sc.nextLine(); //// List<String> list = calculate(str); //// int n = list.size(); //// if(n<1){ //// System.out.println(""); //// }else { //// String res = "5a"; //// for (int i = 0; i < n; i++) { //// if(list.get(i)!="") { //// res += list.get(i) + "5a"; //// } //// } //// System.out.println(res); //// } //// } //// } //// //// public static List calculate(String str) { //// List<String> list = new ArrayList<>(); //// String[] res = str.split("5a"); //// for (int i = 1; i < res.length; i++) { //// if (res[i].length() > 3) { //// int size = res[i].charAt(res[i].length() - 2) - '0' + (res[i].charAt(res[i].length() - 3) - '0') * 16; //// String temp = res[i].trim().replace("5b ba", "5a").replace("5b bb", "5b"); //// int count = 0; //// for (int j = 0; j < temp.length(); j++) { //// if (temp.charAt(j) == ' ') { //// count++; //// } //// } //// if (count == size) { //// list.add(res[i]); //// } //// } else { //// list.add(res[i]); //// } //// } //// return list; //// } ////} //// ArrayList<Character> list=new ArrayList<>(); //// for (int i = 0; i <str.length() ; i++) { //// if(str.charAt(i)>='0'&&str.charAt(i)<='9'){ //// list.add(str.charAt(i)); //// } //// } //// Collections.sort(list); //// String res=""; //// for (char c:list) { //// res+=c; //// } //// System.out.println(res); ////public static void copyAllFiles(String srcPath,String desPath) throws IOException { //// File srcfile=new File(srcPath); //// File desFile=new File(desPath); //// if(!srcfile.exists()){ //// System.out.println("文件不存在"); //// } //// if(srcfile.isDirectory()){ //// File [] files=srcfile.listFiles(); //// for (int i = 0; i <files.length ; i++) { //// String des=desPath+File.separator+files[i].getPath().replace(srcPath,""); //// copyAllFiles(files[i].getPath(),des); //// } //// }else { //// copyFile(srcfile,desFile); //// } //// } ////public static void copyFile(File srcFile,File desFile) throws IOException { //// if(!desFile.getParentFile().exists()){ //// desFile.getParentFile().mkdirs(); //// } //// FileInputStream in=new FileInputStream(srcFile); //// FileOutputStream out=new FileOutputStream(desFile); //// byte[] buf=new byte[1024]; //// int len=0; //// while ((in.read(buf))!=-1){ //// out.write(buf,0,len); //// } //// in.close(); //// out.close(); //// } // //
8bf28e0cb670bcff82e29fd48545d91e15e6478a
2177f9092108d66d6b1c80cc503fcb2aba708519
/src/cn/edustar/usermgr/service/impl/UserServiceImpl.java
d24717f13523af9f61e8026f3cb418c4f18b7461
[]
no_license
yxxcrtd/UserMgr2_branches
6b05705e2b0423711928883993ecdaef32069943
c4a4ad90b174b1f4731791e1f6054c0992f50082
refs/heads/master
2020-05-31T20:21:48.195613
2019-06-05T22:01:06
2019-06-05T22:01:06
190,474,498
0
0
null
null
null
null
UTF-8
Java
false
false
5,148
java
package cn.edustar.usermgr.service.impl; import java.util.Date; import cn.edustar.usermgr.pojos.Ticket; import cn.edustar.usermgr.pojos.User; import cn.edustar.usermgr.service.UserService; import cn.edustar.usermgr.service.impl.base.BaseServiceImpl; import cn.edustar.usermgr.util.MD5; /** * UserService * * @author Yang XinXin * @version 2.0.0, 2010-09-02 11:03:12 */ public class UserServiceImpl extends BaseServiceImpl implements UserService { /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#getUserByQueryString(java.lang.String) */ public User getUserByQueryString(String queryString) { if (queryString.contains("@")) { return userDao.getUserByQueryString("email", queryString); } else { return userDao.getUserByQueryString("username", queryString); } } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#getUserCounts() */ public int getUserCounts() { return userDao.getUserCounts(); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#createUserTicket(java.lang.String) */ public Ticket createUserTicket(String username) { Ticket ticket = new Ticket(username); HASHMAP_TICKET.put(ticket.getTicket(), ticket); return ticket; } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#saveOrUpdate(cn.edustar.usermgr.pojos.User) */ public void saveOrUpdate(User user) { userDao.saveOrUpdate(user); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#getUserByUserTicket(java.lang.String) */ public User getUserByUserTicket(String userTicket) { if (null == userTicket || "".equals(userTicket) || userTicket.length() == 0) { return null; } Ticket ticket = getTicketByUserTicket(userTicket); if (null == ticket) { return null; } if (null == ticket.getUsername() || "".equals(ticket.getUsername()) || ticket.getUsername().length() < 0) { return null; } ticket.setLastAccessed(new Date()); return getUserByQueryString(ticket.getUsername()); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#getTicketByUserTicket(java.lang.String) */ public Ticket getTicketByUserTicket(String userTicket) { Ticket ticket = HASHMAP_TICKET.get(userTicket); if (null != ticket) { if (null == ticket.getLastAccessed()) { return null; } } return ticket; } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#verifyUser(java.lang.String) */ public String verifyUser(String username) { User user = getUserByQueryString(username); if (null != user) { if (null == user.getQuestion() || "".equals(user.getQuestion())) { return NULL; } return user.getQuestion(); } else { return ERROR; } } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#verifyAnswer(java.lang.String, java.lang.String) */ public String verifyAnswer(String username, String answer) { User user = getUserByQueryString(username); if (null != user) { if (user.getAnswer().equals(MD5.toMD5(answer))) { return SUCCESS; } else { return ERROR; } } else { return ""; } } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#resetPassword(java.lang.String, java.lang.String) */ public String resetPassword(String username, String password) { User user = getUserByQueryString(username); if (null != user) { user.setPassword(MD5.toMD5(password)); userDao.saveOrUpdate(user); return SUCCESS; } else { return ""; } } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#updatePasswordByUsername(java.lang.String, java.lang.String) */ public void updatePasswordByUsername(String username, String password) { userDao.updatePasswordByUsername(username, MD5.toMD5(password)); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#updateUserInfoByUsername(java.lang.String, int) */ public void updateUserInfoByUsername(String username, String trueName, String email, int role) { userDao.updateUserInfoByUsername(username, trueName, email, role); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#resetQuestionAndAnswerByUsername(java.lang.String, java.lang.String, java.lang.String) */ public void resetQuestionAndAnswerByUsername(String username, String question, String answer) { userDao.resetQuestionAndAnswerByUsername(username, question, MD5.toMD5(answer)); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#updateStatusByUsername(java.lang.String, int) */ public void updateStatusByUsername(String username, int status) { userDao.updateStatusByUsername(username, status); } /* (non-Javadoc) * * @see cn.edustar.usermgr.service.UserService#deleteUser(java.lang.String) */ public void deleteUser(String username) { if (!"".equals(username) || null != username) { userDao.deleteUser(getUserByQueryString(username)); } } }
cb0392b85d143fc9df34819ae7cc60f426a84976
4f9f13d92aa7ccb265d4356bd70895a87f44982c
/app/src/main/java/com/pointhub/db/DatabaseHelper.java
6d16c176e7eff24bb1f1be345912791fd7720c9d
[]
no_license
venugopalbeetkuri/PointHub
e58defb94af25564b7d0690082fc1d72af433b90
c67d829527b13bebffb9f0875d5b39fd551ebbd0
refs/heads/master
2020-05-29T15:15:25.172350
2016-09-06T10:11:03
2016-09-06T10:11:03
63,421,248
1
0
null
null
null
null
UTF-8
Java
false
false
5,258
java
package com.pointhub.db; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * Created by Venu on 02/05/2016. */ public class DatabaseHelper extends SQLiteOpenHelper { // Logcat tag private static final String LOG = "DatabaseHelper"; // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "pointshub"; // Table Names private static final String TABLE_POINTS = "points"; // Common column names private static final String KEY_ID = "id"; private static final String STORE_NAME = "store_name"; private static final String POINTS = "points"; private static final String LAST_VISITED = "last_visited"; // Table Create Statements // Todo table create statement private static final String CREATE_TABLE_POINTS = "CREATE TABLE " + TABLE_POINTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + STORE_NAME + " TEXT," + POINTS + " TEXT," + LAST_VISITED + " TEXT" + ")"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } private static Context context; private static DatabaseHelper helper; // private User currentUser; public static DatabaseHelper getInstance(Context context) { if(helper == null) { helper = new DatabaseHelper(context); } return helper; } @Override public void onCreate(SQLiteDatabase db) { // creating required tables db.execSQL(CREATE_TABLE_POINTS); // db.execSQL(CREATE_TABLE_USER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // on upgrade drop older tables db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_POINTS); // create new tables onCreate(db); } // ------------------------ "todos" table methods ----------------// /* * Creating a todo */ public long createPoints(Points points) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(STORE_NAME, points.getStoreName()); values.put(POINTS, points.getPoints()); values.put(LAST_VISITED, points.getLastVisited()); // insert row long todo_id = db.insert(TABLE_POINTS, null, values); return todo_id; } /* * get single todo */ public Points getPoints(String storeName) { Points point = null; try { SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT * FROM " + TABLE_POINTS + " WHERE " + STORE_NAME + " like '" + storeName + "'"; Log.e(LOG, selectQuery); Cursor c = db.rawQuery(selectQuery, null); if (c != null && c.getCount()>0) { c.moveToFirst(); } else { return point; } point = new Points(); // point.setLastVisited(c.getString(c.getColumnIndex(LAST_VISITED))); point.setStoreName(c.getString(c.getColumnIndex(STORE_NAME))); point.setPoints(c.getString(c.getColumnIndex(POINTS))); point.setId(c.getInt(c.getColumnIndex(KEY_ID))); } catch (Exception ex) { ex.printStackTrace(); } return point; } /** * getting all todos * */ public List<Points> getAllPoints() { List<Points> todos = new ArrayList<Points>(); String selectQuery = "SELECT * FROM " + TABLE_POINTS; Log.e(LOG, selectQuery); SQLiteDatabase db = this.getReadableDatabase(); Cursor c = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (c.moveToFirst()) { do { Points point = new Points(); point.setLastVisited(c.getString(c.getColumnIndex(LAST_VISITED))); point.setStoreName(c.getString(c.getColumnIndex(STORE_NAME))); point.setPoints(c.getString(c.getColumnIndex(POINTS))); point.setId(c.getInt(c.getColumnIndex(KEY_ID))); // adding to todo list todos.add(point); } while (c.moveToNext()); } return todos; } /* * Updating a todo */ public int updatePoints(Points points) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(POINTS, points.getPoints()); values.put(STORE_NAME, points.getStoreName()); values.put(LAST_VISITED, points.getLastVisited()); // updating row return db.update(TABLE_POINTS, values, STORE_NAME + " = ?", new String[] { points.getStoreName() }); } /* * Deleting a todo */ public void deletePoint(String storeName) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_POINTS, STORE_NAME + " = ?", new String[] { storeName }); } public void deletePoint(int id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_POINTS, KEY_ID + " = ?", new String[] { id+"" }); } // closing database public void closeDB() { SQLiteDatabase db = this.getReadableDatabase(); if (db != null && db.isOpen()) db.close(); } /** * get datetime * */ public String getDateTime() { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()); Date date = new Date(); return dateFormat.format(date); } }
bfc72500bdf41acea3fa2e1ad0081528b4b99beb
9cf29da65b935b21f52d9bf5cb32b3309464d429
/contact-center/app/src/main/java/com/chatopera/cc/app/model/WorkOrders.java
b30b4c63985c67366255e3ff26782c28693d382f
[ "Apache-2.0" ]
permissive
zhulong2019/cosin
6e8375debd35f7300b680cb37720aa42e5090790
324fc427ceeed244598aab9a23795ff0b4296c1c
refs/heads/master
2022-09-04T23:37:32.361714
2020-02-26T10:18:50
2020-02-26T10:18:50
243,154,653
1
0
Apache-2.0
2022-09-01T23:20:42
2020-02-26T02:57:32
Java
UTF-8
Java
false
false
11,699
java
/* * Copyright (C) 2017 优客服-多渠道客服系统 * Modifications copyright (C) 2018 Chatopera Inc, <https://www.chatopera.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.chatopera.cc.app.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import com.chatopera.cc.app.basic.MainUtils; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.elasticsearch.annotations.Document; /** * */ @Document(indexName = "cskefu", type = "workorders", createIndex = false) @Entity @Table(name = "uk_workorders") @org.hibernate.annotations.Proxy(lazy = false) public class WorkOrders extends ESBean implements UKAgg { /** * */ private static final long serialVersionUID = 1L; /** * */ private String id = MainUtils.getUUID(); private String orderno; //工单编号 private String sessionid; private String title; //标题 private String content; //内容 private float price; //问题价格 private String keyword; //关键词 private String summary; //摘要 private boolean anonymous; //修改功能 未 是否有上传附件 private boolean top; //是否置顶 private boolean essence; //是否精华 private boolean accept; //是否已采纳最佳答案 private boolean finish; //结贴 private int answers; //回答数量 private int views; //阅读数量 private int followers; //关注数量 private int collections; //收藏数量 private int comments; //评论数量 private boolean frommobile; //是否移动端提问 private String status; // 状态 private String wotype; //工单类型 private boolean datastatus; //数据状态,是否删除 , 逻辑删除 private String taskid; private String orderid; private String dataid; private String eventid; private String ani; private String cate; //工单分类 private String priority; //优先级 private Contacts contacts; private String cusid; private String initiator; //发起人 , 可以是多人发起的工单 private String bpmid; private String tags; private String accdept;// 受理部门 private String accuser; //受理人 private boolean assigned; //已分配 private String username; private String orgi; private String creater; private Date createtime = new Date(); private Date updatetime = new Date(); private String memo; private String organ; // private String agent; // private String shares; private String skill; private int rowcount; private String key; //变更用处,修改为 OrderID private User user; private User current; //当前处理人 private Organ currentorgan; //处理部门 private Favorites fav; /** * @return the id */ @Id @Column(length = 32) @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "assigned") public String getId() { return id; } @Transient public String getSessionid() { return sessionid; } public void setSessionid(String sessionid) { this.sessionid = sessionid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public boolean isAnonymous() { return anonymous; } public void setAnonymous(boolean anonymous) { this.anonymous = anonymous; } public String getWotype() { return wotype; } public void setWotype(String wotype) { this.wotype = wotype; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } @Transient public Contacts getContacts() { return contacts; } public void setContacts(Contacts contacts) { this.contacts = contacts; } public String getCusid() { return cusid; } public void setCusid(String cusid) { this.cusid = cusid; } public String getAccdept() { return accdept; } public void setAccdept(String accdept) { this.accdept = accdept; } public String getAccuser() { return accuser; } public void setAccuser(String accuser) { this.accuser = accuser; } public boolean isAssigned() { return assigned; } public void setAssigned(boolean assigned) { this.assigned = assigned; } public int getAnswers() { return answers; } public void setAnswers(int answers) { this.answers = answers; } @Column(name = "sviews") public int getViews() { return views; } public void setViews(int views) { this.views = views; } public int getFollowers() { return followers; } public void setFollowers(int followers) { this.followers = followers; } public int getCollections() { return collections; } public void setCollections(int collections) { this.collections = collections; } public int getComments() { return comments; } public void setComments(int comments) { this.comments = comments; } public boolean isFrommobile() { return frommobile; } public void setFrommobile(boolean frommobile) { this.frommobile = frommobile; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getOrgi() { return orgi; } public void setOrgi(String orgi) { this.orgi = orgi; } public String getCreater() { return creater; } public void setCreater(String creater) { this.creater = creater; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public Date getUpdatetime() { return updatetime; } public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getOrgan() { return organ; } public void setOrgan(String organ) { this.organ = organ; } public String getAgent() { return agent; } public void setAgent(String agent) { this.agent = agent; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } public void setId(String id) { this.id = id; } public String getCate() { return cate; } public void setCate(String cate) { this.cate = cate; } public boolean isTop() { return top; } public void setTop(boolean top) { this.top = top; } public boolean isEssence() { return essence; } public void setEssence(boolean essence) { this.essence = essence; } public boolean isAccept() { return accept; } public void setAccept(boolean accept) { this.accept = accept; } public boolean isFinish() { return finish; } public void setFinish(boolean finish) { this.finish = finish; } @Transient public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Transient public int getRowcount() { return rowcount; } public void setRowcount(int rowcount) { this.rowcount = rowcount; } @Transient public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getOrderno() { return orderno; } public void setOrderno(String orderno) { this.orderno = orderno; } public String getShares() { return shares; } public void setShares(String shares) { this.shares = shares; } public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public boolean isDatastatus() { return datastatus; } public void setDatastatus(boolean datastatus) { this.datastatus = datastatus; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getBpmid() { return bpmid; } public void setBpmid(String bpmid) { this.bpmid = bpmid; } @Transient public Favorites getFav() { return fav; } public void setFav(Favorites fav) { this.fav = fav; } @Transient public User getCurrent() { return current; } public void setCurrent(User current) { this.current = current; } @Transient public Organ getCurrentorgan() { return currentorgan; } public void setCurrentorgan(Organ currentorgan) { this.currentorgan = currentorgan; } @Transient public String getTaskid() { return taskid; } public void setTaskid(String taskid) { this.taskid = taskid; } @Transient public String getOrderid() { return orderid; } public void setOrderid(String orderid) { this.orderid = orderid; } public String getDataid() { return dataid; } public void setDataid(String dataid) { this.dataid = dataid; } public String getEventid() { return eventid; } public void setEventid(String eventid) { this.eventid = eventid; } public String getAni() { return ani; } public void setAni(String ani) { this.ani = ani; } }
089fb41b1ee418876d8d1cac9cf3f84cec873452
e723dd5f7cdda19ee80c4ce82e8394296c43706d
/ontrack-extension/ontrack-extension-svn/src/main/java/net/ontrack/extension/svn/dao/jdbc/IssueRevisionJdbcDao.java
f31246abde84eeccc0eedb3bb5882d8d7c5cb1b6
[ "MIT" ]
permissive
cpf/ontrack
9422a89b15238194c9ba05b78bbc6d0a4afcad8f
15a1d66c2841f964fd4cbc612c62c806631399d2
refs/heads/master
2021-01-18T08:55:47.368338
2014-01-31T10:52:31
2014-01-31T10:52:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,441
java
package net.ontrack.extension.svn.dao.jdbc; import net.ontrack.dao.AbstractJdbcDao; import net.ontrack.extension.svn.dao.IssueRevisionDao; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.util.List; @Component public class IssueRevisionJdbcDao extends AbstractJdbcDao implements IssueRevisionDao { private static final int ISSUE_KEY_MAX_LENGTH = 20; private final Logger logger = LoggerFactory.getLogger(IssueRevisionDao.class); @Autowired public IssueRevisionJdbcDao(DataSource dataSource) { super(dataSource); } @Override @Transactional public void link(long revision, String key) { if (StringUtils.isBlank(key)) { logger.warn("Cannot insert a null or blank key (revision {})", revision); } else if (key.length() > ISSUE_KEY_MAX_LENGTH) { logger.warn("Cannot insert a key longer than {} characters: {} for revision {}", ISSUE_KEY_MAX_LENGTH, key, revision); } else { getNamedParameterJdbcTemplate().update( "INSERT INTO REVISION_ISSUE (REVISION, ISSUE) VALUES (:revision, :key)", params("revision", revision).addValue("key", key)); } } @Override @Transactional(readOnly = true) public List<String> findIssuesByRevision(long revision) { return getNamedParameterJdbcTemplate().queryForList( "SELECT ISSUE FROM REVISION_ISSUE WHERE REVISION = :revision ORDER BY ISSUE", params("revision", revision), String.class ); } @Override @Transactional(readOnly = true) public boolean isIndexed(String key) { return getFirstItem( "SELECT ISSUE FROM REVISION_ISSUE WHERE ISSUE = :key", params("key", key), String.class) != null; } @Override @Transactional(readOnly = true) public List<Long> findRevisionsByIssue(String key) { return getNamedParameterJdbcTemplate().queryForList( "SELECT REVISION FROM REVISION_ISSUE WHERE ISSUE = :key ORDER BY REVISION DESC", params("key", key), Long.class); } }
cfdb51c0b63a9472a7f3e2037e14b94d9d09bb98
776ad0b5e19f8bd24cb662d12cebcef69449f18b
/examples/SimpleUI4/src/com/example/simpleui4/ShowMessageActivity.java
7e84062a40e833c4abc09da44199d3e54acfc679
[]
no_license
chinchih/android_class
7f78a37094e1962c7ad90796324a021eb4032250
b687deaf25a9369fa23d1c1d11afefd7b9b97892
refs/heads/master
2021-01-16T22:35:39.401496
2013-04-28T18:33:16
2013-04-28T18:33:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,409
java
package com.example.simpleui4; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; public class ShowMessageActivity extends Activity { private ListView listView; private MessageDBHelper dbhelp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.message); listView = (ListView) findViewById(R.id.listView1); dbhelp = new MessageDBHelper(this); Intent intent = this.getIntent(); String text = intent.getStringExtra("message"); boolean isEncrypt = intent.getBooleanExtra("isEncrypt", false); dbhelp.insert(new Message(text, isEncrypt)); /* 兩種方法實作 Adapter */ // listView.setAdapter(getSimpleAdapter()); listView.setAdapter(getCursorAdapter()); } public SimpleCursorAdapter getCursorAdapter() { Cursor c = dbhelp.getMessagesCursor(); String[] from = new String[] { "text", "isEncrypt" }; int[] to = new int[] { R.id.textView1, R.id.textView2 }; /* * 這個建構方法在 API level 11 的時候被列為不建議使用。 * 建議改用 LoaderManager 搭配 CursorLoader。 */ SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listview_item, c, from, to); return cursorAdapter; } public SimpleAdapter getSimpleAdapter() { List<Map<String, String>> data = new ArrayList<Map<String, String>>(); List<Message> messages = dbhelp.getMessages(); for (Message mes : messages) { Map<String, String> t = new HashMap<String, String>(); t.put("text", mes.getText()); t.put("isEncrypt", String.valueOf(mes.isEncrypt())); data.add(t); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, R.layout.listview_item, new String[] { "text", "isEncrypt" }, new int[] { R.id.textView1, R.id.textView2 }); return simpleAdapter; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
faf8cb47a4a65951f22fa83f02b62c1aadcd5e47
6710524ee90cbb4921324f4f05600a2e0920a12c
/app/src/main/java/com/example/test/db_project/Main2Activity.java
576f9145d2b4c398e38dc49e6a166fe1f95e4975
[]
no_license
moonkihun/DB_Project
40cd5375863e2dbe61224c33a932b29775720700
d2eb504fb4d6ea1bea9b2530ee9a91ec610d24cf
refs/heads/master
2020-04-08T07:30:02.887961
2018-11-26T08:39:57
2018-11-26T08:39:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
710
java
package com.example.test.db_project; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } public void Reservation(View v){ Intent intent_01 = new Intent(getApplicationContext(), Reservation.class); startActivity(intent_01); } public void Room(View v){ Intent intent_02 = new Intent(getApplicationContext(), Room.class); startActivity(intent_02); } }
36e7e238d4c5620c57122d1e54ce4fc86afbecd6
f216214c9cf74451fa722587ef0abd138515f122
/app/src/mock/java/com/dnod/simplemovie/service/impl/api/ImagesMockMarshaller.java
db8150b8050dd847727846a0c3650509b65c9e29
[]
no_license
DnoD/SimpleMovie
f88222d79e02eaec10c4635412dbe65af23053bb
4018793ccad78f1077ef2a0049d9eb8d248695ca
refs/heads/develop
2021-01-19T22:47:41.763330
2018-03-01T15:05:23
2018-03-01T15:05:23
83,779,842
0
0
null
null
null
null
UTF-8
Java
false
false
923
java
package com.dnod.simplemovie.service.impl.api; import android.text.TextUtils; import com.dnod.simplemovie.data.Images; import com.dnod.simplemovie.data.Movie; import com.dnod.simplemovie.service.Marshaller; import com.dnod.simplemovie.service.impl.api.dto.ImagesMockDTO; import com.dnod.simplemovie.service.impl.api.dto.MovieMockDTO; import com.dnod.simplemovie.utils.TimeUtils; final class ImagesMockMarshaller extends Marshaller<ImagesMockDTO, Images> { private static final ImagesMockMarshaller instance = new ImagesMockMarshaller(); static ImagesMockMarshaller getInstance() { return instance; } @Override public Images fromEntity(ImagesMockDTO entity) { return new Images().setOriginalUrl(entity.getOriginalUrl()) .setThumbnailUrl(entity.getThumbnailUrl()); } @Override public ImagesMockDTO toEntity(Images entity) { return null; } }
8de80edb4c4a08663ca40b23bbfd12a5a5c2da6a
0fa2722cc49e4222af6e921ae2cae2de3206b081
/Core/src/id/base/app/util/ReflectionFunction.java
0829c60cfd744d4b7ee5ecbc5f0ff7ec954086c3
[]
no_license
utharamadhan/SimpleRestFramework
185a8a08bf7c91e0a851d9ae088e8cce14b6a1f0
153df491517d08615506bc4d84bf1b7cbe9f54bd
refs/heads/master
2021-01-11T13:32:42.832023
2017-02-10T04:36:59
2017-02-10T04:36:59
81,526,307
0
0
null
null
null
null
UTF-8
Java
false
false
4,751
java
package id.base.app.util; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URLEncoder; import javax.persistence.Column; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReflectionFunction { private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionFunction.class); public static String getColumnName(Class domainClass, String fieldName) { try { Method method = domainClass.getMethod("get"+Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1), null); Column column = method.getAnnotation(Column.class); return column.name(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void setProperties(Class domainClass, String prop, String value) { try { Field field = domainClass.getField(prop); if (field.getType().isAssignableFrom(Integer.class) || field.getType().isAssignableFrom(int.class)) { field.setInt(null, Integer.valueOf(value)); } else if (field.getType().isAssignableFrom(Long.class) || field.getType().isAssignableFrom(long.class)) { field.setLong(null, Integer.valueOf(value)); } else if (field.getType().isAssignableFrom(Boolean.class) || field.getType().isAssignableFrom(boolean.class)) { field.setBoolean(null, Boolean.parseBoolean(value)); } else if (field.getType().isAssignableFrom(Double.class) || field.getType().isAssignableFrom(double.class)) { field.setDouble(null, Double.parseDouble(value)); } else { // string value field.set(null, value); } } catch (SecurityException e) { e.printStackTrace(); LOGGER.error("Failed setting domain property due to security. Please change checkMemberAccess(this, Member.PUBLIC) or checkPackageAccess() to allow the access."); } catch (NoSuchFieldException e) { LOGGER.error("Field {} has not been declared yet in {}.", new Object[] {prop, domainClass.getName()}); } catch (IllegalArgumentException e) { e.printStackTrace(); LOGGER.error("Illegal value is given for field {}. The value given is {}", new Object[] {prop, value}); } catch (IllegalAccessException e) { e.printStackTrace(); LOGGER.error("Failed setting domain property due to field {} is inaccessible.", prop); } } public static Object getPropertyValue(Class domainClass, String prop){ Object value = null; try { Field field = domainClass.getField(prop); if (field.getType().isAssignableFrom(Integer.class) || field.getType().isAssignableFrom(int.class)) { value = field.getInt(null); } else if (field.getType().isAssignableFrom(Long.class) || field.getType().isAssignableFrom(long.class)) { value = field.getLong(null); } else if (field.getType().isAssignableFrom(Boolean.class) || field.getType().isAssignableFrom(boolean.class)) { value = field.getBoolean(null); } else if (field.getType().isAssignableFrom(Double.class) || field.getType().isAssignableFrom(double.class)) { value = field.getDouble(null); } else { // string value value = field.get(null); } } catch (SecurityException e) { e.printStackTrace(); LOGGER.error("Failed setting domain property due to security. Please change checkMemberAccess(this, Member.PUBLIC) or checkPackageAccess() to allow the access."); } catch (NoSuchFieldException e) { try { LOGGER.error("Field {} has not been declared yet in {}.", new Object[] {URLEncoder.encode(StringUtils.trimToEmpty(prop), "UTF-8"), domainClass.getName()}); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } catch (IllegalAccessException e) { e.printStackTrace(); try { if (LOGGER.isErrorEnabled()) LOGGER.error("Failed setting domain property due to field {} is inaccessible.", URLEncoder.encode(StringUtils.trimToEmpty(prop), "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } return value; } public static Field getField(Class cc, String name) throws NoSuchFieldException{ Field res = null; try{ res = cc.getDeclaredField(name); return res; }catch(NoSuchFieldException e){ Class c = cc.getSuperclass(); if (c != null) { try{ res = getField(c, name); return res; }catch(NoSuchFieldException ee){ throw new NoSuchFieldException(name); } }else{ throw new NoSuchFieldException(name); } } } }
9cb337273ee152174dbfa0090467898cbdc6996e
1a4770c215544028bad90c8f673ba3d9e24f03ad
/second/quark/src/main/java/com/airbnb/lottie/ax.java
99f0b227ca0fe2297b9c1cf8aa7e1a0471a5a743
[]
no_license
zhang1998/browser
e480fbd6a43e0a4886fc83ea402f8fbe5f7c7fce
4eee43a9d36ebb4573537eddb27061c67d84c7ba
refs/heads/master
2021-05-03T06:32:24.361277
2018-02-10T10:35:36
2018-02-10T10:35:36
120,590,649
8
10
null
null
null
null
UTF-8
Java
false
false
592
java
package com.airbnb.lottie; import android.graphics.PointF; import org.json.JSONArray; import org.json.JSONObject; /* compiled from: ProGuard */ final class ax implements ay<PointF> { static final ax a = new ax(); private ax() { } public final /* synthetic */ Object a(Object obj, float f) { if (obj instanceof JSONArray) { return bb.a((JSONArray) obj, f); } if (obj instanceof JSONObject) { return bb.a((JSONObject) obj, f); } throw new IllegalArgumentException("Unable to parse point from " + obj); } }
4449fe65b9c82ce507a1f7af20a2b024d21ee9a5
12c7451269650ca797831a3ae627c97b46c65fe6
/src/main/java/com/example/resumegeneratorbackend/service/UserDetailServices.java
a6133a28249b127c0756c3445db5f77da6ab421b
[]
no_license
cebed/Resume-Generator-Backend
7f507de3297e0e300cd30713387095ba685af2e1
a69b1fa63ce00b206e355b1539c6bab23b446c5c
refs/heads/master
2023-08-07T20:48:53.018956
2019-11-20T18:31:30
2019-11-20T18:31:30
176,706,477
0
0
null
2023-07-21T20:19:28
2019-03-20T10:10:35
Java
UTF-8
Java
false
false
1,195
java
package com.example.resumegeneratorbackend.service; import com.example.resumegeneratorbackend.model.Users; import com.example.resumegeneratorbackend.repository.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserDetailServices implements UserDetailsService { @Autowired private UsersRepository usersRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Users users = usersRepository.findByUsername(username); if(users==null) new UsernameNotFoundException("User not found"); return users; } @Transactional public Users loadUserById(Long id){ Users users = usersRepository.getById(id); if(users==null) new UsernameNotFoundException("User not found"); return users; } }
fb91f0740b2e15a5e7a946e3e2160c2acd014671
1e7b2da3b11609894d0cb1e5fd841746f411f7f8
/webpro/src/com/nathcorp/webpro/servlett/LoginPageServlet.java
049defb22168826f1d6704ea9f88818a94487615
[]
no_license
pawankumarsharm/Nathcorp
f97583b47a16b88b9cb90691d882d572ba43adf5
cbe6f1e829fa93e9365dfe6e45453f768417bd53
refs/heads/master
2022-05-29T19:16:01.669416
2020-04-25T03:53:32
2020-04-25T03:53:32
258,469,749
0
0
null
null
null
null
UTF-8
Java
false
false
920
java
package com.nathcorp.webpro.servlett; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @WebServlet("/login.html") public class LoginPageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies=req.getCookies(); if(cookies!=null) { for (Cookie cookie : cookies) { if(cookie.getName().equals("alwaysRemember")) { } } } }//end of do Get @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }//end of LoginServlet
da1424b6eaf8b519ed73548924fc3bbd5d04641d
faf7d2e5ac7c5fe55f005f08a2cadf9e26e8cb86
/iflytransporter-common/src/main/java/com/iflytransporter/common/bean/Company.java
6068ac2ba8cf9dd293a5604a52310299ec1bdc8a
[ "Apache-2.0" ]
permissive
zhangyiran0314/20180316
7ab39b4eb49048d79bf795b0fc7212aa78a94241
bddf49414cbc25f43fedf8b708c70f3c0e9cb0d1
refs/heads/master
2021-09-09T17:59:23.816269
2018-03-18T19:08:38
2018-03-18T19:08:38
110,239,220
0
0
null
null
null
null
UTF-8
Java
false
false
2,542
java
package com.iflytransporter.common.bean; import com.alibaba.fastjson.JSONObject; import com.iflytransporter.common.base.BaseEntity; public class Company extends BaseEntity{ private static final long serialVersionUID = 1L; private String name; private String code; private String email; private String address; private Integer status; private String attachmentId1; private String userId; private Integer userType; private String attachmentId2;//spad照片 private String attachmentId3;//公司保单 private Integer amount;//保险额度 public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getAttachmentId1() { return attachmentId1; } public void setAttachmentId1(String attachmentId1) { this.attachmentId1 = attachmentId1 == null ? null : attachmentId1.trim(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAttachmentId2() { return attachmentId2; } public void setAttachmentId2(String attachmentId2) { this.attachmentId2 = attachmentId2; } public String getAttachmentId3() { return attachmentId3; } public void setAttachmentId3(String attachmentId3) { this.attachmentId3 = attachmentId3; } public Integer getUserType() { return userType; } public void setUserType(Integer userType) { this.userType = userType; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } @Override public String toString() { return JSONObject.toJSONString(this).toString(); } }
464c5c8e8a9429f0790d660832ea68318ef56987
3955f3bc4b1e9c41ffabb34fcdbfbfb3a8b2f77c
/bizcore/WEB-INF/youbenben_core_src/com/youbenben/youbenben/retailstoreinvestmentinvitation/RetailStoreInvestmentInvitationMapper.java
1852662f010b0039eddcf87bce41b4230665efd9
[]
no_license
1342190832/youbenben
c9ba34117b30988419d4d053a35960f35cd2c3f0
f68fb29f17ff4f74b0de071fe11bc9fb10fd8744
refs/heads/master
2022-04-25T10:17:48.674515
2020-04-25T14:22:40
2020-04-25T14:22:40
258,133,780
0
0
null
null
null
null
UTF-8
Java
false
false
2,230
java
package com.youbenben.youbenben.retailstoreinvestmentinvitation; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.math.BigDecimal; import com.youbenben.youbenben.BaseRowMapper; public class RetailStoreInvestmentInvitationMapper extends BaseRowMapper<RetailStoreInvestmentInvitation>{ protected RetailStoreInvestmentInvitation internalMapRow(ResultSet rs, int rowNumber) throws SQLException{ RetailStoreInvestmentInvitation retailStoreInvestmentInvitation = getRetailStoreInvestmentInvitation(); setId(retailStoreInvestmentInvitation, rs, rowNumber); setComment(retailStoreInvestmentInvitation, rs, rowNumber); setVersion(retailStoreInvestmentInvitation, rs, rowNumber); return retailStoreInvestmentInvitation; } protected RetailStoreInvestmentInvitation getRetailStoreInvestmentInvitation(){ return new RetailStoreInvestmentInvitation(); } protected void setId(RetailStoreInvestmentInvitation retailStoreInvestmentInvitation, ResultSet rs, int rowNumber) throws SQLException{ //there will be issue when the type is double/int/long String id = rs.getString(RetailStoreInvestmentInvitationTable.COLUMN_ID); if(id == null){ //do nothing when nothing found in database return; } retailStoreInvestmentInvitation.setId(id); } protected void setComment(RetailStoreInvestmentInvitation retailStoreInvestmentInvitation, ResultSet rs, int rowNumber) throws SQLException{ //there will be issue when the type is double/int/long String comment = rs.getString(RetailStoreInvestmentInvitationTable.COLUMN_COMMENT); if(comment == null){ //do nothing when nothing found in database return; } retailStoreInvestmentInvitation.setComment(comment); } protected void setVersion(RetailStoreInvestmentInvitation retailStoreInvestmentInvitation, ResultSet rs, int rowNumber) throws SQLException{ //there will be issue when the type is double/int/long Integer version = rs.getInt(RetailStoreInvestmentInvitationTable.COLUMN_VERSION); if(version == null){ //do nothing when nothing found in database return; } retailStoreInvestmentInvitation.setVersion(version); } }
c9108b43c56f0af98ec81229a08ca0220056f330
c81022adf05f8476a57237e5fc4a19362df73aab
/Client.java
3ae326160459ac0509e868369028240faed0e178
[]
no_license
dullbenz/ProjetSysteme_d-exploitation
db171977ca4cf0e6873b048e7daa6c3a7609a8b9
e5c46353d9f2288ecbd76791d81c4af054cb0f51
refs/heads/master
2022-11-20T06:18:51.315620
2020-07-26T22:24:18
2020-07-26T22:24:18
282,742,116
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
package com.socket; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class Client extends ClientServer { private String servadd = "127.0.0.1"; public Client() throws UnknownHostException, IOException { System.out.println("Connecting to server..."); socket = new Socket(servadd, Server.port); System.out.println("Connection established"); } public void setClose() throws IOException { socket.close(); } }
139c33c47259df6385e08931485035f0dc5e822d
b991b1eb27db9e6c81e3a477d1911ef29b446c7a
/src/main/java/com/yichen/jwtauthentication/controller/AuthRestAPIs.java
da087620e36d6caa3a5218d3bd4d8c3ced217d0f
[]
no_license
yichenliang/Todo_Backend
90caa7cf8691db3765eb7db170c1412aa825f9d3
7d771736719825cb199dd1b8d3bb4be096eed500
refs/heads/master
2020-04-28T01:33:13.786082
2019-03-10T18:21:33
2019-03-10T18:21:33
174,777,924
0
0
null
null
null
null
UTF-8
Java
false
false
4,151
java
package com.yichen.jwtauthentication.controller; import java.util.HashSet; import java.util.Set; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yichen.jwtauthentication.message.request.LoginForm; import com.yichen.jwtauthentication.message.request.SignUpForm; import com.yichen.jwtauthentication.message.response.JwtResponse; import com.yichen.jwtauthentication.message.response.ResponseMessage; import com.yichen.jwtauthentication.model.Role; import com.yichen.jwtauthentication.model.RoleName; import com.yichen.jwtauthentication.model.User; import com.yichen.jwtauthentication.repository.RoleRepository; import com.yichen.jwtauthentication.repository.UserRepository; import com.yichen.jwtauthentication.security.jwt.JwtProvider; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api/auth") public class AuthRestAPIs { @Autowired AuthenticationManager authenticationManager; @Autowired UserRepository userRepository; @Autowired RoleRepository roleRepository; @Autowired PasswordEncoder encoder; @Autowired JwtProvider jwtProvider; @PostMapping("/signin") public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginForm loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtProvider.generateJwtToken(authentication); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities())); } @PostMapping("/signup") public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpForm signUpRequest) { if (userRepository.existsByUsername(signUpRequest.getUsername())) { return new ResponseEntity<>(new ResponseMessage("Fail -> Username is already taken!"), HttpStatus.BAD_REQUEST); } if (userRepository.existsByEmail(signUpRequest.getEmail())) { return new ResponseEntity<>(new ResponseMessage("Fail -> Email is already in use!"), HttpStatus.BAD_REQUEST); } // Creating user's account User user = new User(signUpRequest.getName(), signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find.")); roles.add(adminRole); break; case "pm": Role pmRole = roleRepository.findByName(RoleName.ROLE_PM) .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find.")); roles.add(pmRole); break; default: Role userRole = roleRepository.findByName(RoleName.ROLE_USER) .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find.")); roles.add(userRole); } }); user.setRoles(roles); userRepository.save(user); return new ResponseEntity<>(new ResponseMessage("User registered successfully!"), HttpStatus.OK); } }
6d0842d07f515f21b2dc40c0e0294c94d470e544
b8ecb116ed5eb72343d31b66ab0ced0468a7cde1
/src/util/Duet.java
966029fb515d7ad01db8dc7ae8f341622f6ce8f6
[]
no_license
CLOVIS-AI/PMagic
c83dce6626177da8f99003eccbd87a55ce0287a0
ff6eca33c714e7bd3b450d8b754490f42231c098
refs/heads/master
2021-08-10T12:06:16.305550
2017-11-12T14:57:45
2017-11-12T14:57:45
110,441,417
0
0
null
null
null
null
UTF-8
Java
false
false
1,921
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 util; import java.util.Objects; /** * A duet utility class, working with two elements : t and u, of respective types T and U. * @author CLOVIS */ public class Duet<T, U> { private T first; private U second; /** * Creates a Duet object with the two values set. * @param t first element * @param u second element */ public Duet(T t, U u){ first = t; second = u; } /** * Get the first element. * @return t */ public T t(){ return first; } /** * Set the first element. * @param n new value of t */ public void t(T n){ first = n; } /** * Get the second element. * @return u */ public U u(){ return second; } /** * Set the second element. * @param n new value of u */ public void u(U n){ second = n; } @Override public String toString(){ return "{t=" + first.toString() + ";u=" + second.toString() + "}"; } @Override public int hashCode() { int hash = 3; hash = 17 * hash + Objects.hashCode(this.first); hash = 17 * hash + Objects.hashCode(this.second); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Duet<?, ?> other = (Duet<?, ?>) obj; if (!Objects.equals(this.first, other.first)) { return false; } if (!Objects.equals(this.second, other.second)) { return false; } return true; } }
fe579cc836357e2c2c54ee601e363265af8f4105
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/elastic--elasticsearch/610ce078fb3c84c47d6d32aff7d77ba850e28f9d/before/IndexFieldDataCache.java
573d66056057fb95eb03d149711c1a492d038bbd
[]
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
2,773
java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index.fielddata; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.util.Accountable; import org.elasticsearch.index.mapper.FieldMapper; /** * A simple field data cache abstraction on the *index* level. */ public interface IndexFieldDataCache { <FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(AtomicReaderContext context, IFD indexFieldData) throws Exception; <FD extends AtomicFieldData, IFD extends IndexFieldData.Global<FD>> IFD load(final IndexReader indexReader, final IFD indexFieldData) throws Exception; /** * Clears all the field data stored cached in on this index. */ void clear(); /** * Clears all the field data stored cached in on this index for the specified field name. */ void clear(String fieldName); void clear(Object coreCacheKey); interface Listener { void onLoad(FieldMapper.Names fieldNames, FieldDataType fieldDataType, Accountable ramUsage); void onUnload(FieldMapper.Names fieldNames, FieldDataType fieldDataType, boolean wasEvicted, long sizeInBytes); } class None implements IndexFieldDataCache { @Override public <FD extends AtomicFieldData, IFD extends IndexFieldData<FD>> FD load(AtomicReaderContext context, IFD indexFieldData) throws Exception { return indexFieldData.loadDirect(context); } @Override @SuppressWarnings("unchecked") public <FD extends AtomicFieldData, IFD extends IndexFieldData.Global<FD>> IFD load(IndexReader indexReader, IFD indexFieldData) throws Exception { return (IFD) indexFieldData.localGlobalDirect(indexReader); } @Override public void clear() { } @Override public void clear(String fieldName) { } @Override public void clear(Object coreCacheKey) { } } }
dca9de5e6ae51edce5e581b04760a06b5c232291
578c73416f27d6a96314f09d2b7d5e6e6bb268a2
/Booking/src/DAO/Reader.java
4990fd54fc298bc607f7811a0c63a89f019ca365
[]
no_license
byntmr/Booking
5e19bdb9300d522858b305937cb8183c49af80dc
a477f3651da393fb5e5ad3defb7bc5c4359cf516
refs/heads/master
2020-09-12T04:28:30.837454
2019-11-17T20:23:33
2019-11-17T20:23:33
222,083,291
0
0
null
null
null
null
UTF-8
Java
false
false
4,650
java
package DAO; import Flights.Booking; import Flights.Flight; import Flights.User; import java.io.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Reader { public List<Flight> Read_Flight() throws IOException { LinkedList<Flight> Res = new LinkedList<>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("src/flights.txt"))); String line; while ((line = bufferedReader.readLine()) != null) { int number = 0; StringBuilder Id = new StringBuilder(); StringBuilder City = new StringBuilder(); StringBuilder Start = new StringBuilder(); StringBuilder Hour = new StringBuilder(); StringBuilder minute = new StringBuilder(); StringBuilder Num_of_Seats = new StringBuilder(); for (char c : line.toCharArray()) { if (c != ',' && c != ':') { if (number == 0) { Id.append(c); } if (number == 2) { Start.append(c); } if (number == 2) { City.append(c); } if (number == 3) { Hour.append(c); } if (number == 4) { minute.append(c); } if (number == 5) { Num_of_Seats.append(c); } } else number++; } Res.add(new Flight(Integer.parseInt(Id.toString()),Start.toString(),City.toString(),Integer.parseInt(Hour.toString()),Integer.parseInt(minute.toString()),Integer.parseInt(Num_of_Seats.toString()))); } return new ArrayList<>(Res); } public List<Booking> Read_Booking() throws IOException { LinkedList<Booking> result = new LinkedList<>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("src/bookings.txt"))); String line = ""; while ((line = bufferedReader.readLine()) != null) { int number = 0; StringBuilder stringBuilder_Name = new StringBuilder(); StringBuilder StringBuilder_Surname = new StringBuilder(); StringBuilder StringBuilder_Destination = new StringBuilder(); StringBuilder StringBuilder_Start = new StringBuilder(); StringBuilder StringBuilder_Hour = new StringBuilder(); StringBuilder StringBuilder_minunte = new StringBuilder(); StringBuilder stringBuilder_Numofseats = new StringBuilder(); StringBuilder ID = new StringBuilder(); StringBuilder sb_id_booking = new StringBuilder(); for (char ch : line.toCharArray()) { if (ch != ',' && ch != ':') { if (number == 0) { sb_id_booking.append(ch); } if (number == 1) { stringBuilder_Name.append(ch); } if (number == 2) { StringBuilder_Surname.append(ch); } if (number == 3) { ID.append(ch); } if (number == 4) { StringBuilder_Destination.append(ch); } if (number == 5) { StringBuilder_Hour.append(ch); } if (number == 6) { StringBuilder_minunte.append(ch); } if (number == 7) { stringBuilder_Numofseats.append(ch); } } else number++; } result.add(new Booking(new User(stringBuilder_Name.toString(), StringBuilder_Surname.toString()), new Flight(Integer.parseInt(ID.toString()),StringBuilder_Start.toString(), StringBuilder_Destination.toString(), Integer.parseInt(StringBuilder_Hour.toString()), Integer.parseInt(StringBuilder_minunte.toString()), Integer.parseInt(stringBuilder_Numofseats.toString())), Integer.parseInt(sb_id_booking.toString()))); } return result; } }
b4c9f5cc6a2940c66bdff9f908265296bc843d8c
abf09f42e594f943927530d4d7dbd08dda436de5
/allPattern/src/patternDemo/PatternDemo24.java
587ae85af41c74c4434329933e4cebc04182350b
[]
no_license
mortozafsti/Jsp-Web-Project
e232148120b026a8eeb87fa3b2582e36c356e0fc
3920d6a4d9161609a2dc9030ba901728363e5423
refs/heads/master
2022-12-02T19:33:56.584746
2019-09-23T08:06:55
2019-09-23T08:06:55
160,851,448
0
0
null
2022-11-24T09:19:21
2018-12-07T16:53:00
Java
UTF-8
Java
false
false
480
java
package patternDemo; public class PatternDemo24 { public static void main(String[] args) { int row = 4, col = 7; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (i == 0 || j == 0 || i == row - 1 || j == col - 1) { System.out.print("0"); } else { System.out.print("1"); } } System.out.println(""); } } }
35f83cda2d3a0ce3e4c2b1278d77eae9a79012b9
50c83fb7897213e7bd21621f556b98edbb44775e
/rs289/src/main/java/org/hannes/scoundrel/util/ApplicationResources.java
b056a3d0dbe7510b7ed3d84ac0cdb9f0626208be
[]
no_license
hanz0r/rs289
ae40f63f94f5c7e6c5f0792c818bbffe60b53d70
fc31942f6d36943ba77cce3d5512b97153b69d02
refs/heads/master
2021-01-18T13:59:30.879804
2015-09-14T15:24:03
2015-09-14T15:24:03
41,672,589
0
0
null
null
null
null
UTF-8
Java
false
false
1,002
java
package org.hannes.scoundrel.util; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; @ApplicationScoped public class ApplicationResources { /** * The entity manager factory */ private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("test"); /** * Creates a new entity manager when an injection call has been made * * @return */ @Produces public EntityManager produceManager() { return factory.createEntityManager(); } /** * Disposes the entitymanager. Closes the entity manager factory, the entity manager and commits the current active transaction * * @param manager */ public void destroy(@Disposes EntityManager manager) { manager.getTransaction().commit(); manager.close(); } }
789b7c74bae2509afb04f43f856f123e7ed61e2b
95c987aa39866a07f2cbd0a21684a3929b7ff715
/android-app/gen/com/example/gps_zappers/R.java
8d6d58461ddd19d74d07b2088c1078e6c50ca3d1
[]
no_license
Codeniti/Map-my-village
17c7ee3fe608874a7b5b81899a48bbb21bacb02f
f83256ab9a4bec36cb67d3074e149c0fb889246c
refs/heads/master
2020-04-04T13:58:23.849221
2014-03-11T02:18:48
2014-03-11T02:18:48
17,309,462
0
1
null
2014-03-11T02:18:48
2014-03-01T06:37:36
Java
UTF-8
Java
false
false
2,732
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.gps_zappers; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int Start_tracking=0x7f080002; public static final int action_settings=0x7f080003; public static final int fullscreen_content_controls=0x7f080000; public static final int textview1=0x7f080001; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; public static final int start_tracking=0x7f050003; public static final int stop_tracking=0x7f050004; } 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=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
285436c97dd5d4881783b785386580a4349ffc4a
8023fdab8d8142d9b4d34bf5c62b4aa65b54dfe7
/LPC-v2/app/src/main/java/com/example/ives/lpc_v2/Layouts/InteressadoDialogFragment.java
228494357f33dc00fbf74297db7d6ad9f57e86b6
[]
no_license
mhcabral/LPC-v2
2d7b156b754d23988aa4b56bc01847f452fc8a91
4521391ff6088683056ce13a375b23c637d0103c
refs/heads/master
2021-01-10T07:33:39.486508
2016-01-29T21:32:43
2016-01-29T21:32:43
50,674,401
0
0
null
null
null
null
UTF-8
Java
false
false
6,716
java
package com.example.ives.lpc_v2.Layouts; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.ives.lpc_v2.Models.BD; import com.example.ives.lpc_v2.Models.Dialogs; import com.example.ives.lpc_v2.R; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import java.util.Calendar; import java.util.Date; /** * Created by Ives on 15/10/2015. */ public class InteressadoDialogFragment extends DialogFragment { private Button btnCancelar; private int year, month, day; private TextView txtDataNascimento; private TextView txtTitle; private EditText edtEndereco; private EditText edtTelefone; private Button btnDataNascimento; private Button btnAtualizar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(false); initDateHourCalendar(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.interessado_dialog_fragment, null); int width = getResources().getDimensionPixelSize(R.dimen.popup_width); int height = getResources().getDimensionPixelSize(R.dimen.popup_height); view.setMinimumWidth(width); view.setMinimumHeight(height); txtTitle = (TextView) view.findViewById(R.id.txtTitle); txtTitle.setText("Interessado: " + Dialogs.getInteressado_dialog_title()); txtDataNascimento = (TextView)view.findViewById(R.id.txtDataNascimento); edtEndereco = (EditText) view.findViewById(R.id.edtEndereco); edtTelefone = (EditText) view.findViewById(R.id.edtTelefone); //verificacaodados(); btnDataNascimento = (Button)view.findViewById(R.id.btnDataNascimento); btnDataNascimento.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initDateHourCalendar(); Calendar cDefault = Calendar.getInstance(); cDefault.set(year, month, day); DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year2, int monthOfYear, int dayOfMonth) { year = year2; txtDataNascimento.setText( "Data de Nascimento:" + "\n\n" + (day < 10 ? "0" + day : day) + "/" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) + "/" + year ); } }, cDefault.get(Calendar.YEAR), cDefault.get(Calendar.MONTH), cDefault.get(Calendar.DAY_OF_MONTH) ); //Calendar cMin = Calendar.getInstance(); //cMin.set(1900,1,1); //datePickerDialog.setMinDate(cMin); datePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { year = month = day = 0; txtDataNascimento.setText(""); } }); datePickerDialog.show(getActivity().getFragmentManager(), "Data"); } }); btnCancelar = (Button) view.findViewById(R.id.btnCancelarI); btnCancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); btnAtualizar = (Button) view.findViewById(R.id.btnAtualizarI); btnAtualizar.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { BD.getInteressado_selecionado().setEndereco(edtEndereco.getText().toString()); BD.getInteressado_selecionado().setTelefone(edtTelefone.getText().toString()); BD.getInteressado_selecionado().setData_nascimento((Date) new Date(year,month,day)); Log.i("ScriptInteressado", BD.getInteressado_selecionado().toString2()); Toast.makeText(getContext(), "Dados Atualizados", Toast.LENGTH_SHORT); BD.limpaInteressado_selecionado(); dismiss(); } }); return view; } private void verificacaodados() { if(BD.getInteressado_selecionado().getData_nascimento() != null){ txtDataNascimento.setText(BD.getInteressado_selecionado().getData_nascimento().toString()); } if(BD.getInteressado_selecionado().getEndereco()!=null){ edtEndereco.setText(BD.getInteressado_selecionado().getEndereco()); } if(BD.getInteressado_selecionado().getTelefone()!=null){ edtTelefone.setText(BD.getInteressado_selecionado().getTelefone()); } } public void initDateHourCalendar() { if(year == 0) { Calendar c = Calendar.getInstance(); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); day = c.get(Calendar.DAY_OF_MONTH); } } }
22987927cee8f6d651891fa7d89593e6c93b39d0
552d28e539386e6401d19c2a641d046bbf32fe2c
/app/src/main/java/com/shukhratKhaydarov/sudoku/Classifier.java
4b88f60f6193c632b33ac07b83b7c6686056edc0
[]
no_license
SeanKh/ScanSolveSudoku
3797fcd162e66a0b8eb298ed01a0999109259a6b
c25401417a2ef5046d4609e1f5c835292e786fbc
refs/heads/master
2022-11-30T12:46:30.720144
2020-08-05T19:18:19
2020-08-05T19:18:19
261,583,991
1
0
null
null
null
null
UTF-8
Java
false
false
2,648
java
package com.shukhratKhaydarov.sudoku; import android.content.res.AssetManager; import android.util.Log; import org.tensorflow.contrib.android.TensorFlowInferenceInterface; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Classifier { // Only returns if at least this confidence private static final float THRESHOLD = 0.1f; private static final String TAG = "Classifier"; private TensorFlowInferenceInterface tfHelper; private String inputName; private String outputName; private int inputSize; private List<String> labels; private float[] output; private String[] outputNames; static private List<String> readLabels(Classifier c, AssetManager am, String fileName) throws IOException { BufferedReader br = null; br = new BufferedReader(new InputStreamReader(am.open(fileName))); String line; List<String> labels = new ArrayList<>(); while ((line = br.readLine()) != null) { labels.add(line); } br.close(); return labels; } static public Classifier create(AssetManager assetManager, String modelPath, String labelPath, int inputSize, String inputName, String outputName) throws IOException { Classifier classifier = new Classifier(); classifier.inputName = inputName; classifier.outputName = outputName; String labelFile = labelPath.split("file:///android_asset/")[1]; classifier.labels = readLabels(classifier, assetManager, labelFile); classifier.tfHelper = new TensorFlowInferenceInterface(assetManager, modelPath); int numClasses = 10; classifier.inputSize = inputSize; classifier.outputNames = new String[]{outputName}; classifier.outputName = outputName; classifier.output = new float[numClasses]; return classifier; } public Classification recognize(final float[] pixels) { tfHelper.feed(inputName, pixels, new long[]{inputSize * inputSize}); tfHelper.run(outputNames); tfHelper.fetch(outputName, output); // Find the best classification Classification ans = new Classification(); for (int i = 0; i < output.length; ++i) { Log.d(TAG, String.format("Class: %s Conf: %f", labels.get(i), output[i])); if (output[i] > THRESHOLD && output[i] > ans.getConf()) { ans.update(output[i], labels.get(i)); } } return ans; } }
488d787cdae9ae78b5b58547338ac0fbdc8146b9
80dd48bfb2c7e5552530ac0fe20f2d15a60a1c0b
/kostenstellen/persistence/BucheKontoCommandFacade.java
f3a9a5af44c94fa10c63eeb50ce786649a5a5a9c
[]
no_license
AlineLa/kostenstellen
7d8353d7c4f5241ec5239b878dac6637f65a5c74
128d8abb1648829f2588afb254f9f59e79bad697
refs/heads/master
2021-01-24T22:52:07.969724
2014-11-11T11:40:44
2014-11-11T11:40:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,727
java
package persistence; import model.meta.*; import java.sql.*; //import oracle.jdbc.*; public class BucheKontoCommandFacade{ private String schemaName; private Connection con; public BucheKontoCommandFacade(String schemaName, Connection con) { this.schemaName = schemaName; this.con = con; } public PersistentBucheKontoCommand newBucheKontoCommand(long createMinusStorePlus) throws PersistenceException { oracle.jdbc.OracleCallableStatement callable; try{ callable = (oracle.jdbc.OracleCallableStatement)this.con.prepareCall("Begin ? := " + this.schemaName + ".BchKntCMDFacade.newBchKntCMD(?); end;"); callable.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER); callable.setLong(2, createMinusStorePlus); callable.execute(); long id = callable.getLong(1); callable.close(); BucheKontoCommand result = new BucheKontoCommand(null,null,null,id); if (createMinusStorePlus < 0)Cache.getTheCache().put(result); return (PersistentBucheKontoCommand)PersistentProxi.createProxi(id, 120); }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public PersistentBucheKontoCommand newDelayedBucheKontoCommand() throws PersistenceException { oracle.jdbc.OracleCallableStatement callable; try{ callable = (oracle.jdbc.OracleCallableStatement)this.con.prepareCall("Begin ? := " + this.schemaName + ".BchKntCMDFacade.newDelayedBchKntCMD(); end;"); callable.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER); callable.execute(); long id = callable.getLong(1); callable.close(); BucheKontoCommand result = new BucheKontoCommand(null,null,null,id); Cache.getTheCache().put(result); return (PersistentBucheKontoCommand)PersistentProxi.createProxi(id, 120); }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public BucheKontoCommand getBucheKontoCommand(long BucheKontoCommandId) throws PersistenceException{ try{ CallableStatement callable; callable = this.con.prepareCall("Begin ? := " + this.schemaName + ".BchKntCMDFacade.getBchKntCMD(?); end;"); callable.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR); callable.setLong(2, BucheKontoCommandId); callable.execute(); ResultSet obj = ((oracle.jdbc.OracleCallableStatement)callable).getCursor(1); if (!obj.next()) { obj.close(); callable.close(); return null; } Invoker invoker = null; if (obj.getLong(2) != 0) invoker = (Invoker)PersistentProxi.createProxi(obj.getLong(2), obj.getLong(3)); PersistentTransaktion commandReceiver = null; if (obj.getLong(4) != 0) commandReceiver = (PersistentTransaktion)PersistentProxi.createProxi(obj.getLong(4), obj.getLong(5)); PersistentCommonDate myCommonDate = null; if (obj.getLong(6) != 0) myCommonDate = (PersistentCommonDate)PersistentProxi.createProxi(obj.getLong(6), obj.getLong(7)); BucheKontoCommand result = new BucheKontoCommand(invoker, commandReceiver, myCommonDate, BucheKontoCommandId); obj.close(); callable.close(); BucheKontoCommandICProxi inCache = (BucheKontoCommandICProxi)Cache.getTheCache().put(result); BucheKontoCommand objectInCache = (BucheKontoCommand)inCache.getTheObject(); return objectInCache; }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public long getClass(long objectId) throws PersistenceException{ try{ CallableStatement callable; callable = this.con.prepareCall("Begin ? := " + this.schemaName + ".BchKntCMDFacade.getClass(?); end;"); callable.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER); callable.setLong(2, objectId); callable.execute(); long result = callable.getLong(1); callable.close(); return result; }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public void invokerSet(long BucheKontoCommandId, Invoker invokerVal) throws PersistenceException { try{ CallableStatement callable; callable = this.con.prepareCall("Begin " + this.schemaName + ".BchKntCMDFacade.invokerSet(?, ?, ?); end;"); callable.setLong(1, BucheKontoCommandId); callable.setLong(2, invokerVal.getId()); callable.setLong(3, invokerVal.getClassId()); callable.execute(); callable.close(); }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public void commandReceiverSet(long BucheKontoCommandId, PersistentTransaktion commandReceiverVal) throws PersistenceException { try{ CallableStatement callable; callable = this.con.prepareCall("Begin " + this.schemaName + ".BchKntCMDFacade.cReceiverSet(?, ?, ?); end;"); callable.setLong(1, BucheKontoCommandId); callable.setLong(2, commandReceiverVal.getId()); callable.setLong(3, commandReceiverVal.getClassId()); callable.execute(); callable.close(); }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } public void myCommonDateSet(long BucheKontoCommandId, PersistentCommonDate myCommonDateVal) throws PersistenceException { try{ CallableStatement callable; callable = this.con.prepareCall("Begin " + this.schemaName + ".BchKntCMDFacade.myCmmnDtSet(?, ?, ?); end;"); callable.setLong(1, BucheKontoCommandId); callable.setLong(2, myCommonDateVal.getId()); callable.setLong(3, myCommonDateVal.getClassId()); callable.execute(); callable.close(); }catch(SQLException se) { throw new PersistenceException(se.getMessage(), se.getErrorCode()); } } }
409c9937003ffb2efdef9ce460dbc2c35f103931
8b406dd015ce24e8637c3712dd6c1850d13295b6
/Java/08 Encapsulamento/src/exemplo03/Principal.java
c68e0281be3a1d10c7ce5a36c3b7c76755fd8231
[]
no_license
gabrielpereira1999/entra21_matutino
8e3d3aab48d13e3898bc7b8a09055bab968c9e78
03ce1c4ac38c2445e51d6ec16fa07d7ad1678927
refs/heads/master
2020-05-25T06:10:02.046685
2019-05-28T14:54:46
2019-05-28T14:54:46
187,662,131
0
0
null
null
null
null
UTF-8
Java
false
false
137
java
package exemplo03; public class Principal { public static void main(String[] args) { Pessoa p = new Pessoa("Gabriel",20); } }
f25c3a34f1fa9d3d275404fa2cb2ba83f4cb54af
56a318ce387afd82054e0c46608fad64ca50a808
/src/com/design/creational/builder/TestBuilder.java
2d39168fe5c042612440daf86dc1e399b945f39e
[]
no_license
SandDeep/InterviewQuest
ed83c1bff2fc5ca4604827e4074629fdf0c39fe2
ee539177d781433956a8626483d1644de6929ee1
refs/heads/master
2016-08-12T13:21:41.628836
2015-11-18T05:25:02
2015-11-18T05:25:02
46,397,145
0
0
null
null
null
null
UTF-8
Java
false
false
257
java
package com.design.creational.builder; public class TestBuilder { public static void main(String[] args) { Computer computer = new Computer.ComputerBuilder("500 GB", "2 GB") .setBluetoothEnabled(true).build(); System.out.println(computer); } }
7a7aa8848d7a29da2a8a95a286fca4c96a8fb150
1d587bbaade2584b8d3cf7616428869f05b6df87
/LearnC/app/src/main/java/info/rishi/learnc/RobotoTextView.java
f2704253d09429db29216854425138b0ec4e069e
[]
no_license
rishirana/learn_c_language
2d1c03eeca46b441eb17c803bba4cf7b23f0d104
956651726d5a8e32e23d33c58e87fc94e1ad8c06
refs/heads/master
2021-01-19T21:24:07.682890
2017-04-18T18:44:46
2017-04-18T18:44:46
88,654,546
0
0
null
null
null
null
UTF-8
Java
false
false
8,675
java
package info.rishi.learnc; /** * Created by PC on 4/16/2017. */ import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; import info.rishi.learnc.R; public class RobotoTextView extends TextView { public RobotoTextView(Context context) { super(context); if (isInEditMode()) return; parseAttributes(null); } public RobotoTextView(Context context, AttributeSet attrs) { super(context, attrs); if (isInEditMode()) return; parseAttributes(attrs); } public RobotoTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (isInEditMode()) return; parseAttributes(attrs); } public static Typeface getRoboto(Context context , int typeface){ switch (typeface){ case Roboto.ROBOTO_BLACK: if (Roboto.sRobotoBlack == null){ Roboto.sRobotoBlack = Typeface.createFromAsset(context.getAssets(),"fonts/Roboto-Black.ttf"); } return Roboto.sRobotoBlack; case Roboto.ROBOTO_BLACK_ITALIC: if (Roboto.sRobotoBlackItalic == null){ Roboto.sRobotoBlackItalic = Typeface.createFromAsset(context.getAssets(),"fonts/Roboto-BlackItalic.ttf"); } return Roboto.sRobotoBlackItalic; case Roboto.ROBOTO_BOLD: if (Roboto.sRobotoBold == null) { Roboto.sRobotoBold = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf"); } return Roboto.sRobotoBold; case Roboto.ROBOTO_BOLD_CONDENSED: if (Roboto.sRobotoBoldCondensed == null) { Roboto.sRobotoBoldCondensed = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldCondensed.ttf"); } return Roboto.sRobotoBoldCondensed; case Roboto.ROBOTO_BOLD_CONDENSED_ITALIC: if (Roboto.sRobotoBoldCondensedItalic == null) { Roboto.sRobotoBoldCondensedItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldCondensedItalic.ttf"); } return Roboto.sRobotoBoldCondensedItalic; case Roboto.ROBOTO_BOLD_ITALIC: if (Roboto.sRobotoBoldItalic == null) { Roboto.sRobotoBoldItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-BoldItalic.ttf"); } return Roboto.sRobotoBoldItalic; case Roboto.ROBOTO_CONDENSED: if (Roboto.sRobotoCondensed == null) { Roboto.sRobotoCondensed = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Condensed.ttf"); } return Roboto.sRobotoCondensed; case Roboto.ROBOTO_CONDENSED_ITALIC: if (Roboto.sRobotoCondensedItalic == null) { Roboto.sRobotoCondensedItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-CondensedItalic.ttf"); } return Roboto.sRobotoCondensedItalic; case Roboto.ROBOTO_ITALIC: if (Roboto.sRobotoItalic == null) { Roboto.sRobotoItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic.ttf"); } return Roboto.sRobotoItalic; case Roboto.ROBOTO_LIGHT: if (Roboto.sRobotoLight == null) { Roboto.sRobotoLight = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Light.ttf"); } return Roboto.sRobotoLight; case Roboto.ROBOTO_LIGHT_ITALIC: if (Roboto.sRobotoLightItalic == null) { Roboto.sRobotoLightItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-LightItalic.ttf"); } return Roboto.sRobotoLightItalic; case Roboto.ROBOTO_MEDIUM: if (Roboto.sRobotoMedium == null) { Roboto.sRobotoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Medium.ttf"); } return Roboto.sRobotoMedium; case Roboto.ROBOTO_MEDIUM_ITALIC: if (Roboto.sRobotoMediumItalic == null) { Roboto.sRobotoMediumItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-MediumItalic.ttf"); } return Roboto.sRobotoMediumItalic; default: case Roboto.ROBOTO_REGULAR: if (Roboto.sRobotoRegular == null) { Roboto.sRobotoRegular = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf"); } return Roboto.sRobotoRegular; case Roboto.ROBOTO_THIN: if (Roboto.sRobotoThin == null) { Roboto.sRobotoThin = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Thin.ttf"); } return Roboto.sRobotoThin; case Roboto.ROBOTO_THIN_ITALIC: if (Roboto.sRobotoThinItalic == null) { Roboto.sRobotoThinItalic = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-ThinItalic.ttf"); } return Roboto.sRobotoThinItalic; } } private void parseAttributes(AttributeSet attrs){ int typeface; if (attrs == null){ typeface = Roboto.ROBOTO_REGULAR; } else { TypedArray values = getContext().obtainStyledAttributes(attrs,R.styleable.RobotoTextView); typeface = values.getInt(R.styleable.RobotoTextView_typeface,Roboto.ROBOTO_REGULAR); values.recycle(); } setTypeface(getRoboto(typeface)); } private void setRobotoTypeface(int typeface){ setTypeface(getRoboto(typeface)); } private Typeface getRoboto(int typeface){ return getRoboto(getContext(),typeface); } public static class Roboto{ /* From attrs.xml file: <enum name="robotoBlack" value="0" /> <enum name="robotoBlackItalic" value="1" /> <enum name="robotoBold" value="2" /> <enum name="robotoBoldItalic" value="3" /> <enum name="robotoBoldCondensed" value="4" /> <enum name="robotoBoldCondensedItalic" value="5" /> <enum name="robotoCondensed" value="6" /> <enum name="robotoCondensedItalic" value="7" /> <enum name="robotoItalic" value="8" /> <enum name="robotoLight" value="9" /> <enum name="robotoLightItalic" value="10" /> <enum name="robotoMedium" value="11" /> <enum name="robotoMediumItalic" value="12" /> <enum name="robotoRegular" value="13" /> <enum name="robotoThin" value="14" /> <enum name="robotoThinItalic" value="15" /> */ public static final int ROBOTO_BLACK = 0; public static final int ROBOTO_BLACK_ITALIC = 1; public static final int ROBOTO_BOLD = 2; public static final int ROBOTO_BOLD_ITALIC = 3; public static final int ROBOTO_BOLD_CONDENSED = 4; public static final int ROBOTO_BOLD_CONDENSED_ITALIC = 5; public static final int ROBOTO_CONDENSED = 6; public static final int ROBOTO_CONDENSED_ITALIC = 7; public static final int ROBOTO_ITALIC = 8; public static final int ROBOTO_LIGHT = 9; public static final int ROBOTO_LIGHT_ITALIC = 10; public static final int ROBOTO_MEDIUM = 11; public static final int ROBOTO_MEDIUM_ITALIC = 12; public static final int ROBOTO_REGULAR = 13; public static final int ROBOTO_THIN = 14; public static final int ROBOTO_THIN_ITALIC = 15; private static Typeface sRobotoBlack; private static Typeface sRobotoBlackItalic; private static Typeface sRobotoBold; private static Typeface sRobotoBoldItalic; private static Typeface sRobotoBoldCondensed; private static Typeface sRobotoBoldCondensedItalic; private static Typeface sRobotoCondensed; private static Typeface sRobotoCondensedItalic; private static Typeface sRobotoItalic; private static Typeface sRobotoLight; private static Typeface sRobotoLightItalic; private static Typeface sRobotoMedium; private static Typeface sRobotoMediumItalic; private static Typeface sRobotoRegular; private static Typeface sRobotoThin; private static Typeface sRobotoThinItalic; } }
6c533847e45fbc1e953a915c445e83bcec1e6e23
a36dce4b6042356475ae2e0f05475bd6aed4391b
/2005/julypersistence2EJB/ejbModule/com/hps/july/persistence2/EtapDocKey.java
b43ea1b71d01cef59e1075df9a8a93242c82c3e3
[]
no_license
ildar66/WSAD_NRI
b21dbee82de5d119b0a507654d269832f19378bb
2a352f164c513967acf04d5e74f36167e836054f
refs/heads/master
2020-12-02T23:59:09.795209
2017-07-01T09:25:27
2017-07-01T09:25:27
95,954,234
0
1
null
null
null
null
UTF-8
Java
false
false
958
java
package com.hps.july.persistence2; public class EtapDocKey implements java.io.Serializable { private final static long serialVersionUID = 3206093459760846163L; public int sitedoc; /** * Default constructor */ /* WARNING: THIS METHOD WILL BE REGENERATED. */ public EtapDocKey() { super(); } /** * Initialize a key from the passed values * @param argSitedoc int */ /* WARNING: THIS METHOD WILL BE REGENERATED. */ public EtapDocKey(int argSitedoc) { sitedoc = argSitedoc; } /** * equals method * @return boolean * @param o java.lang.Object */ /* WARNING: THIS METHOD WILL BE REGENERATED. */ public boolean equals(Object o) { if (o instanceof EtapDocKey) { EtapDocKey otherKey = (EtapDocKey) o; return (((this.sitedoc == otherKey.sitedoc))); } else return false; } /** * hashCode method * @return int */ /* WARNING: THIS METHOD WILL BE REGENERATED. */ public int hashCode() { return ((new java.lang.Integer(sitedoc).hashCode())); } }
7ad664245511c49f26ed1b007905fdfda708c3e1
e87ecd3ed9d95f19af8502a1e5711e0d8beb2d82
/src/br/com/caelum/mvc/logica/MostraContatoLogic.java
9c7ae7965508e35b0c9c83c67e9ffa7a7fe7c7b4
[]
no_license
francoisjr/fj-21-agenda
259ad553f4aefc415a009f18c957147a2de84697
49c812abea0155bf756d4a5726d75dd7f0a1b4a3
refs/heads/master
2016-09-11T01:10:24.414857
2015-03-16T04:55:15
2015-03-16T04:55:15
32,301,086
0
0
null
null
null
null
UTF-8
Java
false
false
1,132
java
package br.com.caelum.mvc.logica; import java.sql.Connection; import java.text.SimpleDateFormat; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.caelum.jdbc.dao.ContatoDao; import br.com.caelum.jdbc.modelo.Contato; public class MostraContatoLogic implements Logica { @Override public String executa(HttpServletRequest request, HttpServletResponse res) throws Exception { int id = Integer.parseInt(request.getParameter("id")); // busca a conexao pendurada na requisicao Connection connection = (Connection) request.getAttribute("conexao"); ContatoDao dao = new ContatoDao(connection); Contato contato = dao.getContatoByID(id); request.setAttribute("id", id); request.setAttribute("nome", contato.getNome()); request.setAttribute("email", contato.getEmail()); request.setAttribute("endereco", contato.getEndereco()); request.setAttribute("dataNascimento", new SimpleDateFormat( "dd/MM/yyyy").format(contato.getDataNascimento() .getTimeInMillis())); return "/WEB-INF/jsp/altera-contato.jsp"; } }
a5cc957dc79fc1e9c14e199f9cae75dc3b184a76
ef6cd6c9c95f2828c59f02f6971060aa62061bae
/Crowdfunding/CrowdfundingEjb/ejbModule/net/crowdfunding/impl/beans/InvestPlanImpl.java
aa714572f62b79b13ff5d0236cad28bccc049053
[]
no_license
NgalorNgidul/Crowdfunding
b89f56ff67b50041ef84426fbe774b7326cbc327
94a59b210babdb3b2fae399f04c40087cf0a427f
refs/heads/master
2016-09-06T18:34:18.660614
2015-07-13T08:19:32
2015-07-13T08:19:32
33,869,074
0
0
null
null
null
null
UTF-8
Java
false
false
2,189
java
package net.crowdfunding.impl.beans; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import net.crowdfunding.intf.beans.IInvestPlan; import net.crowdfunding.intf.model.InvestPlan; @Stateless @Remote(IInvestPlan.class) public class InvestPlanImpl implements IInvestPlan { @PersistenceContext(unitName = "CrowdfundingEjb", type = PersistenceContextType.TRANSACTION) EntityManager em; @Override public InvestPlan get(long id) { return em.find(InvestPlan.class, id); } @Override public long save(InvestPlan data) { if (data.getId() == 0) { em.persist(data); } else { em.merge(data); } return data.getId(); } @SuppressWarnings("unchecked") @Override public List<InvestPlan> listByMember(long memberId) { Query qry = em.createNamedQuery("listInvestPlanByMember"); qry.setParameter("memberId", memberId); List<InvestPlan> result = qry.getResultList(); return result; } @SuppressWarnings("unchecked") @Override public List<InvestPlan> listByMemberStatus(long memberId, int status) { Query qry = em.createNamedQuery("listInvestPlanByMemberStatus"); qry.setParameter("memberId", memberId); qry.setParameter("status", status); List<InvestPlan> result = qry.getResultList(); return result; } @SuppressWarnings("unchecked") @Override public List<InvestPlan> listAll() { Query qry = em.createNamedQuery("listAllInvestPlan"); List<InvestPlan> result = qry.getResultList(); return result; } @SuppressWarnings("unchecked") @Override public List<InvestPlan> listAllByStatus(int status) { Query qry = em.createNamedQuery("listAllInvestPlanByStatus"); qry.setParameter("status", status); List<InvestPlan> result = qry.getResultList(); return result; } @SuppressWarnings("unchecked") @Override public List<InvestPlan> listByProspect(long prospect) { Query qry = em.createNamedQuery("listInvestPlanByProspect"); qry.setParameter("prospectId", prospect); List<InvestPlan> result = qry.getResultList(); return result; } }
5371b8a4ed52b59e190e9c8ccbbb5bde2f07064d
fbfb047f8400ac0625a4ea7348d1020f1a766f80
/src/main/java/br/com/flaviogranato/login/infra/RoleDao.java
33c3d7232251f065edaabad94a24f0c5f49c59ec
[]
no_license
flaviogranato/job-backend-developer
edd9d90081b79137b22bfda45bb7e72d05948ac8
fc522d5981255c193f3187fcde04ce5713490d8d
refs/heads/master
2020-03-20T19:06:59.028511
2018-06-19T02:37:32
2018-06-19T02:37:32
137,622,171
0
0
null
2018-06-17T01:56:25
2018-06-17T01:56:25
null
UTF-8
Java
false
false
1,562
java
package br.com.flaviogranato.login.infra; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; @Repository public class RoleDao extends JdbcDaoSupport { @Qualifier("role") @Autowired private RedisTemplate redisTemplate; @Autowired public RoleDao(DataSource dataSource) { this.setDataSource(dataSource); } public List<String> getRoleNames(Long userId) { final String REDIS_PREFIX = "role:"; List<String> roles; String sql = "SELECT r.rolename\n" + "FROM user_role ur,\n" + " roles r\n" + "WHERE ur.id = r.id\n" + " AND ur.id = ?"; Object[] params = new Object[]{userId}; @SuppressWarnings("unchecked") List<String> rolesFromRedis = (List<String>) redisTemplate.opsForValue() .get(REDIS_PREFIX + userId); if (rolesFromRedis != null) { roles = rolesFromRedis; } else { roles = this.getJdbcTemplate() .queryForList(sql, params, String.class); redisTemplate.opsForValue() .set(REDIS_PREFIX + userId, roles); } return roles; } }
584b0fe843362ffdfe4091b10803dea564442c1c
ddce3c1d623fc6887e288a4e5fa022abd2707761
/src/com/MCAAlgorithm/bigshua/class34/Problem_0348_DesignTicTacToe.java
c013d102289643fd1b10ce98fd3979f672912c96
[]
no_license
tjzhaomengyi/DataStructure-java
e1632758761ab66f58dee6f84d81ac101d2a3289
7f1a95bd2918ea7a4763df7858d1ea28e538698d
refs/heads/master
2023-07-07T19:09:21.349154
2023-06-27T02:59:12
2023-06-27T02:59:12
81,512,160
0
0
null
null
null
null
UTF-8
Java
false
false
1,115
java
package com.MCAAlgorithm.bigshua.class34; public class Problem_0348_DesignTicTacToe { class TicTacToe { private int[][] rows; private int[][] cols; private int[] leftUp; private int[] rightUp; private boolean[][] matrix; private int N; public TicTacToe(int n) { // rows[a][1] : 1这个人,在a行上,下了几个 // rows[b][2] : 2这个人,在b行上,下了几个 rows = new int[n][3]; //0 1 2 cols = new int[n][3]; // leftUp[2] = 7 : 2这个人,在左对角线上,下了7个 leftUp = new int[3]; // rightUp[1] = 9 : 1这个人,在右对角线上,下了9个 rightUp = new int[3]; matrix = new boolean[n][n]; N = n; } public int move(int row, int col, int player) { if (matrix[row][col]) { return 0; } matrix[row][col] = true; rows[row][player]++; cols[col][player]++; if (row == col) { leftUp[player]++; } if (row + col == N - 1) { rightUp[player]++; } if (rows[row][player] == N || cols[col][player] == N || leftUp[player] == N || rightUp[player] == N) { return player; } return 0; } } }
2705fe2cafcc71ed6715524eb274e580551a7da8
6812bb5da5d825065d533b80daa490e2b993c5ac
/Arrays/OccurrencesInArray.java
50622c576d42befaba93756829c18d75f7474a23
[]
no_license
sarathmanchu/Algos
5945e3b805ee9416c5ab017615057648ec3adcd7
5ccdbab38a8bf1ef4f34d77c3fddd4605574eae3
refs/heads/master
2020-04-02T05:11:30.802997
2016-08-01T16:04:49
2016-08-01T16:04:49
62,740,296
0
0
null
null
null
null
UTF-8
Java
false
false
1,296
java
package com.example.helloworld.producerconsumer.Arrays; /** * Created by sarath on 7/13/16. */ public class OccurrencesInArray { static int firstOccurence(int[] arr,int num,int start,int end){ if(end>=start){ int mid=(start+end)/2; if((mid==0 || arr[mid-1]<num) && arr[mid]==num) return mid; else if(arr[mid]<num) return firstOccurence(arr,num,mid+1,end); else return firstOccurence(arr,num,start,mid-1); }else return -1; } static int lastOccurence(int[] arr,int num,int start,int end){ if(end>=start){ int mid=(start+end)/2; if((mid==arr.length-1 || arr[mid+1]>num) && (arr[mid]==num)) return mid; else if(arr[mid]>num) return lastOccurence(arr,num,start,mid-1); else return lastOccurence(arr,num,mid+1,end); } else return -1; } public static void main(String[] args) { int [] arr = {1,2,2,2,2,2,2,2,3,4,5,5,6}; int f=firstOccurence(arr,2,0,arr.length-1); System.out.println(f); int l=lastOccurence(arr,2,0,arr.length-1); System.out.println(l); System.out.println(l-f+1); } }
14a8699e2c43dbad6942269e3e73d30da2af139e
b502aa870139c134e72ed9296e666aa4ccf4debf
/dunwu-common/src/test/java/io/github/dunwu/util/regex/RegexHelperTests.java
1c1b672fe42a0565e96640a7cc52f301e5753dc3
[ "Apache-2.0" ]
permissive
JavisZ/dunwu
2fd8dcf0004b6d13f30927e5d67e527e66e1ad19
ae5125b0a18a2f18b0d706cd09d6f0ef280fb248
refs/heads/master
2020-05-31T18:24:22.161525
2019-05-24T06:51:34
2019-05-24T06:51:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,000
java
package io.github.dunwu.util.regex; import org.apache.commons.collections4.CollectionUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.List; /** * @author <a href="mailto:[email protected]">Zhang Peng</a> * @since 2019-01-16 * @see RegexHelper */ @DisplayName("正则校验测试例集") public class RegexHelperTests { @Test public void test2() { String content = "rulename,{\"m_login_ip\":{\"login_account_cnt\":3.0,\"login_ip\":\"127.0.0.1\"," + "\"window_time\":1547605830000,\"judgementId\":\"hello\"},\"allowed\":false,\"version\":0}"; String content2 = "rulename,{\"m_login_ip\":{\"login_account_cnt\":3.0,\"login_ip\":\"127.0.0.1\"," + "\"window_time\":1547605830000,\"judgementId\":hello},\"allowed\":false,\"version\":0}"; List<String> matchValues = RegexHelper.getMatchValuesInJson(content, "judgementId"); if (CollectionUtils.isNotEmpty(matchValues)) { matchValues.forEach(item -> { System.out.println(item); }); } List<String> matchValues2 = RegexHelper.getMatchValuesInJson(content2, "judgementId"); if (CollectionUtils.isNotEmpty(matchValues2)) { matchValues2.forEach(item -> { System.out.println(item); }); } } @Nested @DisplayName("校验常用场景") class CheckCommon { @Test @DisplayName("正则校验15位身份证号") public void isValidIdCard15() { Assertions.assertEquals(true, RegexHelper.Checker.isValidIdCard15("110001700101031")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIdCard15("110001701501031")); } @Test @DisplayName("正则校验18位身份证号") public void isValidIdCard18() { Assertions.assertEquals(true, RegexHelper.Checker.isValidIdCard18("11000019900101015X")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIdCard18("990000199001010310")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIdCard18("110001199013010310")); } @Test @DisplayName("正则校验用户名有效") public void isValidUsername() { Assertions.assertEquals(true, RegexHelper.Checker.isValidUsername("gdasg_")); Assertions.assertEquals(false, RegexHelper.Checker.isValidUsername("$dhsagk")); } @Test @DisplayName("正则校验有效邮箱") public void isValidEmail() { Assertions.assertEquals(true, RegexHelper.Checker.isValidEmail("[email protected]")); Assertions.assertEquals(true, RegexHelper.Checker.isValidEmail("[email protected]")); Assertions.assertEquals(true, RegexHelper.Checker.isValidEmail("[email protected]")); Assertions.assertEquals(false, RegexHelper.Checker.isValidEmail("hello@worl_d.com")); Assertions.assertEquals(false, RegexHelper.Checker.isValidEmail("he&[email protected]")); Assertions.assertEquals(false, RegexHelper.Checker.isValidEmail(".hello@wor#.co.uk")); Assertions.assertEquals(false, RegexHelper.Checker.isValidEmail("gdsakh23124")); } @Test @DisplayName("正则校验URL") public void isValidUrl() { Assertions.assertEquals(true, RegexHelper.Checker.isValidUrl("http://google.com/help/me")); Assertions.assertEquals(true, RegexHelper.Checker.isValidUrl("http://www.google.com/help/me/")); Assertions.assertEquals(true, RegexHelper.Checker.isValidUrl("https://www.google.com/help.asp")); Assertions.assertEquals(true, RegexHelper.Checker.isValidUrl("ftp://www.google.com")); Assertions.assertEquals(true, RegexHelper.Checker.isValidUrl("ftps://google.org")); Assertions.assertEquals(false, RegexHelper.Checker.isValidUrl("http://un/www.google.com/index.asp")); } @Test @DisplayName("正则校验IPv4") public void isValidIpv4() { Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv4("0.0.0.0")); Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv4("255.255.255.255")); Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv4("127.0.0.1")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIpv4("10.10.10")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIpv4("10.10.10.2561")); } @Test @DisplayName("正则校验IPv6") public void isValidIpv6() { Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv6("1:2:3:4:5:6:7:8")); Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv6("1:2:3:4:5::8")); Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv6("::255.255.255.255")); Assertions.assertEquals(true, RegexHelper.Checker.isValidIpv6("1:2:3:4:5:6:7::")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIpv6("1.2.3.4.5.6.7.8")); Assertions.assertEquals(false, RegexHelper.Checker.isValidIpv6("1::2::3")); } @Test @DisplayName("正则校验时间") public void isValidTime() { Assertions.assertEquals(true, RegexHelper.Checker.isValidTime("00:00:00")); Assertions.assertEquals(true, RegexHelper.Checker.isValidTime("23:59:59")); Assertions.assertEquals(true, RegexHelper.Checker.isValidTime("17:06:30")); Assertions.assertEquals(false, RegexHelper.Checker.isValidTime("17:6:30")); Assertions.assertEquals(false, RegexHelper.Checker.isValidTime("24:16:30")); } @Test @DisplayName("正则校验日期") public void isValidDate() { Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("2016/1/1")); Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("2016/01/01")); Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("20160101")); Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("2016-01-01")); Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("2016.01.01")); Assertions.assertEquals(true, RegexHelper.Checker.isValidDate("2000-02-29")); Assertions.assertEquals(false, RegexHelper.Checker.isValidDate("2001-02-29")); Assertions.assertEquals(false, RegexHelper.Checker.isValidDate("2016/12/32")); Assertions.assertEquals(false, RegexHelper.Checker.isValidDate("2016.13.1")); } @Test @DisplayName("正则校验中国手机号码") public void isValidChinaMobile() { Assertions.assertEquals(true, RegexHelper.Checker.isValidChinaMobile("+86 18012345678")); Assertions.assertEquals(true, RegexHelper.Checker.isValidChinaMobile("86 18012345678")); Assertions.assertEquals(true, RegexHelper.Checker.isValidChinaMobile("15812345678")); Assertions.assertEquals(false, RegexHelper.Checker.isValidChinaMobile("15412345678")); Assertions.assertEquals(false, RegexHelper.Checker.isValidChinaMobile("12912345678")); Assertions.assertEquals(false, RegexHelper.Checker.isValidChinaMobile("180123456789")); } @Test @DisplayName("正则校验中国手机号码") public void isValidPhone() { Assertions.assertEquals(true, RegexHelper.Checker.isValidPhone("025-85951888")); } } @Nested @DisplayName("校验字符") class CheckChar { @Test @DisplayName("正则校验全是汉字字符") public void isAllChineseChar() { Assertions.assertEquals(true, RegexHelper.Checker.isAllChineseChar("春眠不觉晓")); Assertions.assertEquals(false, RegexHelper.Checker.isAllChineseChar("春眠不觉晓,")); Assertions.assertEquals(false, RegexHelper.Checker.isAllChineseChar("English")); } @Test @DisplayName("正则校验全是英文字母") public void isAllEnglishChar() { Assertions.assertEquals(true, RegexHelper.Checker.isAllEnglishChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assertions.assertEquals(true, RegexHelper.Checker.isAllEnglishChar("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(false, RegexHelper.Checker.isAllEnglishChar("How are you?")); Assertions.assertEquals(false, RegexHelper.Checker.isAllEnglishChar("你奈我何")); } @Test @DisplayName("正则校验全是大写字母") public void isAllUpperEnglishChar() { Assertions.assertEquals(true, RegexHelper.Checker.isAllUpperEnglishChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assertions.assertEquals(false, RegexHelper.Checker.isAllUpperEnglishChar("abcdefghijklmnopqrstuvwxyz")); } @Test @DisplayName("正则校验全是小写字母") public void isAllLowerEnglishChar() { Assertions.assertEquals(true, RegexHelper.Checker.isAllLowerEnglishChar("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(false, RegexHelper.Checker.isAllLowerEnglishChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); } @Test @DisplayName("正则校验全是单词字符") public void isAllWordChar() { Assertions.assertEquals(true, RegexHelper.Checker.isAllWordChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assertions.assertEquals(true, RegexHelper.Checker.isAllWordChar("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(true, RegexHelper.Checker.isAllWordChar("0123456789")); Assertions.assertEquals(true, RegexHelper.Checker.isAllWordChar("_")); } @Test @DisplayName("正则校验全是非单词字符") public void isNoneWordChar() { Assertions.assertEquals(false, RegexHelper.Checker.isNoneWordChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); Assertions.assertEquals(false, RegexHelper.Checker.isNoneWordChar("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(false, RegexHelper.Checker.isNoneWordChar("0123456789")); Assertions.assertEquals(false, RegexHelper.Checker.isNoneWordChar("_")); } } @Nested @DisplayName("校验数字") class CheckNumber { @Test @DisplayName("正则校验全是数字") public void isAllNumber() { Assertions.assertEquals(true, RegexHelper.Checker.isAllNumber("0123456789")); Assertions.assertEquals(false, RegexHelper.Checker.isAllNumber("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(false, RegexHelper.Checker.isAllNumber("How are you?")); Assertions.assertEquals(false, RegexHelper.Checker.isAllNumber("你奈我何")); } @Test @DisplayName("正则校验不含任何数字") public void isNoneNumber() { Assertions.assertEquals(true, RegexHelper.Checker.isNoneNumber("abcdefghijklmnopqrstuvwxyz")); Assertions.assertEquals(false, RegexHelper.Checker.isNoneNumber("0123456789")); Assertions.assertEquals(false, RegexHelper.Checker.isNoneNumber("test008")); } @Test @DisplayName("正则校验不含任何数字") public void isNDigitNumber() { Assertions.assertEquals(true, RegexHelper.Checker.isNDigitNumber("0123456789", 10)); } @Test @DisplayName("正则校验不含任何数字") public void isLeastNDigitNumber() { Assertions.assertEquals(true, RegexHelper.Checker.isLeastNDigitNumber("0123456789", 5)); Assertions.assertEquals(true, RegexHelper.Checker.isLeastNDigitNumber("0123456789", 10)); Assertions.assertEquals(false, RegexHelper.Checker.isLeastNDigitNumber("0123456789", 11)); } @Test @DisplayName("正则校验不含任何数字") public void isMToNDigitNumber() { Assertions.assertEquals(true, RegexHelper.Checker.isMToNDigitNumber("0123456789", 1, 10)); Assertions.assertEquals(false, RegexHelper.Checker.isMToNDigitNumber("0123456789", 6, 9)); Assertions.assertEquals(false, RegexHelper.Checker.isMToNDigitNumber("0123456789", 11, 20)); } } @Nested @DisplayName("校验Markdonw") class CheckMarkdown { @Test @DisplayName("校验含有 Markdonw ![]() ") public void isMarkdownImageTag() { String newstr = RegexHelper.replaceAllMatchContent("![asgad](http://www.baidu.com/test.png)", RegexHelper.Checker.REGEX_MARKDOWN_IMAGE_TAG, "![]("); System.out.println(newstr); } } }
c6e1f47390f137f6f351424be71d27ab45163af8
6a29ceb09031a3f7da87a5b90fd217d2e27bd60d
/BookManager/src/main/java/com/imatia/bookmanager/view/ui/EditUserUi.java
0351c473c92e15c1e0dc83911b537f1c431faf6a
[]
no_license
adrianpm99/biblioteca_ImatiaFCT
47f9ece89e65067f2b724a48c31d1c49e299870c
84aa24a03ebdb996c6a3a3e4237f83c5289691b4
refs/heads/main
2023-05-01T12:04:56.116250
2021-04-30T07:49:44
2021-04-30T07:49:44
359,378,850
0
0
null
null
null
null
UTF-8
Java
false
false
613
java
package com.imatia.bookmanager.view.ui; import com.imatia.bookmanager.view.menus.EditUserMenu; /* * this is the UI to show the user edit view */ public class EditUserUi { public static void showEditUserUi(int id) { System.out.println( "\n********************\r\n" + "** EDITAR USUARIO **\r\n" + "********************\r\n" + "---------------------------------------------\r\n" + "|| Introduzca los nuevos datos del usuario ||\r\n" + "---------------------------------------------"); //show the edit user menu EditUserMenu.showEditUserMenu(id); }//showEditUserUi }
1c90df51832fd97b8a8f923eb406ef6c026f3a11
dbdfb8bbaa0bc22daa30050445fccf34aa37793e
/src/main/java/com/my/Aero.java
67622f7922c9bf95fb3e8647d172d484a2befea8
[]
no_license
avzaleks/AeroHockey
0c73130b6e82595223b232325fdac57ae184c736
a81a5e7bff8b0b21b674047bf5a47fbc4564efa9
refs/heads/master
2021-01-10T13:20:42.004862
2015-12-23T18:04:39
2015-12-23T18:04:39
48,503,631
0
0
null
null
null
null
UTF-8
Java
false
false
6,227
java
package com.my; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.Session; import org.apache.commons.lang3.RandomStringUtils; import org.json.simple.JSONValue; import com.my.wss.MyWss; import com.my.wss.StorageOfEndpoints; public class Aero extends HttpServlet { private static final long serialVersionUID = 1L; private static Map<String, List<String>> mapEndpointsForTranslation = new ConcurrentHashMap<String, List<String>>(); StorageOfEndpoints initialStorageOfEndpoints = StorageOfEndpoints .getStorageOfEndpoints(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> list = null; if (request.getParameter("watch") != null) { if (request.getParameter("watch").equals("false")) { list = new LinkedList<String>(); for (String str : MyWss.getListOfIdWhichIsConnected().keySet()) { if (!str.contains("dop")) { list.add(str); } } String jsonText = JSONValue.toJSONString(list); response.setContentType("Content-type: application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(jsonText); } if (request.getParameter("watch").equals("true") && request.getParameter("idForTrans") != null) { System.out.println(request.getParameter("idForTrans") + "ID" + request.getParameter("myId")); String idFirstEndpoints = request.getParameter("idForTrans"); String idSecondEndpoints = MyWss.getListOfIdWhichIsConnected() .get(idFirstEndpoints); String idSessionForTranslation = request.getParameter("myId"); makeBroadcasting(idFirstEndpoints, idSecondEndpoints, idSessionForTranslation); } if (request.getParameter("watch").equals("stop")) { String idSessionForTranslation = request.getParameter("myId"); stopBroadcasting(idSessionForTranslation); } return; } if (request.getParameter("game") != null) { String action = request.getParameter("game"); String clientId = request.getParameter("clientId"); String opponentId = request.getParameter("opponentId"); String clientIddop = request.getParameter("clientIddop"); String opponentIddop = request.getParameter("opponentIddop"); if (action.equals("start")) { connectTwoSession(clientId, opponentId); connectTwoSession(clientIddop, opponentIddop); } if (action.equals("stop")) { disConnectTwoSession(clientId, opponentId); disConnectTwoSession(clientIddop, opponentIddop); } } String rId = RandomStringUtils.randomAlphanumeric(10); request.setAttribute("rId", rId); if (request.getParameter("opponentId") != null) { request.setAttribute("rId", rId); request.setAttribute("opponentId", request.getParameter("opponentId")); } RequestDispatcher rq = request.getRequestDispatcher("aero.jsp"); rq.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private void connectTwoSession(String clientId, String opponentId) { MyWss.getListOfIdWhichIsConnected().put(clientId, opponentId); MyWss.getListOfIdWhichIsConnected().put(opponentId, clientId); long time = System.currentTimeMillis(); MyWss.getStorageOfEndpoints().get(opponentId) .setSession(clientId, time); MyWss.getStorageOfEndpoints().get(clientId) .setSession(opponentId, time); } private void disConnectTwoSession(String clientId, String opponentId) { MyWss.getStorageOfEndpoints().get(opponentId) .unSetSession(clientId, "stop"); MyWss.getStorageOfEndpoints().get(clientId) .unSetSession(opponentId, "stop"); MyWss.getListOfIdWhichIsConnected().remove(clientId); MyWss.getListOfIdWhichIsConnected().remove(opponentId); } private void makeBroadcasting(String firstId, String secondId, String viewerId) { ArrayList<String> listOfIdForTrans = new ArrayList<String>(); listOfIdForTrans.add(firstId); listOfIdForTrans.add(firstId + "dop"); listOfIdForTrans.add(secondId); listOfIdForTrans.add(secondId + "dop"); Session sessionForBroadcasting = MyWss.getSessions().get(viewerId); Session dopSessionForBroadcasting = MyWss.getSessions().get( viewerId + "dop"); MyWss firstEndpoint = MyWss.getStorageOfEndpoints().get(firstId); MyWss firstEndpointDop = MyWss.getStorageOfEndpoints().get( firstId + "dop"); MyWss secondEndpoint = MyWss.getStorageOfEndpoints().get(secondId); MyWss secondEndpointDop = MyWss.getStorageOfEndpoints().get( secondId + "dop"); firstEndpoint.setMarkerForViewer("f"); firstEndpoint.getViewers().add(sessionForBroadcasting); firstEndpointDop.setMarkerForViewer("fd"); firstEndpointDop.getViewers().add(dopSessionForBroadcasting); secondEndpoint.setMarkerForViewer("s"); secondEndpoint.getViewers().add(sessionForBroadcasting); secondEndpointDop.setMarkerForViewer("sd"); secondEndpointDop.getViewers().add(dopSessionForBroadcasting); mapEndpointsForTranslation.put(viewerId, listOfIdForTrans); } private void stopBroadcasting(String viewerId) { Session session = MyWss.getSessions().get(viewerId); ArrayList<String> listForRemove = (ArrayList<String>) Aero .getMapEndpointsForTranslation().get(viewerId); Aero.getMapEndpointsForTranslation().remove(viewerId); for (String id : listForRemove) { MyWss endpoint = MyWss.getStorageOfEndpoints().get(id); endpoint.getViewers().remove(session); if (endpoint.getViewers().size() == 0) { endpoint.setMarkerForViewer(null); } } } public static Map<String, List<String>> getMapEndpointsForTranslation() { return mapEndpointsForTranslation; } public static void setMapEndpointsForTranslation( Map<String, List<String>> mapEndpointsForTranslation) { Aero.mapEndpointsForTranslation = mapEndpointsForTranslation; } }
d6116b7bc214fdc9c35ddadf672efb1dc5ebf589
3d4789e3a0c3ccb080cafcf1a97e84d67132a573
/src/test/java/gggg/HelloEventListener.java
d0c8967e33b3110dd885eb7c7be9d863ca269cf3
[]
no_license
narci2010/commonDemo
23e0eb53cae4389c6ab366dd8974c0697731df5e
16e05a8079e9084f2fdbdcedd27ea1db23cc3aaf
refs/heads/master
2021-07-08T02:58:09.489358
2017-10-05T04:08:14
2017-10-05T04:08:14
106,831,383
3
1
null
2017-10-13T13:59:19
2017-10-13T13:59:19
null
UTF-8
Java
false
false
1,059
java
package gggg; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; import org.junit.Test; /** * Created by yinlu on 2017/8/3. */ public class HelloEventListener { @Subscribe @AllowConcurrentEvents public void listen(OrderEvent event) { System.out.println("---我来了"); long start = System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { i++; for (int j = 0; j < 100000000; j++) { j++; } } System.out.println("---耗时"+(System.currentTimeMillis()-start)); System.out.println("receive msg:"+event.getMessage()); } @Test public void t() { System.out.println("---我来了"); long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { i++; for (int j = 0; j < 80000; j++) { j++; } } System.out.println("---耗时"+(System.currentTimeMillis()-start)); } }
19a75b7d50755bb773dc4fa5ba7f3473768a04f7
580130b6792a999537f6f859d4291e13983e2587
/Struts2_Spring_demo/src/com/breez/ssd/action/TaskAction.java
ec7cf639990efc9721e4ec7305ed1a964eeeb0db
[]
no_license
chenbinsgithub/Struts2_Spring_demo
9b020d6c2519c75e14e903d480d3e906ce0d6fbb
58c2d06a83ba06a01c50f0c0b9bf2c845d1cb2db
refs/heads/master
2021-01-10T19:51:03.024591
2015-01-05T04:36:58
2015-01-05T04:36:58
28,797,440
0
0
null
null
null
null
UTF-8
Java
false
false
691
java
package com.breez.ssd.action; import java.util.List; import com.breez.ssd.domain.Task; import com.breez.ssd.service.IGetTask; import com.opensymphony.xwork2.ActionSupport; public class TaskAction extends ActionSupport { private IGetTask getTask; private List<Task> tasks; @Override public String execute() throws Exception { this.setTasks(getTask.getTask()); return super.execute(); } public IGetTask getGetTask() { return getTask; } public void setGetTask(IGetTask getTask) { this.getTask = getTask; } public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } }
63dd6faf1d33c009415dd6b8c9affc0e2dbaaf02
72a43944b2d92b3c3d3a9d87d4c01bcdb4673b7b
/Weitu/src/main/java/com/quanjing/weitu/app/ui/user/FollowerFragment.java
fb04155f53415ab5b359bfaa97924f8fcead2000
[]
no_license
JokeLook/QuanjingAPP
ef5d5c21284bc29d0594b45ec36ac456c24186b8
40b2c1c286ffcca46c88942374fdd67a14611260
refs/heads/master
2020-07-15T01:02:27.443815
2015-04-27T06:08:19
2015-04-27T06:08:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,414
java
package com.quanjing.weitu.app.ui.user; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.quanjing.weitu.R; import com.quanjing.weitu.app.common.MWTCallback; import com.quanjing.weitu.app.model.MWTAuthManager; import com.quanjing.weitu.app.model.MWTRestManager; import com.quanjing.weitu.app.model.MWTTalent; import com.quanjing.weitu.app.model.MWTUser; import com.quanjing.weitu.app.model.MWTUserManager; import com.quanjing.weitu.app.protocol.MWTError; import com.quanjing.weitu.app.protocol.MWTUserData; import com.quanjing.weitu.app.protocol.service.MWTFollowerResult; import com.quanjing.weitu.app.protocol.service.MWTUserResult; import com.quanjing.weitu.app.protocol.service.MWTUserService; import com.quanjing.weitu.app.ui.common.MWTBaseActivity; import com.quanjing.weitu.app.ui.community.square.XCRoundImageView; import com.squareup.picasso.Picasso; import org.lcsky.SVProgressHUD; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * A simple {@link Fragment} subclass. */ public class FollowerFragment extends Fragment { private GridView follwerGridView; private FollowGridAdapter adapter; private String userID; private List<MWTUserData> followerResults; final MWTUserManager userManager = MWTUserManager.getInstance(); public FollowerFragment() { } public static FollowerFragment newInstance(String userID) { FollowerFragment followerFragment = new FollowerFragment(); Bundle args = new Bundle(); args.putString("userID", userID); followerFragment.setArguments(args); return followerFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { userID = getArguments().getString("userID"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_following, container, false); loadFollowers(); follwerGridView = (GridView) view.findViewById(R.id.grid_followings); return view; } private void loadFollowers() { SVProgressHUD.showInView(getActivity(), "加载中,请稍候...", true); MWTUserService userService = MWTRestManager.getInstance().create(MWTUserService.class); userService.queryFollowers(userID, 0, 50, new Callback<MWTFollowerResult>() { @Override public void success(MWTFollowerResult mwtFollowerResult, Response response) { SVProgressHUD.dismiss(getActivity()); followerResults = mwtFollowerResult.users; adapter = new FollowGridAdapter(getActivity(), followerResults); follwerGridView.setAdapter(adapter); follwerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { MWTUserData userData = (MWTUserData) adapter.getItem(i); if (userData != null) { Intent intent = new Intent(getActivity(), MWTOtherUserActivity.class); intent.putExtra("userID", userData.userID); startActivity(intent); } } }); } @Override public void failure(RetrofitError error) { SVProgressHUD.dismiss(getActivity()); Context ctx = getActivity(); if (ctx != null) { Toast.makeText(ctx, error.getMessage(), Toast.LENGTH_SHORT).show(); } } }); } class FollowGridAdapter extends BaseAdapter { private Context context; private List<MWTUserData> datas = new ArrayList<>(); public FollowGridAdapter(Context context, List<MWTUserData> datas) { this.context = context; this.datas = datas; } @Override public int getCount() { return datas.size(); } @Override public Object getItem(int position) { return datas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView.inflate(context, R.layout.item_grid_follow, null); XCRoundImageView tx_img = (XCRoundImageView) v.findViewById(R.id.ItemImage); TextView followState = (TextView) v.findViewById(R.id.followState); TextView tx_name = (TextView) v.findViewById(R.id.ItemText); final MWTUserData user = datas.get(position); final int p = position; tx_name.setText((String) user.nickname); followState.setVisibility(View.VISIBLE); MWTUser cUser = userManager.getCurrentUser(); if (cUser != null && cUser.getmwtFellowshipInfo().get_followingUserIDs().size() > 0) { if (cUser.getmwtFellowshipInfo().get_followingUserIDs().contains(user.userID)) followState.setText("取消关注"); else followState.setText("关注"); } followState.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (userManager.getCurrentUser() != null && userManager.getCurrentUser().getmwtFellowshipInfo().get_followingUserIDs().size() > 0) { if (userManager.getCurrentUser().getmwtFellowshipInfo().get_followingUserIDs().contains(user.userID)) cancelAttention(user.userID, p); else addAttention(user.userID, p); } } }); Picasso.with(context) .load(user.avatarImageInfo.url) .centerCrop().resize(200, 200) .placeholder(new ColorDrawable(Color.WHITE)) .into(tx_img); return v; } } /** * 关注 * * @param userid */ private void addAttention(final String userid, final int position) { MWTAuthManager am = MWTAuthManager.getInstance(); if (!am.isAuthenticated()) { new AlertDialog.Builder(getActivity()) .setTitle("请登录") .setMessage("请在登录后使用关注功能") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(getActivity(), MWTAuthSelectActivity.class); startActivity(intent); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .show(); return; } MWTRestManager restManager = MWTRestManager.getInstance(); MWTUserManager userManager = MWTUserManager.getInstance(); MWTUserService userService = restManager.create(MWTUserService.class); MWTUser cUser = userManager.getCurrentUser(); if (cUser == null) return; SVProgressHUD.showInView(getActivity(), "请稍后...", true); userService.addAttention(cUser.getUserID(), "follow", userid, new Callback<MWTUserResult>() { @Override public void success(MWTUserResult mwtUserResult, Response response) { refreshCurrentUser(); } @Override public void failure(RetrofitError error) { SVProgressHUD.dismiss(getActivity()); Toast.makeText(getActivity(), "关注失败", 500).show(); } }); } private void cancelAttention(String userid, final int positon) { MWTAuthManager am = MWTAuthManager.getInstance(); if (!am.isAuthenticated()) { new AlertDialog.Builder(getActivity()) .setTitle("请登录") .setMessage("请在登录后使用关注功能") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(getActivity(), MWTAuthSelectActivity.class); startActivity(intent); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .show(); return; } MWTRestManager restManager = MWTRestManager.getInstance(); MWTUserManager userManager = MWTUserManager.getInstance(); MWTUserService userService = restManager.create(MWTUserService.class); MWTUser cUser = userManager.getCurrentUser(); if (cUser == null) return; SVProgressHUD.showInView(getActivity(), "请稍后...", true); userService.addAttention(cUser.getUserID(), "unfollow", userid, new Callback<MWTUserResult>() { @Override public void success(MWTUserResult mwtUserResult, Response response) { refreshCurrentUser(); } @Override public void failure(RetrofitError error) { SVProgressHUD.dismiss(getActivity()); Toast.makeText(getActivity(), "取消失败", 500).show(); } }); } private void refreshCurrentUser() { MWTUser user = MWTUserManager.getInstance().getCurrentUser(); MWTUserManager.getInstance().refreshCurrentUserInfo(new MWTCallback() { @Override public void success() { SVProgressHUD.dismiss(getActivity()); adapter.notifyDataSetChanged(); } @Override public void failure(MWTError error) { } }); } }
0942683b9b067b71e6e438e2f1706331933b10a0
611b2f6227b7c3b4b380a4a410f357c371a05339
/src/main/java/cn/xports/baselib/util/DensityUtil.java
2f0af7f438f2c2759d6e2751015a44a9f5537548
[]
no_license
obaby/bjqd
76f35fcb9bbfa4841646a8888c9277ad66b171dd
97c56f77380835e306ea12401f17fb688ca1373f
refs/heads/master
2022-12-04T21:33:17.239023
2020-08-25T10:53:15
2020-08-25T10:53:15
290,186,830
3
1
null
null
null
null
UTF-8
Java
false
false
640
java
package cn.xports.baselib.util; import cn.xports.baselib.App; public class DensityUtil { public static int dp2px(float f) { return (int) ((f * App.getInstance().getResources().getDisplayMetrics().density) + 0.5f); } public static int px2dp(float f) { return (int) ((f / App.getInstance().getResources().getDisplayMetrics().density) + 0.5f); } public static int getScreenWidth() { return App.getInstance().getResources().getDisplayMetrics().widthPixels; } public static int getScreenHeight() { return App.getInstance().getResources().getDisplayMetrics().heightPixels; } }
92d67d95ecce9a7f717a29ade8e325573015353f
6c3ac4102c128c9a71797dd5626947cfa8e5ea72
/app/src/main/java/ba/sum/fpmoz/imm/ui/adapters/SubjectsProfesorAdapter.java
dcabd3396210a36e3b280d02df114bc071aafe8c
[]
no_license
mmarijad/Ednevnik-1
7fe8426bc78ea72518188c39beded4af60b7a5ab
77018fd3ae83957485d19f9504f3018fc4e69679
refs/heads/main
2023-03-02T08:59:05.811374
2021-02-07T23:20:53
2021-02-07T23:20:53
334,248,415
0
2
null
2021-02-08T07:07:54
2021-01-29T19:52:46
Java
UTF-8
Java
false
false
4,162
java
package ba.sum.fpmoz.imm.ui.adapters; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import ba.sum.fpmoz.imm.MainActivity; import ba.sum.fpmoz.imm.Ocijeni; import ba.sum.fpmoz.imm.R; import ba.sum.fpmoz.imm.TabbedClassesInfo; import ba.sum.fpmoz.imm.TabbedOcjeneProfesor; import ba.sum.fpmoz.imm.TabbedSubjectsInStudents; import ba.sum.fpmoz.imm.model.Subject; import ba.sum.fpmoz.imm.ui.fragments.classes.ListSubjectsInStudent; public class SubjectsProfesorAdapter extends FirebaseRecyclerAdapter<Subject, SubjectsProfesorAdapter.SubjectClassViewHolder> { public SubjectsProfesorAdapter(@NonNull FirebaseRecyclerOptions<Subject> options) { super(options); } @Override protected void onBindViewHolder(@NonNull SubjectClassViewHolder holder, int position, @NonNull Subject model) { holder.subjectName.setText(model.getName()); holder.id.setText(model.getNastavnik()); } @NonNull @Override public SubjectClassViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewholder_subjects_in_students, parent, false); SubjectClassViewHolder viewHolder = new SubjectsProfesorAdapter.SubjectClassViewHolder(view); viewHolder.setOnClickListener(new Adapter.ClickListener() { @Override public void OnClickListener(View v, int position) { } @Override public void OnLongClickListener(View v, int position) { } }); return viewHolder; } public class SubjectClassViewHolder extends RecyclerView.ViewHolder{ TextView subjectName, id, idd; Button ocjeneBtn, gradeStudentBtn; private FirebaseAuth mAuth; Adapter.ClickListener clickListener; public void setOnClickListener(Adapter.ClickListener clickListener){ this.clickListener = clickListener; } public SubjectClassViewHolder(@NonNull final View itemView) { super(itemView); subjectName = itemView.findViewById(R.id.subjectNameTxt); id = itemView.findViewById(R.id.idTxt); ocjeneBtn = itemView.findViewById(R.id.ocjeneBtn); gradeStudentBtn = itemView.findViewById(R.id.gradeStudentBtn); mAuth = FirebaseAuth.getInstance(); ocjeneBtn.setOnClickListener((v) -> { String key = getRef(getAdapterPosition()).getKey(); String keyy = getRef(getAdapterPosition()).getParent().getParent().getKey(); Intent i = new Intent(itemView.getContext(), TabbedOcjeneProfesor.class); i.putExtra("SUBJECT_ID", key); i.putExtra("STUDENT_ID", keyy); itemView.getContext().startActivity(i); } ); gradeStudentBtn.setOnClickListener((v) -> { String key = getRef(getAdapterPosition()).getKey(); String keyy = getRef(getAdapterPosition()).getParent().getParent().getKey(); Intent i = new Intent(itemView.getContext(), Ocijeni.class); i.putExtra("SUBJECT_ID", key); i.putExtra("STUDENT_ID", keyy); itemView.getContext().startActivity(i); } ); itemView.setOnClickListener((v) -> clickListener.OnClickListener(v, getAdapterPosition())); itemView.setOnLongClickListener((v) -> { clickListener.OnClickListener(v, getAdapterPosition()); return true; } ); } } }
5deabd6088ec1c5a277beee0fdfab4e14ad23e7c
13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3
/crash-reproduction-ws/results/MATH-4b-1-20-Single_Objective_GGA-WeightedSum/org/apache/commons/math3/geometry/euclidean/threed/Line_ESTest.java
5192c2f51145d009db723dceaddf5e8ad4fafc56
[ "MIT", "CC-BY-4.0" ]
permissive
STAMP-project/Botsing-basic-block-coverage-application
6c1095c6be945adc0be2b63bbec44f0014972793
80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da
refs/heads/master
2022-07-28T23:05:55.253779
2022-04-20T13:54:11
2022-04-20T13:54:11
285,771,370
0
0
null
null
null
null
UTF-8
Java
false
false
968
java
/* * This file was automatically generated by EvoSuite * Tue Mar 31 09:42:07 UTC 2020 */ package org.apache.commons.math3.geometry.euclidean.threed; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import org.apache.commons.math3.geometry.euclidean.threed.Line; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class Line_ESTest extends Line_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { Vector3D vector3D0 = Vector3D.PLUS_J; Vector3D vector3D1 = Vector3D.crossProduct(vector3D0, vector3D0); Line line0 = new Line(vector3D1, vector3D0); // Undeclared exception! line0.getAbscissa((Vector3D) null); } }
0d232cf9e9a73088d363e85da2d5e02b26698f37
1829e4f828696e5596e808d7a85c3448f40a8555
/src/main/java/com/urbanfit/bem/util/UploadImageUtil.java
5a38793ed513c0911b881ce27d23a8b7c18998d9
[]
no_license
SunShibo/urbanfit-back-end-management
f5bf729509fce6aa2e2181127830545fa5606f1e
3d6222a18b0fc7034f394a88c5c1905b19199e43
refs/heads/master
2020-03-09T04:59:03.334681
2018-08-20T14:05:13
2018-08-20T14:05:13
128,600,970
0
1
null
null
null
null
UTF-8
Java
false
false
1,673
java
package com.urbanfit.bem.util; import com.urbanfit.bem.cfg.pop.SystemConfig; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.text.MessageFormat; import java.util.Date; /** * Created by Administrator on 2018/7/6. */ public class UploadImageUtil { public static String uploadImage(MultipartFile file, String uploadImageUrl){ //获得文件类型(可以判断如果不是图片,禁止上传) String contentType = file.getContentType(); String random = RandomUtil.generateString(4); //获得文件后缀名称 String imageType = contentType.substring(contentType.indexOf("/") + 1); String yyyyMMdd = DateUtils.formatDate(DateUtils.DATE_PATTERN_PLAIN, new Date()); String yyyyMMddHHmmss = DateUtils.formatDate(DateUtils.LONG_DATE_PATTERN_PLAIN, new Date()); String fileName = yyyyMMddHHmmss + random + "." + imageType; String urlMsg = SystemConfig.getString(uploadImageUrl); urlMsg = MessageFormat.format(urlMsg, new Object[]{yyyyMMdd, fileName}); String imageUrl = urlMsg.replace("/attached", SystemConfig.getString("img_file_root")); String msgUrl = SystemConfig.getString("client_upload_base"); String tmpFileUrl = msgUrl + urlMsg; File ff = new File(tmpFileUrl.substring(0, tmpFileUrl.lastIndexOf('/'))); if (!ff.exists()) { ff.mkdirs(); } byte[] tmp = null; try { tmp = file.getBytes(); } catch (Exception e) { e.printStackTrace(); } FileUtils.getFileFromBytes(tmp, tmpFileUrl); return imageUrl; } }
66aa063b429835975e32fdbf52efdcbbc2d362cd
df5a38e75e28765e54b9bf12908c403d2a005b5c
/src/main/java/util/epub/util/commons/io/BOMInputStream.java
191175a8262c7023d65a918d903b1eecc469ab31
[]
no_license
PorUnaCabeza/EzraPound
dd0452c56216b871c19fc0888c56198b6013c7b1
276dc49a7ea00c3abf5bc55a3c8e5848d598e142
refs/heads/master
2021-01-21T04:30:40.130869
2016-07-28T11:18:21
2016-07-28T11:18:21
49,518,366
6
3
null
null
null
null
UTF-8
Java
false
false
11,348
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 util.epub.util.commons.io; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; /** * This class is used to wrap a stream that includes an encoded * {@link ByteOrderMark} as its first bytes. * * This class detects these bytes and, if required, can automatically skip them * and return the subsequent byte as the first byte in the stream. * * The {@link ByteOrderMark} implementation has the following pre-defined BOMs: * <ul> * <li>UTF-8 - {@link ByteOrderMark#UTF_8}</li> * <li>UTF-16BE - {@link ByteOrderMark#UTF_16LE}</li> * <li>UTF-16LE - {@link ByteOrderMark#UTF_16BE}</li> * </ul> * * * <h3>Example 1 - Detect and exclude a UTF-8 BOM</h3> * <pre> * BOMInputStream bomIn = new BOMInputStream(in); * if (bomIn.hasBOM()) { * // has a UTF-8 BOM * } * </pre> * * <h3>Example 2 - Detect a UTF-8 BOM (but don't exclude it)</h3> * <pre> * boolean include = true; * BOMInputStream bomIn = new BOMInputStream(in, include); * if (bomIn.hasBOM()) { * // has a UTF-8 BOM * } * </pre> * * <h3>Example 3 - Detect Multiple BOMs</h3> * <pre> * BOMInputStream bomIn = new BOMInputStream(in, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE); * if (bomIn.hasBOM() == false) { * // No BOM found * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) { * // has a UTF-16LE BOM * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) { * // has a UTF-16BE BOM * } * </pre> * * @see org.apache.commons.io.ByteOrderMark * @see <a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia - Byte Order Mark</a> * @version $Revision: 1052095 $ $Date: 2010-12-22 23:03:20 +0000 (Wed, 22 Dec 2010) $ * @since Commons IO 2.0 */ public class BOMInputStream extends ProxyInputStream { private final boolean include; private final List<ByteOrderMark> boms; private ByteOrderMark byteOrderMark; private int[] firstBytes; private int fbLength; private int fbIndex; private int markFbIndex; private boolean markedAtStart; /** * Constructs a new BOM InputStream that excludes * a {@link ByteOrderMark#UTF_8} BOM. * @param delegate the InputStream to delegate to */ public BOMInputStream(InputStream delegate) { this(delegate, false, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that detects a * a {@link ByteOrderMark#UTF_8} and optionally includes it. * @param delegate the InputStream to delegate to * @param include true to include the UTF-8 BOM or * false to exclude it */ public BOMInputStream(InputStream delegate, boolean include) { this(delegate, include, ByteOrderMark.UTF_8); } /** * Constructs a new BOM InputStream that excludes * the specified BOMs. * @param delegate the InputStream to delegate to * @param boms The BOMs to detect and exclude */ public BOMInputStream(InputStream delegate, ByteOrderMark... boms) { this(delegate, false, boms); } /** * Constructs a new BOM InputStream that detects the * specified BOMs and optionally includes them. * @param delegate the InputStream to delegate to * @param include true to include the specified BOMs or * false to exclude them * @param boms The BOMs to detect and optionally exclude */ public BOMInputStream(InputStream delegate, boolean include, ByteOrderMark... boms) { super(delegate); if (boms == null || boms.length == 0) { throw new IllegalArgumentException("No BOMs specified"); } this.include = include; this.boms = Arrays.asList(boms); } /** * Indicates whether the stream contains one of the specified BOMs. * * @return true if the stream has one of the specified BOMs, otherwise false * if it does not * @throws IOException if an error reading the first bytes of the stream occurs */ public boolean hasBOM() throws IOException { return (getBOM() != null); } /** * Indicates whether the stream contains the specified BOM. * * @param bom The BOM to check for * @return true if the stream has the specified BOM, otherwise false * if it does not * @throws IllegalArgumentException if the BOM is not one the stream * is configured to detect * @throws IOException if an error reading the first bytes of the stream occurs */ public boolean hasBOM(ByteOrderMark bom) throws IOException { if (!boms.contains(bom)) { throw new IllegalArgumentException("Stream not configure to detect " + bom); } return (byteOrderMark != null && getBOM().equals(bom)); } /** * Return the BOM (Byte Order Mark). * * @return The BOM or null if none * @throws IOException if an error reading the first bytes of the stream occurs */ public ByteOrderMark getBOM() throws IOException { if (firstBytes == null) { int max = 0; for (ByteOrderMark bom : boms) { max = Math.max(max, bom.length()); } firstBytes = new int[max]; for (int i = 0; i < firstBytes.length; i++) { firstBytes[i] = in.read(); fbLength++; if (firstBytes[i] < 0) { break; } byteOrderMark = find(); if (byteOrderMark != null) { if (!include) { fbLength = 0; } break; } } } return byteOrderMark; } /** * Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}. * * @return The BOM charset Name or null if no BOM found * @throws IOException if an error reading the first bytes of the stream occurs * */ public String getBOMCharsetName() throws IOException { getBOM(); return (byteOrderMark == null ? null : byteOrderMark.getCharsetName()); } /** * This method reads and either preserves or skips the first bytes in the * stream. It behaves like the single-byte <code>read()</code> method, * either returning a valid byte or -1 to indicate that the initial bytes * have been processed already. * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException if an I/O error occurs */ private int readFirstBytes() throws IOException { getBOM(); return (fbIndex < fbLength) ? firstBytes[fbIndex++] : -1; } /** * Find a BOM with the specified bytes. * * @return The matched BOM or null if none matched */ private ByteOrderMark find() { for (ByteOrderMark bom : boms) { if (matches(bom)) { return bom; } } return null; } /** * Check if the bytes match a BOM. * * @param bom The BOM * @return true if the bytes match the bom, otherwise false */ private boolean matches(ByteOrderMark bom) { if (bom.length() != fbLength) { return false; } for (int i = 0; i < bom.length(); i++) { if (bom.get(i) != firstBytes[i]) { return false; } } return true; } //---------------------------------------------------------------------------- // Implementation of InputStream //---------------------------------------------------------------------------- /** * Invokes the delegate's <code>read()</code> method, detecting and * optionally skipping BOM. * @return the byte read (excluding BOM) or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read() throws IOException { int b = readFirstBytes(); return (b >= 0) ? b : in.read(); } /** * Invokes the delegate's <code>read(byte[], int, int)</code> method, detecting * and optionally skipping BOM. * @param buf the buffer to read the bytes into * @param off The start offset * @param len The number of bytes to read (excluding BOM) * @return the number of bytes read or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(byte[] buf, int off, int len) throws IOException { int firstCount = 0; int b = 0; while ((len > 0) && (b >= 0)) { b = readFirstBytes(); if (b >= 0) { buf[off++] = (byte) (b & 0xFF); len--; firstCount++; } } int secondCount = in.read(buf, off, len); return (secondCount < 0) ? (firstCount > 0 ? firstCount : -1) : firstCount + secondCount; } /** * Invokes the delegate's <code>read(byte[])</code> method, detecting and * optionally skipping BOM. * @param buf the buffer to read the bytes into * @return the number of bytes read (excluding BOM) * or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public int read(byte[] buf) throws IOException { return read(buf, 0, buf.length); } /** * Invokes the delegate's <code>mark(int)</code> method. * @param readlimit read ahead limit */ @Override public synchronized void mark(int readlimit) { markFbIndex = fbIndex; markedAtStart = (firstBytes == null); in.mark(readlimit); } /** * Invokes the delegate's <code>reset()</code> method. * @throws IOException if an I/O error occurs */ @Override public synchronized void reset() throws IOException { fbIndex = markFbIndex; if (markedAtStart) { firstBytes = null; } in.reset(); } /** * Invokes the delegate's <code>skip(long)</code> method, detecting * and optionallyskipping BOM. * @param n the number of bytes to skip * @return the number of bytes to skipped or -1 if the end of stream * @throws IOException if an I/O error occurs */ @Override public long skip(long n) throws IOException { while ((n > 0) && (readFirstBytes() >= 0)) { n--; } return in.skip(n); } }
b8dbba57af609cbdb227f5c4a66a1fc352954bc3
149edf11f9f4021b6a95a29cd314846bf1ba0fd5
/src/algorithm/FindRunningMedian.java
70609a8e97144503af8acba5ffe805241f520548
[]
no_license
jGomz/Algorithms
ba9b5ea9ecb1cfd1581868479c44d4c8c913d3f5
a2a60e0ae3db3afdaf12acccfb5826f7a9259e6e
refs/heads/master
2023-02-18T09:31:40.778194
2021-01-23T18:33:35
2021-01-23T18:33:35
330,474,794
0
0
null
null
null
null
UTF-8
Java
false
false
2,221
java
package algorithm; import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class FindRunningMedian { /* * Complete the runningMedian function below. */ static double[] runningMedian(int[] a) { /* * Write your code here. */ double[] dArr = new double[a.length]; PriorityQueue<Integer> minHeap = new PriorityQueue<>(); PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); for(int i=0 ; i<a.length ; i++) { if (maxHeap.isEmpty()) { maxHeap.add(a[i]); } else if (maxHeap.size() == minHeap.size()) { if (a[i] < minHeap.peek()) { maxHeap.add(a[i]); } else { minHeap.add(a[i]); maxHeap.add(minHeap.remove()); } } else if (maxHeap.size() > minHeap.size()) { if (a[i] > maxHeap.peek()) { minHeap.add(a[i]); } else { maxHeap.add(a[i]); minHeap.add(maxHeap.remove()); } } if (maxHeap.isEmpty()) { } else if (maxHeap.size() == minHeap.size()) { dArr[i] = (maxHeap.peek() + minHeap.peek()) / 2.0; } else { // maxHeap must have more elements than minHeap dArr[i] = maxHeap.peek(); } } return dArr; } public static void main(String[] args) throws IOException { int[] a = new int[] {94455, 20555, 20535, 53125, 73634, 148, 63772, 17738, 62995, 13401, 95912, 13449, 92211, 17073, 69230, 22016, 22120, 78563, 16571, 1817, 41510, 74518}; double[] result = runningMedian(a); System.out.println(Arrays.toString(result)); } }
a9df26ae73ca36def8c788af08a857117f55cebb
421ef0fe8b716549c67c3abf675e60c878108906
/customer-api-biz/src/main/java/com/duantuke/api/pay/common/RefundService.java
e9f970e99b2825baa6e54a7fb55163b2faf3931a
[]
no_license
maoyuming/customer-api
17273339d71703f6fbc1cd081a89209504adc61b
67b82c8034bdf66f46cefb01769376e8a8f53e80
refs/heads/master
2021-01-20T18:24:06.747446
2016-07-28T08:59:54
2016-07-28T08:59:54
64,301,303
0
0
null
null
null
null
UTF-8
Java
false
false
887
java
package com.duantuke.api.pay.common; /** * User: rizenguo * Date: 2014/10/29 * Time: 16:04 */ public class RefundService extends BaseService{ public RefundService() throws IllegalAccessException, InstantiationException, ClassNotFoundException { super(PayConfig.WECHAT_REFUND_API); } /** * 请求退款服务 * @param refundReqData 这个数据对象里面包含了API要求提交的各种数据字段 * @return API返回的XML数据 * @throws Exception */ public String request(RefundReqData refundReqData) throws Exception { //-------------------------------------------------------------------- //发送HTTPS的Post请求到API地址 //-------------------------------------------------------------------- String responseString = sendPost(refundReqData); return responseString; } }
8a47e8ec9b1a1accc7dcd929c710814132f4a613
e539799efb6cd328ea9e80a38847e9129ca1679b
/SummaryTask4/test/ua/nure/khainson/SummaryTask4/web/filter/CommandAccessFilterTest.java
642395286a19640bc3c07dd87b62c98702df8427
[]
no_license
PolinaKhainson/InternetBanking
96e986dc09c95e47f3a5888dfe55a5778911504b
9cd29f0f5f3ae15bbe2c8032f4a5de842534be63
refs/heads/master
2016-09-14T10:37:27.293935
2016-05-12T05:58:24
2016-05-12T05:58:24
58,612,663
0
0
null
null
null
null
UTF-8
Java
false
false
310
java
package ua.nure.khainson.SummaryTask4.web.filter; import static org.junit.Assert.*; import org.junit.Test; public class CommandAccessFilterTest { @Test public void test() { CommandAccessFilter commandAccessFilter = new CommandAccessFilter(); assertNotNull(commandAccessFilter); } }
46d8f9a1fa42f0d73efd68da9d67579034f7167b
6429ff62e5bb8d68641161a6974e8d7e6f39a999
/src/test/java/org/essentials4j/DoCollTest.java
04b07b7c474215606eaf67dc79a8443c5221b47f
[ "Apache-2.0" ]
permissive
essentials4j/essentials4j
1cbf360c87b6700982cac930264fd877bfc5d956
32791d8442b6e5ed096c21383ae7839a789494f1
refs/heads/master
2023-03-08T17:53:11.364693
2018-02-08T21:40:37
2018-02-08T21:40:37
107,420,829
78
7
Apache-2.0
2018-02-08T21:40:38
2017-10-18T14:38:00
Java
UTF-8
Java
false
false
1,905
java
/*- * #%L * essentials4j * %% * Copyright (C) 2017 Nikolche Mihajlovski * %% * 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. * #L% */ package org.essentials4j; import org.junit.Assert; import org.junit.Test; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Nikolche Mihajlovski * @since 1.0.0 */ public class DoCollTest extends TestCommons { private final List<String> abc = New.list("a", "bb", "cc"); @Test public void doMapToList() { List<Integer> lengths = Do.map(abc).toList(String::length); eq(lengths, New.list(1, 2, 2)); } @Test public void listToMap() { Map<String, Integer> lengthsByWord = Do.map(abc).toMap(s -> s, String::length); expectMap(lengthsByWord, New.map("a", 1, "bb", 2, "cc", 2)); } @Test public void listToMapConflicting() { try { Do.map(abc).toMap(String::length, s -> s); } catch (IllegalArgumentException e) { // this is expected eq(e.getMessage(), "Both values [bb] and [cc] have the same key!"); return; } Assert.fail("Expected IllegalArgumentException!"); } @Test public void groupListBy() { Map<Integer, List<String>> byLength = Do.group(abc).by(String::length); expectMap(byLength, New.map(1, New.list("a"), 2, New.list("bb", "cc"))); } @Test public void listToSet() { Set<Integer> lengths = Do.map(abc).toSet(String::length); eq(lengths, New.set(1, 2)); } }
388c586c5427f51d07073d774a1ead9c59609971
e6f97043701dc95755691f5884959d76f1586e73
/src/br/com/caelum/iogi/conversion/ShortWrapperConverter.java
f7e85cc1b6f404af155042f9b8d4ba80ffff765c
[ "Apache-2.0" ]
permissive
VijayEluri/Iogi
d7a080c1ef18223dcfe24f95599517e7fe447b42
5694075ef519c7842cc4038ecb1f0c57c479b7e6
refs/heads/master
2020-05-20T10:54:11.739275
2015-10-06T21:10:07
2015-10-06T21:10:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package br.com.caelum.iogi.conversion; import br.com.caelum.iogi.reflection.Target; public class ShortWrapperConverter extends TypeConverter<Short> { public boolean isAbleToInstantiate(final Target<?> target) { return target.getClassType() == Short.class; } @Override protected Short convert(final String stringValue, final Target<?> to) { return Short.parseShort(stringValue); } }
0431ff27b9853b7ca504d9977f5fdeba05a8b546
b07ba591f88ce603f9fcf32325b5520612f8c99b
/Exam-13259-20170313-1/src/main/java/JDBCServlet/InsertServlet.java
9bc20caa5d9c67ba3d9ee82b7982b5bcf191777b
[]
no_license
liben13259/gitJavaExam
747a330b7447132d823af47f0b0c7f36c54e3892
19246248d7a1275c692a6867f8021b1d2d3fd1fd
refs/heads/master
2020-05-23T20:16:57.124049
2017-03-13T05:06:58
2017-03-13T05:06:58
84,785,729
0
0
null
null
null
null
UTF-8
Java
false
false
1,642
java
package JDBCServlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import JDBCEntity.Message; import JDBCService.checkService; /** * Servlet implementation class InsertServlet */ public class InsertServlet extends HttpServlet { private static final long serialVersionUID = 1L; private checkService cs = new checkService(); /** * @see HttpServlet#HttpServlet() */ public InsertServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); String description = request.getParameter("description"); String name = request.getParameter("name"); Message msg = new Message(); if(title == "" || description == "" || name == ""){ msg.setMsg("不能为空!"); RequestDispatcher rd = request.getRequestDispatcher("msg_select.jsp"); rd.forward(request, response); return; } cs.insert(title, description, name); RequestDispatcher rd = request.getRequestDispatcher("msg_success.jsp"); rd.forward(request, response); } }
e54bb60813034e001954b9ec876a858752cc732d
b58d1e441881abd947ed30a761a9d1f5585dc356
/src/nl/hu/hadoop/languagefinder/LanguageFinder.java
8024de237af642db83fdf6029c73d0ac9ba13c15
[]
no_license
vincent92/LanguageFinder
a3f661eb46ebf1f5f83fe535cc13004cb521c054
781b29fc95b2a20f81419646e34be53d88462751
refs/heads/master
2021-01-10T01:27:18.631986
2016-03-25T17:19:51
2016-03-25T17:19:51
54,733,312
0
0
null
null
null
null
UTF-8
Java
false
false
2,729
java
package nl.hu.hadoop.languagefinder; import java.io.IOException; import java.text.Normalizer; import java.util.Iterator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.*; import org.apache.hadoop.mapreduce.lib.output.*; public class LanguageFinder { public static void main(String[] args) throws Exception { Job job = new Job(); job.setJarByClass(LanguageFinder.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(PredictorMapper.class); job.setReducerClass(PredictorReducer.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); // job.setOutputValueClass(IntWritable.class); job.waitForCompletion(true); } } class PredictorMapper extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable Key, Text value, Context context) throws IOException, InterruptedException { //convert line to clear and readable characters String line = normalizeSentence(value); // retrieve the words from the line String[] words = line.split("\\s"); for (String word : words) { context.write(new Text(line), new Text(word)); } } private String normalizeSentence(Text value) { String line = value.toString().trim().replaceAll(" +", " "); line = Normalizer.normalize(line, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""); line = line.toLowerCase().replaceAll("[^A-Za-z ]", "").trim().replaceAll(" +", " "); return line; } } class PredictorReducer extends Reducer<Text, Text, Text, Text> { final static String ENGLISH_DICTIONARY = "/home/vincent/hadoop/hadoop-2.7.2/english_dictionary"; private LanguagePredictor predictor = new LanguagePredictor(new Dictionary(ENGLISH_DICTIONARY)); public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { int wordsSize = 0; double sumWordsPrediction = 0; Iterator<Text> words = values.iterator(); while (words.hasNext()) { String word = words.next().toString(); double prediction = predictor.calculatePrediction(word); sumWordsPrediction += prediction; wordsSize++; } double sentencePrediction = (sumWordsPrediction / wordsSize); //round of to two decimals behind comma sentencePrediction = (double) Math.round(sentencePrediction * 100) / 100; context.write(key, new Text(sentencePrediction + "%")); } }
14c360f3dec6c2acceb0ec87dab8617d95d97597
33ea5754504a3a1b409376529d18ba2d94da7054
/MAProject/src/mining/Cluster.java
e1b2a1f52f4bb35e52215e00013c3879898c7ab3
[]
no_license
invito98/Gruppo20
d9b32dedb179b583c3e72b225f53a91b91827e84
29c9ff69bdcfdb8849adb2e64358e39680becdd3
refs/heads/master
2020-03-15T12:55:28.796457
2018-07-26T19:15:10
2018-07-26T19:15:10
132,154,695
0
0
null
2018-05-11T12:51:31
2018-05-04T15:02:39
Java
WINDOWS-1252
Java
false
false
2,279
java
package mining; import java.util.*; import java.io.*; import data.*; public class Cluster implements Serializable{ private Tuple centroid; // vettore di item, contenenti un Attribute e un oggetto private HashSet<Integer> clusteredData; // vettore inizialmente di booleani Cluster() // costruttore con valori casuali { centroid = new Tuple(5); clusteredData = new HashSet<Integer>(); } Cluster(Tuple centroid) { this.centroid = centroid; clusteredData = new HashSet<Integer>(); } Tuple getCentroid() { return centroid; } void computeCentroid(Data data) { for (int i = 0; i < centroid.getLength(); i++) { centroid.get(i).update(data, clusteredData); } } //return true if the tuple is changing cluster boolean addData(int id) { return clusteredData.add(id); } //verifica se una transazione Ë clusterizzata nell'array corrente boolean contain(int id) { Iterator<Integer> itr = clusteredData.iterator(); while (itr.hasNext()) { if (itr.next() == id) { return true; } } return false; } //remove the tuple that has changed the cluster void removeTuple(int id) { Iterator<Integer> itr = clusteredData.iterator(); while (itr.hasNext()) { if (itr.next() == id) { clusteredData.remove((Integer)id); return; } } } public String toString() { String str = "Centroid = ("; for (int i = 0; i < centroid.getLength(); i++) { str += centroid.get(i); } str += ")"; return str; } public String toString(Data data) { String str = "Centroid = ("; for (int i = 0; i < centroid.getLength(); i++) str += centroid.get(i) + " "; str += ")\nExamples:\n"; Iterator<Integer> itr = clusteredData.iterator(); for (int i = 0; i < clusteredData.size(); i++) { int riga = itr.next(); str += "[ "; for (int j = 0; j < data.getNumberOfExplanatoryAttributes(); j++) { str += data.getAttributeValue(riga, j) + " "; } str += "] dist = " + getCentroid().getDistance(data.getItemSet(riga)) + "\n"; } str += "\n AvgDistance = "+ getCentroid().avgDistance(data, clusteredData) + "\n"; return str; } }
4aacd9fe732cde1ac9e4c7e0cd22ef7438b62e71
1930d97ebfc352f45b8c25ef715af406783aabe2
/src/main/java/com/alipay/api/domain/AlipayMarketingCampaignDiscountWhitelistUpdateModel.java
a66dd84e531978856f6a61ee5e656b9dd4911cfb
[ "Apache-2.0" ]
permissive
WQmmm/alipay-sdk-java-all
57974d199ee83518523e8d354dcdec0a9ce40a0c
66af9219e5ca802cff963ab86b99aadc59cc09dd
refs/heads/master
2023-06-28T03:54:17.577332
2021-08-02T10:05:10
2021-08-02T10:05:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
880
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 优惠活动白名单设置 * * @author auto create * @since 1.0, 2019-05-15 15:30:43 */ public class AlipayMarketingCampaignDiscountWhitelistUpdateModel extends AlipayObject { private static final long serialVersionUID = 7515278731691393141L; /** * 活动id */ @ApiField("camp_id") private String campId; /** * 白名单。逗号分隔开 */ @ApiField("user_white_list") private String userWhiteList; public String getCampId() { return this.campId; } public void setCampId(String campId) { this.campId = campId; } public String getUserWhiteList() { return this.userWhiteList; } public void setUserWhiteList(String userWhiteList) { this.userWhiteList = userWhiteList; } }
51afd1df8342e9917b2f396460bc62b0234ec142
07efa03a2f3bdaecb69c2446a01ea386c63f26df
/eclipse_jee/Toolbox/TestPatterns2/com/idc/test/TestVenusInfo.java
a826616200b4e5865d6d7d91112f44a5bf90d9de
[]
no_license
johnvincentio/repo-java
cc21e2b6e4d2bed038e2f7138bb8a269dfabeb2c
1824797cb4e0c52e0945248850e40e20b09effdd
refs/heads/master
2022-07-08T18:14:36.378588
2020-01-29T20:55:49
2020-01-29T20:55:49
84,679,095
0
0
null
2022-06-30T20:11:56
2017-03-11T20:51:46
Java
UTF-8
Java
false
false
1,694
java
package com.idc.test; import java.io.Serializable; import com.idc.pattern.patterns.KeyItemInfo; import com.idc.pattern.patterns.VenusInfo; public class TestVenusInfo extends VenusInfo implements Serializable { private static final long serialVersionUID = 1L; public TestVenusInfo () {super();} public TestVenusInfo (int capacity) {super (capacity);} public void add (DddItemInfo item) {super.add (getKeyItemInfo (item), item);} public KeyItemInfo getKeyItemInfo (DddItemInfo dddItemInfo) { return new DddKeyItemInfo (dddItemInfo.getName(), dddItemInfo.getIValue(), dddItemInfo.getLValue()); } public KeyItemInfo getKeyItemInfo (String name, int iValue, long lValue) { return new DddKeyItemInfo (name, iValue, lValue); } public class DddKeyItemInfo implements KeyItemInfo { private String name; private int iValue; private long lValue; private int hashCode = 0; public DddKeyItemInfo (String name, int iValue, long lValue) { this.name = name; this.iValue = iValue; this.lValue = lValue; hashCode = (name + ";" + Integer.toString(iValue) + ";" + Long.toString(lValue)).hashCode(); System.out.println("DddKeyItemInfo constructor:: name "+name+" iValue "+iValue+" lValue "+lValue); } public String getName() {return name;} public int getIValue() {return iValue;} public long getLValue() {return lValue;} public int hashCode() {return hashCode;} public boolean equals (Object obj) { if (obj == null || ! (obj instanceof KeyItemInfo)) return false; if (this.hashCode != ((KeyItemInfo) obj).hashCode()) return false; return true; } public String toString() { return "("+getName()+","+getIValue()+","+getLValue()+")"; } } }
3b0e42cf5cfef2c87342ec97df1ab9bb35a280b8
b6d311c285bde276527158b06e9280aa630d54dc
/security-jwt-service-resources/src/main/java/charlie/feng/sso/App.java
d51cce0845df48d53fb68058dcf97e731c596688
[]
no_license
fengertao/SpringBootSSO
189bc58957aae8ac0cd195bbbcdaba7074817a23
095a101c7f19df199f5140f2c6db091030db6d50
refs/heads/master
2023-08-02T17:28:14.003378
2021-09-28T06:06:49
2021-09-28T14:37:54
411,156,531
0
0
null
null
null
null
UTF-8
Java
false
false
565
java
package charlie.feng.sso; import charlie.feng.sso.config.RsaKeyProperties; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @MapperScan("charlie.feng.sso.mapper") @EnableConfigurationProperties(RsaKeyProperties.class) public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
99a40a0fe5ebca8f28fb17214d12cd3348a80554
8ec4e48e3f1d2b417862297c3ec593ad56440d45
/src/org/lion/java/sqlite/demo/model/Monkey.java
933f19ab71811348e3a7dff6144b22ea1d8b1913
[]
no_license
onlynight/sqlite-java-demo
52373d70de3a9345ee67a88bc9bb656033dc939a
838ffc038cd73f2148e7b3e3b4c71356d3ed1b6c
refs/heads/master
2020-04-23T13:38:44.047111
2014-05-23T13:13:24
2014-05-23T13:13:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
276
java
package org.lion.java.sqlite.demo.model; import org.lion.database.annotation.Table; @Table public class Monkey extends Animal{ private String monkey; public String getMonkey() { return monkey; } public void setMonkey(String monkey) { this.monkey = monkey; } }
c9c4fb0b5b9cb829df4f031a57d5150da34801b1
287663d96489762f7c72e0eeb20862a2a3669687
/app/src/main/java/com/pablotorres/ifoodist/iu/recipe/AddRecipeFragment/AddRecipeFragment.java
9dc5b3845c4d79043b220fee70bf08070a26d2e0
[]
no_license
PabloTorresGodoy/IFoodist
4559f6f18a788a0575026d352b184f4860faf080
5cfac03b1e12a5bcfbc28725fc7f5c0f9c3994c5
refs/heads/main
2023-05-30T04:11:50.500475
2021-06-09T15:13:55
2021-06-09T15:13:55
364,294,681
0
0
null
null
null
null
UTF-8
Java
false
false
7,709
java
package com.pablotorres.ifoodist.iu.recipe.AddRecipeFragment; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.google.firebase.firestore.FirebaseFirestore; import com.pablotorres.ifoodist.R; import com.pablotorres.ifoodist.data.model.Recipe; import com.pablotorres.ifoodist.data.repository.Account; import com.pablotorres.ifoodist.iu.adapter.IngredienteAdapter; import com.pablotorres.ifoodist.iu.adapter.PasoAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class AddRecipeFragment extends Fragment implements AddRecipeContract.View { private Spinner spinner; private FloatingActionButton fab; private Button btGuardar; private RecyclerView rvIngredientes; private RecyclerView rvPasos; private TextInputEditText tieNombre; private TextInputLayout tilNombre; private TextInputEditText tieDuracion; private TextInputEditText tieCantidad; private ImageButton btAddIngrediente; private ImageButton btAddPaso; private EditText edIngredientes; private EditText edPasos; private IngredienteAdapter adapterIngrediente; private PasoAdapter adapterPaso; private ArrayList<String> prueba = new ArrayList<>(); private Recipe recipe; private FirebaseFirestore db; private AddRecipePresenter presenter; public AddRecipeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_add_receta, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); db = FirebaseFirestore.getInstance(); btGuardar = view.findViewById(R.id.btGuardar); tieNombre=view.findViewById(R.id.tieNombre); tieCantidad=view.findViewById(R.id.tieCantidad); tieDuracion=view.findViewById(R.id.tieDuracion); tilNombre = view.findViewById(R.id.tilNombre); edIngredientes = view.findViewById(R.id.edIngredientes); edPasos = view.findViewById(R.id.edPasos); spinner = view.findViewById(R.id.spCategoria); fab = getActivity().findViewById(R.id.fab); fab.setVisibility(View.GONE); rvIngredientes = view.findViewById(R.id.rvIngredientes); adapterIngrediente = new IngredienteAdapter(new ArrayList<>()); RecyclerView.LayoutManager layoutManagerIngrediente = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL,false ); rvIngredientes.setLayoutManager(layoutManagerIngrediente); rvIngredientes.setAdapter(adapterIngrediente); presenter = new AddRecipePresenter(this); btAddIngrediente = view.findViewById(R.id.btAddIngrediente); btAddIngrediente.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapterIngrediente.insertar(edIngredientes.getText().toString()); edIngredientes.setText(""); } }); rvPasos = view.findViewById(R.id.rvPasos); adapterPaso = new PasoAdapter(new ArrayList<>()); RecyclerView.LayoutManager layoutManagerPaso = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL,false ); rvPasos.setLayoutManager(layoutManagerPaso); rvPasos.setAdapter(adapterPaso); btAddPaso = view.findViewById(R.id.btAddPasos); btAddPaso.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapterPaso.insertar(edPasos.getText().toString()); edPasos.setText(""); } }); btGuardar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!tieNombre.getText().toString().equals("")){ Recipe recipe = new Recipe(tieNombre.getText().toString(), spinner.getSelectedItem().toString(), tieDuracion.getText().toString(), tieCantidad.getText().toString(), adapterIngrediente.getList(), adapterPaso.getList(), false); Map<String, Object> receta = new HashMap<>(); receta.put("nombre", tieNombre.getText().toString()); receta.put("categoria", spinner.getSelectedItem().toString()); receta.put("duracion", tieDuracion.getText().toString()); receta.put("cantidad", tieCantidad.getText().toString()); receta.put("ingredientes", adapterIngrediente.getList()); receta.put("pasos", adapterPaso.getList()); receta.put("favorito", false); presenter.save(receta); } else tilNombre.setError("El nombre no puede estar vacío"); } }); } @Override public void onSuccessSave() { NavHostFragment.findNavController(AddRecipeFragment.this).navigateUp(); } // private void showNotification(){ // //Una PendingIntent tienen un objeto intent en su interior que define lo que // //se quiere ejecutar cuando se pulse sobre la notificacion // //INICIAR UNA ACTIVITY // //Intent intent = new Intent(); // Bundle bundle = new Bundle(); // bundle.putSerializable("recipe",recipe); // //intent.putExtras(bundle); // // //Se construye el PendingIntent // //PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), new Random().nextInt(1000),intent, PendingIntent.FLAG_UPDATE_CURRENT); // PendingIntent pendingIntent = new NavDeepLinkBuilder(getActivity()) // .setGraph(R.navigation.nav_graph) // .setDestination(R.id.addRecetaFragment) // .setArguments(bundle) // .createPendingIntent(); // // // Notification.Builder builder = new Notification.Builder(getActivity(), IFoodistApplication.CHANNEL_ID) // .setAutoCancel(true) // .setSmallIcon(R.drawable.ic_logo) // .setContentTitle(getResources().getString(R.string.notification_title_recipe)) // .setContentText(String.format(getString(R.string.text_add_recipe)+ recipe.getNombre())) // .setContentIntent(pendingIntent); // // //Se añade la notificacion al gestior de notificaciones // NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); // notificationManager.notify(new Random().nextInt(1000),builder.build()); // } }