identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/stepanroznik/wish-list-backend/blob/master/src/common/api-key.guard.ts
Github Open Source
Open Source
MIT
null
wish-list-backend
stepanroznik
TypeScript
Code
43
132
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; @Injectable() export class ApiKeyGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const apiKey = request.headers['x-api-key']; return !!(apiKey === process.env.API_KEY); } }
22,507
https://github.com/ShubhamTiwari007/ExamPortal/blob/master/Backend(using java)/examserver/src/main/java/com/exam/controller/AuthenticateController.java
Github Open Source
Open Source
MIT
null
ExamPortal
ShubhamTiwari007
Java
Code
151
710
package com.exam.controller; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.exam.config.Jwtutil; import com.exam.entities.JwtRequest; import com.exam.entities.JwtResponse; import com.exam.entities.User; import com.exam.helper.UserNotFoundException; import com.exam.service.impl.UserDetailsServiceImpl; @RestController @CrossOrigin("*") public class AuthenticateController { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsServiceImpl userDetailsServiceImpl; @Autowired private Jwtutil jwtutil; //generate token @PostMapping("/generate-token") public ResponseEntity<?> generateToken(@RequestBody JwtRequest jwtRequest) throws Exception{ try { authenticate(jwtRequest.getUsername(), jwtRequest.getPassword()); }catch(UsernameNotFoundException e) { e.printStackTrace(); throw new UserNotFoundException("User not found"); } UserDetails userDetails = this.userDetailsServiceImpl.loadUserByUsername(jwtRequest.getUsername()); String token = this.jwtutil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } private void authenticate(String username, String password) throws Exception { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (DisabledException e) { throw new Exception("USER DISABLED " + e.getMessage()); } catch(BadCredentialsException e) { throw new Exception("Invalid credentials " + e.getMessage()); } } //return the detail of current user @GetMapping("/current-user") public User getCurrentUser(Principal principal) { return (User)this.userDetailsServiceImpl.loadUserByUsername(principal.getName()); } }
5,482
https://github.com/EranBoudjnah/RandomGen/blob/master/randomgen/src/main/java/com/mitteloupe/randomgen/fielddataprovider/PaddedFieldDataProvider.java
Github Open Source
Open Source
MIT
2,018
RandomGen
EranBoudjnah
Java
Code
232
641
package com.mitteloupe.randomgen.fielddataprovider; import com.mitteloupe.randomgen.FieldDataProvider; /** * A {@link FieldDataProvider} that pads generated data (as {@code String}) with repetitions of the provided {@code String}. * * Created by Eran Boudjnah on 16/08/2018. */ public class PaddedFieldDataProvider<OUTPUT_TYPE> implements FieldDataProvider<OUTPUT_TYPE, String> { private final int mMinimumLength; private final String mPaddingString; private final FieldDataProvider<OUTPUT_TYPE, ?> mFieldDataProvider; /** * Creates an instance of {@link PaddedFieldDataProvider} generating a padded {@code String} of * the output generated by the provided {@link FieldDataProvider} instance using an infinitely repeated {@code String} of copies of * the provided padding {@code String}. * * If the {@code String} generated by the {@link FieldDataProvider} instance is not shorter than the provided minimum length, it is returned * as is. * * @param pMinimumLength The minimal returned String length * @param pPaddingString The string to use for padding * @param pFieldDataProvider A provider for strings to pad */ public PaddedFieldDataProvider(int pMinimumLength, String pPaddingString, FieldDataProvider<OUTPUT_TYPE, ?> pFieldDataProvider) { mMinimumLength = pMinimumLength; mPaddingString = pPaddingString; mFieldDataProvider = pFieldDataProvider; } @Override public String generate(OUTPUT_TYPE instance) { String generatedString = getGeneratedString(instance); int charactersMissing = mMinimumLength - generatedString.length(); StringBuilder stringBuilder = getStringBuilderWithPadding(charactersMissing); return stringBuilder .append(generatedString) .toString(); } private StringBuilder getStringBuilderWithPadding(int pPaddingLength) { StringBuilder stringBuilder = new StringBuilder(); while (!mPaddingString.isEmpty() && stringBuilder.length() < pPaddingLength) { stringBuilder.append(mPaddingString); } if (stringBuilder.length() > pPaddingLength && pPaddingLength > 0) { stringBuilder.delete(pPaddingLength, stringBuilder.length()); } return stringBuilder; } private String getGeneratedString(OUTPUT_TYPE instance) { return mFieldDataProvider.generate(instance).toString(); } }
5,818
https://github.com/simplic/WpfDesigner/blob/master/WpfDesign.Designer/Tests/Designer/NamespaceTests.cs
Github Open Source
Open Source
MIT
2,022
WpfDesigner
simplic
C#
Code
537
2,107
// Copyright (c) 2019 AlphaSierraPapa for the SharpDevelop Team // // 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.Windows; using System.Windows.Controls; using NUnit.Framework; namespace ICSharpCode.WpfDesign.Tests.Designer { [TestFixture] public class NamespaceTests : ModelTestHelper { [Test] public void AddControlFromTestNamespace() { DesignItem button = CreateCanvasContext("<Button />"); DesignItem canvas = button.Parent; DesignItem customButton = canvas.Services.Component.RegisterComponentForDesigner(new CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customButton); AssertCanvasDesignerOutput("<Button />\n" + "<t:CustomButton />", canvas.Context); } [Test] public void AddControlWithUndeclaredNamespace() { DesignItem button = CreateCanvasContext("<Button />"); DesignItem canvas = button.Parent; DesignItem customButton = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.OtherControls.CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customButton); AssertCanvasDesignerOutput("<Button />\n" + "<Controls0:CustomButton />", canvas.Context, "xmlns:Controls0=\"clr-namespace:ICSharpCode.WpfDesign.Tests.OtherControls;assembly=ICSharpCode.WpfDesign.Tests\""); } [Test] public void AddControlWithUndeclaredNamespaceThatUsesXmlnsPrefixAttribute() { DesignItem button = CreateCanvasContext("<Button />"); DesignItem canvas = button.Parent; DesignItem customButton = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.Controls.CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customButton); AssertCanvasDesignerOutput("<Button />\n" + "<sdtcontrols:CustomButton />", canvas.Context, "xmlns:sdtcontrols=\"http://sharpdevelop.net/WpfDesign/Tests/Controls\""); } [Test] public void AddMultipleControls() { DesignItem button = CreateCanvasContext("<Button />"); DesignItem canvas = button.Parent; DesignItem customControl = canvas.Services.Component.RegisterComponentForDesigner(new CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.Controls.CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.OtherControls.CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.SpecialControls.CustomButton()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new CustomCheckBox()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.Controls.CustomCheckBox()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.OtherControls.CustomCheckBox()); canvas.Properties["Children"].CollectionElements.Add(customControl); customControl = canvas.Services.Component.RegisterComponentForDesigner(new ICSharpCode.WpfDesign.Tests.SpecialControls.CustomCheckBox()); canvas.Properties["Children"].CollectionElements.Add(customControl); AssertCanvasDesignerOutput("<Button />\n" + "<t:CustomButton />\n" + "<sdtcontrols:CustomButton />\n" + "<Controls0:CustomButton />\n" + "<Controls1:CustomButton />\n" + "<t:CustomCheckBox />\n" + "<sdtcontrols:CustomCheckBox />\n" + "<Controls0:CustomCheckBox />\n" + "<Controls1:CustomCheckBox />", canvas.Context, "xmlns:sdtcontrols=\"http://sharpdevelop.net/WpfDesign/Tests/Controls\"", "xmlns:Controls0=\"clr-namespace:ICSharpCode.WpfDesign.Tests.OtherControls;assembly=ICSharpCode.WpfDesign.Tests\"", "xmlns:Controls1=\"clr-namespace:ICSharpCode.WpfDesign.Tests.SpecialControls;assembly=ICSharpCode.WpfDesign.Tests\""); } } public class CustomButton : Button { public static readonly DependencyProperty TestAttachedProperty = DependencyProperty.RegisterAttached("TestAttached", typeof(double), typeof(CustomButton), new FrameworkPropertyMetadata(Double.NaN)); public static double GetTestAttached(UIElement element) { return (double)element.GetValue(TestAttachedProperty); } public static void SetTestAttached(UIElement element, double value) { element.SetValue(TestAttachedProperty, value); } } public class CustomCheckBox : CheckBox { } } namespace ICSharpCode.WpfDesign.Tests.Controls { public class CustomButton : Button { public static readonly DependencyProperty TestAttachedProperty = DependencyProperty.RegisterAttached("TestAttached", typeof(double), typeof(CustomButton), new FrameworkPropertyMetadata(Double.NaN)); public static double GetTestAttached(UIElement element) { return (double)element.GetValue(TestAttachedProperty); } public static void SetTestAttached(UIElement element, double value) { element.SetValue(TestAttachedProperty, value); } } public class CustomCheckBox : CheckBox { } } namespace ICSharpCode.WpfDesign.Tests.OtherControls { public class CustomButton : Button { public static readonly DependencyProperty TestAttachedProperty = DependencyProperty.RegisterAttached("TestAttached", typeof(double), typeof(CustomButton), new FrameworkPropertyMetadata(Double.NaN)); public static double GetTestAttached(UIElement element) { return (double)element.GetValue(TestAttachedProperty); } public static void SetTestAttached(UIElement element, double value) { element.SetValue(TestAttachedProperty, value); } } public class CustomCheckBox : CheckBox { } } namespace ICSharpCode.WpfDesign.Tests.SpecialControls { public class CustomButton : Button { } public class CustomCheckBox : CheckBox { } }
6,834
https://github.com/shivalinga/Gooru-Web/blob/master/src/main/java/org/ednovo/gooru/server/service/UrlGenerator.java
Github Open Source
Open Source
MIT
null
Gooru-Web
shivalinga
Java
Code
333
660
/******************************************************************************* * Copyright 2013 Ednovo d/b/a Gooru. All rights reserved. * * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ /** * */ package org.ednovo.gooru.server.service; import java.util.Map; import org.ednovo.gooru.server.request.UrlToken; /** * @author Search Team * */ public class UrlGenerator { public static String generateUrl(String endpoint, UrlToken token, Map<String, String> optionalParams, String... params) { String url = generateUrl(endpoint, token, params); if (optionalParams != null) { for (String key : optionalParams.keySet()) { url += "&" + key + "=" + optionalParams.get(key); } } return url; } public static String generateUrl(String endpoint, UrlToken token, String... params) { String url = token.getUrl(); return endpoint + generateUrl(url, params); } public static String generateUrl(String endpoint, UrlToken token) { String url = token.getUrl(); return endpoint + url; } public static String generateUrl(String url, String... params) { if (params != null) { for (int index = 0; index < params.length; index++) { url = url.replace("{" + index + "}", params[index]); } } return url; } }
40,989
https://github.com/cscheid/cscheid-js/blob/master/src/cscheid/random.js
Github Open Source
Open Source
MIT
null
cscheid-js
cscheid
JavaScript
Code
406
991
/** @module cscheid/random */ import * as cscheid from '../cscheid.js'; // plain box-muller let hasPrevGauss = false; let prevGauss; export function normalVariate() { if (hasPrevGauss) { hasPrevGauss = false; return prevGauss; } const u1 = Math.random(); const u2 = Math.random(); const r = Math.sqrt(-2 * Math.log(u1)); const theta = Math.PI * 2 * u2; hasPrevGauss = true; prevGauss = r * Math.cos(theta); return r * Math.sin(theta); } export function choose(lst) { const u = ~~(Math.random() * lst.length); return lst[u]; } export function uniformRange(min, max) { const i = ~~(Math.random() * (max - min)); return min + i; } export function uniformReal(lo, hi) { return Math.random() * (hi - lo) + lo; } // Fisher-Yates shuffle // Thanks, Mike // https://bost.ocks.org/mike/shuffle/ export function shuffle(array) { let m = array.length, t, i; // While there remain elements to shuffle ... while (m) { // Pick a remaining element ... i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; } // //////////////////////////////////////////////////////////////////////////// // A little library for writing random distributions. Meant to be // convenient, not efficient. // // a "distribution" is a function object in which repeated calls to the // function return IID samples from that distribution export const distributions = {}; // transform a distribution by a function of the resulting variate distributions.transform = function(gen, f) { return () => f(gen()); }; distributions.bernoulli = function(p) { return function() { if (Math.random() < p) { return 1; } else { return 0; } }; }; distributions.uniform = function(lower, upper) { return function() { return uniformReal(lower, upper); }; }; distributions.gaussian1D = function(mu, sigma) { return distributions.transform(normalVariate, (v) => mu + sigma * v); }; // axis-aligned variances only for now.. distributions.gaussian2D = function(mu, sigma) { const n = mu.length; const vecGen = distributions.iidVec(normalVariate, n); return function() { const normalVariate = vecGen(); return cscheid.linalg.add( mu, cscheid.linalg.elementMul(normalVariate, sigma)); }; }; // assumes dist is numeric distributions.iidVec = function(dist, k) { return function() { const result = new Float64Array(k); for (let i = 0; i < k; ++i) { result[i] = dist(); } return result; }; }; distributions.mixture = function(ds, ws) { if (ws === undefined) { return function() { return choose(ds)(); }; } else { const sumWeights = cscheid.array.prefixSum(ws); const mixtureDist = distributions.uniform( 0, sumWeights[sumWeights.length - 1]); return function() { const u = mixtureDist(); const i = cscheid.array.upperBound(sumWeights, u); return ds[i](); }; } };
35,165
https://github.com/gaimtime78/kmm-risnov/blob/master/resources/views/user/list-mahasiswa-kkn-detail.blade.php
Github Open Source
Open Source
MIT
null
kmm-risnov
gaimtime78
PHP
Code
206
891
@extends('layout.user') @section('content1') <section class="section"> <div class="container"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-4"> <div class="row"> <div class="col-md-12"> <div class="image-wrap entry"> <img style="width:100%" src="{{asset('design/upload/course_03.jpg')}}" alt="foto mahasiswa" class="img-responsive"> </div><!-- end image-wrap --> </div> </div><!-- end row --> <hr class="invis"> </div><!-- end col --> <div class="col-md-6"> <div class="shop-desc"> <h3>Nama Mahasiswa</h3> <small>NIM Mahasiswa</small> <p><i class="fa fa-book"></i> Tema yang diambil</p> <p><i class="fa fa-building-o"></i> Penempatan</p> <p><i class="fa fa-clock-o"></i> Tanggal KKN</p> <div class="shop-meta"> <a href="{{route('informasi')}}" class="btn btn-primary">Back To Informasi</a> <!-- <ul class="list-inline"> <li> SKU: product-111</li> <li>Categories: <a href="#">Bags</a> </ul> --> </div><!-- end shop meta --> </div><!-- end desc --> </div><!-- end col --> </div><!-- end row --> </div> </section> @endsection @section('content') <section class="section"> <div class="container"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-4"> <div class="row"> <div class="col-md-12"> <div class="image-wrap entry"> <img style="width:80%; margin-top:30px;" src="{{asset('design/images/logo-uns.png')}}" alt="foto mahasiswa" class="img-responsive"> </div><!-- end image-wrap --> </div> </div><!-- end row --> <hr class="invis"> </div><!-- end col --> <div class="col-md-6"> <div class="shop-desc"> <h3>Nama Mahasiswa</h3> <small>NIM Mahasiswa</small> <p><i class="fa fa-book"></i> Tema yang diambil</p> <p><i class="fa fa-building-o"></i> Penempatan</p> <p><i class="fa fa-clock-o"></i> Tanggal KKN</p> <div class="shop-meta"> <a href="{{route('informasi')}}" class="btn btn-primary">Back To Informasi</a> <!-- <ul class="list-inline"> <li> SKU: product-111</li> <li>Categories: <a href="#">Bags</a> </ul> --> </div><!-- end shop meta --> </div><!-- end desc --> </div><!-- end col --> </div><!-- end row --> </div> </section> @endsection @section('js') @endsection
19,416
https://github.com/ideaconnect/fakepay-payum/blob/master/src/Action/ConvertPaymentAction.php
Github Open Source
Open Source
MIT
null
fakepay-payum
ideaconnect
PHP
Code
112
469
<?php namespace IDCT\Payum\Fakepay\Action; use IDCT\Payum\Fakepay\Constants; use Payum\Core\Action\ActionInterface; use Payum\Core\Bridge\Spl\ArrayObject; use Payum\Core\Exception\InvalidArgumentException; use Payum\Core\Exception\RequestNotSupportedException; use Payum\Core\Model\PaymentInterface; use Payum\Core\Request\Convert; class ConvertPaymentAction implements ActionInterface { public function execute($request) { RequestNotSupportedException::assertSupports($this, $request); /** @var PaymentInterface $payment */ $payment = $request->getSource(); $details = ArrayObject::ensureArrayObject($payment->getDetails()); $this->validateCurrency($payment->getCurrencyCode()); $details['amount'] = $payment->getTotalAmount(); $details['currency'] = strtoupper($payment->getCurrencyCode()); $details['description'] = $payment->getDescription(); $details['clientEmail'] = $payment->getClientEmail(); $details['paymentId'] = $payment->getNumber(); $details['status'] = Constants::STATUS_CAPTURED; $request->setResult((array) $details); } /** * {@inheritDoc} */ public function supports($request) { return $request instanceof Convert && $request->getSource() instanceof PaymentInterface && $request->getTo() == 'array' ; } /** * * @param string $currency * @throws InvalidArgumentException */ protected function validateCurrency($currency) { if (!in_array(strtoupper($currency), Constants::getSupportedCurrencies())) { throw new InvalidArgumentException("Currency $currency is not supported.", 400); } } }
17,782
https://github.com/alexwilkinson/immedialist-backend/blob/master/app/services/query/album.rb
Github Open Source
Open Source
MIT
null
immedialist-backend
alexwilkinson
Ruby
Code
14
76
class Query::Album < Query private def query_by_name MusicQuerier.search_by_album_name(name) end def query_by_external_id MusicQuerier.search_by_album_id(external_id) end end
3,402
https://github.com/Dysar/Blinq/blob/master/Blinq/ClientApp/src/app/workers-table/workers-table.component.ts
Github Open Source
Open Source
MIT
null
Blinq
Dysar
TypeScript
Code
254
804
import { Component, AfterViewInit, Inject } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { HttpClient } from '@angular/common/http'; import { MatTableDataSource } from '@angular/material'; import { Observable } from 'rxjs/Observable'; import { interval } from 'rxjs'; import { environment } from '../../environments/environment'; @Component({ selector: 'app-workers-table', templateUrl: './workers-table.component.html', styleUrls: ['./workers-table.component.css'] }) export class WorkersTableComponent implements AfterViewInit { name: string; lastname: string; email: string; exampleDatabase: ExampleHttpDao | null; dataSource = new MatTableDataSource(); constructor(private http: HttpClient, public dialog: MatDialog) { } //resultsLength = 0; isLoadingResults = false; isRateLimitReached = false; /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */ displayedColumns = ['Name', 'Lastname', 'Email']; ngAfterViewInit() { this.exampleDatabase = new ExampleHttpDao(this.http); interval(500).subscribe(x => { this.exampleDatabase!.getRepoMonitoringData() .subscribe(data => { console.log(data); return this.dataSource.data = data; }); }); } openDialog(): void { const dialogRef = this.dialog.open(DialogOverviewExampleDialog, { width: '300px', data: { name: this.name, lastname: this.lastname, email: this.email } }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); }); } } @Component({ selector: 'workers-table.component-dialog', templateUrl: 'workers-table.component-dialog.html', styleUrls: ['./workers-table.component.css'] }) export class DialogOverviewExampleDialog { name: string; lastname: string; email: string; constructor( public dialogRef: MatDialogRef<DialogOverviewExampleDialog>, @Inject(MAT_DIALOG_DATA) public data: DialogData) { } onNoClick(): void { this.dialogRef.close(); } AddWorker(): void { this.dialogRef.close(); }; } export class ExampleHttpDao { constructor(private http: HttpClient) { } getRepoMonitoringData(): Observable<WorkersData[]> { //const url = `${environment.serverUrl}/api/WorkersData`; //const res = this.http.get<WorkersData[]>(url); const obs = new Observable<WorkersData[]>(); return obs; } } export interface WorkersData { Id: string; Name: string; Lastname: string; Email: string; } export interface DialogData { name: string; lastname: string; email: string; }
38,391
https://github.com/dickjustice/bbuddy/blob/master/src/fffind.py
Github Open Source
Open Source
MIT
2,020
bbuddy
dickjustice
Python
Code
565
1,648
#!/usr/bin/env python3 # # fffind.py # # (c) 2020 Dick Justice # Released under MIT license. import sys,os,subprocess from pathlib import Path FFFIND_VER = '0.0.003' RED="\033[1;31m"; YELLOW="\033[0;33m"; GREEN="\033[0;32m"; RESET="\033[0;0m"; BOLD="\033[;1m";BLUE="\033[1;34m" BOLD_YELLOW = "\033[1;33m" BOLD_RED= "\033[1;31m" # returns (match,colorized_file) # match is a boolean, corresponding to whether it matches # colorized_file is the file name with colorization added def does_it_match( file, what ): colorized_file='' if what=='*': matches=True colorized_file = file #for '*' don't colorize at all elif what.startswith( '*' ) and what.endswith( '*' ): mval = what[1:-1] matches = mval in file if matches: parts = file.split( mval ) jval = BOLD_RED + mval + RESET colorized_file = jval.join( parts ) elif what.startswith( '*' ): # Example: *.py mval = what[1:] matches = file.endswith( mval ) if matches: colorized_file = file[:len(file)-len(mval)] + BOLD_RED + mval + RESET elif what.endswith( '*' ): # example: sammy* mval = what[:-1] matches = file.startswith( mval ) if matches: colorized_file = BOLD_RED + mval + RESET + file[len(mval):] else: # exact match required mval = what matches = file==mval if matches: colorized_file = file return( matches, colorized_file ) def does_it_match_and_please_colorize( file, root, what, colorize=True ): matches, colorized_file = does_it_match( file, what ) fn_w_path = root + '/' + file if matches and colorize: fn_w_path = root + '/' + colorized_file return matches, fn_w_path def directory_is_excluded( root, d, exclude_dirs ): for exx in exclude_dirs: if '/' in exx: if os.path.abspath(root+'/'+d) == os.path.abspath(exx): return True else: if d==exx: return True return False def usage_bail(): print( "fffind v %s" % FFFIND_VER ) print( "Usage: fffind [-f|-d] [-bw] [-x dir] <what>") print( " <what> may be like:" ) print( " abc : is exactly abc" ) print( " 'abc*' : starts with abc" ) print( " '*abc' : ends with abc" ) print( " '*abc*' : contains abc" ) print( " '*' : all files and directories match" ) print( " options:" ) print( " -f : files only" ) print( " -d : directories only") print( " -bw : black and white output") print( " -x dir : exclude this directory. may be used multpiple times") print( " if dir contains '/', only the one instance is excluded" ) print( " otherwise, any dir with that name found is excluded" ) print( "If file '.exclude' is present at any level, it excludes its listed directories") exit() def main( argv ): exclude_dirs = [] report_files=True report_dirs= True colorize=True if len(argv)<2: usage_bail() what = argv[-1] opts = argv[ 1:-1 ] exclude_opt_next=False for opt in opts: if exclude_opt_next: exclude_dirs.append( opt ) exclude_opt_next=False else: if opt=='-d': report_files=False elif opt=='-f': report_dirs=False elif opt=='-x': exclude_opt_next=True elif opt=='-bw': colorize=False else: print( "invalid option '%s'" % opt ) usage_bail() for root, dirs, files in os.walk('.'): if '.exclude' in files: with open(root+'/.exclude') as f: lines = f.readlines() for line in lines: strippedline = line.strip() if len(strippedline)>0 and not strippedline.startswith( '#' ): exclude_dirs.append( root +'/'+strippedline ) newdirs=[] for d in dirs: if not directory_is_excluded( root, d, exclude_dirs): #newdirs.append(Path(d).as_posix()) newdirs.append(d) dirs[:] = newdirs root = Path(root).as_posix() if report_files: for file in files: matches, fn_czd = does_it_match_and_please_colorize( file, root, what, colorize=colorize ) if matches: print( fn_czd ) if report_dirs: for dirr in dirs: matches, dir_czd = does_it_match_and_please_colorize( dirr, root, what, colorize=colorize ) if matches: print( dir_czd + '/' ) if len(exclude_dirs)>0: xdirs = [ Path(x).as_posix()+'/' for x in exclude_dirs ] print( "Note: These dirs excluded from search:",', '.join(xdirs) ) #--------- if __name__ == "__main__": main( sys.argv)
21,861
https://github.com/chewtoys/nuxt-typescript-strapi-boilerplate/blob/master/client/assets/sass/_vars.sass
Github Open Source
Open Source
MIT
2,019
nuxt-typescript-strapi-boilerplate
chewtoys
Sass
Code
69
235
$default-font: "font", sans-serif $default-font-size: 24px $d: #283229 $l: #FFEBCD //#EDD1A5 $a: #E5E5E5 $shadow: 0px 3px 8px 0px rgba($d, 0.08) $shadow-active: 3px 6px 12px 3px rgba($d, 0.08) $radius: 3px $space: 10px $gradient: radial-gradient(circle 50px at 20% 30%, #fff, $l) // Grid variables $grid-column: 16 $prefix: xxl, xl, lg, md, sm, xsm, xs $lg-cont-size: 1780px $brakepoint: 1780px, 1560px, 1300px, 992px, 768px, 480px, 320px $cont-sizes: 1560px, 1300px, 992px, 768px, 100%, 100%, 100%
31,895
https://github.com/dot42/api/blob/master/System/Threading/Tasks/TaskFactory_TResult.cs
Github Open Source
Open Source
Apache-2.0
2,017
api
dot42
C#
Code
422
1,248
// Copyright (C) 2014 dot42 // // Original filename: TaskFactory_TResult.cs // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Threading.Tasks { //[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] public class TaskFactory<TResult> { private readonly TaskFactory innerTaskFactory; public TaskFactory() : this(CancellationToken.None) { } public TaskFactory(TaskScheduler scheduler) : this(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, scheduler) { } public TaskFactory(CancellationToken cancellationToken) : this(cancellationToken, TaskCreationOptions.None, TaskContinuationOptions.None, null) { } public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions) : this(CancellationToken.None, creationOptions, continuationOptions, null) { } public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { TaskFactory.CheckContinuationOptions(continuationOptions); this.innerTaskFactory = new TaskFactory(cancellationToken, creationOptions, continuationOptions, scheduler); } /// <summary> /// Gets the default cancellation token for this task factory. /// </summary> public CancellationToken CancellationToken { get { return innerTaskFactory.CancellationToken; } } /// <summary> /// Gets the default task continuation options for this task factory. /// </summary> public TaskContinuationOptions ContinuationOptions { get { return innerTaskFactory.ContinuationOptions; } } /// <summary> /// Gets the default task creation options for this task factory. /// </summary> public TaskCreationOptions CreationOptions { get { return innerTaskFactory.CreationOptions; } } /// <summary> /// Gets the default task scheduler for this task factory. /// </summary> public TaskScheduler Scheduler { get { return innerTaskFactory.Scheduler; } } #region StartNew for Task<TResult> public Task<TResult> StartNew(Func<TResult> function) { return StartNew(function, CancellationToken, CreationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<TResult> function, TaskCreationOptions creationOptions) { return StartNew(function, CancellationToken, creationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken) { return StartNew(function, cancellationToken, CreationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return StartNew((o) => function(), null, cancellationToken, creationOptions, scheduler); } public Task<TResult> StartNew(Func<object, TResult> function, object state) { return StartNew(function, state, CancellationToken, CreationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<object, TResult> function, object state, TaskCreationOptions creationOptions) { return StartNew(function, state, CancellationToken, creationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<object, TResult> function, object state, CancellationToken cancellationToken) { return StartNew(function, state, cancellationToken, CreationOptions, GetScheduler()); } public Task<TResult> StartNew(Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return innerTaskFactory.StartNew<TResult>(function, state, cancellationToken, creationOptions, scheduler); } #endregion private TaskScheduler GetScheduler() { return innerTaskFactory.GetScheduler(); } } }
36,707
https://github.com/zhangrxiang/GolangTraining/blob/master/05_blank-identifier/02_http-get_example/01_with-error-checking/main.go
Github Open Source
Open Source
Apache-2.0
2,020
GolangTraining
zhangrxiang
Go
Code
73
316
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func body(response *http.Response) []byte { page, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { log.Fatal(err) } return page } func response(response *http.Response) { fmt.Println(response.Status) fmt.Println(response.StatusCode) fmt.Println(response.Proto) fmt.Println(response.ProtoMajor) fmt.Println(response.ProtoMinor) headers := response.Header for key, header := range headers { fmt.Println(key, header) } //fmt.Println(headers) //fmt.Println(headers.Get("Cache-Control")) //fmt.Println(headers.Get("Content-Type")) } func main() { res, err := http.Get("http://www.baidu.com/") if err != nil { log.Fatal(err) } response(res) //fmt.Printf("%s", body(res)) }
19,730
https://github.com/Ruben-VandeVelde/mathlib/blob/master/src/data/real/pi.lean
Github Open Source
Open Source
Apache-2.0
2,021
mathlib
Ruben-VandeVelde
Lean
Code
1,920
5,572
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import analysis.special_functions.trigonometric namespace real variable (x : ℝ) /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ | 0 := x | (n+1) := sqrt (2 + sqrt_two_add_series n) lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), sqrt_two_add_series 0 n ≥ 0 | 0 := le_refl 0 | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), sqrt_two_add_series x n ≥ 0 | 0 := h | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2 | 0 := by norm_num | (n+1) := begin refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt two_pos), rw [sqrt_two_add_series, sqrt_lt], apply add_lt_of_lt_sub_left, apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n), norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num end lemma sqrt_two_add_series_succ (x : ℝ) : ∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n | 0 := rfl | (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series] lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) : ∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n | 0 := h | (n+1) := begin rw [sqrt_two_add_series, sqrt_two_add_series], apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left end @[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2 | 0 := by simp | (n+1) := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc, nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul], congr, norm_num, rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc, mul_div_cancel_left], norm_num, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num, apply le_of_lt, apply cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two, { transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos, apply div_pos pi_pos, apply pow_pos, norm_num }, apply div_lt_div' (le_refl pi) _ pi_pos _, refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num} end lemma sin_square_pi_over_two_pow (n : ℕ) : sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 := by rw [sin_square, cos_pi_over_two_pow] lemma sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 := begin rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub], congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, end @[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul], { congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num }, { rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two }, apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi, { apply div_pos pi_pos, apply pow_pos, norm_num }, refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left], refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos, apply pow_pos, all_goals {norm_num} end lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 := by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp } lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 := by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp } lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 := by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp } lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 := by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp } lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 := by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp } lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 := by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp } lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp } lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp } lemma pi_gt_sqrt_two_add_series (n : ℕ) : pi > 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) := begin have : pi > sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2), { apply mul_lt_of_lt_div, apply pow_pos, norm_num, rw [←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, apply pow_pos, norm_num }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : pi < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : pi < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [←div_lt_iff, ←sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { apply div_le_of_le_mul, apply pow_pos, norm_num, refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, apply add_le_add_left, rw div_le_div_right, apply le_div_of_mul_le, apply pow_pos, apply pow_pos, norm_num, rw [←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, apply mul_le_of_le_div, apply pow_pos, norm_num, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div_eq_div_mul], convert le_refl _, norm_num, norm_num, apply pow_pos, norm_num }, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div_eq_div_mul, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (pi / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < pi` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < pi := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine le_mul_of_div_le (pow_pos (by norm_num) _) (le_sqrt_of_sqr_le _), rwa [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg (nat.cast_nonneg _) hd'), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < pi` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (pi / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `pi < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : pi < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_pos two_pos _) }, { exact pow_pos two_pos _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sqr_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `pi < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < pi := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < pi := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : pi < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < pi := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : pi < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < pi := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : pi < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] end real
35,329
https://github.com/hupfdule/exi-testsuite/blob/master/framework/src/fc/fp/util/xmlr/RefTreeImpl.java
Github Open Source
Open Source
W3C-19980720, W3C
2,019
exi-testsuite
hupfdule
Java
Code
60
174
// $Id: RefTreeImpl.java,v 1.1 2010/02/23 20:31:10 tkamiya Exp $ package fc.fp.util.xmlr; /** Default implementation of {@link RefTree}. */ public class RefTreeImpl implements RefTree { protected RefTreeNode root; /** Create a new reftree. * @param root root of the reftree */ public RefTreeImpl(RefTreeNode root) { this.root = root; } public RefTreeNode getRoot() { return root; } } // arch-tag: db2b79aa0b4ca2a07e645fcaa608ba50 *-
39,598
https://github.com/shaojiankui/iOS10-Runtime-Headers/blob/master/Frameworks/Speech.framework/SFSpeechRecognizer.h
Github Open Source
Open Source
MIT
2,018
iOS10-Runtime-Headers
shaojiankui
C
Code
181
774
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/Speech.framework/Speech */ @interface SFSpeechRecognizer : NSObject <AFDictationDelegate> { long long _defaultTaskHint; <SFSpeechRecognizerDelegate> * _delegate; AFDictationConnection * _dictationConnection; <NSObject> * _facetimeObserver; <NSObject> * _foregroundObserver; NSString * _languageCode; NSLocale * _locale; <NSObject> * _preferencesObserver; NSOperationQueue * _queue; } @property (getter=_isAvailableForForcedOfflineRecognition, nonatomic, readonly) bool _availableForForcedOfflineRecognition; @property (getter=isAvailable, nonatomic, readonly) bool available; @property (getter=isAvailableForRecordingRecognition, nonatomic, readonly) bool availableForRecordingRecognition; @property (readonly, copy) NSString *debugDescription; @property (nonatomic) long long defaultTaskHint; @property (nonatomic) <SFSpeechRecognizerDelegate> *delegate; @property (readonly, copy) NSString *description; @property (readonly) unsigned long long hash; @property (nonatomic, readonly, copy) NSLocale *locale; @property (nonatomic, retain) NSOperationQueue *queue; @property (readonly) Class superclass; + (void)_fetchSupportedForcedOfflineLocalesWithCompletion:(id /* block */)arg1; + (long long)authorizationStatus; + (void)initialize; + (void)requestAuthorization:(id /* block */)arg1; + (id)supportedLocales; - (void).cxx_destruct; - (void)_informDelegateOfAvailabilityChange; - (void)_informDelegateOfPreferencesChange; - (bool)_isAvailableForForcedOfflineRecognition; - (bool)_isInternalTaskHint:(long long)arg1; - (id)_recognitionTaskWithResultHandler:(id /* block */)arg1; - (void)_requestOfflineDictationSupportWithCompletion:(id /* block */)arg1; - (void)_sendEngagementFeedback:(long long)arg1 requestIdentifier:(id)arg2; - (void)dealloc; - (long long)defaultTaskHint; - (id)delegate; - (void)dictationConnnectionDidChangeAvailability:(id)arg1; - (id)init; - (id)initWithLocale:(id)arg1; - (bool)isAvailable; - (bool)isAvailableForRecordingRecognition; - (id)locale; - (void)prepareWithRequest:(id)arg1; - (id)queue; - (id)recognitionTaskWithRequest:(id)arg1 delegate:(id)arg2; - (id)recognitionTaskWithRequest:(id)arg1 resultHandler:(id /* block */)arg2; - (void)setDefaultTaskHint:(long long)arg1; - (void)setDelegate:(id)arg1; - (void)setQueue:(id)arg1; @end
5,909
https://github.com/RDJGraceShopper/graceshopper/blob/master/client/store/order.js
Github Open Source
Open Source
MIT
null
graceshopper
RDJGraceShopper
JavaScript
Code
512
1,471
import axios from 'axios' // ACTION TYPES import { GOT_ALL_ORDERS, GOT_SINGLE_ORDER, GOT_OPEN_ORDER, REMOVE_FROM_CART } from './actionTypes' // INITIAL STATE const initialState = { selectedOrder: {}, orders: [], openOrder: {} } // ACTION CREATORS const gotOrders = orders => { return { type: GOT_ALL_ORDERS, orders } } export const gotSingleOrder = order => { return { type: GOT_SINGLE_ORDER, order } } export const gotOpenOrder = openOrder => { return { type: GOT_OPEN_ORDER, openOrder } } const removeFromCart = openOrder => { return { type: REMOVE_FROM_CART, openOrder } } // THUNK CREATORS export const getOrders = () => { return async dispatch => { try { const response = await axios.get('/api/orders') dispatch(gotOrders(response.data)) } catch (error) { console.log(error) } } } export const getOrdersForUser = userId => { return async dispatch => { try { const response = await axios.get(`/api/users/${userId}/orders`) dispatch(gotOrders(response.data)) } catch (error) { console.log(error) } } } export const getSingleOrder = orderId => { return async dispatch => { try { const response = await axios.get(`/api/orders/${orderId}`) dispatch(gotSingleOrder(response.data)) } catch (error) { console.log(error) } } } // open order export const makeOrder = order => { return async dispatch => { try { const response = await axios.post('/api/orders/', order) dispatch(gotOpenOrder(response.data)) } catch (error) { console.log(error) } } } export const getOpenOrder = userId => { return async dispatch => { try { const response = await axios.get(`/api/users/${userId}/openOrder`) dispatch(gotOpenOrder(response.data)) } catch (error) { console.log(error) } } } export const getOpenGuestOrder = orderId => { return async dispatch => { try { const response = await axios.get(`/api/orders/${orderId}`) dispatch(gotOpenOrder(response.data)) } catch (error) { console.log(error) } } } export const updateOpenOrder = (userId, product, orderId) => { return async dispatch => { try { const response = await axios.post(`/api/orderproducts/`, { orderId: orderId, product }) if (userId) { dispatch(getOpenOrder(userId)) } else { dispatch(getOpenGuestOrder(orderId)) } } catch (error) { console.log(error) } } } export const deleteFromOrder = (userId, product, orderId) => { return async dispatch => { try { // console.log('OrderID===>', orderId) // console.log('Product===>', product) const response = await axios.put('/api/orderproducts', { orderId: orderId, product: product }) // console.log(response) if (userId) { dispatch(getOpenOrder(userId)) } else { dispatch(getOpenGuestOrder(orderId)) } } catch (error) { console.log(error) } } } export const deleteOneFromOrder = (userId, product, orderId) => { return async dispatch => { try { const response = await axios.put('/api/orderproducts', { orderId: orderId, product: product, quantity: 1 }) if (userId) { dispatch(getOpenOrder(userId)) } else { dispatch(getOpenGuestOrder(orderId)) } } catch (error) { console.log(error) } } } export const completeOrder = (userId, order) => { return async dispatch => { try { const response = await axios.put(`/api/orders/${order.id}`, { status: 'Completed' }) if (userId) { dispatch(makeOrder({userId})) } else { dispatch(makeOrder({})) } } catch (error) { console.log(error) } } } // REDUCERS export const ordersReducer = (state = initialState.orders, action) => { switch (action.type) { case GOT_ALL_ORDERS: return action.orders default: return state } } export const openOrderReducer = (state = initialState.openOrder, action) => { switch (action.type) { case GOT_OPEN_ORDER: return action.openOrder default: return state } } export const orderReducer = (state = initialState.selectedOrder, action) => { switch (action.type) { case GOT_SINGLE_ORDER: return action.order default: return state } }
1,919
https://github.com/pozetroninc/qrbarco_de-frontend/blob/master/src/App.vue
Github Open Source
Open Source
Apache-2.0
2,023
qrbarco_de-frontend
pozetroninc
Vue
Code
485
1,913
<template> <div id="app"> <app-header :active-color-scheme="ACTIVE_COLOR_SCHEME_KEY" :active-method="method" :handle-method-change="switchMethod" /> <section class="section"> <div class="container"> <div class="columns"> <div class="column is-two-thirds"> <app-form :payload="payload" :active-color-scheme="ACTIVE_COLOR_SCHEME_KEY" :active-method="method" :handle-submit="handleSubmit" :loading="loading" :disabled="disabled" @payload-input="payload = $event.target.value" /> </div> <div class="column"> <app-error v-if="error != null" :error="error" @close="error=null" /> <app-result v-if="result != null" :active-color-scheme="ACTIVE_COLOR_SCHEME_KEY" :result="result" /> </div> </div> </div> </section> <a v-if="GITHUB_LINK" :href="GITHUB_LINK"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" > </a> <footer class="footer"> <div class="content has-text-centered"> <p> from <a href="https://www.pozetron.com">Pozetron</a> with <span class="icon is-small has-text-danger"><i class="fas fa-heart"></i></span><br> </p> </div> </footer> </div> </template> <script> import './styles/main.scss' import config from './../app.config.json' import sassConfig from './../app.sass.config.json' import axios from 'axios' import Raven from 'raven-js' import AppHeader from './components/Header.vue' import AppForm from './components/Form.vue' import AppResult from './components/Result.vue' import AppError from './components/Error.vue' // Prepeare some configs const QRCODE_SERVICE = process.env.NODE_ENV === 'development' ? config.DEV_QRCODE_SERVICE : config.PROD_QRCODE_SERVICE const RECAPTCHA_ENABLED = config.RECAPTCHA_SITE_KEY ? true : false // Select a random color scheme const COLOR_SCHEMES_KEYS = Object.keys(sassConfig.COLOR_SCHEMES) const ACTIVE_COLOR_SCHEME_KEY = COLOR_SCHEMES_KEYS.length ? COLOR_SCHEMES_KEYS[Math.floor(Math.random() * COLOR_SCHEMES_KEYS.length)] : null export default { name: 'app', components: { 'app-header': AppHeader, 'app-form': AppForm, 'app-result': AppResult, 'app-error': AppError }, data() { return { ACTIVE_COLOR_SCHEME_KEY: ACTIVE_COLOR_SCHEME_KEY, GITHUB_LINK: config.GITHUB_LINK, method: 'text', // 'text' | 'base64' payload: '', recaptcha_ready: false, loading: false, result: null, error: null } }, computed: { disabled: function() { return ( !this.payload || this.loading || (RECAPTCHA_ENABLED && !this.recaptcha_ready) ) } }, mounted: function() { if (RECAPTCHA_ENABLED) { let recaptchaScript = document.createElement('script') recaptchaScript.onload = () => { window.grecaptcha.ready(() => { this.recaptcha_ready = true }) } recaptchaScript.setAttribute( 'src', `https://www.google.com/recaptcha/api.js?render=${ config.RECAPTCHA_SITE_KEY }` ) document.body.appendChild(recaptchaScript) } }, methods: { switchMethod(m) { this.method = m this.payload = '' }, fetchQRCode(recaptcha_token = null) { let data = new URLSearchParams() data.append(this.method, this.payload) data.append('color_scheme', this.ACTIVE_COLOR_SCHEME_KEY) if (recaptcha_token) { data.append('recaptcha', recaptcha_token) } axios .post(QRCODE_SERVICE, data, { responseType: 'arraybuffer' }) .then(response => { if (response.status == 200) { this.result = `data:${ response.headers['content-type'] };base64,${btoa( String.fromCharCode.apply(null, new Uint8Array(response.data)) )}` } this.loading = false }) .catch(error => { this.loading = false if (error.response) { let error_data = {} try { error_data = JSON.parse( String.fromCharCode.apply( null, new Uint8Array(error.response.data) ) ) } catch (e) { // Forgive only invalid json errors if (e.name !== 'SyntaxError') { throw e } } if (error.response.status == 400 && error_data.description) { this.error = error_data.description } else { this.error = 'Oops! Something went wrong.' } } else { this.error = 'Oops! Something went wrong.' } if (Raven.isSetup()) { Raven.captureMessage('Failed to generate barcode', { level: 'warning', extra: { error: error, response: error.response, data, description: this.error } }) } }) }, handleSubmit() { this.result = null this.error = null this.loading = true if (RECAPTCHA_ENABLED) { window.grecaptcha .execute(config.RECAPTCHA_SITE_KEY, {action: 'homepage'}) .then( token => { this.fetchQRCode(token) }, error => { this.loading = false this.error = 'Oops! Could not verify you are not a robot.' if (Raven.isSetup()) { Raven.captureMessage( 'Failed to verify recaptcha on client-side', { level: 'warning', extra: { error } } ) } } ) } else { this.fetchQRCode() } } } } </script>
32,374
https://github.com/cloud-hybrid/factory/blob/master/src/commands/factory/initialize.ts
Github Open Source
Open Source
BSD-3-Clause
null
factory
cloud-hybrid
TypeScript
Code
861
1,873
import Assertion from "assert"; import FS from "fs"; import Module from "module"; import Path from "path"; import Process from "process"; import Utility from "util"; import { Argv } from "yargs"; import { Distributable } from "../../library/types/distributable.js"; const Remove = Utility.promisify( FS.rm ); /*** *Current Module Path* */ const File: string = import.meta.url.replace( "file" + ":" + "//", "" ); const Import: NodeRequire = Module.createRequire( File ); /*** * Lambda Functions * ---------------- * Locates Lambda Functions * * @param directory {string} * @constructor * */ function * Packages(directory: string): Generator { /*** Exclusions to Avoid Recursive Parsing; i.e. libraries, lambda-layers, or otherwise bundled requirements */ const Exclusions = [ ".git", "library" ]; const Files = FS.readdirSync( directory, { withFileTypes: true } ); for ( const file of Files ) { if ( !Exclusions.includes( file.name ) ) { if ( file.isDirectory() ) { yield * Packages( Path.join( directory, file.name ) ); } else { yield Path.join( directory, file.name ); } } } } /*** * Library (Lambda Layers) * ----------------------- * Locates Lambda Layers * * @param directory {string} * @constructor * */ function * Library(directory: string): Generator { const Inclusions = [ "library" ]; const Files = FS.readdirSync( directory, { withFileTypes: true } ); for ( const file of Files ) { if ( Inclusions.includes( file.name ) ) { if ( file.isDirectory() ) { yield * Packages( Path.join( directory, file.name ) ); } else { yield Path.join( directory, file.name ); } } } } /*** * NPM Package Directory Locator * ----------------------------- * Locates Packages based on simple file inclusion: `package.json` * * @param files {string[]} * * @constructor * */ function Locate(files: string[] | any) { const Data: string[] = []; for ( const file in files ) { const Target = files[ file ]; if ( Target.includes( "package.json" ) && !Target.includes( "scripts" ) ) { Data.push( Path.dirname( Target ) ); } } return Data; } /*** Debug Console Utility String Generator */ const Input = (input: ( string | number )[]) => "[Debug] CLI Input" + " " + "(" + input.toString().replace( ",", ", " ).toUpperCase() + ")"; /*** * Command Configuration, Composition * * Acquires and configures settings specific to the module's {@link Command} Function-Constant. * * @param Arguments {Argv} CLI Input Arguments for Derivative Command * * @constructor * */ function Configuration(Arguments: Argv) { const Syntax = (command: string) => [ command, "? [--debug] ? [--help]" ].join( " " ); Arguments.hide( "version" ); Arguments.help( "help", "Display Usage Guide" ).default( "help", false ); Arguments.option( "debug", { type: "boolean" } ).alias( "debug", "d" ).default( "debug", false ); Arguments.describe( "debug", "Enable Debug Logging" ); } /*** * Module Entry-Point Command * ========================== * * @param $ {Argv} Commandline Arguments (Implicitly passed from cli.ts). * * @constructor * */ const Command = async ($: Argv) => { const Arguments: Argv = $; console.warn( "[Warning] The Current Command is Under Development." ); console.warn( "... To view runtime debug logs, provide the \"--debug\" flag", "\n" ); Configuration( Arguments ); Arguments.check( async ($: { [ p: string ]: unknown, _: ( string | number )[], $0: string }) => { await Remove( Path.join( Process.cwd(), "distribution" ), { recursive: true, force: true, maxRetries: 5 } ); await Remove( Path.join( Process.cwd(), "factory" ), { recursive: true, force: true, maxRetries: 5 } ); $.debug = ( $?.debug === true ) ? $.debug : false; ( $?.debug ) && console.debug( Input( $._ ), JSON.stringify( $, null, 4 ), "\n" ); const packages = [ ... Packages( Process.cwd() ) ]; const library = [ ... Library( Process.cwd() ) ]; ( $?.debug ) && console.debug( "[Debug] Runtime Location" + ":", import.meta.url, "\n" ); ( $?.debug ) && console.debug( "[Debug] CWD" + ":", Process.cwd(), "\n" ); ( $?.debug ) && console.debug( "[Debug] File Structure (Packages)" + ":", [ packages ], "\n" ); ( $?.debug ) && console.debug( "[Debug] File Structure (Library)" + ":", [ library ], "\n" ); /*** * Configuration File Assertion * ---------------------------- * ***Note*** - the `factory.json` file is a hard requirement * */ Assertion.strictEqual( FS.existsSync( Path.join( Process.cwd(), "factory.json" ) ), true, "factory.json Configuration Not Found" ); const Factory: object = Import( Path.join( Process.cwd(), "factory.json" ) ); ( $?.debug ) && console.debug( "[Debug] Factory Definition (factory.json)" + ":", Factory, "\n" ); /*** Recursively Searched Folder(s) w/package.json Files, Excluding Library */ const Resources = Locate( packages ); // ==> Lambda Functions ( $?.debug ) && console.debug( "[Debug] Target Package(s) (Resources)" + ":", Resources, "\n" ); const Share = Locate( library ); // ==> Lambda Layers ( $?.debug ) && console.debug( "[Debug] Target Library (Shared Resources)" + ":", Share, "\n" ); for ( const Target of Resources ) Distributable.define( Target, false ); for ( const Target of Share ) Distributable.define( Target, true ); ( $?.debug ) && console.debug( "[Debug] Distribution + Package Data" + ":", Distributable.packages, "\n" ); ( $?.debug ) && console.debug( "[Debug] Compiling Distribution(s) ..." + "\n" ); await Distributable.distribute(); ( $?.debug ) && console.debug( "[Debug] Writing factory.json Distribution ...", "\n" ); FS.writeFileSync( Path.join( Process.cwd(), "distribution", "factory.json" ), JSON.stringify( Factory ) ); ( $?.debug ) && console.debug( "[Debug] Initialization Complete", "\n" ); return true; } ).strict(); }; export { Command as Initialize }; export default { Command };
18,932
https://github.com/kapiya/137-stopmove/blob/master/src/main/java/onethreeseven/stopmove/command/FindStopsMovesGBSMoT.java
Github Open Source
Open Source
MIT
2,018
137-stopmove
kapiya
Java
Code
240
707
package onethreeseven.stopmove.command; import com.beust.jcommander.Parameter; import onethreeseven.datastructures.model.STPt; import onethreeseven.datastructures.model.STStopTrajectory; import onethreeseven.datastructures.model.SpatioCompositeTrajectory; import onethreeseven.stopmove.algorithm.GBSMoT; import java.util.Map; /** * Command for {@link GBSMoT}. * @author Luke Bermingham */ public class FindStopsMovesGBSMoT extends AbstractStopMoveCommand { @Parameter(names = {"-r", "-regionSizeMetres"}, description = "This algorithm partitions the trajectory using grid cells of this size (metres).") private double regionSizeMetres; @Parameter(names = {"-t", "-minStopTime"}, description = "The minimum time for a trajectory to stay in a region for it to be considered a stop.") private int minStopTimeSeconds; @Override protected String generateLayerNameForNewStopMoveTrajs(Map<String, SpatioCompositeTrajectory<? extends STPt>> allTrajs) { return allTrajs.size() + " Stop/Moves Trajectories (POSMIT) Region=" + regionSizeMetres + "m"; } @Override protected STStopTrajectory toStopMoveTraj(SpatioCompositeTrajectory<? extends STPt> traj) { GBSMoT gbsMoT = new GBSMoT(); long minStopTimeMillis = minStopTimeSeconds * 1000L; return gbsMoT.run(traj, regionSizeMetres, minStopTimeMillis); } @Override protected String getUsage() { return "gbsmot -r 100 -t 10"; } @Override protected boolean parametersValid() { if(regionSizeMetres < 0){ System.err.println("Region size must be a positive integer."); return false; } if(minStopTimeSeconds < 0){ System.err.println("Minimum stop time must be greater than zero."); return false; } return super.parametersValid(); } @Override public boolean shouldStoreRerunAlias() { return false; } @Override public String generateRerunAliasBasedOnParams() { return null; } @Override public String getCommandName() { return "gbsmot"; } @Override public String[] getOtherCommandNames() { return new String[0]; } @Override public String getDescription() { return "Partitions the trajectory using a grid of specified cell size and then classifies " + "entries that stay in grid cells for a certain duration as stops."; } }
28,439
https://github.com/isabella232/p2p_incentives/blob/master/node.py
Github Open Source
Open Source
Apache-2.0
2,020
p2p_incentives
isabella232
Python
Code
2,844
6,377
""" This module contains Neighbor and Peer classes. They are both representatives of nodes. Note that sometimes we use "node" and "peer" interchangeably in the comment. """ import collections import copy from typing import Deque, Set, Dict, List, Tuple, TYPE_CHECKING from message import OrderInfo, Order from data_types import PeerTypeName, Preference, NameSpacing, Priority if TYPE_CHECKING: from engine import Engine class Neighbor: """ Each peer maintains a set of neighbors. Note, a neighbor is physically also a node, but a neighbor instance is not a peer instance; instead, it has specialized information from a peer's viewpoint. For information stored in the Peer instance, refer to the mapping table in the SingleRun instance and find the corresponding Peer instance. """ def __init__( self, engine: "Engine", peer: "Peer", master: "Peer", est_time: int, preference: Preference = None, ) -> None: self.engine: "Engine" = engine # design choice self.est_time: int = est_time # establishment time self.preference: Preference = preference # "peer" is the peer instance of this neighbor # "master" is the peer instance of whom that regards me as a neighbor. # The following function sets up the master node's preference to this neighbor self.engine.set_preference_for_neighbor( neighbor=self, peer=peer, master=master, preference=preference ) # If peer A shares his info to peer B, we say peer A contributes to B. # Such contribution is recorded in peer B's local record, i.e., # the neighbor instance for peer A in the local storage of peer B. # Formally, "share_contribution" is a queue to record a length of "score_length" # of contributions, each corresponding to the score in one of the previous batches. self.share_contribution: Deque[float] = collections.deque() for _ in range(engine.score_length): self.share_contribution.append(0.0) self.score: float = 0.0 # the score to evaluate my neighbor. # lazy_round is the number of batch periods over which this peer has be regarded as a # lazy neighbor. A neighbor is regarded as lazy if its score in one batch is below a # certain value. Default for lazy_round is 0. Increased by 1 if its score is below that # certain value, or reset to 0 otherwise. self.lazy_round: int = 0 # Peer class, each peer instance being a node in the mesh. class Peer: """ The Peer class is the main representation of a node in the Mesh. """ def __init__( self, engine: "Engine", seq: int, birth_time: int, init_orders: Set[Order], namespacing: NameSpacing, peer_type: PeerTypeName, ) -> None: # Note: initialization deals with initial orders, but does not establish neighborhood # relationships. self.local_clock: int = birth_time # simple parameter setting self.engine: "Engine" = engine # design choice self.seq: int = seq # sequence number. Not in use now, for reserve purpose only. self.birth_time: int = birth_time self.init_orderbook_size: int = len(init_orders) # interest in certain trading groups self.namespacing: NameSpacing = namespacing self.peer_type: PeerTypeName = peer_type # e.g., big/small relayer # This denotes if this peer is a free rider (no contribution to other peers) # This is a redundant variable, for better readability only. # A free rider sits in the system, listens to orders, and does nothing else. # It does not generate orders by itself. self.is_free_rider: bool = (peer_type == "free_rider") # mapping from the order instance to orderinfo instances that have been formally stored. self.order_orderinfo_mapping: Dict[Order, OrderInfo] = {} # mapping from the peer instance to neighbor instance. Note, neighborhood relationship # must be bilateral. self.peer_neighbor_mapping: Dict["Peer", Neighbor] = {} # set of newly and formally-stored orders that have NEVER been shared out by this peer. self.new_order_set: Set[Order] = set() # The following mapping maintains a table of pending orders, by recording their orderinfo # instance. Note that an order can have multiple orderinfo instances, because it can be # forwarded by different neighbors. self.order_pending_orderinfo_mapping: Dict[Order, List[OrderInfo]] = {} # The following mapping maintains an expected completion time of on-chain verification for # the list of orders. It is a Dict, key is the completion time, value is the list of orders. # If the completion time is 0, it means this batch has not started so there is no # estimation for now. There is always an entry with key 0. # # # The method to determine the completion time: # Once we start a new p2p loop, send the batch of orders for on-chain verification, the # simulator will check the hosting server's workload (which is # SingleRun.server_response_time), and returns the expected verification completion time. # In our context, the expected verification completion time will be the accurate # completion time. # Note that this is definitely different from the real system, but it will greatly # simplify the simulator design. self.verification_time_orders_mapping: Dict[int, List[Order]] = {0: []} # the following records the last time this peer started a loop (sending orders to # on-chain check) self.previous_loop_starting_time: int = self.birth_time if self.is_free_rider and init_orders: raise ValueError("Free riders should not have their own orders.") # initiate orderinfo instances # initial orders will directly be stored without going through the storage decision. for order in init_orders: # if this order is created by this peer, but in the peer initialization, # it was unable to define the creator as this peer since the peer has not been created. # there we defined the creator as None, and we will modify here. if order.creator is None: order.creator = self priority: Priority = None # we don't set the priority for now new_orderinfo = OrderInfo( engine=engine, order=order, master=self, arrival_time=birth_time, priority=priority, ) self.order_orderinfo_mapping[order] = new_orderinfo self.new_order_set.add(order) # not sure if this is useful. Just keep it here to keep consistency. new_orderinfo.storage_decision = True order.holders.add(self) def should_start_a_new_loop(self, init_birth_span) -> bool: """ This method determines whether a new loop should be started, i.e., do we want to assemble the newly received but unverified orders for an on-chain verification. :return: True if to start a new loop, or False otherwise. """ return self.engine.should_a_peer_start_a_new_loop( peer=self, time_now=self.local_clock, init_birth_span=init_birth_span ) def send_orders_to_on_chain_check(self, expected_completion_time: int) -> None: """ This method sends all unverified orders for an on-chain verification. It will copy self.verification_time_orders_mapping[0] to self.verification_time_order_mapping[ expected_completion_time]. If the new entry does not exist, it creates the new entry; otherwise, it extends the original list by putting elements in self.verification_time_orders_mapping[0] to the end of the original list. Finally, self.verification_time_orders_mapping[0] is cleared. :return: None. """ if expected_completion_time in self.verification_time_orders_mapping: # move orders to the entry self.verification_time_orders_mapping[ expected_completion_time ] += copy.copy(self.verification_time_orders_mapping[0]) else: # create a key expected_completion_time whose value is the same as key 0's value. self.verification_time_orders_mapping[expected_completion_time] = copy.copy( self.verification_time_orders_mapping[0] ) # clear the entry 0 self.verification_time_orders_mapping[0].clear() def should_accept_neighbor_request(self, requester: "Peer") -> bool: """ This method is for a peer instance to determine whether they accept a neighbor establishment request or not. It is called when a request of establishing a neighborhood relationship is called from another peer. This peer, which is requested, will return True for agreement by default, False if the current number of neighbors already reaches the maximal. :param requester: the peer instance of another node requesting to establish a new neighborhood relationship. :return: True if accepted, or False otherwise. Note: this method does not establish neighborhood relationship by itself. It accepts or rejects the request only. """ if requester in self.peer_neighbor_mapping or requester == self: raise ValueError("Called by a wrong peer.") return len(self.peer_neighbor_mapping) < self.engine.neighbor_max def add_neighbor(self, peer: "Peer") -> None: """ This method establishes a neighborhood relationship. This method can only be called in method add_new_links_helper() in class SingleRun. Once it is called, a neighborhood relationship should be ready for establishment; otherwise, it is an error (e.g., one party has already had the other party as a neighbor). :param peer: the peer instance of the node to be added as a neighbor. :return: None """ if peer in self.peer_neighbor_mapping or peer == self: raise ValueError("Function called by a wrong peer.") # create new neighbor in my local storage new_neighbor = Neighbor( engine=self.engine, peer=peer, master=self, est_time=self.local_clock ) self.peer_neighbor_mapping[peer] = new_neighbor def accept_neighbor_cancellation(self, requester: "Peer") -> None: """ This method defines what a peer will do if it's notified by someone for cancelling a neighborhood relationship. It will always accept the cancellation, and delete that peer from his neighbor. Note that this is different from a real system that a peer simply drops a neighborhood relationship without need of being accepted by the other side. This function is for simulation bookkeeping purpose only. :param requester: peer instance of the node requesting to cancel neighborhood. :return: None. Explanation: If I am removed as a neighbor by my neighbor, I will delete him as well. But I will not remove orders from him, and I don't need to inform him to delete me again. """ if requester in self.peer_neighbor_mapping: self.del_neighbor(peer=requester, remove_order=False, notification=False) def del_neighbor( self, peer: "Peer", remove_order: bool = False, notification: bool = True ) -> None: """ This method deletes a neighbor. :param peer: the peer instance of the neighbor to be deleted. :param remove_order: If remove_order is True, then all orderinfo instances with the prev_owner being this neighbor will also be deleted (order instances are still there). :param notification: whether to notify the other party to cancel neighborhood. :return: None """ if peer not in self.peer_neighbor_mapping: raise ValueError("This peer is not my neighbor. Unable to delete.") # if remove_order is True, delete all orders whose previous owner is this neighbor if remove_order: for order in list(self.order_orderinfo_mapping): orderinfo = self.order_orderinfo_mapping[order] if orderinfo.prev_owner == peer: order.holders.remove(self) self.new_order_set.discard(order) del self.order_orderinfo_mapping[order] for order in list(self.order_pending_orderinfo_mapping): orderinfo_list = self.order_pending_orderinfo_mapping[order] for idx, orderinfo in enumerate(orderinfo_list): if orderinfo.prev_owner == peer: del orderinfo_list[idx] if ( not orderinfo_list ): # no pending orderinfo. need to delete this entry order.hesitators.remove(self) del self.order_pending_orderinfo_mapping[order] # if this neighbor is still an active peer, notify him to delete me as well. if notification: peer.accept_neighbor_cancellation(self) # delete this neighbor del self.peer_neighbor_mapping[peer] def receive_order_external(self, order: Order) -> None: """ This method is called by method order_arrival() in class SingleRun. An OrderInfo instance will be created and put into pending table (just to keep consistent with method receive_order_internal(), though most likely it will be accepted). :param order: the order instance of the order arrived externally. :return: None """ if order in self.order_pending_orderinfo_mapping: raise ValueError("Duplicated external order in pending table.") if order in self.order_orderinfo_mapping: raise ValueError("Duplicated external order in local storage.") if self.engine.should_accept_external_order(self, order): # create the orderinfo instance and add it into the local mapping table new_orderinfo = OrderInfo( engine=self.engine, order=order, master=self, arrival_time=self.local_clock, ) self.order_pending_orderinfo_mapping[order] = [new_orderinfo] self.verification_time_orders_mapping[0].append(order) # update the number of replicas for this order and hesitator of this order # a peer is a hesitator of an order if this order is in its pending table order.hesitators.add(self) def receive_order_internal( self, peer: "Peer", order: Order, novelty_update: bool = False ) -> None: """ The method is called by method share_order() in class SingleRun. It will immediately decide whether to put the order from the peer (who is my neighbor) into my pending table. :param peer: the peer instance of the node who sends the order :param order: the order instance. :param novelty_update: an binary option. if True, the value of OrderInfo instance will increase by one once transmitted. :return: None """ if ( self not in peer.peer_neighbor_mapping or peer not in self.peer_neighbor_mapping ): raise ValueError("Receiving order from non-neighbor.") neighbor: Neighbor = self.peer_neighbor_mapping[peer] if not self.engine.should_accept_internal_order(self, peer, order): # update the contribution of my neighbor for his sharing neighbor.share_contribution[-1] += self.engine.penalty_a return if order in self.order_orderinfo_mapping: # no need to store again orderinfo: OrderInfo = self.order_orderinfo_mapping[order] if orderinfo.prev_owner == peer: # I have this order in my local storage. My neighbor is sending me the same order # again. It may be due to randomness of sharing old orders. neighbor.share_contribution[-1] += self.engine.reward_a else: # I have this order in my local storage, but it was from someone else. # No need to store it anymore. Just update the reward for the uploader. neighbor.share_contribution[-1] += self.engine.reward_b return # If this order has not been formally stored: Need to write it into the pending table ( # even if there has been one with the same sequence number). if novelty_update: order_novelty = peer.order_orderinfo_mapping[order].novelty + 1 else: order_novelty = peer.order_orderinfo_mapping[order].novelty # create an orderinfo instance new_orderinfo: OrderInfo = OrderInfo( engine=self.engine, order=order, master=self, arrival_time=self.local_clock, priority=None, prev_owner=peer, novelty=order_novelty, ) # If no such order in the pending list, create an entry for it if order not in self.order_pending_orderinfo_mapping: # order not in the pending set self.order_pending_orderinfo_mapping[order] = [new_orderinfo] self.verification_time_orders_mapping[0].append(order) order.hesitators.add(self) # Put into the pending table. Reward will be updated when storing decision is made. return # If there is such an order in the pending list, check if it is from the same prev_owner. for existing_orderinfo in self.order_pending_orderinfo_mapping[order]: if peer == existing_orderinfo.prev_owner: # This neighbor is sending duplicates to me in a short period of time. Likely to # be a malicious one. # Penalty is imposed to this neighbor. But please be noted that this peer's # previous copy is still in the pending list, and if it is finally stored, # this peer will still get a reward for the order being stored. neighbor.share_contribution[-1] += self.engine.penalty_b return # My neighbor is honest, but he is late in sending me the message. # Add it to the pending list anyway since later, his version of the order might be selected. self.order_pending_orderinfo_mapping[order].append(new_orderinfo) def store_orders(self) -> None: """ This method determines which orders to store and which to discard, for all orders in the pending table. It is proactively called by each peer at the end of a batch period. :return: None """ if self.local_clock not in self.verification_time_orders_mapping: raise RuntimeError( "Store order decision should not be called at this time." ) # change orderinfo.storage_decision to True if you would like to store this order. self.engine.store_or_discard_orders(self) # Now store an orderinfo if necessary for order in list(self.order_pending_orderinfo_mapping): if order in self.verification_time_orders_mapping[self.local_clock]: orderinfo_list = self.order_pending_orderinfo_mapping[order] # Sort the list of pending orderinfo with the same order instance, so that if # there is some order to be stored, it will be the first one. orderinfo_list.sort( key=lambda item: item.storage_decision, reverse=True ) # Update the order instance, e.g., number of pending orders, and remove the # hesitator, in advance. order.hesitators.remove(self) # After sorting, for all pending orderinfo with the same order instance, # either (1) no one is to be stored, or (2) only the first one is stored if not orderinfo_list[0].storage_decision: # if nothing is to be stored for pending_orderinfo in orderinfo_list: # Find the global instance of the sender, and update it. # If it is an internal order and sender is still a neighbor if pending_orderinfo.prev_owner in self.peer_neighbor_mapping: self.peer_neighbor_mapping[ pending_orderinfo.prev_owner ].share_contribution[-1] += self.engine.reward_c else: # the first element is to be stored first_pending_orderinfo: OrderInfo = orderinfo_list[0] # Find the global instance for the sender, and update it. # If it is an internal order and sender is still a neighbor if first_pending_orderinfo.prev_owner in self.peer_neighbor_mapping: self.peer_neighbor_mapping[ first_pending_orderinfo.prev_owner ].share_contribution[-1] += self.engine.reward_d # Add the orderinfo instance into the local storage, # and update the order instance self.order_orderinfo_mapping[order] = first_pending_orderinfo self.new_order_set.add(order) order.holders.add(self) # For the remaining pending orderinfo in the list, no need to store them, # but may need updates. for pending_orderinfo in orderinfo_list[1:]: if pending_orderinfo.storage_decision: raise ValueError( "Should not store multiple copies of same orders." ) # internal order, sender is still neighbor if pending_orderinfo.prev_owner in self.peer_neighbor_mapping: # update the share contribution self.peer_neighbor_mapping[ pending_orderinfo.prev_owner ].share_contribution[-1] += self.engine.reward_e # delete this entry from the pending mapping table del self.order_pending_orderinfo_mapping[order] def share_orders(self, birth_time_span) -> Tuple[Set[Order], Set["Peer"]]: """ This method determines which orders to be shared to which neighbors. It will return the set of orders to share, and the set of neighboring peers to share. This method is only called by each peer proactively at the end of a batch period. :param birth_time_span: scenario.birth_time_span :return: Tuple[set of orders to share, set of peers to share] """ if self.local_clock not in self.verification_time_orders_mapping: raise RuntimeError( "Share order decision should not be called at this time." ) # free riders do not share any order. if self.is_free_rider: self.new_order_set.clear() return set(), set() # Otherwise, this function has to go through order by order and neighbor by neighbor. # orders to share order_to_share_set: Set[Order] = self.engine.find_orders_to_share(self) # clear self.new_order_set for future use self.new_order_set.clear() # peers to share peer_to_share_set: Set["Peer"] = self.engine.find_neighbors_to_share( self.local_clock, self, max(self.birth_time, birth_time_span - 1) ) return order_to_share_set, peer_to_share_set def del_order(self, order: Order) -> None: """ This method deletes all orderinfo instances of a particular order. :param order: the order instance of the order to be deleted. :return: None """ # check if this order is in the pending table if order in self.order_pending_orderinfo_mapping: order.hesitators.remove(self) del self.order_pending_orderinfo_mapping[order] # check if this order is in the local storage if order in self.order_orderinfo_mapping: self.new_order_set.discard(order) del self.order_orderinfo_mapping[order] order.holders.remove(self) def score_neighbors(self) -> None: """ This method calculates and updates the scores of my neighbors. It needs to be run every time before making sharing order decisions. :return: None """ self.engine.score_neighbors(self) def refresh_neighbors(self) -> None: """ This method eliminates unnecessary neighbors if any. :return: None. """ self.engine.neighbor_refreshment(self) def rank_neighbors(self) -> List["Peer"]: """ This method ranks neighbors according to their scores. It is called by internal method share_orders(). :return: a list peer instances ranked by the scores of their corresponding neighbor instances, from top to down. """ peer_list: List["Peer"] = list(self.peer_neighbor_mapping) peer_list.sort( key=lambda item: self.peer_neighbor_mapping[item].score, reverse=True ) return peer_list
27,222
https://github.com/apache/activemq-artemis/blob/master/artemis-jdbc-store/src/main/java/org/apache/activemq/artemis/jdbc/store/journal/JDBCJournalLoaderCallback.java
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-public-domain, MIT, OFL-1.1
2,023
activemq-artemis
apache
Java
Code
340
876
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.jdbc.store.journal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.activemq.artemis.core.journal.LoaderCallback; import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo; import org.apache.activemq.artemis.core.journal.RecordInfo; import org.apache.activemq.artemis.core.journal.TransactionFailureCallback; class JDBCJournalLoaderCallback implements LoaderCallback { private final List<PreparedTransactionInfo> preparedTransactions; private final TransactionFailureCallback failureCallback; /* We keep track of list entries for each ID. This preserves order and allows multiple record insertions with the same ID. We use this for deleting records */ private final Map<Long, List<Integer>> deleteReferences = new HashMap<>(); private final List<RecordInfo> committedRecords; private long maxId = -1; JDBCJournalLoaderCallback(final List<RecordInfo> committedRecords, final List<PreparedTransactionInfo> preparedTransactions, final TransactionFailureCallback failureCallback, final boolean fixBadTX) { this.committedRecords = committedRecords; this.preparedTransactions = preparedTransactions; this.failureCallback = failureCallback; } private synchronized void checkMaxId(long id) { if (maxId < id) { maxId = id; } } @Override public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) { preparedTransactions.add(preparedTransaction); } @Override public synchronized void addRecord(final RecordInfo info) { int index = committedRecords.size(); committedRecords.add(index, info); ArrayList<Integer> indexes = new ArrayList<>(); indexes.add(index); deleteReferences.put(info.id, indexes); checkMaxId(info.id); } @Override public synchronized void updateRecord(final RecordInfo info) { int index = committedRecords.size(); committedRecords.add(index, info); } @Override public synchronized void deleteRecord(final long id) { for (int i : deleteReferences.get(id)) { committedRecords.remove(i); } } @Override public void failedTransaction(final long transactionID, final List<RecordInfo> records, final List<RecordInfo> recordsToDelete) { if (failureCallback != null) { failureCallback.failedTransaction(transactionID, records, recordsToDelete); } } public long getMaxId() { return maxId; } }
27,766
https://github.com/dcarrol3/Otter-Game/blob/master/core/src/com/game/otter/game/GameScreen.java
Github Open Source
Open Source
MIT
null
Otter-Game
dcarrol3
Java
Code
1,814
6,024
// Otter Game // Main game screen // By Doug Carroll and Jon Jordan package com.game.otter.game; import java.util.ArrayList; import java.util.Random; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.game.otter.menu.Button; import com.game.otter.menu.GameOver; import com.game.otter.menu.MainMenu; import com.game.otter.menu.Pause; import com.game.otter.start.OtterGame; public class GameScreen implements Screen { final OtterGame game; private OrthographicCamera camera; // Main game camera private Texture background; // Background texture private Texture slowmo; // Slow Mo texture private Player player; // Player or otter private Music music; // Background music private Random rand; // Random private ArrayList<Shark> sharkList; // Shark list private ArrayList<Clam> clamList; // Clam list private ArrayList<Clam> specialList; // Specials list private ArrayList<Float> doubleTimers; // Handles timers for double bonus ArrayList<Bullet> bulletList; // Handles bullets public final int STARTINGSHARKS = 5; // Number of sharks to start with public final int MAXSHARKS = 20; // Max sharks that will ever be in the game public final int STARTINGCLAMS = 3; // Starting number of clams public final float levelTime = 15.0f; // Time between levels public final int levelDifficulty = 2; // Sets shark speed increase per level public final float DOUBLETIME = 15.0f; // Time for double bounus public final float SLOWMULTI = 0.5f; // Multiplier for slow mo public final float SLOWTIME = 15.0f; // Time for SlowMo bonus private float playTimeSec = 0.0f; // Game timer seconds private int playTimeMin = 0; // Game timer minutes private float levelTimeCount; // Helper for keeping track of time private int level; // Level number private static int state; // Controls game state 0 for paused, 1 for running private float delta; // In game time keeper private float slowMoTimer= 0.0f; // Hanldes SlowMo time private int slowMoState = 0; // Handles state of slowmo private Pause pause; // Pause menu public GameScreen(final OtterGame gam){ this.game = gam; bulletList = new ArrayList<Bullet>(); sharkList = new ArrayList<Shark>(); clamList = new ArrayList<Clam>(); specialList = new ArrayList<Clam>(); doubleTimers = new ArrayList<Float>(); player = new Player(game, bulletList); rand = new Random(); pause = new Pause(game); state = 1; // 1 for running, 0 for paused level = 1; // Starting level levelTimeCount = 0.0f; // Build shark list for (int i = 0; i < STARTINGSHARKS; i++) sharkList.add(new Shark(game, (level-1)*levelDifficulty)); // Build clam list for (int i = 0; i < STARTINGCLAMS; i++) clamList.add(new Clam(game)); // Textures background = new Texture("gamebackground.png"); slowmo = new Texture("slowmo.png"); // Sounds music = Gdx.audio.newMusic(Gdx.files.internal("runaway.mp3")); // Load in music file music.setVolume(Prefs.getMusicVolume()); music.play(); // Play music music.setLooping(true); // Sets music to looping // Camera camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 480); // Screen size } public static int getState() { return state; } public static void setState(int state) { state = state; } @Override public void render(float delta) { // Clears screen and repaints with background color Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Updates the screen camera.update(); this.delta = delta; // Tells sprites to render on screen game.batch.setProjectionMatrix(camera.combined); // Checks for game state gameState(); // Updates game screen update(); //Start new sprite batch game.batch.begin(); display(); pauseDisplay(); // Pause display - MUST be after normal display game.batch.end(); // Checks if player is dead - MUST be at bottom of render ifDead(); } @Override public void resize(int width, int height) {} @Override public void show() {} @Override public void hide() {} // Handles pause menu @Override public void pause() { pause.update(); } @Override public void resume() {} // Disposes of objects on screen @Override public void dispose() { music.stop(); // Stop music background.dispose(); player.dispose(); // Dispose of sharks sharkList.clear(); // Pause dispose pause.dispose(); state = 1; // Make sure state is not paused } // Updates game elements void update(){ // If game is running if(state == 1){ // Increases game time increaseTime(); // Movements player.movement(); moveSharks(); moveClams(); moveSpecials(); // Collision checks sharkCollision(); clamCollision(); specialCollision(); // Special spawns specialChance(); // Logic Checks player.fireCheck(); // Checks if user hits fire button levels(); removeSlowMo(); delDoubleBonus(); } // If paused else pause(); } // Handles display for GameScreen void display(){ game.batch.draw(background, 0, 0); // Background game.toonyFont.draw(game.batch, ("Ammo: " + player.getAmmo()), 30, 380); game.toonyFont.draw(game.batch, ("Score: " + player.getScore()), 110, 380); // Double bonus if(player.getScoreOffset() > 1){game.doubleFont.draw(game.batch, (("x" + player.getScoreOffset())), 192, 382);} // SlowMo if(slowMoState == 1){game.batch.draw(slowmo, 185, 433);} game.toonyFont.draw(game.batch, playTime(), 100, 450); game.toonyFont.draw(game.batch, ("Level: " + level), 30, 450); displayBullets(); // Displays bullets displaySharks(); // Displays shark sprites displayClams(); // Displays clam sprites displaySpecials(); // Displays special clams player.display(); // Display player sprite - Must be before sharks player.displayLife(); // Display lives } // Handles shark movement for the list private void moveSharks(){ for(int i = 0; i < sharkList.size(); i++) sharkList.get(i).movement(); } // Handles clam movement for the list private void moveClams(){ for(int i = 0; i < clamList.size(); i++) clamList.get(i).movement(); } // Handles specials movement private void moveSpecials(){ for(int i = 0; i < specialList.size(); i++){ specialList.get(i).movement(); } } // Displays clams private void displayClams(){ for(int i = 0; i < clamList.size(); i++) clamList.get(i).display(); } // Handles displaying specials private void displaySpecials(){ for(int i = 0; i < specialList.size(); i++){ specialList.get(i).display(); } } // Displays sharks private void displaySharks(){ for (int i = 0; i < sharkList.size(); i++) sharkList.get(i).display(); } // Display bullets and handle bullet movement private void displayBullets(){ for (int i = 0; i < bulletList.size(); i++){ // Handles bullet movement bulletList.get(i).movement(); // Display bullet bulletList.get(i).display(); // Check if bullet goes off screen if(bulletList.get(i).getxCoord() < -100 || bulletList.get(i).getyCoord() < -100 || bulletList.get(i).getyCoord() > game.getHeight() + 100){ bulletList.get(i).dispose(); bulletList.remove(bulletList.get(i)); } } } // If a special is to be spawned this picks which one void spawnSpecial(){ int random = rand.nextInt(3)+1; // For special spawns if(random == 1) specialList.add(new SlowMoClam(game, clamList.get(0).getSpeed())); else if(random == 2) specialList.add(new DoubleClam(game, clamList.get(0).getSpeed())); else if(random == 3) specialList.add(new HealthClam(game, clamList.get(0).getSpeed())); } // Handles special spawning void specialChance(){ // 5 out of 1000 chance per cycle int random = rand.nextInt(1000) + 1; if(random <= 5) spawnSpecial(); } // Special collisions and end of screen private void specialCollision(){ for(int i = 0; i < specialList.size(); i++){ // Player collision or off screen // Slow mo clams if(specialList.get(i) instanceof SlowMoClam){ // Player if(specialList.get(i).hitBox.overlaps(player.hitBox)){ specialList.remove(i); player.hitByClam(); addSlowMo(); // Starts slow mo } // Off screen else if(specialList.get(i).getxCoord() > game.getWidth() + 200){ specialList.remove(i); } } // Double clams else if(specialList.get(i) instanceof DoubleClam){ // Player if(specialList.get(i).hitBox.overlaps(player.hitBox)){ specialList.remove(i); player.hitByClam(); addDoubleBonus(); } // Off screen else if(specialList.get(i).getxCoord() > game.getWidth() + 200){ specialList.remove(i); } } // Health clams else if(specialList.get(i) instanceof HealthClam){ // Player if(specialList.get(i).hitBox.overlaps(player.hitBox)){ specialList.remove(i); player.hitByClam(); player.addLife(); // Add life bonus } // Off screen else if(specialList.get(i).getxCoord() > game.getWidth() + 200){ specialList.remove(i); } } } } // Clam collision private void clamCollision(){ for(int i = 0; i < clamList.size(); i++){ // Player his clam if(clamList.get(i).hitBox.overlaps(player.hitBox)){ clamList.get(i).respawnClam(); // Kill clam player.hitByClam(); } // Clam hits clam for(int j = 0; j < clamList.size(); j++){ // Clam hits clam if(clamList.get(i).hitBox.overlaps(clamList.get(j).hitBox) && i != j){ clamList.get(i).respawnClam(); clamList.get(j).respawnClam(); } } // Clam spawns on special for(int k = 0; k < specialList.size(); k++){ // Respawn that special if(specialList.get(k).hitBox.overlaps(clamList.get(i).hitBox)) specialList.get(k).respawnClam(); } } } // Collision check with sharks private void sharkCollision() { for (int i = 0; i < sharkList.size(); i++) { // Player hits shark if(sharkList.get(i).hitBox.overlaps(player.hitBox)) player.hitByShark(); // If sharks hit sharks for (int j = 0; j < sharkList.size(); j++) { // Shark hits shark if(sharkList.get(i).hitBox.overlaps(sharkList.get(j).hitBox) && i != j){ sharkList.get(i).respawnShark(); sharkList.get(j).respawnShark(); } } // If bullets hit sharks kill shark and remove bullet for (int k = 0; k < bulletList.size(); k++){ if(sharkList.get(i).hitBox.overlaps(bulletList.get(k).hitBox)){ sharkList.get(i).respawnShark(); bulletList.remove(bulletList.get(k)); } } // If shark spawns on clam at same speed for (int l = 0; l < clamList.size(); l++){ if(sharkList.get(i).getSpeed() == sharkList.get(i).STARTSPEED && slowMoState == 0 && clamList.get(l).hitBox.overlaps(sharkList.get(i).hitBox)) // Respawn that clam clamList.get(l).respawnClam(); } // If shark spawns on special clam at same speed for(int m = 0; m < specialList.size(); m++){ if(sharkList.get(i).getSpeed() == sharkList.get(i).STARTSPEED && slowMoState == 0){ // Respawn that special if(specialList.get(m).hitBox.overlaps(sharkList.get(i).hitBox)) specialList.get(m).respawnClam(); } } } } // Handles adding double bounses void addDoubleBonus(){ doubleTimers.add(playTimeSec); // Starts new double timer player.increaseScoreMulti(1); } // Handles removing double bonuses - runs in update void delDoubleBonus(){ for(int i = 0; i < doubleTimers.size(); i++) if((doubleTimers.get(i) + DOUBLETIME) <= playTimeSec){ player.decreaseScoreMulti(1); doubleTimers.remove(i); } } // Adds SlowMo void addSlowMo(){ slowMoTimer = playTimeSec; // Start slow mo timer if(slowMoState == 0){ slowMoState = 1; // Slow sharks down for(int i = 0; i < sharkList.size(); i++){ sharkList.get(i).setSpeed(sharkList.get(i).getSpeed() * SLOWMULTI); } // Slow bullets down for(int i = 0; i < player.bulletList.size(); i++){ bulletList.get(i).setSpeed(bulletList.get(i).getSpeed() * SLOWMULTI); } // Slow future bullets down player.setBulletSpeed(player.getBulletSpeed() * SLOWMULTI); // Slow player movement player.setSpeed(player.getSpeed() * SLOWMULTI); // Slow clams for(int i = 0; i < clamList.size(); i++){ clamList.get(i).setSpeed(clamList.get(i).getSpeed() * SLOWMULTI); } // Slow specials for(int i = 0; i < specialList.size(); i++){ specialList.get(i).setSpeed(specialList.get(i).getSpeed() * SLOWMULTI); } } } // Removes SlowMo - runs in update void removeSlowMo(){ if(slowMoState == 1 && (slowMoTimer + SLOWTIME <= playTimeSec)){ // Resume sharks for(int i = 0; i < sharkList.size(); i++){ sharkList.get(i).setSpeed(sharkList.get(i).getSpeed() / SLOWMULTI); } // Resume bullets for(int i = 0; i < player.bulletList.size(); i++){ bulletList.get(i).setSpeed(bulletList.get(i).getSpeed() / SLOWMULTI); } // Slow future bullets down player.setBulletSpeed(player.getBulletSpeed() / SLOWMULTI); // Resume player movement player.setSpeed(player.getSpeed() / SLOWMULTI); // Resume clams for(int i = 0; i < clamList.size(); i++){ clamList.get(i).setSpeed(clamList.get(i).getSpeed() / SLOWMULTI); } // Resume specials for(int i = 0; i < specialList.size(); i++){ specialList.get(i).setSpeed(specialList.get(i).getSpeed() / SLOWMULTI); } slowMoState = 0; // Reset Slow Mo state } } // When lives are gone void ifDead(){ if(player.getLives() <= 0){ // Time for sounds try { Thread.sleep(300); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } dispose(); game.setScreen(new GameOver(game, player.getScore(), playTime(), level)); } } // Handles levels void levels(){ levelTimeCount += delta; // Checks if hits level time, must be 0.03 instead of 0 if(levelTimeCount >= levelTime){ level++; spawnSpecial(); // Increase sharks speed for (int i = 0; i < sharkList.size(); i++) { // Check slow mo state if(slowMoState == 0) sharkList.get(i).setSpeed((sharkList.get(i).getSpeed() + levelDifficulty)); else sharkList.get(i).setSpeed((sharkList.get(i).getSpeed() + (levelDifficulty * SLOWMULTI))); } // Add shark (speed constructor for slowmo) sharkList.add(new Shark(game, 0, sharkList.get(0).getSpeed())); levelTimeCount = 0.0f; } } // Increases game time void increaseTime(){ playTimeSec += delta; } // Handles playtime and converting it to string String playTime(){ playTimeMin = (int) (playTimeSec / 60); return "Time: " + playTimeMin + (Math.round((playTimeSec - (60 * playTimeMin))) < 10? ":0" : ":") + Math.round((playTimeSec - (60 * playTimeMin))); } // Sets game state void gameState(){ if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)){ // Pause if(state == 1){ state = 0; music.pause(); // Pause music } // Resume else if(state == 0){ state = 1; music.play(); } } // Handles Androids pause else if(Gdx.app.getType() == ApplicationType.Android){ // Handles back button for Android Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(final int keycode) { if (keycode == Keys.BACK) { // Pause if(state == 1){ state = 0; music.pause(); // Pause music } // Resume else if(state == 0){ state = 1; music.play(); } } return false; } }); } } // Pause display void pauseDisplay(){ // If game is paused if(state == 0){ pause.display(); } } }
24,874
https://github.com/chisuhua/llvm/blob/master/try/run_ppu_test.sh
Github Open Source
Open Source
Apache-2.0
null
llvm
chisuhua
Shell
Code
251
2,348
#!/bin/bash # -*- coding: utf-8 -*- CPU=riscv32 CPU=PPU #CPU=AMDGPU if [ $CPU == "AMDGPU" ]; then OPT_CPU="-mtriple=amdgcn-unknown-unknown" cpu="amdgpu" triple="amdgcn" fi #OPT_CPU="-mtriple=ppu-unknown-unknown" if [ $CPU == "PPU" ]; then OPT_CPU="-mtriple=ppu" cpu="ppu" triple="ppu" fi #cd /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/test && /home/shchi/anaconda2/bin/python /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Transforms/SimplifyCFG/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Transforms/SimplifyCFG/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/MC/Disassembler/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/MC/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Transforms/ConstantHoisting/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Transforms/AtomicExpand/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Analysis/CostModel/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Object/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -svva /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/CodeGen/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/DebugInfo/PPU #/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -sv /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm/test/Transforms/ReconvergeCFG #exit ROOT=/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/llvm BIN=/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/bin NAME=setvl NAME=ppuv-copyreg NAME=ppuv-reg-imm-op NAME=ppuv-shifted-add NAME=ppuv-stripmined-binop NAME=ppuv-vr-gpr-alu-op NAME=alu32 NAME=analyze-branch NAME=branch NAME=ppuv-simple_branch ## vop2 NAME=add SUBD=vop2 TEST=$ROOT/test/CodeGen/PPU/$SUBD/$NAME.ll ## vop2 NAME=vadd NAME=sign_extend_1 NAME=sign_extend_2 NAME=s_addk_i32 TEST=$ROOT/test/CodeGen/PPU/$NAME.ll #DEBUG="--print-machineinstrs --print-after-all --stop-after=ppu-isel" DEBUG="" #DEBUG="-debug $DEBUG" #DEBUG="-debug-pass=Details $DEBUG" #DEBUG="-debug-pass=Executions $DEBUG" #NAME=ppu_vlw #TEST=$NAME.ll #DEBUG="-time-passes $DEBUG" DEBUG="-debug-only=isel $DEBUG" #DEBUG="-debug-only=ppu-isel $DEBUG" #DEBUG="-debug-only=ppu-lower $DEBUG" #DEBUG="-debug-only=asm-printer $DEBUG" #DEBUG="-debug $DEBUG" #DEBUG="--print-machineinstrs $DEBUG" DEBUG="--print-after-all $DEBUG" #DEBUG="--view-isel-dags $DEBUG" #DEBUG="--stop-after=ppu-isel $DEBUG" #DEBUG="-stop-after=ppu-lower $DEBUG" #DEBUG="-stop-after=amdgpu-isel $DEBUG" #DEBUG="--view-sched-dags $DEBUG" DEBUG="--verify-machineinstrs $DEBUG" DEBUG="-o $NAME.s" #DEBUG="$DEBUG -asm-show-inst" #DEBUG="$DEBUG -asm-verbose" #LIT="/work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/./bin/llvm-lit -s -vv -a $TEST" #echo $LIT #$LIT #DBG_RUN="$BIN/llc -mtriple=ppu -mattr=+v -mattr=+r $DEBUG $TEST" DBG_RUN="$BIN/llc -mtriple=$triple -mattr=+t,+r $DEBUG $TEST" #DBG_RUN="$BIN/llc -mtriple=$triple -mattr=-t $DEBUG $TEST" echo $DBG_RUN $DBG_RUN exit ####################################################### ##################################################### ### ReconvergeCFG OPT_TYPE="-reconvergecfg" NAME=if-else-phi #NAME=loop-exit #NAME=loop-phi TEST=$ROOT/test/Transforms/ReconvergeCFG/$NAME.ll ### Scalarize OPT_TYPE="-Scalarizer -Scalarizer-load-store" NAME=basic TEST=$ROOT/test/Transforms/Scalarizer/$NAME.ll ### VscaleProp OPT_TYPE="-vscaleprop" NAME=if-else-phi TEST=$ROOT/test/Transforms/VscaleProp/$NAME.ll ### Divergence OPT_TYPE="-analyze -divergence" NAME=loads NAME=llvm.$triple.buffer.atomic NAME=llvm.$triple.image.atomic NAME=no-return-blocks NAME=phi-undef NAME=unreachable-loop-block NAME=intrinsics NAME=kernel-args NAME=diverge #NAME=workitem-intrinsics TEST=$ROOT/test/Analysis/LegacyDivergenceAnalysis/$CPU/$NAME.ll OPT_TYPE="$OPT_TYPE -use-gpu-divergence-analysis" NAME=atomics NAME=hidden_diverge NAME=hidden_loopdiverge NAME=irreducible NAME=kernel-args NAME=no-return-blocks NAME=phi-undef NAME=temporal_diverge NAME=always_uniform TEST=$ROOT/test/Analysis/DivergenceAnalysis/$CPU/$NAME.ll ### VscaleProp OPT_TYPE="-reconvergecfg" #OPT_TYPE="-analyze -divergence" NAME=if-else-phi #NAME=loop-exit #NAME=loop-phi TEST=$ROOT/test/Transforms/ReconvergeCFG/$NAME.ll NAME=vadd_tid_novolatile TEST=$ROOT/$NAME.ll #NAME=uniform #NAME=nonuniform #NAME=uniform-regions #TEST=$ROOT/test/Transforms/ReconvergeCFG/PPU/$NAME.ll OPT_RUN="$BIN/opt $OPT_CPU $DEBUG -S $OPT_TYPE $TEST -o $NAME.$CPU.s" echo $OPT_RUN $OPT_RUN exit # End ##################################################### # gdb command /work/git/chisuhua/projects/sw/mixlang/tools/toolchain/build/llvm/bin/llc -mtriple=ppu -verify-machineinstrs
1,612
https://github.com/yashghantala/quarkusio.github.io/blob/master/_generated-config/config/quarkus-micrometer-config-group-config-micrometer-config-binder-config.adoc
Github Open Source
Open Source
CC-BY-3.0
null
quarkusio.github.io
yashghantala
AsciiDoc
Code
160
860
[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference, cols="80,.^10,.^10"] |=== h|[[quarkus-micrometer-config-group-config-micrometer-config-binder-config_configuration]]link:#quarkus-micrometer-config-group-config-micrometer-config-binder-config_configuration[Configuration property] h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.vertx.enabled]]`link:#quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.vertx.enabled[quarkus.micrometer.binder.vertx.enabled]` [.description] -- Vert.x metrics support. Support for Vert.x metrics will be enabled if micrometer support is enabled, Vert.x MetricsOptions is on the classpath and either this value is true, or this value is unset and `quarkus.micrometer.binder-enabled-default` is true. --|boolean | a|icon:lock[title=Fixed at build time] [[quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.mp-metrics.enabled]]`link:#quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.mp-metrics.enabled[quarkus.micrometer.binder.mp-metrics.enabled]` [.description] -- Microprofile Metrics support. Support for Microprofile metrics will be enabled if micrometer support is enabled, and this value is true. You need to also include the microprofile api jar to your dependencies: <dependency> <groupId>org.eclipse.microprofile.metrics</groupId> <artifactId>microprofile-metrics-api</artifactId> </dependency> --|boolean | a|icon:lock[title=Fixed at build time] [[quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.jvm]]`link:#quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.jvm[quarkus.micrometer.binder.jvm]` [.description] -- Micrometer JVM metrics support. Micrometer JVM metrics support is enabled by default. --|boolean |`true` a|icon:lock[title=Fixed at build time] [[quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.system]]`link:#quarkus-micrometer-config-group-config-micrometer-config-binder-config_quarkus.micrometer.binder.system[quarkus.micrometer.binder.system]` [.description] -- Micrometer System metrics support. Micrometer System metrics support is enabled by default. --|boolean |`true` |===
14,932
https://github.com/cytomine/Cytomine-core/blob/master/test/functional/be/cytomine/security/SecurityTestsAbstract.groovy
Github Open Source
Open Source
Apache-2.0
2,023
Cytomine-core
cytomine
Groovy
Code
241
646
package be.cytomine.security /* * Copyright (c) 2009-2022. Authors: see NOTICE file. * * 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 be.cytomine.test.BasicInstanceBuilder /** * Created by IntelliJ IDEA. * User: lrollus * Date: 2/03/11 * Time: 11:08 * To change this template use File | Settings | File Templates. */ class SecurityTestsAbstract { /** * Security test */ static String USERNAMEWITHOUTDATA = "USERNAMEWITHOUTDATA" static String PASSWORDWITHOUTDATA = "PASSWORDWITHOUTDATA" static String USERNAME1 = "USERNAME1" static String PASSWORD1 = "PASSWORD1" static String USERNAME2 = "USERNAME2" static String PASSWORD2 = "PASSWORD2" static String USERNAME3 = "USERNAME3" static String PASSWORD3 = "PASSWORD3" static String GUEST1 = "GUEST1" static String GPASSWORD1 = "GPASSWORD1" static String USERNAMEADMIN = "USERNAMEADMIN" static String PASSWORDADMIN = "PASSWORDADMIN" static String USERNAMEBAD = "BADUSER" static String PASSWORDBAD = "BADPASSWORD" User getUser1() { BasicInstanceBuilder.getUser(USERNAME1,PASSWORD1) } User getUser2() { BasicInstanceBuilder.getUser(USERNAME2,PASSWORD2) } User getUser3() { BasicInstanceBuilder.getUser(USERNAME3,PASSWORD3) } User getGuest1() { BasicInstanceBuilder.getGhest(GUEST1,GPASSWORD1) } User getUserAdmin() { BasicInstanceBuilder.getSuperAdmin(USERNAMEADMIN,PASSWORDADMIN) } User getUserBad() { BasicInstanceBuilder.getUser(USERNAMEBAD,PASSWORDBAD) } }
27,481
https://github.com/skeletongo/cube/blob/master/module/init.go
Github Open Source
Open Source
Apache-2.0
null
cube
skeletongo
Go
Code
77
204
package module import ( "github.com/skeletongo/cube/base" ) var Obj *base.Object type sink struct { } func (s *sink) OnStart() { } func (s *sink) OnTick() { gModuleMgr.OnTick() } func (s *sink) OnStop() { } var Config = new(Configuration) type Configuration struct { Options *base.Options } func (c *Configuration) Name() string { return "module" } func (c *Configuration) Init() error { Obj = base.NewObject("module", c.Options, new(sink)) Obj.Run() return nil } func (c *Configuration) Close() error { return nil }
30,095
https://github.com/javaobjects/ipm_boot/blob/master/src/main/java/com/protocolsoft/word/service/ReportModalService.java
Github Open Source
Open Source
MulanPSL-2.0, LicenseRef-scancode-mulanpsl-2.0-en, LicenseRef-scancode-unknown-license-reference
2,023
ipm_boot
javaobjects
Java
Code
196
717
/** *<p>Copyright © 北京协软科技有限公司版权所有。</p> */ package com.protocolsoft.word.service; import java.util.List; import java.util.Map; import com.protocolsoft.user.bean.SystemUserBean; import com.protocolsoft.word.bean.ReportModalBean; /** * * @ClassName: ReportModalService * @Description: * @author 刘斌 * */ public interface ReportModalService { /** * @Title: insertTimerReort * @Description: 插入定时报表信息接口 * @param bean * @return int * @author 刘斌 */ boolean insertReportModal(ReportModalBean bean); /** * @Title: deleteTimerReort * @Description: 按id杀出定时报表基础信息接口 * @param id * @return boolean * @author 刘斌 */ boolean deleteReportModalBean(int id, SystemUserBean bean); /** * @Title: searchTimerReort * @Description: 按id查找定时报表接口 * @param id * @return TimerReportBean * @author 刘斌 */ Map<String, Object> searchReportModal(int id); /** * @Title: searchAllTimerReorty * @Description: 获取素有定时报表基础信息列表 * @return List<TimerReportBean> * @author 刘斌 */ String searchAllReportModal(); /** * @Title: updateTimerReort * @Description: 修改定时报表基础信息接口 * @param bean * @param beanq * @return JSONObject * @author 刘斌 */ boolean updateReportModal(ReportModalBean bean); /** * @Title: selectNeedTimerReort * @Description: 按归档类型获取定时报表基础信息列表接口 * @param typeId * @return List<TimerReportBean> * @author 刘斌 */ List<ReportModalBean> selectNeedReportModal(int typeId); /** * * @Title: selectModuleIds * @Description: * @param id * @return String * @author 刘斌 */ String selectModuleIds(Integer id); /** * * @Title: deleteModalByUserId * @Description: * @param id * @return boolean * @author 刘斌 */ boolean deleteModalByUserId(Integer id, SystemUserBean userBean); }
36,888
https://github.com/NardiniA/Design-Test/blob/master/ShapeMorphIdeas/js/demo3.js
Github Open Source
Open Source
MIT
2,019
Design-Test
NardiniA
JavaScript
Code
69
294
/** * demo3.js * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2017, Codrops * http://www.codrops.com */ { class MorphingBG { constructor(el) { this.DOM = {}; this.DOM.el = el; this.DOM.paths = Array.from(this.DOM.el.querySelectorAll('path')); this.animate(); } animate() { this.DOM.paths.forEach((path) => { setTimeout(() => { anime({ targets: path, duration: anime.random(3000,5000), easing: [0.5,0,0.5,1], d: path.getAttribute('pathdata:id'), loop: true, direction: 'alternate' }); }, anime.random(0,1000)); }); } }; new MorphingBG(document.querySelector('svg.scene')); };
10,989
https://github.com/Pyriaxis/gbf-teambuilder/blob/master/src/data/calculation.js
Github Open Source
Open Source
MIT
null
gbf-teambuilder
Pyriaxis
JavaScript
Code
247
794
import * as buffs from "./category/buffs"; import * as nukes from "./category/nukes"; import {round} from "lodash"; import {CHARGE_BAR_BOOST} from "./category/buffs"; export function calcNormalAtk(array){ let multiplier = 1.00; let mulA = 0; let mulB = 0; let mulC = 0; array.forEach(buff=>{ if (buff instanceof buffs.ATK_UP_SINGLE){ mulA = Math.max(buff.getValue(), mulA) } else if (buff instanceof buffs.ATK_UP_DUAL){ mulB = Math.max(buff.getValue(), mulB) } else if (buff instanceof buffs.ATK_UP_OUGI){ mulC = Math.max(buff.getValue(), mulC); } }); return multiplier + mulA + mulB + mulC; } export function calcUniqueAtk(array){ let multiplier = 1.00; array.forEach(buff=>{ if (buff instanceof buffs.ATK_UP_STK_UNIQUE || buff instanceof buffs.ATK_UP_UNIQUE){ multiplier *= (1+buff.getValue()); } }); multiplier = round(multiplier, 2); return multiplier; } export function calcCritical(array){ let multiplier = 1.00; array.forEach(buff=>{ if (buff instanceof buffs.CRITICAL){ multiplier += buff.getValue(); } }); multiplier = round(multiplier, 2); return multiplier; } export function calcMultiattack(array){ let multiplier = 1.00; //@todo: this is not a very accurate calculation array.forEach(buff=>{ if (buff instanceof buffs.MULTIATTACK){ multiplier += buff.getValue(); } }); multiplier = round(multiplier, 2); return multiplier; } export function calcEcho(array){ let multiplier = 1.00; array.forEach(buff=>{ if (buff instanceof buffs.ECHO){ multiplier += buff.getValue(); } }); multiplier = round(multiplier, 2); return multiplier; } export function calcOugiSpecUp(array){ let multiplier = 1.00; array.forEach(buff=>{ if (buff instanceof buffs.OUGI_SPEC_UP){ multiplier += buff.getValue(); } }); return multiplier; } export function calcOugiEcho(array){ let addition = 0; array.forEach(nuke=>{ if (nuke instanceof nukes.OUGI_ECHO){ addition += nuke.getValue(); } }); return addition; } export function calcChargeBarBoost(array){ let cboost = 0; array.forEach(boost=>{ if (boost instanceof buffs.CHARGE_BAR_BOOST){ cboost += boost.getValue(); } }) return cboost; }
45,402
https://github.com/g-yonchev/TelerikAcademy/blob/master/Homeworks/C# 2/ExamsPractice/Examples/01. Zerg - SecondWay/ZergProblem.cs
Github Open Source
Open Source
MIT
2,015
TelerikAcademy
g-yonchev
C#
Code
146
389
namespace Zerg { using System; class ZergProblem { static int ConvertZergDigitToInt(string digit) { switch (digit) { case "Rawr": return 0; break; case "Rrrr": return 1; break; case "Hsst": return 2; break; case "Ssst": return 3; break; case "Grrr": return 4; break; case "Rarr": return 5; break; case "Mrrr": return 6; break; case "Psst": return 7; break; case "Uaah": return 8; break; case "Uaha": return 9; break; case "Zzzz": return 10; break; case "Bauu": return 11; break; case "Djav": return 12; break; case "Myau": return 13; break; case "Gruh": return 14; break; default: throw new ArgumentException(); } } static void Main() { string zergMessage = Console.ReadLine(); int position = zergMessage.Length / 4 - 1; long sum = 0; for (int i = 0; i < zergMessage.Length; i += 4) { string digit = zergMessage.Substring(i, 4); sum += ConvertZergDigitToInt(digit) * (long)Math.Pow(15, position); position--; } Console.WriteLine(sum); } } }
35,284
https://github.com/JacekDanecki/compute-runtime/blob/master/opencl/test/unit_test/api/cl_release_command_queue_tests.inl
Github Open Source
Open Source
MIT
2,021
compute-runtime
JacekDanecki
C++
Code
190
884
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/test/common/helpers/unit_test_helper.h" #include "opencl/source/context/context.h" #include "opencl/test/unit_test/fixtures/device_host_queue_fixture.h" #include "opencl/test/unit_test/mocks/mock_kernel.h" #include "cl_api_tests.h" #include <type_traits> using namespace NEO; namespace DeviceHostQueue { typedef ::testing::Types<CommandQueue, DeviceQueue> QueueTypes; template <typename T> class clReleaseCommandQueueTypeTests : public DeviceHostQueueFixture<T> {}; TYPED_TEST_CASE(clReleaseCommandQueueTypeTests, QueueTypes); TYPED_TEST(clReleaseCommandQueueTypeTests, GivenValidCmdQueueWhenReleasingCmdQueueThenSucessIsReturned) { if (std::is_same<TypeParam, DeviceQueue>::value && !this->pDevice->getHardwareInfo().capabilityTable.supportsDeviceEnqueue) { return; } using BaseType = typename TypeParam::BaseType; auto queue = this->createClQueue(); ASSERT_EQ(CL_SUCCESS, this->retVal); auto qObject = castToObject<TypeParam>(static_cast<BaseType *>(queue)); ASSERT_NE(qObject, nullptr); this->retVal = clReleaseCommandQueue(queue); EXPECT_EQ(CL_SUCCESS, this->retVal); } TEST(clReleaseCommandQueueTypeTests, GivenNullCmdQueueWhenReleasingCmdQueueThenClInvalidCommandQueueErrorIsReturned) { auto retVal = clReleaseCommandQueue(nullptr); EXPECT_EQ(CL_INVALID_COMMAND_QUEUE, retVal); } } // namespace DeviceHostQueue namespace ULT { typedef api_tests clReleaseCommandQueueTests; TEST_F(clReleaseCommandQueueTests, givenBlockedEnqueueWithOutputEventStoredAsVirtualEventWhenReleasingCmdQueueThenInternalRefCountIsDecrementedAndQueueDeleted) { cl_command_queue cmdQ = nullptr; cl_queue_properties properties = 0; ClDevice *device = (ClDevice *)testedClDevice; MockKernelWithInternals kernelInternals(*device, pContext); cmdQ = clCreateCommandQueue(pContext, testedClDevice, properties, &retVal); ASSERT_NE(nullptr, cmdQ); ASSERT_EQ(CL_SUCCESS, retVal); size_t offset[] = {0, 0, 0}; size_t gws[] = {1, 1, 1}; cl_int retVal = CL_SUCCESS; cl_int success = CL_SUCCESS; cl_event event = clCreateUserEvent(pContext, &retVal); cl_event eventOut = nullptr; EXPECT_EQ(success, retVal); retVal = clEnqueueNDRangeKernel(cmdQ, kernelInternals.mockMultiDeviceKernel, 1, offset, gws, nullptr, 1, &event, &eventOut); EXPECT_EQ(success, retVal); EXPECT_NE(nullptr, eventOut); clSetUserEventStatus(event, CL_COMPLETE); clReleaseEvent(event); clReleaseEvent(eventOut); retVal = clReleaseCommandQueue(cmdQ); EXPECT_EQ(success, retVal); } } // namespace ULT
20,584
https://github.com/billy-poon/yii2-app-basic/blob/master/models/tree/TreeNodeInterface.php
Github Open Source
Open Source
BSD-3-Clause
null
yii2-app-basic
billy-poon
PHP
Code
46
118
<?php namespace app\models\tree; interface TreeNodeInterface { public function getDepth(); public function getParent(); public function setParent(TreeNodeInterface $node = null); public function getChildren(); public function appendChild(TreeNodeInterface $node); public function each($bfs = false); public function print($formatter, $depth = 0, $prepend = '', $isLastNode = true, $level = 0); }
13,275
https://github.com/yudaprama/iso20022/blob/master/model/TradeLeg9.go
Github Open Source
Open Source
MIT
2,023
iso20022
yudaprama
Go
Code
937
2,731
package model // Provides the trade leg details. type TradeLeg9 struct { // Margin account where the negotiation and liquidation risks will be calculated. MarginAccount *SecuritiesAccount19 `xml:"MrgnAcct,omitempty"` // Account opened by the central counterparty in the name of the clearing member or its settlement agent within the account structure, for settlement purposes (gives information about the clearing member/its settlement agent account at the central securities depository). DeliveryAccount *SecuritiesAccount19 `xml:"DlvryAcct,omitempty"` // Unambiguous identification of the transaction (that is the trade leg) as known by the instructing party. TradeLegIdentification *Max35Text `xml:"TradLegId"` // Reference allocated by the broker dealer. TradeIdentification *Max35Text `xml:"TradId,omitempty"` // Unique reference assigned by the trading venue when the trade is executed. TradeExecutionIdentification *Max35Text `xml:"TradExctnId"` // Identifies the order sent by the final investor to an intermediary in order to initiate a trade in the former's name. This identification is then matched with the equivalent trade by the clearing. OrderIdentification *Max35Text `xml:"OrdrId,omitempty"` // Identifies the portion of assets within a determined trade that shall be allocated to different clients. AllocationIdentification *Max35Text `xml:"AllcnId,omitempty"` // Provides details about the non clearing member identification and account. NonClearingMember *PartyIdentificationAndAccount31 `xml:"NonClrMmb,omitempty"` // Provides the date and time of trade transaction. TradeDate *ISODateTime `xml:"TradDt"` // Date and time used to determine the price applicable to a trade. If the trade is registered "after market" hours, the trading price will the price of the day but the actual trade date will be the next working day. TransactionDateAndTime *ISODateTime `xml:"TxDtAndTm,omitempty"` // Provides the contractual settlement date. SettlementDate *DateFormat15Choice `xml:"SttlmDt,omitempty"` // Provides details about the security identification. FinancialInstrumentIdentification *SecurityIdentification14 `xml:"FinInstrmId"` // Specifies the ISO code of the trade currency. TradingCurrency *CurrencyCode `xml:"TradgCcy,omitempty"` // Identifies the trade leg indicator which gives the trade side (buy or sell). BuySellIndicator *Side1Code `xml:"BuySellInd"` // Identifies the quantity of the trade leg. TradeQuantity *FinancialInstrumentQuantity1Choice `xml:"TradQty"` // Specifies the price of the traded financial instrument. DealPrice *Price4 `xml:"DealPric"` // Interest that has accumulated on a bond since the last interest payment up to, but not including, the settlement date. AccruedInterestAmount *AmountAndDirection21 `xml:"AcrdIntrstAmt,omitempty"` // Place at which the security is traded. PlaceOfTrade *MarketIdentification84 `xml:"PlcOfTrad"` // Place at which the security is listed. PlaceOfListing *MarketIdentification85 `xml:"PlcOfListg,omitempty"` // Identifies the type of trade transaction. TradeType *TradeType1Code `xml:"TradTp"` // Indicates that the trade is for settlement of an exercised derivatives contract. DerivativeRelatedTrade *YesNoIndicator `xml:"DerivRltdTrad,omitempty"` // Party that identifies a broker when required (for example, authorised broker or prime broker). Broker *PartyIdentificationAndAccount100 `xml:"Brkr,omitempty"` // Provides the identification of the trading party. TradingParty *PartyIdentification35Choice `xml:"TradgPty"` // Indicates in which session the transaction/operation was executed by the final investor or an intermediary. TradeRegistrationOrigin *Max35Text `xml:"TradRegnOrgn,omitempty"` // Identifier of the trading participant's account at the trading venue using the venue's coding system. TradingPartyAccount *SecuritiesAccount19 `xml:"TradgPtyAcct,omitempty"` // Specifies the role of the trading party in the transaction. TradingCapacity *TradingCapacity5Code `xml:"TradgCpcty"` // Indicates how a trade is maintained in the clearing account. TradePostingCode *TradePosting1Code `xml:"TradPstngCd,omitempty"` // Place where the securities are safe-kept, physically or notionally. This place can be, for example, a local custodian, a Central Securities Depository (CSD) or an International Central Securities Depository (ICSD). SafekeepingPlace *SafekeepingPlaceFormat7Choice `xml:"SfkpgPlc,omitempty"` // Account to or from which a securities entry is made. SafekeepingAccount *SecuritiesAccount19 `xml:"SfkpgAcct,omitempty"` // Provides settlement details such as the settlement amount or the place of settlement. SettlementDetails *Settlement1 `xml:"SttlmDtls,omitempty"` // Provides clearing details such as the non clearing member identification or the settlement netting (or not) eligibility code. ClearingDetails *Clearing4 `xml:"ClrDtls,omitempty"` // Principal amount of a trade (price multiplied by quantity). GrossAmount *AmountAndDirection21 `xml:"GrssAmt,omitempty"` } func (t *TradeLeg9) AddMarginAccount() *SecuritiesAccount19 { t.MarginAccount = new(SecuritiesAccount19) return t.MarginAccount } func (t *TradeLeg9) AddDeliveryAccount() *SecuritiesAccount19 { t.DeliveryAccount = new(SecuritiesAccount19) return t.DeliveryAccount } func (t *TradeLeg9) SetTradeLegIdentification(value string) { t.TradeLegIdentification = (*Max35Text)(&value) } func (t *TradeLeg9) SetTradeIdentification(value string) { t.TradeIdentification = (*Max35Text)(&value) } func (t *TradeLeg9) SetTradeExecutionIdentification(value string) { t.TradeExecutionIdentification = (*Max35Text)(&value) } func (t *TradeLeg9) SetOrderIdentification(value string) { t.OrderIdentification = (*Max35Text)(&value) } func (t *TradeLeg9) SetAllocationIdentification(value string) { t.AllocationIdentification = (*Max35Text)(&value) } func (t *TradeLeg9) AddNonClearingMember() *PartyIdentificationAndAccount31 { t.NonClearingMember = new(PartyIdentificationAndAccount31) return t.NonClearingMember } func (t *TradeLeg9) SetTradeDate(value string) { t.TradeDate = (*ISODateTime)(&value) } func (t *TradeLeg9) SetTransactionDateAndTime(value string) { t.TransactionDateAndTime = (*ISODateTime)(&value) } func (t *TradeLeg9) AddSettlementDate() *DateFormat15Choice { t.SettlementDate = new(DateFormat15Choice) return t.SettlementDate } func (t *TradeLeg9) AddFinancialInstrumentIdentification() *SecurityIdentification14 { t.FinancialInstrumentIdentification = new(SecurityIdentification14) return t.FinancialInstrumentIdentification } func (t *TradeLeg9) SetTradingCurrency(value string) { t.TradingCurrency = (*CurrencyCode)(&value) } func (t *TradeLeg9) SetBuySellIndicator(value string) { t.BuySellIndicator = (*Side1Code)(&value) } func (t *TradeLeg9) AddTradeQuantity() *FinancialInstrumentQuantity1Choice { t.TradeQuantity = new(FinancialInstrumentQuantity1Choice) return t.TradeQuantity } func (t *TradeLeg9) AddDealPrice() *Price4 { t.DealPrice = new(Price4) return t.DealPrice } func (t *TradeLeg9) AddAccruedInterestAmount() *AmountAndDirection21 { t.AccruedInterestAmount = new(AmountAndDirection21) return t.AccruedInterestAmount } func (t *TradeLeg9) AddPlaceOfTrade() *MarketIdentification84 { t.PlaceOfTrade = new(MarketIdentification84) return t.PlaceOfTrade } func (t *TradeLeg9) AddPlaceOfListing() *MarketIdentification85 { t.PlaceOfListing = new(MarketIdentification85) return t.PlaceOfListing } func (t *TradeLeg9) SetTradeType(value string) { t.TradeType = (*TradeType1Code)(&value) } func (t *TradeLeg9) SetDerivativeRelatedTrade(value string) { t.DerivativeRelatedTrade = (*YesNoIndicator)(&value) } func (t *TradeLeg9) AddBroker() *PartyIdentificationAndAccount100 { t.Broker = new(PartyIdentificationAndAccount100) return t.Broker } func (t *TradeLeg9) AddTradingParty() *PartyIdentification35Choice { t.TradingParty = new(PartyIdentification35Choice) return t.TradingParty } func (t *TradeLeg9) SetTradeRegistrationOrigin(value string) { t.TradeRegistrationOrigin = (*Max35Text)(&value) } func (t *TradeLeg9) AddTradingPartyAccount() *SecuritiesAccount19 { t.TradingPartyAccount = new(SecuritiesAccount19) return t.TradingPartyAccount } func (t *TradeLeg9) SetTradingCapacity(value string) { t.TradingCapacity = (*TradingCapacity5Code)(&value) } func (t *TradeLeg9) SetTradePostingCode(value string) { t.TradePostingCode = (*TradePosting1Code)(&value) } func (t *TradeLeg9) AddSafekeepingPlace() *SafekeepingPlaceFormat7Choice { t.SafekeepingPlace = new(SafekeepingPlaceFormat7Choice) return t.SafekeepingPlace } func (t *TradeLeg9) AddSafekeepingAccount() *SecuritiesAccount19 { t.SafekeepingAccount = new(SecuritiesAccount19) return t.SafekeepingAccount } func (t *TradeLeg9) AddSettlementDetails() *Settlement1 { t.SettlementDetails = new(Settlement1) return t.SettlementDetails } func (t *TradeLeg9) AddClearingDetails() *Clearing4 { t.ClearingDetails = new(Clearing4) return t.ClearingDetails } func (t *TradeLeg9) AddGrossAmount() *AmountAndDirection21 { t.GrossAmount = new(AmountAndDirection21) return t.GrossAmount }
21,527
https://github.com/arankin-irl/LWSL/blob/master/src/test/java/xyz/baddeveloper/lwsl/client/SocketClientTest.java
Github Open Source
Open Source
Apache-2.0
null
LWSL
arankin-irl
Java
Code
271
1,149
package xyz.baddeveloper.lwsl.client; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import xyz.baddeveloper.lwsl.client.exceptions.ConnectException; import xyz.baddeveloper.lwsl.packet.Packet; import xyz.baddeveloper.lwsl.server.SocketServer; import xyz.baddeveloper.lwsl.ssl.SSLContextConfig; import xyz.baddeveloper.lwsl.ssl.SSLContextUtility; import javax.net.ssl.SSLContext; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class SocketClientTest { private SSLContext sslContext; @Before public void setUp() { final SSLContextConfig config = SSLContextConfig.builder() .keystoreLocation("keystore.jks") .keystorePassword("changeit") .truststoreLocation("truststore.jks") .truststorePassword("changeit") .build(); sslContext = SSLContextUtility.getInstance().getSslContext(config); } @Test public void testSocketClient() throws Exception { final List<Packet> receivedPackets = new ArrayList<>(); final SocketServer socketServer = new SocketServer(25566) .setMaxConnections(0) .addPacketReceivedEvent((socket, packet) -> receivedPackets.add(packet)); socketServer.start(); assertTrue(socketServer.getClients().isEmpty()); assertTrue(receivedPackets.isEmpty()); final SocketClient socketClient = new SocketClient("localhost", 25566); socketClient.connect(); assertTrue(socketClient.isConnected()); awaitOrFail(socketServer.getClients(), 1, 1000); assertTrue(receivedPackets.isEmpty()); JSONObject jsonObject = new JSONObject(); jsonObject.put("Key", "Value"); socketClient.sendPacket(new Packet(jsonObject)); awaitOrFail(receivedPackets, 1, 1000); assertEquals("Value", receivedPackets.get(0).getObject().get("Key")); socketClient.sendPacket(new Packet()); awaitOrFail(receivedPackets, 2, 1000); socketClient.shutdown(); socketServer.stop(); } @Test public void testSecureSocketClient() throws Exception { final List<Packet> receivedPackets = new ArrayList<>(); final SocketServer socketServer = new SocketServer(25568, sslContext) .setMaxConnections(0) .addPacketReceivedEvent((socket, packet) -> receivedPackets.add(packet)); socketServer.start(); assertTrue(socketServer.getClients().isEmpty()); assertTrue(receivedPackets.isEmpty()); final SocketClient socketClient = new SocketClient("localhost", 25568, sslContext) .addPacketReceivedEvent(((socket, packet) -> receivedPackets.add(packet))); socketClient.connect(); assertTrue(socketClient.isConnected()); awaitOrFail(socketServer.getClients(), 1, 1000); assertTrue(receivedPackets.isEmpty()); JSONObject jsonObject = new JSONObject(); jsonObject.put("Key", "Value"); socketClient.sendPacket(new Packet(jsonObject)); awaitOrFail(receivedPackets, 1, 5000); assertEquals("Value", receivedPackets.get(0).getObject().get("Key")); socketServer.getClients().get(0).sendPacket(new Packet()); awaitOrFail(receivedPackets, 2, 5000); socketClient.shutdown(); socketServer.stop(); } private void awaitOrFail(List list, int expectedSize, int timeout) throws InterruptedException { // Packets can take a few ms to arrive, and so be counted. We wait until we reach the expected size, or hit the timeout final long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() < startTime + timeout) && (list.size() != expectedSize)) { Thread.sleep(20); } assertEquals(expectedSize, list.size()); } @Test(expected = ConnectException.class) public void testFailedConnection() throws Exception { final SocketClient socketClient = new SocketClient("localhost", 25567) .addConnectEvent(socket -> fail("Should not have connected")); socketClient.connect(); } }
3,268
https://github.com/theoners/C-OOP-February-2019/blob/master/Reflection and Attributes - Lab/01.Stealer/Spy.cs
Github Open Source
Open Source
MIT
2,019
C-OOP-February-2019
theoners
C#
Code
69
236
 using System; using System.Linq; using System.Reflection; using System.Text; public class Spy { public string StealFieldInfo(string className, params string[] requestedFields) { var classType = Type.GetType(className); var fields = classType.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) .Where(f => requestedFields.Contains(f.Name)); var stringBuilder = new StringBuilder(); var classInstance = Activator.CreateInstance(classType, new object[] { }); stringBuilder.AppendLine($"Class under investigation: {classType}"); foreach (var field in fields) { stringBuilder.AppendLine($"{field.Name} = {field.GetValue(classInstance)}"); } return stringBuilder.ToString().Trim(); } }
30,805
https://github.com/reysatu/sisGest/blob/master/app/Http/Controllers/AuthController.php
Github Open Source
Open Source
MIT
null
sisGest
reysatu
PHP
Code
113
427
<?php namespace App\Http\Controllers; use App\Models\Usuario; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Auth; use Symfony\Component\HttpFoundation\Response; use Illuminate\Support\Facades\Cookie; class AuthController extends Controller { public function register(Request $request) { $user = User::create([ 'nombre' => $request->input('nombre'), 'user' => $request->input('user'), 'password' => Hash::make($request->input('password')), ]); return $user; } public function login(Request $request) { $credentials = [ 'user' => $request['user'], 'password' => $request['password'], ]; if (!Auth::attempt($credentials)) { return response([ 'message' => 'invalid credendials' ], Response::HTTP_UNAUTHORIZED); } $user = User::where("user", $request['user'])->first(); $token = $user->createToken('token')->plainTextToken; $cookie = cookie('jwt', $token, 60 * 24); return response([ 'messaje' => $token ])->withCookie($cookie); } public function user() { return Auth::user(); } public function logout() { $cookie = Cookie::forget('jwt'); return response([ 'message' => 'Success' ])->withCookie($cookie); } }
9,319
https://github.com/rxrdsoft/gestionar-datos/blob/master/resources/views/auth/login.blade.php
Github Open Source
Open Source
MIT
null
gestionar-datos
rxrdsoft
PHP
Code
208
885
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card-group"> <div class="card p-4"> <div class="card-body"> <form action="{{ route('login') }}" method="POST"> @csrf <h1>Iniciar sesión</h1> <p class="text-muted">Iniciar sesión en su cuenta</p> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="icon-user"></i> </span> </div> <input type="email" name="email" value="{{ old('email') }}" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" placeholder="Email" required autofocus> @if ($errors->has('email')) <span class="invalid-feedback"> <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> <div class="input-group mb-4"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="icon-lock"></i> </span> </div> <input type="password" name="password" required class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" placeholder="Contrseña"> @if ($errors->has('password')) <span class="invalid-feedback"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> <div class="row"> <div class="col-6"> <div class="checkbox"> <label class="text-muted"> <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('Recordarme') }} </label> </div> </div> </div> <div class="row"> <div class="col-6"> <button type="submit" class="btn btn-primary px-4">Entrar</button> </div> <div class="col-6 text-right"> {{--<button type="button" class="btn btn-link px-0">Forgot password?</button>--}} </div> </div> </form> </div> </div> <div class="card text-white bg-primary py-5 d-md-down-none" style="width:44%"> <div class="card-body text-center"> <div> <img class="img-thumbnail" style="background-color: transparent; border: none;" src="{{ asset('images/CYMEDIA-LOGO-BL.png') }}" alt=""> {{--<h2>Sign up</h2>--}} {{--<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>--}} {{--<button type="button" class="btn btn-primary active mt-3">Register Now!</button>--}} </div> </div> </div> </div> </div> </div> </div> @endsection
32,012
https://github.com/adrian-tarau/testware/blob/master/spi/src/test/java/net/microfalx/testware/spi/HookTest.java
Github Open Source
Open Source
Apache-2.0
null
testware
adrian-tarau
Java
Code
56
323
package net.microfalx.testware.spi; import net.microfalx.testware.spi.metadata.ClassDescriptor; import net.microfalx.testware.spi.metadata.MethodDescriptor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class HookTest { @org.junit.jupiter.api.Test void createDefault() throws Exception { Hook hook = Hook.create(create("createDefault").build()).build(); assertNotNull(hook); assertNotNull(hook.getClassDescriptor().get()); assertNotNull(hook.getMethodDescriptor().get()); assertEquals(Hook.Type.BEFORE_EACH, hook.getType()); } @org.junit.jupiter.api.Test void createIntegration() throws Exception { Hook hook = Hook.create(create("createDefault").build()).type(Hook.Type.BEFORE_ALL).build(); assertEquals(Hook.Type.BEFORE_ALL, hook.getType()); } private MethodDescriptor.Builder create(String methodName) throws Exception { return MethodDescriptor.create(ClassDescriptor.create(HookTest.class).build(), TestTest.class.getDeclaredMethod(methodName)); } }
34,773
https://github.com/cbsa-informatik-uni-siegen/gtitool/blob/master/tinylaf/source/de/muntjak/tinylookandfeel/Theme.java
Github Open Source
Open Source
MIT
null
gtitool
cbsa-informatik-uni-siegen
Java
Code
20,000
33,554
/******************************************************************************* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Tiny Look and Feel * * (C) Copyright 2003 - 2007 Hans Bickel * * For * licensing information and credits, please refer to the * comment in file * de.muntjak.tinylookandfeel.TinyLookAndFeel * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package de.muntjak.tinylookandfeel; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import de.muntjak.tinylookandfeel.controlpanel.ColorReference; import de.muntjak.tinylookandfeel.controlpanel.ColoredFont; import de.muntjak.tinylookandfeel.controlpanel.HSBReference; /** * Theme * * @version 1.3 * @author Hans Bickel */ @SuppressWarnings ( { "all" } ) public class Theme { public static final String DEFAULT_THEME = "Default.theme"; public static final String FILE_EXTENSION = ".theme"; public static final int TINY_STYLE = 0; public static final int W99_STYLE = 1; public static final int YQ_STYLE = 2; public static final int CUSTOM_STYLE = 3; public static int style = YQ_STYLE; private static final int FILE_ID_1 = 0x1234; private static final int FILE_ID_2 = 0x2234; public static final int FILE_ID_3A = 0x3234; public static final int FILE_ID_3B = 0x3235; public static final int FILE_ID_3C = 0x3236; public static final int FILE_ID_3D = 0x3237; public static final int FILE_ID_3E = 0x3238; public static final int FILE_ID_3F = 0x3239; public static int fileID; public static int [] derivedStyle = new int [ 4 ]; // Colors public static ColorReference mainColor[] = new ColorReference [ 4 ]; public static ColorReference disColor[] = new ColorReference [ 4 ]; public static ColorReference backColor[] = new ColorReference [ 4 ]; public static ColorReference frameColor[] = new ColorReference [ 4 ]; public static ColorReference sub1Color[] = new ColorReference [ 4 ]; public static ColorReference sub2Color[] = new ColorReference [ 4 ]; public static ColorReference sub3Color[] = new ColorReference [ 4 ]; public static ColorReference sub4Color[] = new ColorReference [ 4 ]; public static ColorReference sub5Color[] = new ColorReference [ 4 ]; public static ColorReference sub6Color[] = new ColorReference [ 4 ]; public static ColorReference sub7Color[] = new ColorReference [ 4 ]; public static ColorReference sub8Color[] = new ColorReference [ 4 ]; // Fonts public static ColoredFont [] plainFont = new ColoredFont [ 4 ]; public static ColoredFont [] boldFont = new ColoredFont [ 4 ]; public static ColoredFont [] buttonFont = new ColoredFont [ 4 ]; public static ColorReference [] buttonFontColor = new ColorReference [ 4 ]; public static ColoredFont [] labelFont = new ColoredFont [ 4 ]; public static ColorReference [] labelFontColor = new ColorReference [ 4 ]; public static ColoredFont [] comboFont = new ColoredFont [ 4 ]; public static ColoredFont [] popupFont = new ColoredFont [ 4 ]; public static ColoredFont [] listFont = new ColoredFont [ 4 ]; public static ColoredFont [] menuFont = new ColoredFont [ 4 ]; public static ColorReference [] menuFontColor = new ColorReference [ 4 ]; public static ColoredFont [] menuItemFont = new ColoredFont [ 4 ]; public static ColorReference [] menuItemFontColor = new ColorReference [ 4 ]; public static ColoredFont [] passwordFont = new ColoredFont [ 4 ]; public static ColoredFont [] radioFont = new ColoredFont [ 4 ]; public static ColorReference [] radioFontColor = new ColorReference [ 4 ]; public static ColoredFont [] checkFont = new ColoredFont [ 4 ]; public static ColorReference [] checkFontColor = new ColorReference [ 4 ]; public static ColoredFont [] tableFont = new ColoredFont [ 4 ]; public static ColorReference [] tableFontColor = new ColorReference [ 4 ]; public static ColoredFont [] tableHeaderFont = new ColoredFont [ 4 ]; public static ColorReference [] tableHeaderFontColor = new ColorReference [ 4 ]; public static ColoredFont [] textAreaFont = new ColoredFont [ 4 ]; public static ColoredFont [] textFieldFont = new ColoredFont [ 4 ]; public static ColoredFont [] textPaneFont = new ColoredFont [ 4 ]; public static ColoredFont [] titledBorderFont = new ColoredFont [ 4 ]; public static ColorReference [] titledBorderFontColor = new ColorReference [ 4 ]; public static ColoredFont [] toolTipFont = new ColoredFont [ 4 ]; public static ColorReference [] toolTipFontColor = new ColorReference [ 4 ]; public static ColoredFont [] treeFont = new ColoredFont [ 4 ]; public static ColoredFont [] tabFont = new ColoredFont [ 4 ]; public static ColorReference [] tabFontColor = new ColorReference [ 4 ]; public static ColoredFont [] editorFont = new ColoredFont [ 4 ]; public static ColoredFont [] frameTitleFont = new ColoredFont [ 4 ]; public static ColoredFont [] internalFrameTitleFont = new ColoredFont [ 4 ]; public static ColoredFont [] internalPaletteTitleFont = new ColoredFont [ 4 ]; public static ColoredFont [] progressBarFont = new ColoredFont [ 4 ]; // Progressbar public static ColorReference [] progressColor = new ColorReference [ 4 ]; public static ColorReference [] progressTrackColor = new ColorReference [ 4 ]; public static ColorReference [] progressBorderColor = new ColorReference [ 4 ]; public static ColorReference [] progressDarkColor = new ColorReference [ 4 ]; public static ColorReference [] progressLightColor = new ColorReference [ 4 ]; public static ColorReference [] progressSelectForeColor = new ColorReference [ 4 ]; public static ColorReference [] progressSelectBackColor = new ColorReference [ 4 ]; // Text public static ColorReference [] textBgColor = new ColorReference [ 4 ]; public static ColorReference [] textSelectedBgColor = new ColorReference [ 4 ]; public static ColorReference [] textDisabledBgColor = new ColorReference [ 4 ]; public static ColorReference [] textTextColor = new ColorReference [ 4 ]; public static ColorReference [] textSelectedTextColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderDarkColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderLightColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] textBorderLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] textCaretColor = new ColorReference [ 4 ]; public static ColorReference [] textPaneBgColor = new ColorReference [ 4 ]; public static ColorReference [] editorPaneBgColor = new ColorReference [ 4 ]; public static ColorReference [] desktopPaneBgColor = new ColorReference [ 4 ]; public static Insets [] textInsets = new Insets [ 4 ]; // Combo public static ColorReference [] comboBorderColor = new ColorReference [ 4 ]; public static ColorReference [] comboDarkColor = new ColorReference [ 4 ]; public static ColorReference [] comboLightColor = new ColorReference [ 4 ]; public static ColorReference [] comboBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboSelectedBgColor = new ColorReference [ 4 ]; public static ColorReference [] comboSelectedTextColor = new ColorReference [ 4 ]; public static ColorReference [] comboFocusBgColor = new ColorReference [ 4 ]; public static ColorReference [] comboArrowColor = new ColorReference [ 4 ]; public static ColorReference [] comboArrowDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtPressedColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtBorderColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtDarkColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtLightColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboButtLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] comboBgColor = new ColorReference [ 4 ]; public static ColorReference [] comboTextColor = new ColorReference [ 4 ]; public static int [] comboButtonWidth = new int [ 4 ]; public static int [] comboSpreadLight = new int [ 4 ]; public static int [] comboSpreadLightDisabled = new int [ 4 ]; public static int [] comboSpreadDark = new int [ 4 ]; public static int [] comboSpreadDarkDisabled = new int [ 4 ]; public static Insets [] comboInsets = new Insets [ 4 ]; public static boolean [] comboRollover = new boolean [ 4 ]; public static boolean [] comboFocus = new boolean [ 4 ]; // List public static ColorReference [] listBgColor = new ColorReference [ 4 ]; public static ColorReference [] listTextColor = new ColorReference [ 4 ]; public static ColorReference [] listSelectedBgColor = new ColorReference [ 4 ]; public static ColorReference [] listSelectedTextColor = new ColorReference [ 4 ]; // Menu public static ColorReference [] menuBarColor = new ColorReference [ 4 ]; public static ColorReference [] menuRolloverBgColor = new ColorReference [ 4 ]; public static ColorReference [] menuRolloverFgColor = new ColorReference [ 4 ]; public static ColorReference [] menuDisabledFgColor = new ColorReference [ 4 ]; public static ColorReference [] menuItemRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] menuSelectedTextColor = new ColorReference [ 4 ]; public static ColorReference [] menuBorderColor = new ColorReference [ 4 ]; public static ColorReference [] menuDarkColor = new ColorReference [ 4 ]; public static ColorReference [] menuLightColor = new ColorReference [ 4 ]; public static ColorReference [] menuPopupColor = new ColorReference [ 4 ]; public static ColorReference [] menuInnerHilightColor = new ColorReference [ 4 ]; public static ColorReference [] menuInnerShadowColor = new ColorReference [ 4 ]; public static ColorReference [] menuOuterHilightColor = new ColorReference [ 4 ]; public static ColorReference [] menuOuterShadowColor = new ColorReference [ 4 ]; public static ColorReference [] menuIconColor = new ColorReference [ 4 ]; public static ColorReference [] menuIconRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] menuIconDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] menuIconShadowColor = new ColorReference [ 4 ]; public static ColorReference [] menuSepDarkColor = new ColorReference [ 4 ]; public static ColorReference [] menuSepLightColor = new ColorReference [ 4 ]; public static int [] menuSeparatorHeight = new int [ 4 ]; public static Insets [] menuBorderInsets = new Insets [ 4 ]; public static boolean [] menuRollover = new boolean [ 4 ]; // Toolbar public static ColorReference [] toolBarColor = new ColorReference [ 4 ]; public static ColorReference [] toolBarDarkColor = new ColorReference [ 4 ]; public static ColorReference [] toolBarLightColor = new ColorReference [ 4 ]; public static ColorReference [] toolButtColor = new ColorReference [ 4 ]; public static ColorReference [] toolButtSelectedColor = new ColorReference [ 4 ]; public static ColorReference [] toolButtRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] toolButtPressedColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderSelectedColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderPressedColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderDarkColor = new ColorReference [ 4 ]; public static ColorReference [] toolBorderLightColor = new ColorReference [ 4 ]; public static ColorReference [] toolGripDarkColor = new ColorReference [ 4 ]; public static ColorReference [] toolGripLightColor = new ColorReference [ 4 ]; public static ColorReference [] toolSepDarkColor = new ColorReference [ 4 ]; public static ColorReference [] toolSepLightColor = new ColorReference [ 4 ]; // new in 1.3 public static int [] toolMarginTop = new int [ 4 ]; public static int [] toolMarginLeft = new int [ 4 ]; public static int [] toolMarginBottom = new int [ 4 ]; public static int [] toolMarginRight = new int [ 4 ]; public static boolean [] toolFocus = new boolean [ 4 ]; public static boolean [] toolRollover = new boolean [ 4 ]; // Button public static ColorReference [] buttonNormalColor = new ColorReference [ 4 ]; public static ColorReference [] buttonRolloverBgColor = new ColorReference [ 4 ]; public static ColorReference [] buttonPressedColor = new ColorReference [ 4 ]; public static ColorReference [] buttonDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] buttonRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] buttonDefaultColor = new ColorReference [ 4 ]; public static ColorReference [] buttonCheckColor = new ColorReference [ 4 ]; public static ColorReference [] buttonCheckDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] buttonBorderColor = new ColorReference [ 4 ]; public static ColorReference [] buttonDarkColor = new ColorReference [ 4 ]; public static ColorReference [] buttonLightColor = new ColorReference [ 4 ]; public static ColorReference [] buttonBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] buttonDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] buttonLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] buttonDisabledFgColor = new ColorReference [ 4 ]; public static ColorReference [] checkDisabledFgColor = new ColorReference [ 4 ]; public static ColorReference [] radioDisabledFgColor = new ColorReference [ 4 ]; public static boolean [] buttonRollover = new boolean [ 4 ]; public static boolean [] buttonFocus = new boolean [ 4 ]; public static boolean [] buttonFocusBorder = new boolean [ 4 ]; public static boolean [] buttonEnter = new boolean [ 4 ]; // new in 1.3.04 public static boolean [] shiftButtonText = new boolean [ 4 ]; public static int [] buttonMarginTop = new int [ 4 ]; public static int [] buttonMarginLeft = new int [ 4 ]; public static int [] buttonMarginBottom = new int [ 4 ]; public static int [] buttonMarginRight = new int [ 4 ]; public static int [] buttonSpreadLight = new int [ 4 ]; public static int [] buttonSpreadLightDisabled = new int [ 4 ]; public static int [] buttonSpreadDark = new int [ 4 ]; public static int [] buttonSpreadDarkDisabled = new int [ 4 ]; // CheckBox public static Dimension [] checkSize = new Dimension [ 4 ]; // new in 1.3 public static int [] checkMarginTop = new int [ 4 ]; public static int [] checkMarginLeft = new int [ 4 ]; public static int [] checkMarginBottom = new int [ 4 ]; public static int [] checkMarginRight = new int [ 4 ]; // Tabbed public static ColorReference [] tabPaneBorderColor = new ColorReference [ 4 ]; public static ColorReference [] tabPaneDarkColor = new ColorReference [ 4 ]; public static ColorReference [] tabPaneLightColor = new ColorReference [ 4 ]; public static ColorReference [] tabNormalColor = new ColorReference [ 4 ]; public static ColorReference [] tabSelectedColor = new ColorReference [ 4 ]; public static ColorReference [] tabDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] tabDisabledSelectedColor = new ColorReference [ 4 ]; public static ColorReference [] tabDisabledTextColor = new ColorReference [ 4 ]; public static ColorReference [] tabBorderColor = new ColorReference [ 4 ]; public static ColorReference [] tabDarkColor = new ColorReference [ 4 ]; public static ColorReference [] tabLightColor = new ColorReference [ 4 ]; public static ColorReference [] tabRolloverColor = new ColorReference [ 4 ]; public static int [] firstTabDistance = new int [ 4 ]; public static boolean [] tabRollover = new boolean [ 4 ]; // new in 1.3.05 public static boolean [] tabFocus = new boolean [ 4 ]; public static boolean [] ignoreSelectedBg = new boolean [ 4 ]; public static boolean [] fixedTabs = new boolean [ 4 ]; public static Insets [] tabInsets = new Insets [ 4 ]; public static Insets [] tabAreaInsets = new Insets [ 4 ]; // Slider public static Dimension [] sliderVertSize = new Dimension [ 4 ]; public static Dimension [] sliderHorzSize = new Dimension [ 4 ]; public static boolean [] sliderRolloverEnabled = new boolean [ 4 ]; // new in 1.3.05 public static boolean [] sliderFocusEnabled = new boolean [ 4 ]; public static ColorReference [] sliderThumbColor = new ColorReference [ 4 ]; public static ColorReference [] sliderThumbRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] sliderThumbPressedColor = new ColorReference [ 4 ]; public static ColorReference [] sliderThumbDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] sliderBorderColor = new ColorReference [ 4 ]; public static ColorReference [] sliderDarkColor = new ColorReference [ 4 ]; public static ColorReference [] sliderLightColor = new ColorReference [ 4 ]; public static ColorReference [] sliderBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] sliderDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] sliderLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTrackColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTrackBorderColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTrackDarkColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTrackLightColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTickColor = new ColorReference [ 4 ]; public static ColorReference [] sliderTickDisabledColor = new ColorReference [ 4 ]; // new in 1.3.05 public static ColorReference [] sliderFocusColor = new ColorReference [ 4 ]; // Spinner public static boolean [] spinnerRollover = new boolean [ 4 ]; public static ColorReference [] spinnerButtColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerButtRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerButtPressedColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerButtDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerBorderColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerDarkColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerLightColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerArrowColor = new ColorReference [ 4 ]; public static ColorReference [] spinnerArrowDisabledColor = new ColorReference [ 4 ]; public static int [] spinnerSpreadLight = new int [ 4 ]; public static int [] spinnerSpreadLightDisabled = new int [ 4 ]; public static int [] spinnerSpreadDark = new int [ 4 ]; public static int [] spinnerSpreadDarkDisabled = new int [ 4 ]; // Scrollbar public static ColorReference [] scrollTrackColor = new ColorReference [ 4 ]; public static ColorReference [] scrollTrackDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollTrackBorderColor = new ColorReference [ 4 ]; public static ColorReference [] scrollTrackBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollThumbColor = new ColorReference [ 4 ]; public static ColorReference [] scrollThumbRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] scrollThumbPressedColor = new ColorReference [ 4 ]; public static ColorReference [] scrollThumbDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollButtColor = new ColorReference [ 4 ]; public static ColorReference [] scrollButtRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] scrollButtPressedColor = new ColorReference [ 4 ]; public static ColorReference [] scrollButtDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollArrowColor = new ColorReference [ 4 ]; public static ColorReference [] scrollArrowDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollGripLightColor = new ColorReference [ 4 ]; public static ColorReference [] scrollGripDarkColor = new ColorReference [ 4 ]; public static ColorReference [] scrollBorderColor = new ColorReference [ 4 ]; public static ColorReference [] scrollDarkColor = new ColorReference [ 4 ]; public static ColorReference [] scrollLightColor = new ColorReference [ 4 ]; public static ColorReference [] scrollBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] scrollPaneBorderColor = new ColorReference [ 4 ]; public static int [] scrollSpreadLight = new int [ 4 ]; public static int [] scrollSpreadLightDisabled = new int [ 4 ]; public static int [] scrollSpreadDark = new int [ 4 ]; public static int [] scrollSpreadDarkDisabled = new int [ 4 ]; public static boolean [] scrollRollover = new boolean [ 4 ]; // Tree public static ColorReference [] treeBgColor = new ColorReference [ 4 ]; public static ColorReference [] treeTextColor = new ColorReference [ 4 ]; public static ColorReference [] treeTextBgColor = new ColorReference [ 4 ]; public static ColorReference [] treeSelectedTextColor = new ColorReference [ 4 ]; public static ColorReference [] treeSelectedBgColor = new ColorReference [ 4 ]; public static ColorReference [] treeLineColor = new ColorReference [ 4 ]; // Frame public static ColorReference [] frameCaptionColor = new ColorReference [ 4 ]; public static ColorReference [] frameCaptionDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameBorderColor = new ColorReference [ 4 ]; public static ColorReference [] frameDarkColor = new ColorReference [ 4 ]; public static ColorReference [] frameLightColor = new ColorReference [ 4 ]; public static ColorReference [] frameBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameLightDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameTitleColor = new ColorReference [ 4 ]; public static ColorReference [] frameTitleDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtPressedColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtClosePressedColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtBorderColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtDarkColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtLightColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtLightDisabledColor = new ColorReference [ 4 ]; public static int [] frameButtSpreadLight = new int [ 4 ]; public static int [] frameButtSpreadDark = new int [ 4 ]; public static int [] frameButtSpreadLightDisabled = new int [ 4 ]; public static int [] frameButtSpreadDarkDisabled = new int [ 4 ]; public static ColorReference [] frameButtCloseBorderColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseDarkColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseLightColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseBorderDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseDarkDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameButtCloseLightDisabledColor = new ColorReference [ 4 ]; public static int [] frameButtCloseSpreadLight = new int [ 4 ]; public static int [] frameButtCloseSpreadLightDisabled = new int [ 4 ]; public static int [] frameButtCloseSpreadDark = new int [ 4 ]; public static int [] frameButtCloseSpreadDarkDisabled = new int [ 4 ]; public static ColorReference [] frameSymbolColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolPressedColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolDarkColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolLightColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolCloseColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolClosePressedColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolCloseDisabledColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolCloseDarkColor = new ColorReference [ 4 ]; public static ColorReference [] frameSymbolCloseLightColor = new ColorReference [ 4 ]; public static Dimension [] frameExternalButtonSize = new Dimension [ 4 ]; public static Dimension [] frameInternalButtonSize = new Dimension [ 4 ]; public static Dimension [] framePaletteButtonSize = new Dimension [ 4 ]; public static int [] frameSpreadDark = new int [ 4 ]; public static int [] frameSpreadLight = new int [ 4 ]; public static int [] frameSpreadDarkDisabled = new int [ 4 ]; public static int [] frameSpreadLightDisabled = new int [ 4 ]; public static int [] frameBorderWidth = new int [ 4 ]; public static int [] frameTitleHeight = new int [ 4 ]; public static int [] frameInternalTitleHeight = new int [ 4 ]; public static int [] framePaletteTitleHeight = new int [ 4 ]; public static boolean [] frameIsTransparent = new boolean [ 4 ]; // Table public static ColorReference [] tableBackColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderBackColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderRolloverBackColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderRolloverColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderArrowColor = new ColorReference [ 4 ]; public static ColorReference [] tableGridColor = new ColorReference [ 4 ]; public static ColorReference [] tableSelectedBackColor = new ColorReference [ 4 ]; public static ColorReference [] tableSelectedForeColor = new ColorReference [ 4 ]; public static ColorReference [] tableBorderDarkColor = new ColorReference [ 4 ]; public static ColorReference [] tableBorderLightColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderDarkColor = new ColorReference [ 4 ]; public static ColorReference [] tableHeaderLightColor = new ColorReference [ 4 ]; // Icons public static ColorReference [] frameIconColor = new ColorReference [ 4 ]; public static ColorReference [] treeIconColor = new ColorReference [ 4 ]; public static ColorReference [] fileViewIconColor = new ColorReference [ 4 ]; public static ColorReference [] fileChooserIconColor = new ColorReference [ 4 ]; public static ColorReference [] optionPaneIconColor = new ColorReference [ 4 ]; public static int [] hue = new int [ 4 ]; public static HSBReference [][] colorizer = new HSBReference [ 20 ] [ 4 ]; public static boolean [][] colorize = new boolean [ 4 ] [ 20 ]; public static boolean [] colorizeFrameIcon = new boolean [ 4 ]; public static boolean [] colorizeTreeIcon = new boolean [ 4 ]; public static boolean [] colorizeFileViewIcon = new boolean [ 4 ]; public static boolean [] colorizeFileChooserIcon = new boolean [ 4 ]; public static boolean [] colorizeOptionPaneIcon = new boolean [ 4 ]; // Separator public static ColorReference [] sepDarkColor = new ColorReference [ 4 ]; public static ColorReference [] sepLightColor = new ColorReference [ 4 ]; // ToolTip public static ColorReference [] tipBorderColor = new ColorReference [ 4 ]; public static ColorReference [] tipBorderDis = new ColorReference [ 4 ]; public static ColorReference [] tipBgColor = new ColorReference [ 4 ]; public static ColorReference [] tipBgDis = new ColorReference [ 4 ]; public static ColorReference [] tipTextColor = new ColorReference [ 4 ]; public static ColorReference [] tipTextDis = new ColorReference [ 4 ]; // Misc public static ColorReference [] titledBorderColor = new ColorReference [ 4 ]; static { initData (); } public static void initData () { derivedStyle [ 0 ] = TINY_STYLE; derivedStyle [ 1 ] = W99_STYLE; derivedStyle [ 2 ] = YQ_STYLE; // Colors mainColor [ 0 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); mainColor [ 1 ] = new ColorReference ( new Color ( 0, 106, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); mainColor [ 2 ] = new ColorReference ( new Color ( 0, 106, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); mainColor [ 3 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); disColor [ 0 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.ABS_COLOR, true ); disColor [ 1 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.ABS_COLOR, true ); disColor [ 2 ] = new ColorReference ( new Color ( 143, 142, 139 ), 0, 0, ColorReference.ABS_COLOR, true ); disColor [ 3 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.ABS_COLOR, true ); backColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.ABS_COLOR, true ); backColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.ABS_COLOR, true ); backColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.ABS_COLOR, true ); backColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.ABS_COLOR, true ); frameColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); frameColor [ 1 ] = new ColorReference ( new Color ( 10, 36, 106 ), 0, 0, ColorReference.ABS_COLOR, true ); frameColor [ 2 ] = new ColorReference ( new Color ( 0, 85, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); frameColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR, true ); sub1Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub1Color [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), -18, -55, ColorReference.MAIN_COLOR ); sub1Color [ 2 ] = new ColorReference ( new Color ( 197, 213, 252 ), 0, 0, ColorReference.ABS_COLOR ); sub1Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub2Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub2Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub2Color [ 2 ] = new ColorReference ( new Color ( 34, 161, 34 ), 0, 0, ColorReference.ABS_COLOR ); sub2Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub3Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub3Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub3Color [ 2 ] = new ColorReference ( new Color ( 231, 232, 245 ), 0, 0, ColorReference.ABS_COLOR ); sub3Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub4Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub4Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub4Color [ 2 ] = new ColorReference ( new Color ( 227, 92, 60 ), 0, 0, ColorReference.ABS_COLOR ); sub4Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub5Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub5Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub5Color [ 2 ] = new ColorReference ( new Color ( 120, 123, 189 ), 0, 0, ColorReference.ABS_COLOR ); sub5Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub6Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub6Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub6Color [ 2 ] = new ColorReference ( new Color ( 248, 179, 48 ), 0, 0, ColorReference.ABS_COLOR ); sub6Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub7Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub7Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub7Color [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub7Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub8Color [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub8Color [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub8Color [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); sub8Color [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.ABS_COLOR ); // Font plainFont [ 0 ] = new ColoredFont ( "sansserif", Font.PLAIN, 12 ); plainFont [ 1 ] = new ColoredFont ( "sansserif", Font.PLAIN, 12 ); plainFont [ 2 ] = new ColoredFont ( "Tahoma", Font.PLAIN, 11 ); plainFont [ 3 ] = new ColoredFont ( "sansserif", Font.PLAIN, 12 ); boldFont [ 0 ] = new ColoredFont ( "sansserif", Font.BOLD, 11 ); boldFont [ 1 ] = new ColoredFont ( "sansserif", Font.BOLD, 11 ); boldFont [ 2 ] = new ColoredFont ( "Tahoma", Font.BOLD, 11 ); boldFont [ 3 ] = new ColoredFont ( "sansserif", Font.BOLD, 11 ); buttonFont [ 0 ] = new ColoredFont ( buttonFontColor ); buttonFont [ 1 ] = new ColoredFont ( buttonFontColor ); buttonFont [ 2 ] = new ColoredFont ( buttonFontColor ); buttonFont [ 3 ] = new ColoredFont ( buttonFontColor ); labelFont [ 0 ] = new ColoredFont ( labelFontColor ); labelFont [ 1 ] = new ColoredFont ( labelFontColor ); labelFont [ 2 ] = new ColoredFont ( labelFontColor ); labelFont [ 3 ] = new ColoredFont ( labelFontColor ); passwordFont [ 0 ] = new ColoredFont (); passwordFont [ 1 ] = new ColoredFont (); passwordFont [ 2 ] = new ColoredFont (); passwordFont [ 3 ] = new ColoredFont (); comboFont [ 0 ] = new ColoredFont (); comboFont [ 1 ] = new ColoredFont (); comboFont [ 2 ] = new ColoredFont (); comboFont [ 3 ] = new ColoredFont (); // with version 1.1, popupFont disappeared // but still must be initialized for 1.0 popupFont [ 0 ] = new ColoredFont (); popupFont [ 1 ] = new ColoredFont (); popupFont [ 2 ] = new ColoredFont (); popupFont [ 3 ] = new ColoredFont (); listFont [ 0 ] = new ColoredFont (); listFont [ 1 ] = new ColoredFont (); listFont [ 2 ] = new ColoredFont (); listFont [ 3 ] = new ColoredFont (); menuFont [ 0 ] = new ColoredFont ( menuFontColor ); menuFont [ 1 ] = new ColoredFont ( menuFontColor ); menuFont [ 2 ] = new ColoredFont ( menuFontColor ); menuFont [ 3 ] = new ColoredFont ( menuFontColor ); menuItemFont [ 0 ] = new ColoredFont ( menuItemFontColor ); menuItemFont [ 1 ] = new ColoredFont ( menuItemFontColor ); menuItemFont [ 2 ] = new ColoredFont ( menuItemFontColor ); menuItemFont [ 3 ] = new ColoredFont ( menuItemFontColor ); radioFont [ 0 ] = new ColoredFont ( radioFontColor ); radioFont [ 1 ] = new ColoredFont ( radioFontColor ); radioFont [ 2 ] = new ColoredFont ( radioFontColor ); radioFont [ 3 ] = new ColoredFont ( radioFontColor ); checkFont [ 0 ] = new ColoredFont ( checkFontColor ); checkFont [ 1 ] = new ColoredFont ( checkFontColor ); checkFont [ 2 ] = new ColoredFont ( checkFontColor ); checkFont [ 3 ] = new ColoredFont ( checkFontColor ); tableFont [ 0 ] = new ColoredFont ( tableFontColor ); tableFont [ 1 ] = new ColoredFont ( tableFontColor ); tableFont [ 2 ] = new ColoredFont ( tableFontColor ); tableFont [ 3 ] = new ColoredFont ( tableFontColor ); tableHeaderFont [ 0 ] = new ColoredFont ( tableHeaderFontColor ); tableHeaderFont [ 1 ] = new ColoredFont ( tableHeaderFontColor ); tableHeaderFont [ 2 ] = new ColoredFont ( tableHeaderFontColor ); tableHeaderFont [ 3 ] = new ColoredFont ( tableHeaderFontColor ); textAreaFont [ 0 ] = new ColoredFont (); textAreaFont [ 1 ] = new ColoredFont (); textAreaFont [ 2 ] = new ColoredFont (); textAreaFont [ 3 ] = new ColoredFont (); textFieldFont [ 0 ] = new ColoredFont (); textFieldFont [ 1 ] = new ColoredFont (); textFieldFont [ 2 ] = new ColoredFont (); textFieldFont [ 3 ] = new ColoredFont (); textPaneFont [ 0 ] = new ColoredFont (); textPaneFont [ 1 ] = new ColoredFont (); textPaneFont [ 2 ] = new ColoredFont (); textPaneFont [ 3 ] = new ColoredFont (); titledBorderFont [ 0 ] = new ColoredFont ( titledBorderFontColor ); titledBorderFont [ 1 ] = new ColoredFont ( titledBorderFontColor ); titledBorderFont [ 2 ] = new ColoredFont ( titledBorderFontColor ); titledBorderFont [ 3 ] = new ColoredFont ( titledBorderFontColor ); // sine 1.3C toolTipFont has no color property ... toolTipFont [ 0 ] = new ColoredFont (); toolTipFont [ 1 ] = new ColoredFont (); toolTipFont [ 2 ] = new ColoredFont (); toolTipFont [ 3 ] = new ColoredFont (); // ... but we must still initialize toolTipFontColor toolTipFontColor [ 0 ] = new ColorReference ( Color.BLACK, 0, -100, ColorReference.BACK_COLOR ); toolTipFontColor [ 1 ] = new ColorReference ( Color.BLACK, 0, -100, ColorReference.BACK_COLOR ); toolTipFontColor [ 2 ] = new ColorReference ( Color.BLACK, 0, -100, ColorReference.BACK_COLOR ); toolTipFontColor [ 3 ] = new ColorReference ( Color.BLACK, 0, -100, ColorReference.BACK_COLOR ); treeFont [ 0 ] = new ColoredFont (); treeFont [ 1 ] = new ColoredFont (); treeFont [ 2 ] = new ColoredFont (); treeFont [ 3 ] = new ColoredFont (); tabFontColor [ 0 ] = new ColorReference ( new Color ( 10, 50, 105 ) ); tabFontColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ) ); tabFontColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ) ); tabFontColor [ 3 ] = new ColorReference ( new Color ( 10, 50, 105 ) ); tabFont [ 0 ] = new ColoredFont ( "sansserif", Font.BOLD, 11, tabFontColor ); tabFont [ 1 ] = new ColoredFont ( tabFontColor ); tabFont [ 2 ] = new ColoredFont ( tabFontColor ); tabFont [ 3 ] = new ColoredFont ( "sansserif", Font.BOLD, 11, tabFontColor ); tabFont [ 0 ].setBoldFont ( true ); tabFont [ 1 ].setBoldFont ( false ); tabFont [ 2 ].setBoldFont ( false ); tabFont [ 3 ].setBoldFont ( true ); editorFont [ 0 ] = new ColoredFont (); editorFont [ 1 ] = new ColoredFont (); editorFont [ 2 ] = new ColoredFont (); editorFont [ 3 ] = new ColoredFont (); frameTitleFont [ 0 ] = new ColoredFont (); frameTitleFont [ 1 ] = new ColoredFont ( "Tahoma", Font.BOLD, 12 ); frameTitleFont [ 2 ] = new ColoredFont ( "dialog", Font.BOLD, 13 ); frameTitleFont [ 3 ] = new ColoredFont (); internalFrameTitleFont [ 0 ] = new ColoredFont (); internalFrameTitleFont [ 1 ] = new ColoredFont ( "Tahoma", Font.BOLD, 11 ); internalFrameTitleFont [ 2 ] = new ColoredFont ( "dialog", Font.BOLD, 12 ); internalFrameTitleFont [ 3 ] = new ColoredFont (); internalPaletteTitleFont [ 0 ] = new ColoredFont (); internalPaletteTitleFont [ 1 ] = new ColoredFont ( "Tahoma", Font.BOLD, 11 ); internalPaletteTitleFont [ 2 ] = new ColoredFont ( "dialog", Font.BOLD, 11 ); internalPaletteTitleFont [ 3 ] = new ColoredFont (); progressBarFont [ 0 ] = new ColoredFont (); progressBarFont [ 1 ] = new ColoredFont (); progressBarFont [ 2 ] = new ColoredFont (); progressBarFont [ 3 ] = new ColoredFont (); // Progressbar progressColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.ABS_COLOR ); progressColor [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), 0, 0, ColorReference.SUB1_COLOR ); progressColor [ 2 ] = new ColorReference ( new Color ( 44, 212, 43 ), 43, 19, ColorReference.SUB2_COLOR ); progressColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.ABS_COLOR ); progressTrackColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.ABS_COLOR ); progressTrackColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); progressTrackColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); progressTrackColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.ABS_COLOR ); progressBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); progressBorderColor [ 2 ] = new ColorReference ( new Color ( 104, 104, 104 ), -100, -54, ColorReference.BACK_COLOR ); progressBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressDarkColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); progressDarkColor [ 2 ] = new ColorReference ( new Color ( 190, 190, 190 ), -100, -16, ColorReference.BACK_COLOR ); progressDarkColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressLightColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); progressLightColor [ 2 ] = new ColorReference ( new Color ( 238, 238, 238 ), -100, 40, ColorReference.BACK_COLOR ); progressLightColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); progressSelectForeColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectForeColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); progressSelectForeColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectForeColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectBackColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectBackColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectBackColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); progressSelectBackColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); // Text textBgColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.BACK_COLOR ); textBgColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textBgColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textBgColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.BACK_COLOR ); textPaneBgColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textPaneBgColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textPaneBgColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textPaneBgColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); editorPaneBgColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); editorPaneBgColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); editorPaneBgColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); editorPaneBgColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); desktopPaneBgColor [ 0 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, -10, ColorReference.BACK_COLOR ); desktopPaneBgColor [ 1 ] = new ColorReference ( new Color ( 191, 187, 180 ), 0, -10, ColorReference.BACK_COLOR ); desktopPaneBgColor [ 2 ] = new ColorReference ( new Color ( 212, 210, 194 ), 0, -10, ColorReference.BACK_COLOR ); desktopPaneBgColor [ 3 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, -10, ColorReference.BACK_COLOR ); textTextColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textTextColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textTextColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textTextColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textCaretColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textCaretColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textCaretColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textCaretColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); textSelectedBgColor [ 0 ] = new ColorReference ( new Color ( 51, 51, 154 ), 0, 0, ColorReference.BACK_COLOR ); textSelectedBgColor [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), 0, 0, ColorReference.SUB1_COLOR ); textSelectedBgColor [ 2 ] = new ColorReference ( new Color ( 43, 107, 197 ), -36, -6, ColorReference.MAIN_COLOR ); textSelectedBgColor [ 3 ] = new ColorReference ( new Color ( 51, 51, 154 ), 0, 0, ColorReference.BACK_COLOR ); textSelectedTextColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textSelectedTextColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textSelectedTextColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textSelectedTextColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textDisabledBgColor [ 0 ] = new ColorReference ( new Color ( 236, 236, 236 ), 0, 0, ColorReference.BACK_COLOR ); textDisabledBgColor [ 1 ] = new ColorReference ( new Color ( 231, 229, 224 ), 0, 44, ColorReference.BACK_COLOR ); textDisabledBgColor [ 2 ] = new ColorReference ( new Color ( 244, 243, 233 ), 0, 44, ColorReference.BACK_COLOR ); textDisabledBgColor [ 3 ] = new ColorReference ( new Color ( 236, 236, 236 ), 0, 0, ColorReference.BACK_COLOR ); textBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); textBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); textBorderColor [ 2 ] = new ColorReference ( new Color ( 128, 152, 186 ), -70, 23, ColorReference.MAIN_COLOR ); textBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkColor [ 0 ] = new ColorReference ( new Color ( 137, 137, 137 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); textBorderDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkColor [ 3 ] = new ColorReference ( new Color ( 137, 137, 137 ), 0, 0, ColorReference.BACK_COLOR ); textBorderLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textBorderLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textBorderLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); textBorderLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); textBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 199, 199, 199 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 191, 187, 180 ), 0, -10, ColorReference.BACK_COLOR ); textBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, -15, ColorReference.BACK_COLOR ); textBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 199, 199, 199 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 210, 210, 210 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 201, 198, 190 ), 0, -5, ColorReference.BACK_COLOR ); textBorderDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); textBorderDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 210, 210, 210 ), 0, 0, ColorReference.BACK_COLOR ); textBorderLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 228, 228, 228 ), 0, 0, ColorReference.BACK_COLOR ); textBorderLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 221, 217, 211 ), 0, 20, ColorReference.BACK_COLOR ); textBorderLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); textBorderLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 228, 228, 228 ), 0, 0, ColorReference.BACK_COLOR ); textInsets [ 0 ] = new Insets ( 2, 3, 2, 3 ); textInsets [ 1 ] = new Insets ( 1, 3, 3, 3 ); textInsets [ 2 ] = new Insets ( 2, 3, 2, 3 ); textInsets [ 3 ] = new Insets ( 2, 3, 2, 3 ); // Button buttonRollover [ 0 ] = false; buttonRollover [ 1 ] = false; buttonRollover [ 2 ] = true; buttonRollover [ 3 ] = false; buttonFocus [ 0 ] = true; buttonFocus [ 1 ] = true; buttonFocus [ 2 ] = true; buttonFocus [ 3 ] = true; buttonFocusBorder [ 0 ] = false; buttonFocusBorder [ 1 ] = false; buttonFocusBorder [ 2 ] = false; buttonFocusBorder [ 3 ] = false; buttonEnter [ 0 ] = false; buttonEnter [ 1 ] = false; buttonEnter [ 2 ] = false; buttonEnter [ 3 ] = false; shiftButtonText [ 0 ] = true; shiftButtonText [ 1 ] = true; shiftButtonText [ 2 ] = true; shiftButtonText [ 3 ] = true; buttonNormalColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonNormalColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); buttonNormalColor [ 2 ] = new ColorReference ( new Color ( 231, 232, 245 ), 0, 0, ColorReference.SUB3_COLOR ); buttonNormalColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonRolloverBgColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonRolloverBgColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); buttonRolloverBgColor [ 2 ] = new ColorReference ( new Color ( 239, 240, 248 ), 0, 33, ColorReference.SUB3_COLOR ); buttonRolloverBgColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonPressedColor [ 0 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); buttonPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); buttonPressedColor [ 2 ] = new ColorReference ( new Color ( 217, 218, 230 ), 0, -6, ColorReference.SUB3_COLOR ); buttonPressedColor [ 3 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); buttonDisabledColor [ 0 ] = new ColorReference ( new Color ( 229, 227, 222 ), 0, 0, ColorReference.BACK_COLOR ); buttonDisabledColor [ 1 ] = new ColorReference ( new Color ( 225, 222, 217 ), 0, 30, ColorReference.BACK_COLOR ); buttonDisabledColor [ 2 ] = new ColorReference ( new Color ( 245, 244, 235 ), 0, 48, ColorReference.BACK_COLOR ); buttonDisabledColor [ 3 ] = new ColorReference ( new Color ( 229, 227, 222 ), 0, 0, ColorReference.BACK_COLOR ); buttonBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); buttonBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); buttonBorderColor [ 2 ] = new ColorReference ( new Color ( 21, 61, 117 ), -30, -46, ColorReference.MAIN_COLOR ); buttonBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); buttonDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkColor [ 3 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); buttonLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); buttonLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); buttonLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); buttonLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); buttonBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); buttonBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); buttonBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, -15, ColorReference.BACK_COLOR ); buttonBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); buttonDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); buttonDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 240, 239, 236 ), 0, 66, ColorReference.BACK_COLOR ); buttonLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); buttonLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); buttonDisabledFgColor [ 0 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); buttonDisabledFgColor [ 1 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); buttonDisabledFgColor [ 2 ] = new ColorReference ( new Color ( 143, 142, 139 ), 0, 0, ColorReference.DIS_COLOR ); buttonDisabledFgColor [ 3 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); checkDisabledFgColor [ 0 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); checkDisabledFgColor [ 1 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); checkDisabledFgColor [ 2 ] = new ColorReference ( new Color ( 143, 142, 139 ), 0, 0, ColorReference.DIS_COLOR ); checkDisabledFgColor [ 3 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); radioDisabledFgColor [ 0 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); radioDisabledFgColor [ 1 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); radioDisabledFgColor [ 2 ] = new ColorReference ( new Color ( 143, 142, 139 ), 0, 0, ColorReference.DIS_COLOR ); radioDisabledFgColor [ 3 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); for ( int i = 0 ; i < 4 ; i++ ) { buttonMarginTop [ i ] = 2; buttonMarginLeft [ i ] = 12; buttonMarginBottom [ i ] = 2; buttonMarginRight [ i ] = 12; } buttonRolloverColor [ 0 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); buttonRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); buttonRolloverColor [ 2 ] = new ColorReference ( new Color ( 248, 179, 48 ), 0, 0, ColorReference.SUB6_COLOR ); buttonRolloverColor [ 3 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); buttonDefaultColor [ 0 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); buttonDefaultColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); buttonDefaultColor [ 2 ] = new ColorReference ( new Color ( 160, 182, 235 ), 38, -12, ColorReference.SUB1_COLOR ); buttonDefaultColor [ 3 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); buttonCheckColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); buttonCheckColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); buttonCheckColor [ 2 ] = new ColorReference ( new Color ( 34, 161, 34 ), 0, 0, ColorReference.SUB2_COLOR ); buttonCheckColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); buttonCheckDisabledColor [ 0 ] = new ColorReference ( new Color ( 187, 183, 176 ), 0, -12, ColorReference.BACK_COLOR ); buttonCheckDisabledColor [ 1 ] = new ColorReference ( new Color ( 187, 183, 176 ), 0, -12, ColorReference.BACK_COLOR ); buttonCheckDisabledColor [ 2 ] = new ColorReference ( new Color ( 208, 205, 190 ), 0, -12, ColorReference.BACK_COLOR ); buttonCheckDisabledColor [ 3 ] = new ColorReference ( new Color ( 187, 183, 176 ), 0, -12, ColorReference.BACK_COLOR ); checkSize [ 0 ] = new Dimension ( 14, 12 ); checkSize [ 1 ] = new Dimension ( 13, 13 ); checkSize [ 2 ] = new Dimension ( 13, 13 ); checkSize [ 3 ] = new Dimension ( 14, 12 ); for ( int i = 0 ; i < 4 ; i++ ) { checkMarginTop [ i ] = 2; checkMarginLeft [ i ] = 2; checkMarginBottom [ i ] = 2; checkMarginRight [ i ] = 2; } buttonSpreadLight [ 0 ] = 20; buttonSpreadLight [ 1 ] = 0; buttonSpreadLight [ 2 ] = 20; buttonSpreadLight [ 3 ] = 20; buttonSpreadDark [ 0 ] = 3; buttonSpreadDark [ 1 ] = 0; buttonSpreadDark [ 2 ] = 3; buttonSpreadDark [ 3 ] = 3; buttonSpreadLightDisabled [ 0 ] = 20; buttonSpreadLightDisabled [ 1 ] = 0; buttonSpreadLightDisabled [ 2 ] = 20; buttonSpreadLightDisabled [ 3 ] = 20; buttonSpreadDarkDisabled [ 0 ] = 1; buttonSpreadDarkDisabled [ 1 ] = 0; buttonSpreadDarkDisabled [ 2 ] = 1; buttonSpreadDarkDisabled [ 3 ] = 1; // Scrollbar scrollRollover [ 0 ] = false; scrollRollover [ 1 ] = false; scrollRollover [ 2 ] = true; scrollRollover [ 3 ] = false; // Track scrollTrackColor [ 0 ] = new ColorReference ( new Color ( 170, 170, 170 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackColor [ 1 ] = new ColorReference ( new Color ( 233, 231, 227 ), -15, 49, ColorReference.BACK_COLOR ); scrollTrackColor [ 2 ] = new ColorReference ( new Color ( 249, 249, 247 ), -50, 76, ColorReference.BACK_COLOR ); scrollTrackColor [ 3 ] = new ColorReference ( new Color ( 170, 170, 170 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackDisabledColor [ 0 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackDisabledColor [ 1 ] = new ColorReference ( new Color ( 233, 231, 227 ), -15, 49, ColorReference.BACK_COLOR ); scrollTrackDisabledColor [ 2 ] = new ColorReference ( new Color ( 249, 249, 247 ), -50, 76, ColorReference.BACK_COLOR ); scrollTrackDisabledColor [ 3 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackBorderColor [ 0 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackBorderColor [ 1 ] = new ColorReference ( new Color ( 233, 231, 227 ), -15, 49, ColorReference.BACK_COLOR ); scrollTrackBorderColor [ 2 ] = new ColorReference ( new Color ( 234, 231, 218 ), -23, 0, ColorReference.BACK_COLOR ); scrollTrackBorderColor [ 3 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); scrollTrackBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 233, 231, 227 ), -15, 49, ColorReference.BACK_COLOR ); scrollTrackBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 234, 231, 218 ), -23, 0, ColorReference.BACK_COLOR ); scrollTrackBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); // Thumb scrollThumbColor [ 0 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbColor [ 2 ] = new ColorReference ( new Color ( 197, 213, 252 ), 0, 0, ColorReference.SUB1_COLOR ); scrollThumbColor [ 3 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbRolloverColor [ 0 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbRolloverColor [ 2 ] = new ColorReference ( new Color ( 226, 234, 254 ), 0, 50, ColorReference.SUB1_COLOR ); scrollThumbRolloverColor [ 3 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbPressedColor [ 0 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbPressedColor [ 2 ] = new ColorReference ( new Color ( 187, 202, 239 ), 0, -5, ColorReference.SUB1_COLOR ); scrollThumbPressedColor [ 3 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbDisabledColor [ 0 ] = new ColorReference ( new Color ( 214, 214, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbDisabledColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollThumbDisabledColor [ 2 ] = new ColorReference ( new Color ( 238, 238, 231 ), 0, -3, ColorReference.SUB1_COLOR ); scrollThumbDisabledColor [ 3 ] = new ColorReference ( new Color ( 214, 214, 255 ), 0, 0, ColorReference.BACK_COLOR ); // Grip scrollGripLightColor [ 0 ] = new ColorReference ( new Color ( 204, 204, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollGripLightColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); scrollGripLightColor [ 2 ] = new ColorReference ( new Color ( 238, 243, 254 ), 0, 71, ColorReference.SUB1_COLOR ); scrollGripLightColor [ 3 ] = new ColorReference ( new Color ( 204, 204, 255 ), 0, 0, ColorReference.BACK_COLOR ); scrollGripDarkColor [ 0 ] = new ColorReference ( new Color ( 51, 51, 153 ), 0, 0, ColorReference.BACK_COLOR ); scrollGripDarkColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); scrollGripDarkColor [ 2 ] = new ColorReference ( new Color ( 171, 185, 219 ), 0, -13, ColorReference.SUB1_COLOR ); scrollGripDarkColor [ 3 ] = new ColorReference ( new Color ( 51, 51, 153 ), 0, 0, ColorReference.BACK_COLOR ); // Buttons scrollButtColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtColor [ 2 ] = new ColorReference ( new Color ( 197, 213, 252 ), 0, 0, ColorReference.SUB1_COLOR ); scrollButtColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtRolloverColor [ 0 ] = new ColorReference ( new Color ( 243, 243, 243 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtRolloverColor [ 2 ] = new ColorReference ( new Color ( 226, 234, 254 ), 0, 50, ColorReference.SUB1_COLOR ); scrollButtRolloverColor [ 3 ] = new ColorReference ( new Color ( 243, 243, 243 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtPressedColor [ 0 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtPressedColor [ 2 ] = new ColorReference ( new Color ( 187, 202, 239 ), 0, -5, ColorReference.SUB1_COLOR ); scrollButtPressedColor [ 3 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtDisabledColor [ 0 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtDisabledColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); scrollButtDisabledColor [ 2 ] = new ColorReference ( new Color ( 238, 237, 231 ), -48, 29, ColorReference.BACK_COLOR ); scrollButtDisabledColor [ 3 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); scrollSpreadLight [ 0 ] = 20; scrollSpreadLight [ 1 ] = 0; scrollSpreadLight [ 2 ] = 20; scrollSpreadLight [ 3 ] = 20; scrollSpreadDark [ 0 ] = 2; scrollSpreadDark [ 1 ] = 0; scrollSpreadDark [ 2 ] = 2; scrollSpreadDark [ 3 ] = 2; scrollSpreadLightDisabled [ 0 ] = 20; scrollSpreadLightDisabled [ 1 ] = 0; scrollSpreadLightDisabled [ 2 ] = 20; scrollSpreadLightDisabled [ 3 ] = 20; scrollSpreadDarkDisabled [ 0 ] = 1; scrollSpreadDarkDisabled [ 1 ] = 0; scrollSpreadDarkDisabled [ 2 ] = 1; scrollSpreadDarkDisabled [ 3 ] = 1; // Arrow scrollArrowColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); scrollArrowColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); scrollArrowColor [ 2 ] = new ColorReference ( new Color ( 77, 100, 132 ), -74, -18, ColorReference.MAIN_COLOR ); scrollArrowColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); scrollArrowDisabledColor [ 0 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); scrollArrowDisabledColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); scrollArrowDisabledColor [ 2 ] = new ColorReference ( new Color ( 193, 193, 193 ), -100, -15, ColorReference.BACK_COLOR ); scrollArrowDisabledColor [ 3 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); // Border scrollBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); scrollBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); scrollBorderColor [ 2 ] = new ColorReference ( new Color ( 212, 210, 194 ), 0, -10, ColorReference.SUB1_COLOR ); scrollBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); scrollDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); scrollDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); scrollDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); scrollDarkColor [ 3 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); scrollLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); scrollLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); scrollLightColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.SUB1_COLOR ); scrollLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); scrollBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); scrollBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); scrollBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 232, 230, 220 ), -41, 0, ColorReference.BACK_COLOR ); scrollBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); scrollDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); scrollDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); scrollDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 232, 230, 220 ), -41, 0, ColorReference.BACK_COLOR ); scrollDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); scrollLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); scrollLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 240, 239, 236 ), 0, 66, ColorReference.BACK_COLOR ); scrollLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 232, 230, 220 ), -41, 0, ColorReference.BACK_COLOR ); scrollLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); // ScrollPane border scrollPaneBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); scrollPaneBorderColor [ 1 ] = new ColorReference ( new Color ( 191, 187, 188 ), 0, -10, ColorReference.BACK_COLOR ); scrollPaneBorderColor [ 2 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, -15, ColorReference.BACK_COLOR ); scrollPaneBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); // Tabbed tabPaneBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); tabPaneBorderColor [ 2 ] = new ColorReference ( new Color ( 143, 160, 183 ), -78, 28, ColorReference.MAIN_COLOR ); tabPaneBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneDarkColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); tabPaneDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneDarkColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneLightColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); tabPaneLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); tabPaneLightColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabNormalColor [ 0 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); tabNormalColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabNormalColor [ 2 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 69, ColorReference.BACK_COLOR ); tabNormalColor [ 3 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); tabSelectedColor [ 0 ] = new ColorReference ( new Color ( 251, 251, 250 ), 0, 0, ColorReference.BACK_COLOR ); tabSelectedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabSelectedColor [ 2 ] = new ColorReference ( new Color ( 251, 251, 250 ), 0, 91, ColorReference.BACK_COLOR ); tabSelectedColor [ 3 ] = new ColorReference ( new Color ( 251, 251, 250 ), 0, 0, ColorReference.BACK_COLOR ); // since 1.3 tabDisabledColor [ 0 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledColor [ 2 ] = new ColorReference ( new Color ( 244, 242, 232 ), 0, 40, ColorReference.BACK_COLOR ); tabDisabledColor [ 3 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledSelectedColor [ 0 ] = new ColorReference ( new Color ( 251, 251, 250 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledSelectedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledSelectedColor [ 2 ] = new ColorReference ( new Color ( 251, 251, 247 ), 0, 80, ColorReference.BACK_COLOR ); tabDisabledSelectedColor [ 3 ] = new ColorReference ( new Color ( 251, 251, 250 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledTextColor [ 0 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledTextColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabDisabledTextColor [ 2 ] = new ColorReference ( new Color ( 188, 187, 185 ), 0, 40, ColorReference.DIS_COLOR ); tabDisabledTextColor [ 3 ] = new ColorReference ( new Color ( 242, 240, 238 ), 0, 0, ColorReference.BACK_COLOR ); // end since 1.3 tabBorderColor [ 0 ] = new ColorReference ( new Color ( 143, 160, 183 ), 0, 0, ColorReference.BACK_COLOR ); tabBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); tabBorderColor [ 2 ] = new ColorReference ( new Color ( 143, 160, 183 ), -78, 28, ColorReference.MAIN_COLOR ); tabBorderColor [ 3 ] = new ColorReference ( new Color ( 143, 160, 183 ), 0, 0, ColorReference.BACK_COLOR ); tabDarkColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); tabDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); tabDarkColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabLightColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); tabLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); tabLightColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); tabRolloverColor [ 0 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); tabRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); tabRolloverColor [ 2 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.SUB6_COLOR ); tabRolloverColor [ 3 ] = new ColorReference ( new Color ( 255, 199, 59 ), 0, 0, ColorReference.BACK_COLOR ); firstTabDistance [ 0 ] = 2; firstTabDistance [ 1 ] = 2; firstTabDistance [ 2 ] = 2; firstTabDistance [ 3 ] = 2; tabRollover [ 0 ] = true; tabRollover [ 1 ] = false; tabRollover [ 2 ] = true; tabRollover [ 3 ] = true; // since 1.3.05 tabFocus [ 0 ] = true; tabFocus [ 1 ] = true; tabFocus [ 2 ] = true; tabFocus [ 3 ] = true; ignoreSelectedBg [ 0 ] = false; ignoreSelectedBg [ 1 ] = false; ignoreSelectedBg [ 2 ] = false; ignoreSelectedBg [ 3 ] = false; fixedTabs [ 0 ] = true; fixedTabs [ 1 ] = true; fixedTabs [ 2 ] = true; fixedTabs [ 3 ] = true; tabInsets [ 0 ] = new Insets ( 1, 6, 4, 6 ); tabInsets [ 1 ] = new Insets ( 1, 6, 4, 6 ); tabInsets [ 2 ] = new Insets ( 1, 6, 4, 6 ); tabInsets [ 3 ] = new Insets ( 1, 6, 4, 6 ); tabAreaInsets [ 0 ] = new Insets ( 4, 2, 0, 0 ); tabAreaInsets [ 1 ] = new Insets ( 4, 2, 0, 0 ); tabAreaInsets [ 2 ] = new Insets ( 4, 2, 0, 0 ); tabAreaInsets [ 3 ] = new Insets ( 4, 2, 0, 0 ); // Slider sliderRolloverEnabled [ 0 ] = false; sliderRolloverEnabled [ 1 ] = false; sliderRolloverEnabled [ 2 ] = true; sliderRolloverEnabled [ 3 ] = false; // since 1.3.05 sliderFocusEnabled [ 0 ] = true; sliderFocusEnabled [ 1 ] = true; sliderFocusEnabled [ 2 ] = true; sliderFocusEnabled [ 3 ] = true; sliderVertSize [ 0 ] = new Dimension ( 16, 13 ); sliderHorzSize [ 0 ] = new Dimension ( 13, 16 ); sliderVertSize [ 1 ] = new Dimension ( 22, 11 ); sliderHorzSize [ 1 ] = new Dimension ( 11, 21 ); sliderVertSize [ 2 ] = new Dimension ( 22, 11 ); sliderHorzSize [ 2 ] = new Dimension ( 11, 22 ); sliderVertSize [ 3 ] = new Dimension ( 16, 13 ); sliderHorzSize [ 3 ] = new Dimension ( 13, 16 ); // Thumb sliderThumbColor [ 0 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbColor [ 2 ] = new ColorReference ( new Color ( 244, 243, 239 ), -50, 50, ColorReference.BACK_COLOR ); sliderThumbColor [ 3 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbRolloverColor [ 0 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbRolloverColor [ 2 ] = new ColorReference ( new Color ( 233, 166, 0 ), 100, -26, ColorReference.SUB6_COLOR ); sliderThumbRolloverColor [ 3 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbPressedColor [ 0 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbPressedColor [ 1 ] = new ColorReference ( new Color ( 234, 232, 228 ), 0, 50, ColorReference.BACK_COLOR ); sliderThumbPressedColor [ 2 ] = new ColorReference ( new Color ( 244, 243, 239 ), -50, 50, ColorReference.BACK_COLOR ); sliderThumbPressedColor [ 3 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbDisabledColor [ 0 ] = new ColorReference ( new Color ( 212, 212, 212 ), 0, 0, ColorReference.BACK_COLOR ); sliderThumbDisabledColor [ 1 ] = new ColorReference ( new Color ( 225, 222, 217 ), 0, 30, ColorReference.BACK_COLOR ); sliderThumbDisabledColor [ 2 ] = new ColorReference ( new Color ( 244, 243, 233 ), 0, 44, ColorReference.BACK_COLOR ); sliderThumbDisabledColor [ 3 ] = new ColorReference ( new Color ( 212, 212, 212 ), 0, 0, ColorReference.BACK_COLOR ); // Border sliderBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); sliderBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); sliderBorderColor [ 2 ] = new ColorReference ( new Color ( 176, 189, 207 ), -76, 50, ColorReference.MAIN_COLOR ); sliderBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); sliderDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); sliderDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); sliderDarkColor [ 2 ] = new ColorReference ( new Color ( 119, 130, 146 ), -89, 4, ColorReference.MAIN_COLOR ); sliderDarkColor [ 3 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); sliderLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderLightColor [ 2 ] = new ColorReference ( new Color ( 27, 155, 27 ), 16, -7, ColorReference.SUB2_COLOR ); sliderLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); sliderBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); sliderBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 215, 212, 197 ), 0, -9, ColorReference.BACK_COLOR ); sliderBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); sliderDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); sliderDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); sliderDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 38, 84, 149 ), -41, -27, ColorReference.BACK_COLOR ); sliderDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); sliderLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); sliderLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 240, 239, 236 ), 0, 66, ColorReference.BACK_COLOR ); sliderLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 38, 84, 149 ), -41, -27, ColorReference.BACK_COLOR ); sliderLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); // Track sliderTrackColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackColor [ 3 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); sliderTrackBorderColor [ 2 ] = new ColorReference ( new Color ( 157, 156, 150 ), -53, -32, ColorReference.BACK_COLOR ); sliderTrackBorderColor [ 3 ] = new ColorReference ( new Color ( 157, 156, 150 ), -53, -32, ColorReference.BACK_COLOR ); sliderTrackDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); sliderTrackDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); sliderTrackDarkColor [ 2 ] = new ColorReference ( new Color ( 198, 196, 181 ), 0, -16, ColorReference.BACK_COLOR ); sliderTrackDarkColor [ 3 ] = new ColorReference ( new Color ( 198, 196, 181 ), 0, -16, ColorReference.BACK_COLOR ); sliderTrackLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderTrackLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderTrackLightColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); sliderTrackLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); // Ticks sliderTickColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); sliderTickColor [ 1 ] = new ColorReference ( new Color ( 106, 104, 100 ), 0, -50, ColorReference.BACK_COLOR ); sliderTickColor [ 2 ] = new ColorReference ( new Color ( 118, 117, 108 ), 0, -50, ColorReference.BACK_COLOR ); sliderTickColor [ 3 ] = new ColorReference ( new Color ( 157, 156, 150 ), -53, -32, ColorReference.BACK_COLOR ); sliderTickDisabledColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); sliderTickDisabledColor [ 1 ] = new ColorReference ( new Color ( 162, 160, 159 ), 0, 17, ColorReference.DIS_COLOR ); sliderTickDisabledColor [ 2 ] = new ColorReference ( new Color ( 174, 174, 171 ), 0, 28, ColorReference.DIS_COLOR ); sliderTickDisabledColor [ 3 ] = new ColorReference ( new Color ( 198, 196, 181 ), 0, -16, ColorReference.BACK_COLOR ); // since 1.3.05 sliderFocusColor [ 0 ] = new ColorReference ( new Color ( 113, 112, 104 ), 0, -52, ColorReference.BACK_COLOR ); sliderFocusColor [ 1 ] = new ColorReference ( new Color ( 113, 112, 104 ), 0, -52, ColorReference.BACK_COLOR ); sliderFocusColor [ 2 ] = new ColorReference ( new Color ( 113, 112, 104 ), 0, -52, ColorReference.BACK_COLOR ); sliderFocusColor [ 3 ] = new ColorReference ( new Color ( 113, 112, 104 ), 0, -52, ColorReference.BACK_COLOR ); // Spinner spinnerRollover [ 0 ] = false; spinnerRollover [ 1 ] = false; spinnerRollover [ 2 ] = false; spinnerRollover [ 3 ] = false; // Button spinnerButtColor [ 0 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtColor [ 2 ] = new ColorReference ( new Color ( 198, 213, 250 ), 0, 0, ColorReference.SUB1_COLOR ); spinnerButtColor [ 3 ] = new ColorReference ( new Color ( 153, 153, 255 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtRolloverColor [ 0 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtRolloverColor [ 2 ] = new ColorReference ( new Color ( 232, 238, 254 ), 0, 60, ColorReference.SUB1_COLOR ); spinnerButtRolloverColor [ 3 ] = new ColorReference ( new Color ( 175, 175, 255 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtPressedColor [ 0 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtPressedColor [ 2 ] = new ColorReference ( new Color ( 175, 190, 224 ), 0, -11, ColorReference.SUB1_COLOR ); spinnerButtPressedColor [ 3 ] = new ColorReference ( new Color ( 122, 122, 204 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtDisabledColor [ 0 ] = new ColorReference ( new Color ( 212, 212, 212 ), 0, 0, ColorReference.BACK_COLOR ); spinnerButtDisabledColor [ 1 ] = new ColorReference ( new Color ( 225, 222, 217 ), 0, 30, ColorReference.BACK_COLOR ); spinnerButtDisabledColor [ 2 ] = new ColorReference ( new Color ( 242, 240, 228 ), 0, 30, ColorReference.BACK_COLOR ); spinnerButtDisabledColor [ 3 ] = new ColorReference ( new Color ( 212, 212, 212 ), 0, 0, ColorReference.BACK_COLOR ); spinnerSpreadLight [ 0 ] = 20; spinnerSpreadLight [ 1 ] = 0; spinnerSpreadLight [ 2 ] = 20; spinnerSpreadLight [ 3 ] = 20; spinnerSpreadDark [ 0 ] = 3; spinnerSpreadDark [ 1 ] = 0; spinnerSpreadDark [ 2 ] = 3; spinnerSpreadDark [ 3 ] = 3; spinnerSpreadLightDisabled [ 0 ] = 20; spinnerSpreadLightDisabled [ 1 ] = 0; spinnerSpreadLightDisabled [ 2 ] = 20; spinnerSpreadLightDisabled [ 3 ] = 20; spinnerSpreadDarkDisabled [ 0 ] = 1; spinnerSpreadDarkDisabled [ 1 ] = 0; spinnerSpreadDarkDisabled [ 2 ] = 1; spinnerSpreadDarkDisabled [ 3 ] = 1; spinnerBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); spinnerBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); spinnerBorderColor [ 2 ] = new ColorReference ( new Color ( 150, 173, 227 ), 36, -16, ColorReference.SUB1_COLOR ); spinnerBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); spinnerDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkColor [ 3 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); spinnerLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); spinnerLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); spinnerLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); spinnerLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); spinnerBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); spinnerBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); spinnerBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 215, 212, 197 ), 0, -9, ColorReference.BACK_COLOR ); spinnerBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); spinnerDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); spinnerDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); spinnerLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); spinnerLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 240, 239, 236 ), 0, 66, ColorReference.BACK_COLOR ); spinnerLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); spinnerLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); spinnerArrowColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); spinnerArrowColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); spinnerArrowColor [ 2 ] = new ColorReference ( new Color ( 77, 100, 132 ), -74, -18, ColorReference.MAIN_COLOR ); spinnerArrowColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); spinnerArrowDisabledColor [ 0 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); spinnerArrowDisabledColor [ 1 ] = new ColorReference ( new Color ( 195, 191, 184 ), 0, -8, ColorReference.BACK_COLOR ); spinnerArrowDisabledColor [ 2 ] = new ColorReference ( new Color ( 212, 210, 194 ), 0, -10, ColorReference.BACK_COLOR ); spinnerArrowDisabledColor [ 3 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); // Combo comboBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); comboBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); comboBorderColor [ 2 ] = new ColorReference ( new Color ( 128, 152, 186 ), -70, 23, ColorReference.MAIN_COLOR ); comboBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkColor [ 0 ] = new ColorReference ( new Color ( 137, 137, 137 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); comboDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkColor [ 3 ] = new ColorReference ( new Color ( 137, 137, 137 ), 0, 0, ColorReference.BACK_COLOR ); comboLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 200, 199, 193 ), 0, 0, ColorReference.BACK_COLOR ); comboBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 188, 186, 183 ), -60, -13, ColorReference.BACK_COLOR ); comboBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, -15, ColorReference.BACK_COLOR ); comboBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 200, 199, 193 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 210, 210, 210 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 208, 207, 204 ), -60, 0, ColorReference.BACK_COLOR ); comboDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 210, 210, 210 ), 0, 0, ColorReference.BACK_COLOR ); comboLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 228, 228, 228 ), 0, 0, ColorReference.BACK_COLOR ); comboLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 208, 207, 204 ), -60, 0, ColorReference.BACK_COLOR ); comboLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 228, 228, 228 ), 0, 0, ColorReference.BACK_COLOR ); comboSelectedBgColor [ 0 ] = new ColorReference ( new Color ( 51, 51, 154 ), 0, 0, ColorReference.BACK_COLOR ); comboSelectedBgColor [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), 0, 0, ColorReference.SUB1_COLOR ); comboSelectedBgColor [ 2 ] = new ColorReference ( new Color ( 43, 107, 197 ), -36, -6, ColorReference.MAIN_COLOR ); comboSelectedBgColor [ 3 ] = new ColorReference ( new Color ( 51, 51, 154 ), 0, 0, ColorReference.BACK_COLOR ); comboSelectedTextColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboSelectedTextColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboSelectedTextColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboSelectedTextColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboFocusBgColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.ABS_COLOR ); comboFocusBgColor [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), 0, 0, ColorReference.SUB1_COLOR ); comboFocusBgColor [ 2 ] = new ColorReference ( new Color ( 43, 107, 197 ), 0, 0, ColorReference.ABS_COLOR ); comboFocusBgColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.ABS_COLOR ); comboBgColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.BACK_COLOR ); comboBgColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboBgColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboBgColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 0, ColorReference.BACK_COLOR ); comboTextColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboTextColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboTextColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboTextColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); // Button comboButtColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); comboButtColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); comboButtColor [ 2 ] = new ColorReference ( new Color ( 197, 213, 252 ), 0, 0, ColorReference.SUB1_COLOR ); comboButtColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); comboButtRolloverColor [ 0 ] = new ColorReference ( new Color ( 243, 243, 243 ), 0, 0, ColorReference.BACK_COLOR ); comboButtRolloverColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); comboButtRolloverColor [ 2 ] = new ColorReference ( new Color ( 226, 234, 254 ), 0, 50, ColorReference.SUB1_COLOR ); comboButtRolloverColor [ 3 ] = new ColorReference ( new Color ( 243, 243, 243 ), 0, 0, ColorReference.BACK_COLOR ); comboButtPressedColor [ 0 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); comboButtPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); comboButtPressedColor [ 2 ] = new ColorReference ( new Color ( 175, 190, 224 ), 0, -11, ColorReference.SUB1_COLOR ); comboButtPressedColor [ 3 ] = new ColorReference ( new Color ( 126, 126, 126 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDisabledColor [ 0 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDisabledColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDisabledColor [ 2 ] = new ColorReference ( new Color ( 238, 237, 231 ), -48, 29, ColorReference.BACK_COLOR ); comboButtDisabledColor [ 3 ] = new ColorReference ( new Color ( 238, 238, 238 ), 0, 0, ColorReference.BACK_COLOR ); comboSpreadLight [ 0 ] = 20; comboSpreadLight [ 1 ] = 0; comboSpreadLight [ 2 ] = 20; comboSpreadLight [ 3 ] = 20; comboSpreadDark [ 0 ] = 3; comboSpreadDark [ 1 ] = 0; comboSpreadDark [ 2 ] = 3; comboSpreadDark [ 3 ] = 3; comboSpreadLightDisabled [ 0 ] = 20; comboSpreadLightDisabled [ 1 ] = 0; comboSpreadLightDisabled [ 2 ] = 20; comboSpreadLightDisabled [ 3 ] = 20; comboSpreadDarkDisabled [ 0 ] = 1; comboSpreadDarkDisabled [ 1 ] = 0; comboSpreadDarkDisabled [ 2 ] = 1; comboSpreadDarkDisabled [ 3 ] = 1; // Button Border comboButtBorderColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); comboButtBorderColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); comboButtBorderColor [ 2 ] = new ColorReference ( new Color ( 212, 210, 194 ), 0, -10, ColorReference.SUB1_COLOR ); comboButtBorderColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkColor [ 0 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); comboButtDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkColor [ 3 ] = new ColorReference ( new Color ( 119, 119, 119 ), 0, 0, ColorReference.BACK_COLOR ); comboButtLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboButtLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboButtLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboButtLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); comboButtBorderDisabledColor [ 0 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); comboButtBorderDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); comboButtBorderDisabledColor [ 2 ] = new ColorReference ( new Color ( 232, 230, 220 ), -41, 0, ColorReference.BACK_COLOR ); comboButtBorderDisabledColor [ 3 ] = new ColorReference ( new Color ( 201, 198, 184 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkDisabledColor [ 1 ] = new ColorReference ( new Color ( 180, 177, 170 ), 0, -15, ColorReference.BACK_COLOR ); comboButtDarkDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboButtDarkDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); comboButtLightDisabledColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); comboButtLightDisabledColor [ 1 ] = new ColorReference ( new Color ( 240, 239, 236 ), 0, 66, ColorReference.BACK_COLOR ); comboButtLightDisabledColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); comboButtLightDisabledColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); // Arrow comboArrowColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboArrowColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboArrowColor [ 2 ] = new ColorReference ( new Color ( 77, 100, 132 ), -74, -18, ColorReference.MAIN_COLOR ); comboArrowColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); comboArrowDisabledColor [ 0 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); comboArrowDisabledColor [ 1 ] = new ColorReference ( new Color ( 182, 179, 172 ), 0, -14, ColorReference.BACK_COLOR ); comboArrowDisabledColor [ 2 ] = new ColorReference ( new Color ( 203, 200, 186 ), 0, -14, ColorReference.BACK_COLOR ); comboArrowDisabledColor [ 3 ] = new ColorReference ( new Color ( 136, 136, 136 ), 0, 0, ColorReference.BACK_COLOR ); comboButtonWidth [ 0 ] = 22; comboButtonWidth [ 1 ] = 18; comboButtonWidth [ 2 ] = 18; comboButtonWidth [ 3 ] = 22; comboInsets [ 0 ] = new Insets ( 2, 2, 2, 2 ); comboInsets [ 1 ] = new Insets ( 2, 2, 2, 2 ); comboInsets [ 2 ] = new Insets ( 2, 2, 2, 2 ); comboInsets [ 3 ] = new Insets ( 2, 2, 2, 2 ); comboRollover [ 0 ] = false; comboRollover [ 1 ] = false; comboRollover [ 2 ] = false; comboRollover [ 3 ] = false; comboFocus [ 0 ] = false; comboFocus [ 1 ] = false; comboFocus [ 2 ] = false; comboFocus [ 3 ] = false; // Menu menuBarColor [ 0 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuBarColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); menuBarColor [ 2 ] = new ColorReference ( new Color ( 238, 237, 230 ), -43, 28, ColorReference.BACK_COLOR ); menuBarColor [ 3 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuSelectedTextColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSelectedTextColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSelectedTextColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuSelectedTextColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuPopupColor [ 0 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuPopupColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); menuPopupColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuPopupColor [ 3 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuRolloverBgColor [ 0 ] = new ColorReference ( new Color ( 189, 208, 234 ), -50, 66, ColorReference.MAIN_COLOR ); menuRolloverBgColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); menuRolloverBgColor [ 2 ] = new ColorReference ( new Color ( 189, 208, 234 ), -50, 66, ColorReference.MAIN_COLOR ); menuRolloverBgColor [ 3 ] = new ColorReference ( new Color ( 189, 208, 234 ), -50, 66, ColorReference.MAIN_COLOR ); menuRolloverFgColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuRolloverFgColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuRolloverFgColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuRolloverFgColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuDisabledFgColor [ 0 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); menuDisabledFgColor [ 1 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); menuDisabledFgColor [ 2 ] = new ColorReference ( new Color ( 143, 142, 139 ), 0, 0, ColorReference.DIS_COLOR ); menuDisabledFgColor [ 3 ] = new ColorReference ( new Color ( 143, 141, 139 ), 0, 0, ColorReference.DIS_COLOR ); menuItemRolloverColor [ 0 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuItemRolloverColor [ 1 ] = new ColorReference ( new Color ( 10, 50, 105 ), 0, 0, ColorReference.SUB1_COLOR ); menuItemRolloverColor [ 2 ] = new ColorReference ( new Color ( 189, 208, 234 ), -50, 66, ColorReference.MAIN_COLOR ); menuItemRolloverColor [ 3 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); menuBorderColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuBorderColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); menuBorderColor [ 2 ] = new ColorReference ( new Color ( 173, 170, 153 ), 4, -28, ColorReference.BACK_COLOR ); menuBorderColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuDarkColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); menuDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); menuDarkColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); menuLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerHilightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerHilightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerHilightColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerHilightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerShadowColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuInnerShadowColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); menuInnerShadowColor [ 2 ] = new ColorReference ( new Color ( 213, 212, 207 ), -70, -7, ColorReference.BACK_COLOR ); menuInnerShadowColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuOuterHilightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuOuterHilightColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); menuOuterHilightColor [ 2 ] = new ColorReference ( new Color ( 173, 170, 153 ), 4, -28, ColorReference.BACK_COLOR ); menuOuterHilightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuOuterShadowColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuOuterShadowColor [ 1 ] = new ColorReference ( new Color ( 64, 64, 64 ), -100, -69, ColorReference.BACK_COLOR ); menuOuterShadowColor [ 2 ] = new ColorReference ( new Color ( 173, 170, 153 ), 4, -28, ColorReference.BACK_COLOR ); menuOuterShadowColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuIconColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconColor [ 1 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconRolloverColor [ 0 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconRolloverColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuIconRolloverColor [ 2 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconRolloverColor [ 3 ] = new ColorReference ( new Color ( 0, 0, 0 ), 0, -100, ColorReference.BACK_COLOR ); menuIconDisabledColor [ 0 ] = new ColorReference ( new Color ( 128, 128, 128 ), 0, 50, ColorReference.BACK_COLOR ); menuIconDisabledColor [ 1 ] = new ColorReference ( new Color ( 165, 162, 156 ), 0, -22, ColorReference.BACK_COLOR ); menuIconDisabledColor [ 2 ] = new ColorReference ( new Color ( 165, 163, 151 ), 0, -30, ColorReference.BACK_COLOR ); menuIconDisabledColor [ 3 ] = new ColorReference ( new Color ( 128, 128, 128 ), 0, 50, ColorReference.BACK_COLOR ); menuIconShadowColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuIconShadowColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuIconShadowColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); menuIconShadowColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSepDarkColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuSepDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); menuSepDarkColor [ 2 ] = new ColorReference ( new Color ( 173, 170, 153 ), 4, -28, ColorReference.BACK_COLOR ); menuSepDarkColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); menuSepLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSepLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSepLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); menuSepLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); menuSeparatorHeight [ 0 ] = 3; menuSeparatorHeight [ 1 ] = 4; menuSeparatorHeight [ 2 ] = 3; menuSeparatorHeight [ 3 ] = 3; menuBorderInsets [ 0 ] = new Insets ( 2, 2, 2, 2 ); menuBorderInsets [ 1 ] = new Insets ( 3, 3, 3, 3 ); menuBorderInsets [ 2 ] = new Insets ( 2, 2, 2, 2 ); menuBorderInsets [ 3 ] = new Insets ( 2, 2, 2, 2 ); menuRollover [ 0 ] = true; menuRollover [ 1 ] = true; menuRollover [ 2 ] = true; menuRollover [ 3 ] = true; // Toolbar toolBarColor [ 0 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); toolBarColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolBarColor [ 2 ] = new ColorReference ( new Color ( 239, 237, 229 ), -35, 28, ColorReference.BACK_COLOR ); toolBarColor [ 3 ] = new ColorReference ( new Color ( 189, 208, 234 ), 0, 0, ColorReference.BACK_COLOR ); toolBarLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBarLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBarLightColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBarLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBarDarkColor [ 0 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolBarDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); toolBarDarkColor [ 2 ] = new ColorReference ( new Color ( 214, 210, 187 ), 10, -11, ColorReference.BACK_COLOR ); toolBarDarkColor [ 3 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolButtColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolButtColor [ 2 ] = new ColorReference ( new Color ( 239, 237, 229 ), -35, 28, ColorReference.BACK_COLOR ); toolButtColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtSelectedColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtSelectedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolButtSelectedColor [ 2 ] = new ColorReference ( new Color ( 243, 242, 239 ), -51, 52, ColorReference.BACK_COLOR ); toolButtSelectedColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtRolloverColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtRolloverColor [ 1 ] = new ColorReference ( new Color ( 234, 232, 228 ), 0, 50, ColorReference.BACK_COLOR ); toolButtRolloverColor [ 2 ] = new ColorReference ( new Color ( 251, 251, 248 ), -30, 81, ColorReference.BACK_COLOR ); toolButtRolloverColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtPressedColor [ 0 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolButtPressedColor [ 1 ] = new ColorReference ( new Color ( 212, 208, 200 ), 0, 0, ColorReference.BACK_COLOR ); toolButtPressedColor [ 2 ] = new ColorReference ( new Color ( 225, 224, 218 ), -58, -2, ColorReference.BACK_COLOR ); toolButtPressedColor [ 3 ] = new ColorReference ( new Color ( 221, 221, 221 ), 0, 0, ColorReference.BACK_COLOR ); toolBorderDarkColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolBorderDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); toolBorderDarkColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); toolBorderDarkColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolBorderLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBorderLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolBorderLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233, 216 ), 0, 0, ColorReference.BACK_COLOR ); toolBorderLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolGripDarkColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolGripDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); toolGripDarkColor [ 2 ] = new ColorReference ( new Color ( 167, 167, 163 ), -70, -27, ColorReference.BACK_COLOR ); toolGripDarkColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolGripLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolGripLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolGripLightColor [ 2 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolGripLightColor [ 3 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolSepDarkColor [ 0 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolSepDarkColor [ 1 ] = new ColorReference ( new Color ( 128, 128, 128 ), -100, -38, ColorReference.BACK_COLOR ); toolSepDarkColor [ 2 ] = new ColorReference ( new Color ( 167, 167, 163 ), -70, -27, ColorReference.BACK_COLOR ); toolSepDarkColor [ 3 ] = new ColorReference ( new Color ( 167, 167, 163 ), 0, 0, ColorReference.BACK_COLOR ); toolSepLightColor [ 0 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolSepLightColor [ 1 ] = new ColorReference ( new Color ( 255, 255, 255 ), 0, 100, ColorReference.BACK_COLOR ); toolSepLightColor [ 2 ] = new ColorReference ( new Color ( 236, 233,
43,602
https://github.com/akashkalal/grow/blob/master/grow/ui/sass/composite/admin.sass
Github Open Source
Open Source
MIT
2,022
grow
akashkalal
Sass
Code
71
221
html, body font-family: "Roboto", "Helvetica", sans-serif ul ul margin: 10px 0 header .title margin: 0 0 15px header nav margin-bottom: 15px table border-collapse: collapse table tr td, table tr th border: 1px sol #efefef padding: 5px 10px table tr th font-weight: bd text-align: left dt font-weight: bold margin-top: 1em nav display: flex flex-flow: row a flex-grow: 1 footer margin: 1.5em 0 .subtitle font-style: italic font-size: 0.9rem // Import partials @import ../../admin/partials/routes/routes
31,378
https://github.com/dusktreader/py-buzz/blob/master/examples/with_buzz_class.py
Github Open Source
Open Source
MIT
2,023
py-buzz
dusktreader
Python
Code
122
342
""" This example shows how the Buzz exception class might be used as the base of a derived class """ from buzz import Buzz from helpers import wrap_demo class DerivedError(Buzz): pass def demo_check_expression(): with DerivedError.check_expressions(f"Some of our expressions were falsey!") as check: check(False, "False is always False") check(0, "Zero is the only falsey integer") check("", "Empty strings are also falsey!") def demo_handle_errors(): with DerivedError.handle_errors("something went wrong (simple example)"): print("we are fine") raise ValueError("here we die") print("we should not get here") def demo_require_conditions(): DerivedError.require_condition(True, 'This condition should always pass') DerivedError.require_condition(False, 'This condition should always fail') if __name__ == '__main__': with wrap_demo("Demonstrating check_expressions from Buzz derived class"): demo_check_expression() with wrap_demo("Demonstrating handle_errors from Buzz derived class"): demo_handle_errors() with wrap_demo("Demonstrating require_conditions from Buzz derived class"): demo_handle_errors()
43,756
https://github.com/l2c2technologies/sms-send-in-esms/blob/master/t/liveaccttest.t
Github Open Source
Open Source
Artistic-1.0
null
sms-send-in-esms
l2c2technologies
Perl
Code
120
324
# Before 'make install' is performed this script should be runnable with # 'make test'. After 'make install' it should work as 'perl SMS-Send-IN-eSMS.t' ######################### # Actual live test of sending transactional SMS via eSMS # Requires paid account with at least one approved message # template along with login credentials use Test::More; use SMS::Send; if ( exists $ENV{'eSMS_LOGIN'} && $ENV{'eSMS_DESTP'}) { plan tests => 2; } else { plan skip_all => 'No login information available, skipping all tests.'; } # Get the sender and login my $sender = SMS::Send->new( 'IN::eSMS', _login => $ENV{'eSMS_LOGIN'}, _password => $ENV{'eSMS_PASSW'}, _senderid => $ENV{'eSMS_SENDR'}, ); isa_ok( $sender, 'SMS::Send' ); my $sent = $sender->send_sms( text => $ENV{'eSMS_MSGTP'}, to => $ENV{'eSMS_DESTP'}, ); ok($sent, 'message was sent');
45,487
https://github.com/skn123/GPc/blob/master/ndlassert.cpp
Github Open Source
Open Source
MIT
2,022
GPc
skn123
C++
Code
91
304
#include "ndlassert.h" void ndlCheckBounds(bool cond) { if(cond) return; else { throw std::out_of_range("Bound check failed."); } } void ndlCheckDimension(bool cond) { if(cond) return; else { throw ndlexceptions::Error("Dimension match check failed."); } } void ndlCheckCharArguments(bool cond) { if(cond) return; else { throw ndlexceptions::Error("Char argument check failed."); } } void ndlCheckMatrixProperties(bool cond) { if(cond) return; else { throw ndlexceptions::Error("Matrix properties check failed"); } } void ndlCheckSanity(bool cond) { if(cond) return; else { throw ndlexceptions::Error("Sanity check failed."); } } void ndlCheckZeroOrPositive(bool cond) { if(cond) return; else { throw ndlexceptions::Error("Zero or positive check failed."); } }
35,079
https://github.com/yeeezsh/FluentSearch-Mini/blob/master/src/insight/schema/insight.schema.ts
Github Open Source
Open Source
MIT
2,021
FluentSearch-Mini
yeeezsh
TypeScript
Code
73
157
import { InsightSchema } from 'fluentsearch-types'; import { Document, Schema } from 'mongoose'; export type InsightDoc = Document<InsightSchema>; export const insightSchema = new Schema<InsightDoc>({ fileId: { type: String, required: true }, result: { type: String, required: true }, model: { type: String }, bbox: { type: Object }, prob: { type: Number }, lang: { type: String }, createAt: { type: Date, default: Date.now }, updateAt: { type: Date, default: Date.now }, });
17,622
https://github.com/onesky/onesky-sdk-cl/blob/master/src/build/build.go
Github Open Source
Open Source
BSD-3-Clause
2,022
onesky-sdk-cl
onesky
Go
Code
21
92
package build import ( "github.com/onesky/onesky-sdk-cli/src/app" ) var DefaultConfig = app.Config{ Title: "OneSky config", Api: app.Api{ Url: "https://management-api.onesky.app/v1", Timeout: 30, }, }
21,786
https://github.com/MorevM/more-bem-classnames/blob/master/src/bem-fn.ts
Github Open Source
Open Source
MIT
null
more-bem-classnames
MorevM
TypeScript
Code
119
330
import { isObject, kebabCase } from '@morev/helpers'; import type { FunctionOptions, ModuleOptions } from '../types'; export default function bemFn( { namespace, block, element, modifiers, mixins, }: FunctionOptions, { hyphenate, delimiters: ds }: ModuleOptions, ) { if (!block) return ''; const root = element ? namespace + block + ds.element + element : namespace + block; const stack = [root]; const doCase = (str: string) => (hyphenate ? kebabCase(str.toString()) : str.toString()); if (isObject(modifiers)) { Object.entries(modifiers).forEach(([modKey, modValue]) => { if ([false, null, undefined].includes(modValue as any)) return; if (modValue === true) { stack.push(root + ds.modifier + doCase(modKey)); } else { stack.push(root + ds.modifier + doCase(modKey) + ds.modifierValue + doCase(modValue as any)); } }); } mixins.length && stack.push(mixins.join(' ')); return stack.join(' '); }
35,795
https://github.com/FahrenheitKid/WeFixIt/blob/master/WeFixIt/Assets/Scripts/InputManager.cs
Github Open Source
Open Source
MIT
null
WeFixIt
FahrenheitKid
C#
Code
155
573
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum KeyActions { Up, Down, Left, Right, Action } public static class InputManager { private static KeyCode[][] playerKeys = new KeyCode[4][]; public static void Initialize() { playerKeys[0] = new KeyCode[] { KeyCode.W, KeyCode.S, KeyCode.A, KeyCode.D, KeyCode.LeftShift }; playerKeys[1] = new KeyCode[] { KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.LeftArrow, KeyCode.RightArrow, KeyCode.RightControl }; playerKeys[2] = new KeyCode[] { KeyCode.I, KeyCode.K, KeyCode.J, KeyCode.L, KeyCode.Space }; playerKeys[3] = new KeyCode[] { KeyCode.Keypad8, KeyCode.Keypad5, KeyCode.Keypad4, KeyCode.Keypad6, KeyCode.KeypadEnter }; } public static bool GetKey(int player, KeyActions action) { if (Input.GetKey(playerKeys[player][(int)action])) { return true; } return false; } public static bool GetKeyDown(int player, KeyActions action) { if (Input.GetKeyDown(playerKeys[player][(int)action])) { return true; } return false; } public static bool GetKeyUp(int player, KeyActions action) { if (Input.GetKeyUp(playerKeys[player][(int)action])) { return true; } return false; } public static void SetKey(int player, KeyActions action, KeyCode keyCode) { playerKeys[player][(int)action] = keyCode; } public static KeyCode CheckKey(int player, KeyActions action) { return playerKeys[player][(int)action]; } }
24,374
https://github.com/minigame-network/evolution/blob/master/src/me/chasertw123/evolution/game/GameManager.java
Github Open Source
Open Source
MIT
null
evolution
minigame-network
Java
Code
1,041
5,087
package me.chasertw123.evolution.game; import de.robingrether.idisguise.iDisguise; import me.chasertw123.evolution.Main; import me.chasertw123.evolution.game.ai.AIPlayer; import me.chasertw123.evolution.game.ai.GeneralPlayerContainer; import me.chasertw123.evolution.game.boards.Scoreboard_Game; import me.chasertw123.evolution.game.evolutions.Evolution; import me.chasertw123.evolution.game.loops.*; import me.chasertw123.evolution.maps.GameMap; import me.chasertw123.evolution.user.EvolutionPlayer; import me.chasertw123.minigames.core.api.misc.Title; import me.chasertw123.minigames.core.api.v2.CoreAPI; import me.chasertw123.minigames.core.user.data.stats.Stat; import me.chasertw123.minigames.core.utils.items.AbstractItem; import me.chasertw123.minigames.core.utils.items.Items; import me.chasertw123.minigames.core.utils.items.cItemStack; import me.chasertw123.minigames.shared.framework.GeneralServerStatus; import me.chasertw123.minigames.shared.framework.ServerSetting; import me.chasertw123.minigames.shared.utils.MessageUtil; import net.minecraft.server.v1_8_R3.NBTTagCompound; import org.bukkit.*; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import java.util.*; public class GameManager { public static final int REQUIRED_PLAYERS = 2, MAX_PLAYERS = 8, GAME_TIME = 60 * 15; private GameState gameState; private GameLoop currentGameLoop; private GameMap gameMap; private UUID winner = null; private List<AIPlayer> aiPlayers; public GameManager() { gameState = GameState.LOBBY; currentGameLoop = new Loop_Lobby(); CoreAPI.getServerDataManager().updateServerState(GeneralServerStatus.LOBBY, MAX_PLAYERS); aiPlayers = new ArrayList<>(); new Loop_AI(); } public List<AIPlayer> getAiPlayers() { return aiPlayers; } public List<GeneralPlayerContainer> getGeneralPlayerControllers() { List<GeneralPlayerContainer> generalPlayerContainers = new ArrayList<>(); generalPlayerContainers.addAll(aiPlayers); generalPlayerContainers.addAll(Main.getInstance().getEvolutionPlayerManager().getEvolutionPlayers()); return generalPlayerContainers; } public void setWinner(UUID winner) { this.winner = winner; } public void checkGame() { if(gameState != GameState.INGAME) return; if(Bukkit.getServer().getOnlinePlayers().size() < 2) { // There is only one player (or less) on the server endGame(); } } public List<GeneralPlayerContainer> getGeneralPlayersByScore() { List<GeneralPlayerContainer> generalPlayerContainers = getGeneralPlayerControllers(); generalPlayerContainers.sort(Comparator.comparingInt(GeneralPlayerContainer::getScore).reversed()); return generalPlayerContainers; } public void setGameMap(GameMap gameMap) { this.gameMap = gameMap; } public GameMap getGameMap() { return gameMap; } public void startGame() { CoreAPI.getServerDataManager().updateServerState(GeneralServerStatus.INGAME, MAX_PLAYERS); // Send information to the Mongo database for the queue system currentGameLoop = new Loop_Game(); new Loop_Countdown(); new Loop_PlayerTracker(); int spawnCount = 0; for(me.chasertw123.minigames.core.user.User user : CoreAPI.getOnlinePlayers()) { user.incrementStat(Stat.EVOLUTION_GAMES_PLAYED); Location spawn = gameMap.getSpawns(Main.getInstance().getMapManager().getGame()).get(spawnCount++); user.setScoreboard(new Scoreboard_Game(Main.getInstance().getEvolutionPlayerManager().getPlayer(user.getPlayer()))); user.getPlayer().getInventory().clear(); EvolutionPlayer evolutionPlayer = Main.getInstance().getEvolutionPlayerManager().getPlayer(user.getPlayer()); user.getPlayer().setMaxHealth(evolutionPlayer.getEvolution().getHealth()); user.getPlayer().setHealth(evolutionPlayer.getEvolution().getHealth()); user.getPlayer().setFoodLevel(20); user.getPlayer().teleport(spawn); iDisguise.getInstance().getAPI().disguise(evolutionPlayer.getPlayer(), evolutionPlayer.getEvolution().getDisguiseType().newInstance()); // the mob to be disguised as } // // // See how many AI players need to be made // if(MAX_PLAYERS - Bukkit.getServer().getOnlinePlayers().size() != 0) { // Bukkit.broadcastMessage(ChatColor.GRAY + "It seems as though all of the player slots were not filled! Do not worry - AI will populate those positions!"); // Bukkit.broadcastMessage(ChatColor.GRAY + "Creating " + ChatColor.AQUA + "" + (MAX_PLAYERS - Bukkit.getServer().getOnlinePlayers().size()) + ChatColor.GRAY + " AI player(s)"); // // for (int i = 0; i < (MAX_PLAYERS - Bukkit.getServer().getOnlinePlayers().size()); i++) { // Location spawn = gameMap.getSpawns(Main.getInstance().getMapManager().getGame()).get(spawnCount++); // // AIPlayer aiPlayer = new AIPlayer(spawn); // aiPlayers.add(aiPlayer); // } // } } public void realStartGame() { gameState = GameState.INGAME; for(me.chasertw123.minigames.core.user.User user : CoreAPI.getOnlinePlayers()) { user.setServerSetting(ServerSetting.DAMAGE, true); user.getPlayer().getInventory().clear(); EvolutionPlayer evolutionPlayer = Main.getInstance().getEvolutionPlayerManager().getPlayer(user.getPlayer()); new AbstractItem(evolutionPlayer.getEvolution().getItemStack(), evolutionPlayer.getCoreUser(), 0, (type) -> { if(type == AbstractItem.InteractType.RIGHT) evolutionPlayer.tryAbility(); }); user.getPlayer().getInventory().setItem(1, new cItemStack(Material.COMPASS, ChatColor.GREEN + "Player Tracker")); user.getPlayer().setMaxHealth(evolutionPlayer.getEvolution().getHealth()); user.getPlayer().setHealth(evolutionPlayer.getEvolution().getHealth()); user.getPlayer().setFoodLevel(20); user.getPlayer().playSound(user.getPlayer().getLocation(), Sound.ENDERDRAGON_GROWL, 1F, 1F); } } public void endGame() { CoreAPI.getServerDataManager().updateServerState(GeneralServerStatus.RESTARTING, MAX_PLAYERS); gameState = GameState.ENDING; List<EvolutionPlayer> scoredList = Main.getInstance().getEvolutionPlayerManager().getEvolutionPlayersSortedByScore(); new Loop_GameOver(); if(winner == null) winner = scoredList.get(0).getUUID(); Main.getInstance().getEvolutionPlayerManager().getPlayer(winner).getCoreUser().incrementStat(Stat.EVOLUTION_GAMES_WON); for(EvolutionPlayer evolutionPlayer : Main.getInstance().getEvolutionPlayerManager().getEvolutionPlayers()) { Player player = evolutionPlayer.getPlayer(); String ord = ordinal(scoredList.indexOf(evolutionPlayer) + 1); if(evolutionPlayer.getUUID() != winner) evolutionPlayer.getPlayer().teleport(Bukkit.getServer().getPlayer(winner)); // TP to the winner player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.GOLD + "" + ChatColor.STRIKETHROUGH + "---------------------------------")); player.sendMessage(MessageUtil.createCenteredMessage(" ")); player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.AQUA + Main.getInstance().getEvolutionPlayerManager().getPlayer(winner).getPlayer().getName() + ChatColor.RED + " has won the game!")); player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.BLUE + "" + ChatColor.ITALIC + "You placed " + ord)); evolutionPlayer.getCoreUser().addActivity(ord + " Evolution"); if(!evolutionPlayer.getCoreUser().isDeluxe()) { player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.YELLOW + "You don't have deluxe! Help the server at:")); player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.YELLOW + "http://store.pvpcentral.net")); } player.sendMessage(MessageUtil.createCenteredMessage(" ")); player.sendMessage(MessageUtil.createCenteredMessage(ChatColor.GOLD + "" + ChatColor.STRIKETHROUGH + "---------------------------------")); player.getInventory().clear(); player.playSound(player.getLocation(), Sound.ENDERDRAGON_GROWL, 0.75F, 1F); for (Player player1 : Bukkit.getOnlinePlayers()) if (!player.getUniqueId().equals(player1.getUniqueId())) { player1.showPlayer(player); player.showPlayer(player1); } player.setAllowFlight(true); player.setFlying(true); player.setWalkSpeed(0.2f); player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); new AbstractItem(Items.PLAY_AGAIN.getItemStack(), evolutionPlayer.getCoreUser(), 7, (type) -> evolutionPlayer.getCoreUser().addToQueue("evolution")); new AbstractItem(Items.RETURN_TO_HUB.getItemStack(), evolutionPlayer.getCoreUser(), 8, (type) -> evolutionPlayer.getCoreUser().sendToServer("hub")); if(iDisguise.getInstance().getAPI().isDisguised((OfflinePlayer) player)) iDisguise.getInstance().getAPI().undisguise(player); } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> { for(me.chasertw123.minigames.core.user.User player : CoreAPI.getOnlinePlayers()) player.sendToServer("hub"); }, 20 * 15); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "restart"), 20 * 25); } public GameLoop getCurrentGameLoop() { return currentGameLoop; } public GameState getGameState() { return gameState; } public void evolute(EvolutionPlayer evolutionPlayer) { if(evolutionPlayer.getEvolution() == Evolution.ENDERMAN) { // This kids won setWinner(evolutionPlayer.getUUID()); endGame(); return; } evolutionPlayer.getCoreUser().incrementStat(Stat.EVOLUTION_EVOLVES); evolutionPlayer.getPlayer().getInventory().clear(); Location originalLocation = evolutionPlayer.getPlayer().getLocation(); Title.sendActionbar(evolutionPlayer.getPlayer(), ChatColor.GREEN + "" + ChatColor.BOLD + "EVOLUTION COMPLETE"); Evolution evolution = evolutionPlayer.incrementEvolution(); evolutionPlayer.getPlayer().setMaxHealth(evolution.getHealth()); evolutionPlayer.getPlayer().setHealth(evolutionPlayer.getPlayer().getMaxHealth()); evolutionPlayer.setEvolutionPrimed(false); // Send Evolution message evolutionPlayer.getPlayer().sendMessage(ChatColor.GREEN + "" + ChatColor.STRIKETHROUGH + "---------------------------------------------------"); evolutionPlayer.getPlayer().sendMessage(" "); evolutionPlayer.getPlayer().sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "You've evolved! New mob: " + ChatColor.RED + evolution.getCustomName()); evolutionPlayer.getPlayer().sendMessage(" "); evolutionPlayer.getPlayer().sendMessage(ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD + "Health: " + ChatColor.RED + (evolution.getHealth() / 2) + "❤"); evolutionPlayer.getPlayer().sendMessage(ChatColor.YELLOW + "" + ChatColor.BOLD + "Ability: " + ChatColor.WHITE + evolution.getItemStack().getItemMeta().getDisplayName()); evolutionPlayer.getPlayer().sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + "Ability Cooldown: " + ChatColor.WHITE + evolution.getCooldown() + "s"); evolutionPlayer.getPlayer().sendMessage(" "); evolutionPlayer.getPlayer().sendMessage(ChatColor.GREEN + "" + ChatColor.STRIKETHROUGH + "---------------------------------------------------"); Location loc = gameMap.getUpgradeLocation(Main.getInstance().getMapManager().getGame()); LivingEntity entity = (LivingEntity) loc.getWorld().spawnEntity(loc, evolution.getEntityType()); Vector entityDirection = loc.clone().subtract(loc.clone().add(5, 5, 0)).toVector(); Location newEntityLocation = loc.setDirection(entityDirection); entity.teleport(newEntityLocation); entity.setCustomName(ChatColor.GREEN + "" + ChatColor.BOLD + evolution.toString()); entity.setCustomNameVisible(true); net.minecraft.server.v1_8_R3.Entity nmsEntity = ((CraftEntity) entity).getHandle(); NBTTagCompound tag = nmsEntity.getNBTTag(); if (tag == null) tag = new NBTTagCompound(); nmsEntity.c(tag); tag.setInt("NoAI", 1); tag.setInt("Silent", 1); tag.setInt("Invulnerable", 1); nmsEntity.f(tag); evolutionPlayer.getPlayer().teleport(loc.clone().add(5, 0, 0)); evolutionPlayer.getPlayer().setWalkSpeed(0f); evolutionPlayer.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.JUMP, Integer.MAX_VALUE, 128, false, false)); Vector dir = loc.clone().subtract(evolutionPlayer.getPlayer().getEyeLocation()).toVector(); Location newLocation = evolutionPlayer.getPlayer().getLocation().setDirection(dir); evolutionPlayer.getPlayer().teleport(newLocation); LivingEntity descriptionHologram = spawnHolographicDisplay(loc.clone().add(0, 0.5f, 0), ChatColor.AQUA + "" + ChatColor.BOLD + "Ability: " + ChatColor.WHITE + evolution.getItemStack().getItemMeta().getDisplayName()); LivingEntity healthHologram = spawnHolographicDisplay(loc.clone().add(0, 1f, 0), ChatColor.RED + "" + ChatColor.BOLD + "Health: " + ChatColor.WHITE + (evolution.getHealth() / 2) + ChatColor.RED + "❤"); Bukkit.getOnlinePlayers().stream().filter(player -> !player.getUniqueId().equals(evolutionPlayer.getUUID())).forEach(player -> { me.chasertw123.minigames.core.Main.getEntityHider().hideEntity(player, descriptionHologram); me.chasertw123.minigames.core.Main.getEntityHider().hideEntity(player, healthHologram); me.chasertw123.minigames.core.Main.getEntityHider().hideEntity(player, entity); player.hidePlayer(evolutionPlayer.getPlayer()); }); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> { evolutionPlayer.getPlayer().teleport(originalLocation); entity.remove(); descriptionHologram.remove(); healthHologram.remove(); evolutionPlayer.getPlayer().getInventory().clear(); new AbstractItem(evolutionPlayer.getEvolution().getItemStack(), evolutionPlayer.getCoreUser(), 0, (type) -> { if(type == AbstractItem.InteractType.RIGHT) evolutionPlayer.tryAbility(); }); evolutionPlayer.getPlayer().getInventory().setItem(1, new cItemStack(Material.COMPASS, ChatColor.GREEN + "Player Tracker")); // un-hide the player Bukkit.getOnlinePlayers().stream().filter(player -> !player.getUniqueId().equals(evolutionPlayer.getUUID())) .forEach(player -> player.showPlayer(evolutionPlayer.getPlayer())); evolutionPlayer.getPlayer().setWalkSpeed(0.2f); evolutionPlayer.getPlayer().removePotionEffect(PotionEffectType.JUMP); // Set the player to the new mob iDisguise.getInstance().getAPI().disguise(evolutionPlayer.getPlayer(), evolution.getDisguiseType().newInstance()); // the mob to be disguised as }, 20 * 5); } public LivingEntity spawnHolographicDisplay(Location location, String text) { ArmorStand entity = (ArmorStand) location.getWorld().spawnEntity(location, EntityType.ARMOR_STAND); entity.setGravity(false); entity.setVisible(false); entity.setCustomName(text); entity.setCustomNameVisible(true); return entity; } public Location getSpawnLocation(Player p) { // return the spawn with players the furthest away List<Location> spawns = gameMap.getSpawns(Main.getInstance().getMapManager().getGame()); Map<Location, Integer> maxDistances = new HashMap<>(); for(Location location : spawns) { int maxDistance = 0; for(Player player : Bukkit.getServer().getOnlinePlayers()) if(p.getUniqueId() != player.getUniqueId() && maxDistance < player.getLocation().distance(location)) maxDistance = (int) player.getLocation().distance(location); maxDistances.put(location, maxDistance); } int maxDistance = 0; Location maxLocation = spawns.get(0); for(Map.Entry<Location, Integer> entry : maxDistances.entrySet()) { if(entry.getValue() > maxDistance) { maxDistance = entry.getValue(); maxLocation = entry.getKey(); } } return maxLocation; } private String ordinal(int i) { String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" }; switch (i % 100) { case 11: case 12: case 13: return i + "th"; default: return i + sufixes[i % 10]; } } }
4,529
https://github.com/isabella232/msgraph-beta-sdk-java/blob/master/src/main/java/com/microsoft/graph/models/extensions/DataSharingConsent.java
Github Open Source
Open Source
MIT
null
msgraph-beta-sdk-java
isabella232
Java
Code
341
836
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models.extensions; import com.microsoft.graph.serializer.ISerializer; import com.microsoft.graph.serializer.IJsonBackedObject; import com.microsoft.graph.serializer.AdditionalDataManager; import java.util.EnumSet; import com.microsoft.graph.models.extensions.Entity; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Data Sharing Consent. */ public class DataSharingConsent extends Entity implements IJsonBackedObject { /** * The Grant Date Time. * The time consent was granted for this account */ @SerializedName(value = "grantDateTime", alternate = {"GrantDateTime"}) @Expose public java.util.Calendar grantDateTime; /** * The Granted. * The granted state for the data sharing consent */ @SerializedName(value = "granted", alternate = {"Granted"}) @Expose public Boolean granted; /** * The Granted By Upn. * The Upn of the user that granted consent for this account */ @SerializedName(value = "grantedByUpn", alternate = {"GrantedByUpn"}) @Expose public String grantedByUpn; /** * The Granted By User Id. * The UserId of the user that granted consent for this account */ @SerializedName(value = "grantedByUserId", alternate = {"GrantedByUserId"}) @Expose public String grantedByUserId; /** * The Service Display Name. * The display name of the service work flow */ @SerializedName(value = "serviceDisplayName", alternate = {"ServiceDisplayName"}) @Expose public String serviceDisplayName; /** * The Terms Url. * The TermsUrl for the data sharing consent */ @SerializedName(value = "termsUrl", alternate = {"TermsUrl"}) @Expose public String termsUrl; /** * The raw representation of this class */ private JsonObject rawObject; /** * The serializer */ private ISerializer serializer; /** * Gets the raw representation of this class * * @return the raw representation of this class */ public JsonObject getRawObject() { return rawObject; } /** * Gets serializer * * @return the serializer */ protected ISerializer getSerializer() { return serializer; } /** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { this.serializer = serializer; rawObject = json; } }
18,304
https://github.com/hyxiaohaiyang/N0018-Genesis-crowd-funding/blob/master/letv-crowdfund-web/src/main/java/com/fbd/web/app/sxyPay/action/SxyPayWithDrawAction.java
Github Open Source
Open Source
Apache-2.0
2,017
N0018-Genesis-crowd-funding
hyxiaohaiyang
Java
Code
395
2,634
package com.fbd.web.app.sxyPay.action; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.fbd.core.app.sxyPay.common.ResultHandler; import com.fbd.core.app.sxyPay.common.SxyPayConstants; import com.fbd.core.app.sxyPay.common.SxyPayConstants.SyxParam; import com.fbd.core.app.sxyPay.utils.SxyPayMd5; import com.fbd.core.app.thirdtrusteeship.common.TrusteeshipConstants; import com.fbd.core.app.thirdtrusteeship.service.ITrusteeshipOperationService; import com.fbd.core.base.BaseAction; import com.fbd.core.exception.ApplicationException; import com.fbd.core.util.HttpServletUtils; import com.fbd.web.app.common.FbdConstants; import com.fbd.web.app.sxyPay.service.ISxyPayRechargeService; import com.fbd.web.app.user.service.IUserService; @Controller @Scope("prototype") @RequestMapping("/sxyPay/withDraw") public class SxyPayWithDrawAction extends BaseAction { /** * */ private static final long serialVersionUID = 583651072172660381L; private static final Logger logger = LoggerFactory.getLogger(SxyPayWithDrawAction.class); @Resource private ISxyPayRechargeService sxyPayRechargeService; @Resource private IUserService userService; @Resource private ITrusteeshipOperationService trusteeshipOperationService; @RequestMapping(value = "/withDrawNotify.html") public void withDrawNotify(HttpServletRequest request,HttpServletResponse res) throws Exception{ logger.info("---------->首信易支付充值接口同步回调开始调用============"); String result = this.receiveRechargeCallback(request); logger.info("---------->首信易支付充值接口同步回调调用结束,返回的结果为::" + result); HttpServletUtils.outString(res, "sent"); } private String receiveRechargeCallback(HttpServletRequest request) { String handlerResult = FbdConstants.RESULT_TRUE; try { //获取参数 String v_oid = request.getParameter("v_oid");//订单编号 logger.info("-----------首易信充值异步通知订单号-orderId:-->"+v_oid); String v_pmode = request.getParameter("v_pmode");//支付方式 String v_pstatus = request.getParameter("v_pstatus");//支付结果 1支付成功 3 支付失败 logger.info("-----------首易信充值异步通知支付状态-orderId:-->"+v_oid); String v_pstring = request.getParameter("v_pstring");//支付结果信息说明 logger.info("-----------首易信充值异步通知支付结果信息-pstring:-->"+v_pstring); String v_count = request.getParameter("v_count");//订单个数 logger.info("-----------首易信充值异步通知订单个数-count:-->"+v_count); String v_amount = request.getParameter("v_amount");//订单金额 logger.info("-----------首易信充值异步通知订单金额-amount:-->"+v_amount); String v_moneytype = request.getParameter("v_moneytype");//币种 logger.info("-----------首易信充值异步通知币种-moneytype:-->"+v_moneytype); String v_md5money = request.getParameter("v_md5money");//数字指纹 logger.info("-----------首易信充值异步通知数字指纹-md5money:-->"+v_md5money); String v_mac = request.getParameter("v_mac");//数字指纹 logger.info("-----------首易信充值异步通知数字指纹-v_mac:-->"+v_mac); String v_sign = request.getParameter("v_sign");//RSA数字指纹 logger.info("-----------首易信充值异步通知数字指纹-v_sign:-->"+v_sign); // v_pstring = new String(v_pstring.getBytes("utf-8")); // v_pmode = new String(v_pmode.getBytes("utf-8")); v_pstring = java.net.URLEncoder.encode(v_pstring,"utf-8"); v_pmode = java.net.URLEncoder.encode(v_pmode,"utf-8"); //拆分参数 String[] resultoid = v_oid.split("[|][_][|]"); String[] resultpmode = v_pmode.split("[|][_][|]"); String[] resultstatus = v_pstatus.split("[|][_][|]"); String[] resultpstring = v_pstring.split("[|][_][|]"); String[] resultamount = v_amount.split("[|][_][|]"); String[] resultmoneytype = v_moneytype.split("[|][_][|]"); String source1 = v_oid + v_pmode + v_pstatus + v_pstring + v_count; String source2 = v_amount +v_moneytype; logger.info("----------------->source1:"+source1); logger.info("----------------->source2:"+source2); logger.info("----------------->source1Md5:"+SxyPayMd5.createMd5(source1)); logger.info("----------------->source2Md5:"+SxyPayMd5.createMd5(source2)); if (v_mac.equals(SxyPayMd5.createMd5(source1)) && v_md5money.equals(SxyPayMd5.createMd5(source2))) { logger.info("---------------->验签通过-------------"); String status = ""; if(v_pstatus.equals("1")){//充值成功 status = TrusteeshipConstants.Status.PASSED; }else{ status = TrusteeshipConstants.Status.REFUSED; } trusteeshipOperationService.updateOperationModel(request.getParameter(SyxParam.v_oid), SxyPayConstants.BusiType.recharge, null, SxyPayConstants.THIRD_ID, status,v_pstring); if(v_pstatus.equals("1")){//充值成功 Map<String,String> resultMap = this.getMap(request); sxyPayRechargeService.updateRechargSucess(resultMap); }else{ logger.info("---------------->充值失败-------------"); } }else{ logger.info("---------------->验签失败------------"); } } catch (ApplicationException e) { handlerResult = e.getMessage(); logger.error(e.getMessage()); } catch (Exception e) { logger.error(e.getMessage()); } return handlerResult; } private String receiveRechargeCallback1(HttpServletRequest request) { String handlerResult = FbdConstants.RESULT_TRUE; try { Map<String, String> handerResultMap = ResultHandler.convert2Map(request); logger.info("------------------->充值异步通知参数:"+handerResultMap); String resultCode = handerResultMap.get("respCode"); logger.info("------------------->resultCode:"+resultCode); String respDesc = handerResultMap.get("respDesc"); String result = resultCode+";"+respDesc; String status = ""; if(resultCode.equals("20")){//充值成功 status = TrusteeshipConstants.Status.PASSED; }else{ status = TrusteeshipConstants.Status.REFUSED; } trusteeshipOperationService.updateOperationModel(request.getParameter(SyxParam.v_oid), SxyPayConstants.BusiType.recharge, null, SxyPayConstants.THIRD_ID, status, result); if(resultCode.equals("20")){//充值成功 Map<String,String> resultMap = this.getMap(request); sxyPayRechargeService.updateRechargSucess(resultMap); }else{ if(StringUtils.isEmpty(respDesc)){ respDesc = "充值失败,请联系客服!"; } throw new ApplicationException(respDesc); } logger.info("汇付宝满标投资接口回调返回的结果为::" + result); } catch (ApplicationException e) { handlerResult = e.getMessage(); logger.error(e.getMessage()); } catch (Exception e) { handlerResult = "满标投资失败,请联系客服处理"; logger.error(e.getMessage()); } return handlerResult; } private Map<String, String> getMap(HttpServletRequest request) { Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put(SyxParam.v_oid, request.getParameter(SyxParam.v_oid)); return paramMap; } }
40,731
https://github.com/Elwalle/openshift-ansible-contrib-master/blob/master/reference-architecture/gcp/3.9/bastion.sh
Github Open Source
Open Source
Apache-2.0
2,022
openshift-ansible-contrib-master
Elwalle
Shell
Code
553
3,115
#!/bin/bash set -eo pipefail warnuser(){ cat << EOF ########### # WARNING # ########### This script is distributed WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND Refer to the official documentation https://access.redhat.com/documentation/en-us/reference_architectures/2018/html-single/deploying_and_managing_openshift_3.9_on_google_cloud_platform/ EOF } die(){ echo "$1" exit $2 } usage(){ warnuser echo "$0 <vars_file>" echo " vars_file The file containing all the required variables" echo "Examples:" echo " $0 myvars" } if [[ ( $@ == "--help") || $@ == "-h" ]] then usage exit 0 fi if [[ $# -lt 1 ]] then usage die "vars_file not provided" 2 fi warnuser VARSFILE=${1} if [[ ! -f ${VARSFILE} ]] then usage die "vars_file not found" 2 fi read -p "Are you sure? " -n 1 -r echo # (optional) move to a new line if [[ ! $REPLY =~ ^[Yy]$ ]] then die "User cancel" 4 fi source ${VARSFILE} if [ -z $RHUSER ]; then sudo subscription-manager register --activationkey=${AK} --org=${ORGID} else sudo subscription-manager register --user=${RHUSER} --password=${RHPASS} fi sudo subscription-manager attach --pool=${POOLID} sudo subscription-manager repos --disable="*" \ --enable="rhel-7-server-rpms" \ --enable="rhel-7-server-extras-rpms" \ --enable="rhel-7-server-ose-${OCPVER}-rpms" \ --enable="rhel-7-fast-datapath-rpms" \ --enable="rhel-7-server-ansible-2.4-rpms" sudo yum install atomic-openshift-utils tmux -y sudo yum update -y cat <<'EOF' > ./ansible.cfg [defaults] forks = 20 host_key_checking = False remote_user = MYUSER roles_path = roles/ gathering = smart fact_caching = jsonfile fact_caching_connection = $HOME/ansible/facts fact_caching_timeout = 600 log_path = $HOME/ansible.log nocows = 1 callback_whitelist = profile_tasks [ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=600s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=false -o ForwardAgent=yes control_path = %(directory)s/%%h-%%r pipelining = True timeout = 10 [persistent_connection] connect_timeout = 30 connect_retries = 30 connect_interval = 1 EOF sed -i -e "s/MYUSER/${MYUSER}/g" ./ansible.cfg cat <<'EOF' > ./inventory [OSEv3:children] masters etcd nodes glusterfs [OSEv3:vars] ansible_become=true openshift_release=vOCPVER os_firewall_use_firewalld=True openshift_clock_enabled=true openshift_cloudprovider_kind=gce openshift_gcp_project=PROJECTID openshift_gcp_prefix=CLUSTERID # If deploying single zone cluster set to "False" openshift_gcp_multizone="True" openshift_gcp_network_name=CLUSTERID-net openshift_master_api_port=443 openshift_master_console_port=443 openshift_node_local_quota_per_fsgroup=512Mi openshift_hosted_registry_replicas=1 openshift_hosted_registry_storage_kind=object openshift_hosted_registry_storage_provider=gcs openshift_hosted_registry_storage_gcs_bucket=CLUSTERID-registry openshift_master_cluster_method=native openshift_master_cluster_hostname=CLUSTERID-ocp.DOMAIN openshift_master_cluster_public_hostname=CLUSTERID-ocp.DOMAIN openshift_master_default_subdomain=CLUSTERID-apps.DOMAIN os_sdn_network_plugin_name=redhat/openshift-ovs-networkpolicy deployment_type=openshift-enterprise # Required per https://access.redhat.com/solutions/3480921 oreg_url=registry.access.redhat.com/openshift3/ose-${component}:${version} openshift_examples_modify_imagestreams=true openshift_storage_glusterfs_image=registry.access.redhat.com/rhgs3/rhgs-server-rhel7 openshift_storage_glusterfs_block_image=registry.access.redhat.com/rhgs3/rhgs-gluster-block-prov-rhel7 openshift_storage_glusterfs_s3_image=registry.access.redhat.com/rhgs3/rhgs-s3-server-rhel7 openshift_storage_glusterfs_heketi_image=registry.access.redhat.com/rhgs3/rhgs-volmanager-rhel7 # Service catalog openshift_hosted_etcd_storage_kind=dynamic openshift_hosted_etcd_storage_volume_name=etcd-vol openshift_hosted_etcd_storage_access_modes=["ReadWriteOnce"] openshift_hosted_etcd_storage_volume_size=SC_STORAGE openshift_hosted_etcd_storage_labels={'storage': 'etcd'} # Metrics openshift_metrics_install_metrics=true openshift_metrics_cassandra_storage_type=dynamic openshift_metrics_storage_volume_size=METRICS_STORAGE openshift_metrics_cassandra_nodeselector={"region":"infra"} openshift_metrics_hawkular_nodeselector={"region":"infra"} openshift_metrics_heapster_nodeselector={"region":"infra"} # Aggregated logging openshift_logging_install_logging=true openshift_logging_es_pvc_dynamic=true openshift_logging_es_pvc_size=LOGGING_STORAGE openshift_logging_es_cluster_size=3 openshift_logging_es_nodeselector={"region":"infra"} openshift_logging_kibana_nodeselector={"region":"infra"} openshift_logging_curator_nodeselector={"region":"infra"} openshift_logging_es_number_of_replicas=1 openshift_master_identity_providers=[{'name': 'htpasswd_auth','login': 'true','challenge': 'true','kind': 'HTPasswdPasswordIdentityProvider','filename': '/etc/origin/master/htpasswd'}] openshift_master_htpasswd_users={'admin': 'HTPASSWD'} openshift_hosted_prometheus_deploy=true openshift_prometheus_node_selector={"region":"infra"} openshift_prometheus_storage_type=pvc [masters] CLUSTERID-master-0 CLUSTERID-master-1 CLUSTERID-master-2 [etcd] CLUSTERID-master-0 CLUSTERID-master-1 CLUSTERID-master-2 [nodes] CLUSTERID-master-0 openshift_node_labels="{'region': 'master'}" CLUSTERID-master-1 openshift_node_labels="{'region': 'master'}" CLUSTERID-master-2 openshift_node_labels="{'region': 'master'}" CLUSTERID-infra-0 openshift_node_labels="{'region': 'infra', 'node-role.kubernetes.io/infra': 'true'}" CLUSTERID-infra-1 openshift_node_labels="{'region': 'infra', 'node-role.kubernetes.io/infra': 'true'}" CLUSTERID-infra-2 openshift_node_labels="{'region': 'infra', 'node-role.kubernetes.io/infra': 'true'}" CLUSTERID-app-0 openshift_node_labels="{'region': 'apps'}" CLUSTERID-app-1 openshift_node_labels="{'region': 'apps'}" CLUSTERID-app-2 openshift_node_labels="{'region': 'apps'}" CLUSTERID-cns-0 openshift_node_labels="{'region': 'cns', 'node-role.kubernetes.io/cns': 'true'}" CLUSTERID-cns-1 openshift_node_labels="{'region': 'cns', 'node-role.kubernetes.io/cns': 'true'}" CLUSTERID-cns-2 openshift_node_labels="{'region': 'cns', 'node-role.kubernetes.io/cns': 'true'}" [glusterfs] CLUSTERID-cns-0 glusterfs_devices='[ "/dev/disk/by-id/google-CLUSTERID-cns-0-gluster" ]' openshift_node_local_quota_per_fsgroup="" CLUSTERID-cns-1 glusterfs_devices='[ "/dev/disk/by-id/google-CLUSTERID-cns-1-gluster" ]' openshift_node_local_quota_per_fsgroup="" CLUSTERID-cns-2 glusterfs_devices='[ "/dev/disk/by-id/google-CLUSTERID-cns-2-gluster" ]' openshift_node_local_quota_per_fsgroup="" EOF sed -i -e "s/MYUSER/${MYUSER}/g" \ -e "s/OCPVER/${OCPVER}/g" \ -e "s/CLUSTERID/${CLUSTERID}/g" \ -e "s/PROJECTID/${PROJECTID}/g" \ -e "s/DOMAIN/${DOMAIN}/g" \ -e "s/HTPASSWD/${HTPASSWD}/g" \ -e "s/LOGGING_STORAGE/${LOGGING_STORAGE}/g" \ -e "s/METRICS_STORAGE/${METRICS_STORAGE}/g" \ -e "s/SC_STORAGE/${SC_STORAGE}/g" \ ./inventory if [ -z $RHUSER ]; then ansible nodes -i inventory -b -m redhat_subscription -a \ "state=present activationkey=${AK} org_id=${ORGID} pool_ids=${POOLID}" else ansible nodes -i inventory -b -m redhat_subscription -a \ "state=present user=${RHUSER} password=${RHPASS} pool_ids=${POOLID}" fi ansible nodes -i inventory -b -m shell -a \ "subscription-manager repos --disable=\* \ --enable=rhel-7-server-rpms \ --enable=rhel-7-server-extras-rpms \ --enable=rhel-7-server-ose-${OCPVER}-rpms \ --enable=rhel-7-fast-datapath-rpms \ --enable=rhel-7-server-ansible-2.4-rpms" ansible *-infra-* -i inventory -b -m firewalld -a \ "port=1936/tcp permanent=true state=enabled" ansible nodes -i inventory -b -m firewalld -a \ "port=10256/tcp permanent=true state=enabled" ansible all -i inventory -b -m yum -a "name=* state=latest" ansible all -i inventory -b -m command -a "reboot"
45,184
https://github.com/cmoser8892/MoleDymCode/blob/master/Sourcefiles/clusterGenerator.cpp
Github Open Source
Open Source
MIT
null
MoleDymCode
cmoser8892
C++
Code
1,120
2,986
// // ih.C // // Create Mackay icosaheron structure. // // Written by: Yanting Wang 07/21/2003 // #include "../Headerfiles/clusterGenerator.h" #include "../Headerfiles/xyz.h" #include <iostream> #include <stdlib.h> #include <libgen.h> struct Particle { char s[10]; Vector v; }*p; struct Edge { int i; int j; }e[30]; struct Facet { int i; int j; int k; }f[30]; Vector b[12]; // basic vectors of the edges int num=0; // // function np // // Calculate number of particles on the nth layer. // int np( int n ) { if( n<0 ) return -1; else if( n==0 ) return 1; else if( n==1 ) return 12; else if( n==2 ) return 42; else { int count = 0; count += 12; // edge particles count += (n-1)*30; // side particles for( int i=1; i<=n-2; i++ ) count += i*20; // body particles return count; } } // // function init // // Initialize some constants. // void init() { p = NULL; // // Initialize basic vectors. // const double HT = ( sqrt(5.0) + 1.0 ) / 4.0; // half Tao b[0] = Vector( HT, 0.0, 0.5 ); b[1] = Vector( HT, 0.0, -0.5 ); b[2] = Vector( 0.5, HT, 0.0 ); b[3] = Vector( -0.5, HT, 0.0 ); b[4] = Vector( 0.0, 0.5, HT ); b[5] = Vector( 0.0, -0.5, HT ); b[6] = Vector( 0.5, -HT, 0.0 ); b[7] = Vector( 0.0, 0.5, -HT ); b[8] = Vector( -HT, 0.0, 0.5 ); b[9] = Vector( 0.0, -0.5, -HT ); b[10] = Vector( -HT, 0.0, -0.5 ); b[11] = Vector( -0.5, -HT, 0.0 ); // // Initialize 30 edges // e[0].i = 0; e[0].j = 1; e[1].i = 0; e[1].j = 2; e[2].i = 0; e[2].j = 4; e[3].i = 0; e[3].j = 5; e[4].i = 0; e[4].j = 6; e[5].i = 10; e[5].j = 3; e[6].i = 10; e[6].j = 7; e[7].i = 10; e[7].j = 8; e[8].i = 10; e[8].j = 9; e[9].i = 10; e[9].j = 11; e[10].i = 1; e[10].j = 2; e[11].i = 1; e[11].j = 6; e[12].i = 1; e[12].j = 7; e[13].i = 1; e[13].j = 9; e[14].i = 8; e[14].j = 3; e[15].i = 8; e[15].j = 4; e[16].i = 8; e[16].j = 5; e[17].i = 8; e[17].j = 11; e[18].i = 2; e[18].j = 3; e[19].i = 2; e[19].j = 4; e[20].i = 2; e[20].j = 7; e[21].i = 11; e[21].j = 5; e[22].i = 11; e[22].j = 6; e[23].i = 11; e[23].j = 9; e[24].i = 6; e[24].j = 5; e[25].i = 6; e[25].j = 9; e[26].i = 3; e[26].j = 4; e[27].i = 3; e[27].j = 7; e[28].i = 7; e[28].j = 9; e[29].i = 5; e[29].j = 4; // // Initialize 20 facets // f[0].i = 0; f[0].j = 1; f[0].k = 2; f[1].i = 0; f[1].j = 2; f[1].k = 4; f[2].i = 0; f[2].j = 4; f[2].k = 5; f[3].i = 0; f[3].j = 5; f[3].k = 6; f[4].i = 0; f[4].j = 1; f[4].k = 6; f[5].i = 10; f[5].j = 3; f[5].k = 7; f[6].i = 10; f[6].j = 3; f[6].k = 8; f[7].i = 10; f[7].j = 8; f[7].k = 11; f[8].i = 10; f[8].j = 9; f[8].k = 11; f[9].i = 10; f[9].j = 7; f[9].k = 9; f[10].i = 1; f[10].j = 2; f[10].k = 7; f[11].i = 1; f[11].j = 7; f[11].k = 9; f[12].i = 1; f[12].j = 6; f[12].k = 9; f[13].i = 8; f[13].j = 5; f[13].k = 11; f[14].i = 8; f[14].j = 4; f[14].k = 5; f[15].i = 8; f[15].j = 3; f[15].k = 4; f[16].i = 2; f[16].j = 3; f[16].k = 7; f[17].i = 2; f[17].j = 3; f[17].k = 4; f[18].i = 11; f[18].j = 5; f[18].k = 6; f[19].i = 11; f[19].j = 6; f[19].k = 9; } // // function ih // // Create nth layer particles. Return the number of particles on this layer. // The distance between nearest neighbors has the unit length of 1. void ih( int n ) { if( n < 0 ) return; int count = num; num += np( n ); p = (Particle *)realloc( p, num * sizeof(Particle) ); if( n==0 ) // center particle only { strcpy( p[0].s, "Au" ); p[0].v = Vector( 0.0, 0.0, 0.0 ); return; } // // Generate edge particles // for( int i=0; i<12; i++ ) { strcpy( p[count].s, "Au" ); p[count].v = b[i] * n; count++; } // // Generate side particles // if( n<2 ) return; for( int i=0; i<30; i++ ) { Vector e1 = b[ e[i].i ] * n; Vector e2 = b[ e[i].j ] * n; for( int j=1; j<=n-1; j++ ) { strcpy( p[count].s, "Au" ); p[count].v = e1 + (e2-e1) * j / double(n); count++; } } // // Generate body particles // if( n<3 ) return; for( int i=0; i<20; i++ ) { Vector e1 = b[ f[i].i ] * n; Vector e2 = b[ f[i].j ] * n; Vector e3 = b[ f[i].k ] * n; for( int j=1; j<=n-2; j++ ) { Vector v1 = e1 + (e2-e1) * (j+1) / double(n); Vector v2 = e1 + (e3-e1) * (j+1) / double(n); for( int k=1; k<=j; k++ ) { strcpy( p[count].s, "Au" ); p[count].v = v1 + (v2-v1) * k / double(j+1); count++; } } } } bool onceClusters = false; /** * @fn int generateCluster( int argc, char *argv[] ) * @brief generates the clusters depending on the variables (clearly not myn) dont use more than once per program Run !!! will produce corrupted files * @param argc * @param argv * @return */ int generateCluster( int argc, char *argv[] ) { if(onceClusters == false) { onceClusters = true; } else { std::cerr << "Dont run more than once per global run !!!!!!" << std::endl; return -10; } if( argc < 4 ) { std::cerr << "Usage: " << basename( argv[0] ) << " #_of_layers unit_length" << std::endl; std::cerr << "If unit_length<=0, only the total particle number " << "will be reported." << std::endl; return -1; } int n = atoi( argv[1] ); double d = atof( argv[2] ); if( n < 0 ) { std::cerr << "n=" << n << ": #_of_layers must >=0." << std::endl; return -2; } if( d <= 0.0 ) { int count=0; for( int i=0; i<=n; i++ ) count += np( i ); std::cout << count << std::endl; return 0; } //starting here init(); //generate for( int i=0; i<=n; i++ ) { ih( i ); } std::ofstream file(argv[3]); //output with .xyz format file << num << std::endl; file << std::endl; for( int i=0; i<num; i++ ) { file << p[i].s << " " << p[i].v*d << std::endl; } file.close(); return 0; }
8,920
https://github.com/IIGhouLII/IITC_Ingress/blob/master/keys.user.js
Github Open Source
Open Source
MIT
null
IITC_Ingress
IIGhouLII
JavaScript
Code
1,415
6,191
// ==UserScript== // @id iitc-plugin-keys@xelio // @name IITC plugin: Keys // @category Keys // @version 0.3.0.20161003.4740 // @namespace https://github.com/jonatkins/ingress-intel-total-conversion // @updateURL https://static.iitc.me/build/release/plugins/keys.meta.js // @downloadURL https://static.iitc.me/build/release/plugins/keys.user.js // @description [iitc-2016-10-03-004740] Allow manual entry of key counts for each portal. Use the 'keys-on-map' plugin to show the numbers on the map, and 'sync' to share between multiple browsers or desktop/mobile. // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript== function wrapper(plugin_info) { // ensure plugin framework is there, even if iitc is not yet loaded if(typeof window.plugin !== 'function') window.plugin = function() {}; //PLUGIN AUTHORS: writing a plugin outside of the IITC build environment? if so, delete these lines!! //(leaving them in place might break the 'About IITC' page or break update checks) plugin_info.buildName = 'iitc'; plugin_info.dateTimeVersion = '20161003.4740'; plugin_info.pluginId = 'keys'; //END PLUGIN AUTHORS NOTE // PLUGIN START //////////////////////////////////////////////////////// // use own namespace for plugin window.plugin.keys = function() {}; // delay in ms window.plugin.keys.SYNC_DELAY = 5000; window.plugin.keys.LOCAL_STORAGE_KEY = 'plugin-keys-data'; window.plugin.keys.KEY = {key: 'plugin-keys-data', field: 'keys'}; window.plugin.keys.UPDATE_QUEUE = {key: 'plugin-keys-data-queue', field: 'updateQueue'}; window.plugin.keys.UPDATING_QUEUE = {key: 'plugin-keys-data-updating-queue', field: 'updatingQueue'}; window.plugin.keys.CapsuleID=0 window.plugin.keys.keys = []; window.plugin.keys.updateQueue = []; window.plugin.keys.updatingQueue = []; window.plugin.keys.NCapsules=11; for (i = 0; i < plugin.keys.NCapsules; i++) { window.plugin.keys.keys[i] = {"TOTAL":0}; window.plugin.keys.updateQueue[i] = {"TOTAL":0}; window.plugin.keys.updatingQueue[i] = {"TOTAL":0}; } window.plugin.keys.enableSync = false; window.plugin.keys.disabledMessage = null; window.plugin.keys.contentHTML = null; window.plugin.keys.addToSidebar = function() { if(typeof(Storage) === "undefined") { $('#portaldetails > .imgpreview').after(plugin.keys.disabledMessage); return; } $('#portaldetails > .imgpreview').after(plugin.keys.contentHTML); plugin.keys.updateDisplayCount(); } window.plugin.keys.updateDisplayCount = function() { var guid = window.selectedPortal; var count = plugin.keys.keys[plugin.keys.CapsuleID][guid] || 0; $('#keys-count').html(count); switch (plugin.keys.CapsuleID) { case 0: $('#Capsule-count').html("All"); break; case 1: $('#Capsule-count').html("G"); break; case 2: $('#Capsule-count').html("B"); break; case 3: $('#Capsule-count').html("W"); break; case 4: $('#Capsule-count').html("R"); break; case 5: $('#Capsule-count').html("Y"); break; default: $('#Capsule-count').html(plugin.keys.CapsuleID); break; } $('#Total-count').html(plugin.keys.keys[plugin.keys.CapsuleID]['TOTAL'] ||0 ); } window.plugin.keys.changeCapsuleID = function(addCount) { plugin.keys.CapsuleID=Math.min(Math.max(plugin.keys.CapsuleID + addCount, 0),plugin.keys.NCapsules-1); plugin.keys.updateDisplayCount(); window.runHooks('pluginKeysRefreshAll'); } window.plugin.keys.addKey = function(addCount, guid) { if (plugin.keys.CapsuleID==0) return; if(guid == undefined) guid = window.selectedPortal; // if (plugin.keys.keys[plugin.keys.CapsuleID]==undefined) // var oldCount = 0; // else // var oldCount = (plugin.keys.keys[plugin.keys.CapsuleID][guid]|| 0); var oldCount = (plugin.keys.keys[plugin.keys.CapsuleID][guid]|| 0); var newCount = Math.max(oldCount + addCount, 0); if(oldCount !== newCount) { if(newCount === 0) { delete plugin.keys.keys[plugin.keys.CapsuleID][guid]; plugin.keys.updateQueue[plugin.keys.CapsuleID][guid] = null; } else { // if (plugin.keys.keys[plugin.keys.CapsuleID]==undefined) plugin.keys.keys[plugin.keys.CapsuleID] = {}; // if (plugin.keys.updateQueue[plugin.keys.CapsuleID]==undefined) plugin.keys.updateQueue[plugin.keys.CapsuleID] = {}; // if (plugin.keys.Total[plugin.keys.CapsuleID]==undefined) plugin.keys.Total[plugin.keys.CapsuleID] = 0; plugin.keys.keys[plugin.keys.CapsuleID][guid] = newCount plugin.keys.updateQueue[plugin.keys.CapsuleID][guid] = newCount; } plugin.keys.keys[0][guid] = (plugin.keys.keys[0][guid] || 0) +newCount-oldCount; plugin.keys.updateQueue[0][guid] = plugin.keys.keys[0][guid]; if (plugin.keys.keys[0][guid]==0){ delete plugin.keys.keys[0][guid]; plugin.keys.updateQueue[0][guid] = null; } plugin.keys.keys[plugin.keys.CapsuleID]['TOTAL']=plugin.keys.keys[plugin.keys.CapsuleID]['TOTAL']+newCount-oldCount; plugin.keys.keys[0]['TOTAL']=plugin.keys.keys[0]['TOTAL']+newCount-oldCount; plugin.keys.updateQueue[plugin.keys.CapsuleID]['TOTAL']=plugin.keys.updateQueue[plugin.keys.CapsuleID]['TOTAL']+newCount-oldCount; plugin.keys.updateQueue[0]['TOTAL']=plugin.keys.updateQueue[0]['TOTAL']+newCount-oldCount; // if ((plugin.keys.CapsuleID==plugin.keys.keys.length-1)&&(plugin.keys.Total[plugin.keys.CapsuleID]==0)) { // // console.log("Passed by here"); // plugin.keys.keys.splice(plugin.keys.CapsuleID,1); // plugin.keys.Total.splice(plugin.keys.CapsuleID,1); // for (Index=1; Index<plugin.keys.CapsuleID;Index++){ // if (plugin.keys.Total[plugin.keys.CapsuleID-Index]!=0) // break; // plugin.keys.keys.splice(plugin.keys.CapsuleID-Index,1); // plugin.keys.Total.splice(plugin.keys.CapsuleID-Index,1); // } // plugin.keys.CapsuleID=plugin.keys.CapsuleID-Index; // } plugin.keys.storeLocal(plugin.keys.KEY); plugin.keys.storeLocal(plugin.keys.UPDATE_QUEUE); plugin.keys.updateDisplayCount(); window.runHooks('pluginKeysUpdateKey', {guid: guid, count: newCount}); plugin.keys.delaySync(); } } // Delay the syncing to group a few updates in a single request window.plugin.keys.delaySync = function() { if(!plugin.keys.enableSync) return; clearTimeout(plugin.keys.delaySync.timer); plugin.keys.delaySync.timer = setTimeout(function() { plugin.keys.delaySync.timer = null; window.plugin.keys.syncNow(); }, plugin.keys.SYNC_DELAY); } // Store the updateQueue in updatingQueue and upload window.plugin.keys.syncNow = function() { if(!plugin.keys.enableSync) return; $.extend(plugin.keys.updatingQueue, plugin.keys.updateQueue); window.plugin.keys.updateQueue = []; for (i = 0; i < plugin.keys.NCapsules; i++) { window.plugin.keys.updateQueue[i] = {"TOTAL":0}; } plugin.keys.storeLocal(plugin.keys.UPDATING_QUEUE); plugin.keys.storeLocal(plugin.keys.UPDATE_QUEUE); // plugin.sync.updateMap('keys', 'keys', Object.keys(plugin.keys.updatingQueue)); plugin.sync.updateMap('keys', 'keys', plugin.keys.updatingQueue); } // Call after IITC and all plugin loaded window.plugin.keys.registerFieldForSyncing = function() { if(!window.plugin.sync) return; window.plugin.sync.registerMapForSync('keys', 'keys', window.plugin.keys.syncCallback, window.plugin.keys.syncInitialed); } // Call after local or remote change uploaded window.plugin.keys.syncCallback = function(pluginName, fieldName, e, vv,fullUpdated) { console.warn("Keys: I am in syncCallback"); if(fieldName === 'keys') { plugin.keys.storeLocal(plugin.keys.KEY); // All data is replaced if other client update the data during this client offline, // fire 'pluginKeysRefreshAll' to notify a full update if(fullUpdated) { plugin.keys.updateDisplayCount(); window.runHooks('pluginKeysRefreshAll'); return; } if(!e) return; if(e.isLocal) { console.warn("Keys: e.isLocal: True"); // Update pushed successfully, remove it from updatingQueue delete plugin.keys.updatingQueue[vv][e.property]; } else { console.warn("Keys: e.isLocal: False"); // Remote update delete plugin.keys.updateQueue[vv][e.property]; plugin.keys.storeLocal(plugin.keys.UPDATE_QUEUE); plugin.keys.updateDisplayCount(); console.warn("Keys:pluginKeysUpdateKey guid="+JSON.stringify(e.property)+ ", count="+plugin.keys.keys[vv][e.property]); window.runHooks('pluginKeysUpdateKey', {guid: e.property, count: plugin.keys.keys[vv][e.property]}); } } } // SyncCode // syncing of the field is initialed, upload all queued update window.plugin.keys.syncInitialed = function(pluginName, fieldName) { if(fieldName === 'keys') { plugin.keys.enableSync = true; if(Object.keys(plugin.keys.updateQueue[0]).length > 0) { console.warn("Keys: I just initiated sync"); plugin.keys.delaySync(); } } } window.plugin.keys.storeLocal = function(mapping) { if(typeof(plugin.keys[mapping.field]) !== 'undefined' && plugin.keys[mapping.field] !== null) { var len=plugin.keys[mapping.field].length localStorage[mapping.key] = JSON.stringify(plugin.keys[mapping.field].slice(1,len)); } else { localStorage.removeItem(mapping.key); } } window.plugin.keys.loadLocal = function(mapping) { var objectJSON = localStorage[mapping.key]; if (!objectJSON) return; plugin.keys[mapping.field] = mapping.convertFunc ? mapping.convertFunc(JSON.parse(objectJSON)) : JSON.parse(objectJSON); if (plugin.keys[mapping.field].length==0) { plugin.keys[mapping.field][0]={"TOTAL":0}; }else{ plugin.keys[mapping.field].splice(0 , 0, {}); plugin.keys[mapping.field][0]=Object.assign({}, plugin.keys[mapping.field][1]); for (i = 2; i < plugin.keys[mapping.field].length; i++) { plugin.keys[mapping.field][0] = window.plugin.keys.mergeKeys(plugin.keys[mapping.field][0] , plugin.keys[mapping.field][i]); } } } // For backward compatibility, will change to use loadLocal after a few version // window.plugin.keys.loadKeys = function() { // var keysObjectJSON = localStorage[plugin.keys.KEY.key]; // if(!keysObjectJSON) return; // var keysObject = JSON.parse(keysObjectJSON); // // Move keys data up one level, it was {keys: keys_data} in localstorage in previous version // plugin.keys.keys = keysObject.keys ? keysObject.keys : keysObject; // if(keysObject.keys) plugin.keys.storeLocal(plugin.keys.KEY); // } window.plugin.keys.setupCSS = function() { $("<style>") .prop("type", "text/css") .html("#keys-content-outer {\n display: table;\n width: 100%;\n height: 26px;\n text-align: center;\n}\n\n\ #keys-content-outer > div{\n display: inline-block;\n vertical-align: middle;\n margin: 6px 3px 1px 3px;\n}\n\n\ \ #Capsule-add {\n}\n\n\ #Capsule-count {\n width: 26px;\n height: 18px !important;\n border: 1px solid;\n text-align: center;\n}\n\n\ #Capsule-subtract {\n}\n\n\ .Capsule-button {\n position:relative;\n width: 16px;\n height: 16px !important;\n}\n\n\ .Capsule-button > div {\n background-color: rgb(32, 168, 177);\n position: absolute;\n}\n\n\ .Capsule-button-minus {\n width: 100%;\n height: 4px;\n top: 6px;\n}\n\n\ .Capsule-button-plus-h {\n width: 100%;\n height: 4px;\n top: 6px;\n}\n\n\ .Capsule-button-plus-v {\n width: 4px;\n height: 100%;\n left: 6px;\n}\n\n\ \ #keys-add {\n}\n\n\ #keys-count {\n width: 26px;\n height: 18px !important;\n border: 1px solid;\n text-align: center;\n}\n\n\ #keys-subtract {\n}\n\n\ .keys-button {\n position:relative;\n width: 16px;\n height: 16px !important;\n}\n\n\ .keys-button > div {\n background-color: rgb(32, 168, 177);\n position: absolute;\n}\n\n\ .keys-button-minus {\n width: 100%;\n height: 4px;\n top: 6px;\n}\n\n\ .keys-button-plus-h {\n width: 100%;\n height: 4px;\n top: 6px;\n}\n\n\ .keys-button-plus-v {\n width: 4px;\n height: 100%;\n left: 6px;\n}\n\n\ #Total-count {\n width: 26px;\n height: 18px !important;\n border: 1px solid;\n text-align: center;\n}\n\n\ \ .portal-list-keys button {\n font-family: monospace;\n font-size: 0.9em;\n text-align: center;\n vertical-align: middle;\n min-width: 0;\n padding: 0;\n width: 1.5em;\n margin: -6px 0 -3px;\n}\n\ #portalslist.mobile .portal-list-keys button {\n width: 3em;\n height: 1.5em;\n}\n\ .portal-list-keys .plus {\n margin-left: 0.3em;\n margin-right: -1px;\n}\n\n" ) .appendTo("head"); } window.plugin.keys.setupContent = function() { plugin.keys.contentHTML = '<div id="keys-content-outer">' + '<div id="Capsule-add" class="Capsule-button" onclick="window.plugin.keys.changeCapsuleID(-1);"> <div class="Capsule-button-minus"></div> </div>' + '<div id="Capsule-count" title="Choose a Capsule"></div>' + '<div id="Capsule-subtract" class="Capsule-button" onclick="window.plugin.keys.changeCapsuleID(1);"> <div class="Capsule-button-plus-v"></div> <div class="Capsule-button-plus-h"></div> </div>' + '<div> &nbsp&nbsp&nbsp </div>' + '<div id="keys-add" class="keys-button" onclick="window.plugin.keys.addKey(-1);"> <div class="keys-button-minus"></div> </div>' + '<div id="keys-count" title="Number of keys for this Portal in Capsule"></div>' + '<div id="keys-subtract" class="keys-button" onclick="window.plugin.keys.addKey(1);"><div class="keys-button-plus-v"></div><div class="keys-button-plus-h"></div></div>' + '<div> &nbsp&nbsp&nbsp </div>' + '<div id="Total-count" title="Total number of keys in Capsule"></div>' + '</div>'; plugin.keys.disabledMessage = '<div id="keys-content-outer" title="Your browser do not support localStorage">Plugin Keys disabled</div>'; } window.plugin.keys.setupPortalsList = function() { if(!window.plugin.portalslist) return; window.addHook('pluginKeysUpdateKey', function(data) { $('[data-list-keycount="'+data.guid+'"]').text(data.count || 0); }); window.addHook('pluginKeysRefreshAll', function() { $('[data-list-keycount]').each(function(i, element) { var guid = element.getAttribute("data-list-keycount"); if (plugin.keys.CapsuleID==plugin.keys.keys.length) $(element).text(0); else $(element).text((plugin.keys.keys[plugin.keys.CapsuleID][guid] || 0)); }); }); window.plugin.portalslist.fields.push({ title: "Keys", value: function(portal) { return portal.options.guid; }, // we store the guid, but implement a custom comparator so the list does sort properly without closing and reopening the dialog sort: function(guidA, guidB) { if (plugin.keys.CapsuleID==plugin.keys.keys.length){ var keysA = 0; var keysB = 0; }else{ var keysA = plugin.keys.keys[plugin.keys.CapsuleID][guidA] || 0; var keysB = plugin.keys.keys[plugin.keys.CapsuleID][guidB] || 0; } return keysA - keysB; }, format: function(cell, portal, guid) { $(cell) .addClass("alignR portal-list-keys ui-dialog-buttonset") // ui-dialog-buttonset for proper button styles .append($('<span>') .text(plugin.keys.keys[plugin.keys.CapsuleID][guid] || 0) .attr({ "class": "value", "data-list-keycount": guid })); // for some reason, jQuery removes event listeners when the list is sorted. Therefore we use DOM's addEventListener $('<button>') .text('+') .addClass("plus") .appendTo(cell) [0].addEventListener("click", function() { window.plugin.keys.addKey(1, guid); }, false); $('<button>') .text('-') .addClass("minus") .appendTo(cell) [0].addEventListener("click", function() { window.plugin.keys.addKey(-1, guid); }, false); }, }); } var setup = function() { if($.inArray('pluginKeysUpdateKey', window.VALID_HOOKS) < 0) window.VALID_HOOKS.push('pluginKeysUpdateKey'); if($.inArray('pluginKeysRefreshAll', window.VALID_HOOKS) < 0) window.VALID_HOOKS.push('pluginKeysRefreshAll'); window.plugin.keys.setupCSS(); window.plugin.keys.setupContent(); window.plugin.keys.loadLocal(plugin.keys.KEY); window.plugin.keys.loadLocal(plugin.keys.UPDATE_QUEUE); window.addHook('portalDetailsUpdated', window.plugin.keys.addToSidebar); window.addHook('iitcLoaded', window.plugin.keys.registerFieldForSyncing); if(window.plugin.portalslist) { window.plugin.keys.setupPortalsList(); } else { setTimeout(function() { if(window.plugin.portalslist) window.plugin.keys.setupPortalsList(); }, 500); } } window.plugin.keys.mergeKeys = function (obj, src) { for (var key in src) { if (src.hasOwnProperty(key)) obj[key] = (obj[key]||0) + src[key]; } return obj; } // PLUGIN END ////////////////////////////////////////////////////////// setup.info = plugin_info; //add the script info data to the function as a property if(!window.bootPlugins) window.bootPlugins = []; window.bootPlugins.push(setup); // if IITC has already booted, immediately run the 'setup' function if(window.iitcLoaded && typeof setup === 'function') setup(); } // wrapper end // inject code into site context var script = document.createElement('script'); var info = {}; if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description }; script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');')); (document.body || document.head || document.documentElement).appendChild(script);
13,050
https://github.com/npocmaka/Windows-Server-2003/blob/master/com/netfx/src/framework/winforms/managed/system/winforms/propertyvaluechangedeventhandler.cs
Github Open Source
Open Source
Unlicense
2,021
Windows-Server-2003
npocmaka
C#
Code
64
183
//------------------------------------------------------------------------------ // <copyright file="PropertyValueChangedEventHandler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Diagnostics; using System; using System.ComponentModel; /// <include file='doc\PropertyValueChangedEventHandler.uex' path='docs/doc[@for="PropertyValueChangedEventHandler"]/*' /> /// <devdoc> /// The event handler class that is invoked when a property /// in the grid is modified by the user. /// </devdoc> public delegate void PropertyValueChangedEventHandler(object s, PropertyValueChangedEventArgs e); }
28,773
https://github.com/DavidArppe/GameOff2020/blob/master/Assets/Misc/Terra/Source/Graph/Generators/AbsFractalNoiseNode.cs
Github Open Source
Open Source
MIT
null
GameOff2020
DavidArppe
C#
Code
47
123
namespace Terra.Graph.Generators { public abstract class AbsFractalNoiseNode: AbsGeneratorNode { [Input] public float Frequency = 1f; [Input] public float Lacunarity = 2.17f; [Input] public int OctaveCount = 6; [Input] public bool Tiling = true; [Input] public float Period = 1f; protected const string MENU_PARENT_NAME = "Terrain/Noise/"; } }
45,034
https://github.com/wyatt-howe/1-out-of-n/blob/master/demo/io-example.js
Github Open Source
Open Source
MIT
2,021
1-out-of-n
wyatt-howe
JavaScript
Code
141
384
/* * Client-Server Communications */ var listeners = {}; var mailbox = {}; const dummy_socket = computation_id => ({ get: function (op_id, session_id, tag) { return new Promise(function (resolve) { tag = computation_id + ':' + op_id + ':' + session_id + ':' + tag; if (mailbox[tag] == null) { // console.log('io.get', tag, 'not ready'); listeners[tag] = resolve; } else { // console.log('io.get', tag, mailbox[tag]); resolve(mailbox[tag]); mailbox[tag] = undefined; } }); }, give: function (op_id, session_id, tag, msg) { tag = computation_id + ':' + op_id + ':' + session_id + ':' + tag; // console.log('io.give', tag, msg); if (listeners[tag] == null) { mailbox[tag] = msg; } else { listeners[tag](msg); listeners[tag] = undefined; } }, listen: function (get, tag, callback, op_id) { get = get.bind(null, op_id); (function thunk(f) { get(tag).then(function (msg) { f(msg); thunk(f); }); }(callback)); } }); module.exports = dummy_socket('example');
47,408
https://github.com/pmaciel/climetlab/blob/master/climetlab/vocabularies/aliases.py
Github Open Source
Open Source
Apache-2.0
null
climetlab
pmaciel
Python
Code
139
383
#!/usr/bin/env python # # (C) Copyright 2021- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation nor # does it submit to any jurisdiction. # import csv import logging import os from climetlab.utils import load_json_or_yaml LOG = logging.getLogger(__name__) ALIASES = {} def load_csv(path): result = {} with open(path) as f: for row in csv.reader(f): result[row[0]] = row[1] return result def _find_aliases(name): if name not in ALIASES: path = os.path.join(os.path.dirname(__file__), name) if os.path.exists(path + ".csv"): ALIASES[name] = load_csv(path + ".csv") else: ALIASES[name] = load_json_or_yaml(path + ".yaml") return ALIASES[name] def unalias(name, value): return _find_aliases(name).get(value, value) if __name__ == "__main__": print(unalias("grib-paramid", "2t"))
43,160
https://github.com/Bhaskers-Blu-Org1/BlueMatter/blob/master/svntrunk/src/pk/pkmain/src/main.cpp
Github Open Source
Open Source
BSD-2-Clause
2,022
BlueMatter
Bhaskers-Blu-Org1
C++
Code
598
1,349
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*************************************************************************** * Project: pK * * Module: pkmain.C * * Purpose: This holds C process env main() so that calls to start * environment can be careated. * * Classification: IBM Internal Use Only * * History: 170297 BGF Created. * ***************************************************************************/ #include "unistd.h" // for nice() #include <pk/debug.hpp> #include <pk/fxlogger.hpp> #include <pk/pktrace.hpp> #include <pk/exception.hpp> // for exception class #include <pk/reactor.hpp> int PkMain( int, char**, char**); #include <iostream.h> // GLOBALS int _pk_PPL_REGLOG_fd = 0; int _pk_PPL_REGLOG_fd_LOCK = 0; // By default, we'll checksum only the first 64KB of the executable. #ifndef PK_MAX_EXCUTABLE_CHECKSUM #define PK_MAX_EXCUTABLE_CHECKSUM (64*1024) #endif #ifdef PK_MPI_ALL long long _pk_ExecutableCheckSum = 0; int AssertExecutableCheckSum( void *TriggerMsg ) { assert( *((long long *)TriggerMsg) == _pk_ExecutableCheckSum ); fprintf(stderr,"CheckSum confirmed task %d\n", MpiSubSys::GetTaskNo() ); fflush(stderr); return(0); } #endif main(int argc, char **argv, char **envp) { nice(1); // parallel process should be nice to each other, right? #if !defined(EXCEPTIONS_UNAVAILABLE) try #endif { #ifdef PK_MPI_ALL // DO a check sum of the executable file to make sure that // all address spaces have been loaded with the same executable. FILE *fp = fopen( argv[0], "r" ); assert( fp != NULL ); // Add up the first bit of the executable file. for(int b = 0; (b < PK_MAX_EXCUTABLE_CHECKSUM) && (! feof( fp )); b++ ) _pk_ExecutableCheckSum += fgetc(fp); fclose( fp ); MpiSubSys::Init( argc, argv ); //MpiDebug::Init() ... this call needs to be created. int start_debug(); start_debug(); PkActiveMsgSubSys::Init(); if( MpiSubSys::TaskNo > 0 ) { // This is the end of the line for all mpi nodes above 0. // Note however that the reactor subsystem has been started. //*** IT SEEMS MPI ON THE SWITCH DOESN'T WANT THREAD ZERO BEING SHUT DOWN *** for(;;) sleep(1); pthread_exit(NULL); assert(0); // better not get here } // Use active message sub system to assert that every // address space has been loaded with the same executable. for( int i=1; i < MpiSubSys::GetTaskCnt(); i++ ) { PkActiveMsgSubSys::Trigger( i, AssertExecutableCheckSum, (void *) &_pk_ExecutableCheckSum, sizeof( _pk_ExecutableCheckSum ) ); } #endif PkMain( argc, argv, envp ); } #if !defined(EXCEPTIONS_UNAVAILABLE) catch(PkException& gfe) { // perhaps these messages should go to a log file? cerr << "Exception caught in pkmain.cpp "; #ifdef MPI cerr << " MPI TaskNo = " << MpiSubSys::TaskNo; #endif cerr << endl; cerr << gfe << endl; exit(-1); // just exit } #endif #ifdef MPI MpiSubSys::Terminate(); #endif return(0); }
20,311
https://github.com/meroxa/apicurio-registry/blob/master/utils/maven-plugin/src/main/java/io/apicurio/registry/maven/AbstractRegistryMojo.java
Github Open Source
Open Source
Apache-2.0
2,022
apicurio-registry
meroxa
Java
Code
229
536
/* * Copyright 2018 Confluent Inc. (adapted from their Mojo) * Copyright 2019 Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apicurio.registry.maven; import io.apicurio.registry.client.RegistryClient; import io.apicurio.registry.client.RegistryService; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; /** * Base class for all Registry Mojo's. * It handles RegistryService's (aka client) lifecycle. * * @author Ales Justin */ public abstract class AbstractRegistryMojo extends AbstractMojo { /** * The registry's url. * e.g. http://localhost:8080/api */ @Parameter(required = true) String registryUrl; private RegistryService client; protected RegistryService getClient() { if (client == null) { client = RegistryClient.cached(registryUrl); } return client; } protected void setClient(RegistryService client) { this.client = client; } @Override public void execute() throws MojoExecutionException, MojoFailureException { try { executeInternal(); } finally { if (client != null) { try { client.close(); } catch (Exception ignored) { } } } } protected abstract void executeInternal() throws MojoExecutionException, MojoFailureException; }
35,306
https://github.com/baggio63446333/incubator-nuttx/blob/master/drivers/video/video.c
Github Open Source
Open Source
Apache-2.0
2,021
incubator-nuttx
baggio63446333
C
Code
3,552
13,709
/**************************************************************************** * drivers/video/video.c * * Copyright 2018 Sony Semiconductor Solutions Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Sony Semiconductor Solutions Corporation nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/ioctl.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <poll.h> #include <nuttx/arch.h> #include <nuttx/board.h> #include <nuttx/kmalloc.h> #include <arch/board/board.h> #include <nuttx/video/video_halif.h> #include "video_framebuff.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define video_printf(format, ...) _info(format, ##__VA_ARGS__) #define MAX_VIDEO_FILE_PATH (32) #define VIDEO_TRUE (1) #define VIDEO_FALSE (0) #define VIDEO_REMAINING_CAPNUM_INFINITY (-1) /* Debug option */ #ifdef CONFIG_DEBUG_VIDEO_ERROR #define videoerr(format, ...) _err(format, ##__VA_ARGS__) #else #define videoerr(x...) #endif #ifdef CONFIG_DEBUG_VIDEO_WARN #define videowarn(format, ...) _warn(format, ##__VA_ARGS__) #else #define videowarn(x...) #endif #ifdef CONFIG_DEBUG_VIDEO_INFO #define videoinfo(format, ...) _info(format, ##__VA_ARGS__) #else #define videoinfo(x...) #endif /**************************************************************************** * Private Types ****************************************************************************/ enum video_state_e { VIDEO_STATE_STREAMOFF = 0, /* DMA trigger event is not received */ VIDEO_STATE_STREAMON = 1, /* DMA trigger event is received, * but DMA is not operated. */ VIDEO_STATE_DMA = 2, /* On DMA */ }; enum video_state_transition_cause { CAUSE_VIDEO_STOP = 0, /* Stop DMA event for video stream */ CAUSE_VIDEO_START = 1, /* Start DMA event for video stream */ CAUSE_VIDEO_DQBUF = 2, /* DQBUF timing for video stream */ CAUSE_STILL_STOP = 3, /* Stop DMA event for still stream */ CAUSE_STILL_START = 4, /* Start DMA event for still stream */ }; enum video_waitend_cause_e { VIDEO_WAITEND_CAUSE_DMADONE = 0, VIDEO_WAITEND_CAUSE_DQCANCEL = 1, VIDEO_WAITEND_CAUSE_STILLSTOP = 2, }; struct video_wait_dma_s { FAR sem_t dqbuf_wait_flg; FAR vbuf_container_t *done_container; /* Save container which dma done */ enum video_waitend_cause_e waitend_cause; }; typedef struct video_wait_dma_s video_wait_dma_t; struct video_type_inf_s { sem_t lock_state; enum video_state_e state; int32_t remaining_capnum; video_wait_dma_t wait_dma; video_framebuff_t bufinf; }; typedef struct video_type_inf_s video_type_inf_t; struct video_mng_s { FAR char *devpath; /* parameter of video_initialize() */ sem_t lock_open_num; uint8_t open_num; FAR struct pollfd *poll_wait; /* poll(setup) information */ video_type_inf_t video_inf; video_type_inf_t still_inf; }; typedef struct video_mng_s video_mng_t; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Character driver methods. */ static int video_open(FAR struct file *filep); static int video_close(FAR struct file *filep); static int video_ioctl(FAR struct file *filep, int cmd, unsigned long arg); static int video_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup); /* Common function */ static int video_lock(FAR sem_t *sem); static int video_unlock(FAR sem_t *sem); static FAR video_type_inf_t *get_video_type_inf (FAR video_mng_t *vmng, uint8_t type); static enum video_state_e estimate_next_video_state (FAR video_mng_t *vmng, enum video_state_transition_cause cause); static void change_video_state(FAR video_mng_t *vmng, enum video_state_e next_state); static bool is_taking_still_picture(FAR video_mng_t *vmng); static bool is_bufsize_sufficient(FAR video_mng_t *vmng, uint32_t bufsize); static void cleanup_resources(FAR video_mng_t *vmng); static bool is_sem_waited(FAR sem_t *sem); /* internal function for each cmds of ioctl */ static int video_reqbufs(FAR struct video_mng_s *vmng, FAR struct v4l2_requestbuffers *reqbufs); static int video_qbuf(FAR struct video_mng_s *vmng, FAR struct v4l2_buffer *buf); static int video_dqbuf(FAR struct video_mng_s *vmng, FAR struct v4l2_buffer *buf); static int video_cancel_dqbuf(FAR struct video_mng_s *vmng, enum v4l2_buf_type type); static int video_enum_fmt(FAR struct v4l2_fmtdesc *fmt); static int video_enum_framesizes(FAR struct v4l2_frmsizeenum *frmsize); static int video_s_fmt(FAR struct video_mng_s *priv, FAR struct v4l2_format *fmt); static int video_enum_frameintervals(FAR struct v4l2_frmivalenum *frmival); static int video_s_parm(FAR struct video_mng_s *priv, FAR struct v4l2_streamparm *parm); static int video_streamon(FAR struct video_mng_s *vmng, FAR enum v4l2_buf_type *type); static int video_streamoff(FAR struct video_mng_s *vmng, FAR enum v4l2_buf_type *type); static int video_do_halfpush(bool enable); static int video_takepict_start(FAR struct video_mng_s *vmng, int32_t capture_num); static int video_takepict_stop(FAR struct video_mng_s *vmng, bool halfpush); static int video_queryctrl(FAR struct v4l2_queryctrl *ctrl); static int video_query_ext_ctrl(FAR struct v4l2_query_ext_ctrl *ctrl); static int video_querymenu(FAR struct v4l2_querymenu *menu); static int video_g_ctrl(FAR struct video_mng_s *priv, FAR struct v4l2_control *ctrl); static int video_s_ctrl(FAR struct video_mng_s *priv, FAR struct v4l2_control *ctrl); static int video_g_ext_ctrls(FAR struct video_mng_s *priv, FAR struct v4l2_ext_controls *ctrls); static int video_s_ext_ctrls(FAR struct video_mng_s *priv, FAR struct v4l2_ext_controls *ctrls); /**************************************************************************** * Public Data ****************************************************************************/ static const struct video_devops_s *g_video_devops; /**************************************************************************** * Private Data ****************************************************************************/ static const struct file_operations g_video_fops = { video_open, /* open */ video_close, /* close */ 0, /* read */ 0, /* write */ 0, /* seek */ video_ioctl, /* ioctl */ #ifndef CONFIG_DISABLE_POLL video_poll, /* poll */ #endif 0 /* unlink */ }; static bool is_initialized = false; static FAR void *video_handler; /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ static int video_lock(FAR sem_t *sem) { if (sem == NULL) { return -EINVAL; } return nxsem_wait_uninterruptible(sem); } static int video_unlock(FAR sem_t *sem) { if (sem == NULL) { return -EINVAL; } return nxsem_post(sem); } static FAR video_type_inf_t *get_video_type_inf (FAR video_mng_t *vmng, uint8_t type) { FAR video_type_inf_t *type_inf; switch (type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: type_inf = &vmng->video_inf; break; case V4L2_BUF_TYPE_STILL_CAPTURE: type_inf = &vmng->still_inf; break; default: /* Error case */ type_inf = NULL; break; } return type_inf; } static enum video_state_e estimate_next_video_state (FAR video_mng_t *vmng, enum video_state_transition_cause cause) { enum video_state_e current_state = vmng->video_inf.state; switch (cause) { case CAUSE_VIDEO_STOP: return VIDEO_STATE_STREAMOFF; case CAUSE_VIDEO_START: if (is_taking_still_picture(vmng)) { return VIDEO_STATE_STREAMON; } else { return VIDEO_STATE_DMA; } case CAUSE_STILL_STOP: if (current_state == VIDEO_STATE_STREAMON) { return VIDEO_STATE_DMA; } else { return current_state; } case CAUSE_STILL_START: if (current_state == VIDEO_STATE_DMA) { return VIDEO_STATE_STREAMON; } else { return current_state; } case CAUSE_VIDEO_DQBUF: if ((current_state == VIDEO_STATE_STREAMON) && !is_taking_still_picture(vmng)) { return VIDEO_STATE_DMA; } else { return current_state; } default: return current_state; } } static void change_video_state(FAR video_mng_t *vmng, enum video_state_e next_state) { enum video_state_e current_state = vmng->video_inf.state; enum video_state_e updated_next_state = next_state; FAR vbuf_container_t *dma_container; if ((current_state != VIDEO_STATE_DMA) && (next_state == VIDEO_STATE_DMA)) { dma_container = video_framebuff_get_dma_container(&vmng->video_inf.bufinf); if (dma_container) { g_video_devops->set_buftype(V4L2_BUF_TYPE_VIDEO_CAPTURE); g_video_devops->set_buf(dma_container->buf.m.userptr, dma_container->buf.length); } else { updated_next_state = VIDEO_STATE_STREAMON; } } else { if ((current_state == VIDEO_STATE_DMA) && (next_state != VIDEO_STATE_DMA)) { g_video_devops->cancel_dma(); } } vmng->video_inf.state = updated_next_state; return; } static bool is_taking_still_picture(FAR video_mng_t *vmng) { return ((vmng->still_inf.state == VIDEO_STATE_STREAMON) || (vmng->still_inf.state == VIDEO_STATE_DMA)); } static bool is_bufsize_sufficient(FAR video_mng_t *vmng, uint32_t bufsize) { /* Depend on format, frame size, and JPEG compression quality */ return true; } static void initialize_streamresources(FAR video_type_inf_t *type_inf) { memset(type_inf, 0, sizeof(video_type_inf_t)); type_inf->remaining_capnum = VIDEO_REMAINING_CAPNUM_INFINITY; nxsem_init(&type_inf->lock_state, 0, 1); nxsem_init(&type_inf->wait_dma.dqbuf_wait_flg, 0, 0); video_framebuff_init(&type_inf->bufinf); return; } static void initialize_resources(FAR video_mng_t *vmng) { initialize_streamresources(&vmng->video_inf); initialize_streamresources(&vmng->still_inf); return; } static void cleanup_streamresources(FAR video_type_inf_t *type_inf) { video_framebuff_uninit(&type_inf->bufinf); nxsem_destroy(&type_inf->wait_dma.dqbuf_wait_flg); nxsem_destroy(&type_inf->lock_state); memset(type_inf, 0, sizeof(video_type_inf_t)); type_inf->remaining_capnum = VIDEO_REMAINING_CAPNUM_INFINITY; return; } static void cleanup_resources(FAR video_mng_t *vmng) { /* clean up resource */ if ((vmng->video_inf.state == VIDEO_STATE_DMA) || (vmng->still_inf.state == VIDEO_STATE_DMA)) { /* If in DMA, stop */ g_video_devops->cancel_dma(); } cleanup_streamresources(&vmng->video_inf); cleanup_streamresources(&vmng->still_inf); return; } static bool is_sem_waited(FAR sem_t *sem) { int ret; int semcount; ret = nxsem_get_value(sem, &semcount); if ((ret == OK) && (semcount < 0)) { return true; } else { return false; } } static int video_open(FAR struct file *filep) { FAR struct inode *inode = filep->f_inode; FAR video_mng_t *priv = (FAR video_mng_t *)inode->i_private; int ret = OK; video_lock(&priv->lock_open_num); if (priv->open_num == 0) { /* Only in first execution, open device */ ret = g_video_devops->open(priv); if (ret == OK) { initialize_resources(priv); } } /* In second or later execution, ret is initial value(=OK) */ if (ret == OK) { priv->open_num++; } video_unlock(&priv->lock_open_num); return ret; } static int video_close(FAR struct file *filep) { FAR struct inode *inode = filep->f_inode; FAR video_mng_t *priv = (FAR video_mng_t *)inode->i_private; int ret = ERROR; video_lock(&priv->lock_open_num); if (priv->open_num == 0) { return OK; } priv->open_num--; if (priv->open_num == 0) { cleanup_resources(priv); g_video_devops->close(); } video_unlock(&priv->lock_open_num); return ret; } static int video_reqbufs(FAR struct video_mng_s *vmng, FAR struct v4l2_requestbuffers *reqbufs) { int ret = OK; FAR video_type_inf_t *type_inf; irqstate_t flags; if ((vmng == NULL) || (reqbufs == NULL)) { return -EINVAL; } type_inf = get_video_type_inf(vmng, reqbufs->type); if (type_inf == NULL) { return -EINVAL; } flags = enter_critical_section(); if (type_inf->state == VIDEO_STATE_DMA) { /* In DMA, REQBUFS is not permitted */ ret = -EPERM; } else { video_framebuff_change_mode(&type_inf->bufinf, reqbufs->mode); ret = video_framebuff_realloc_container(&type_inf->bufinf, reqbufs->count); } leave_critical_section(flags); return ret; } static int video_qbuf(FAR struct video_mng_s *vmng, FAR struct v4l2_buffer *buf) { FAR video_type_inf_t *type_inf; FAR vbuf_container_t *container; enum video_state_e next_video_state; irqstate_t flags; if ((vmng == NULL) || (buf == NULL)) { return -EINVAL; } type_inf = get_video_type_inf(vmng, buf->type); if (type_inf == NULL) { return -EINVAL; } if (!is_bufsize_sufficient(vmng, buf->length)) { return -EINVAL; } container = video_framebuff_get_container(&type_inf->bufinf); if (container == NULL) { return -ENOMEM; } memcpy(&container->buf, buf, sizeof(struct v4l2_buffer)); video_framebuff_queue_container(&type_inf->bufinf, container); video_lock(&type_inf->lock_state); flags = enter_critical_section(); if (type_inf->state == VIDEO_STATE_STREAMON) { leave_critical_section(flags); if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { video_lock(&vmng->still_inf.lock_state); next_video_state = estimate_next_video_state (vmng, CAUSE_VIDEO_START); change_video_state(vmng, next_video_state); video_unlock(&vmng->still_inf.lock_state); } else { container = video_framebuff_get_dma_container(&type_inf->bufinf); if (container) { g_video_devops->set_buftype(buf->type); g_video_devops->set_buf(container->buf.m.userptr, container->buf.length); type_inf->state = VIDEO_STATE_DMA; } } } else { leave_critical_section(flags); } video_unlock(&type_inf->lock_state); return OK; } static int video_dqbuf(FAR struct video_mng_s *vmng, FAR struct v4l2_buffer *buf) { irqstate_t flags; FAR video_type_inf_t *type_inf; FAR vbuf_container_t *container; sem_t *dqbuf_wait_flg; enum video_state_e next_video_state; if ((vmng == NULL) || (buf == NULL)) { return -EINVAL; } type_inf = get_video_type_inf(vmng, buf->type); if (type_inf == NULL) { return -EINVAL; } container = video_framebuff_dq_valid_container(&type_inf->bufinf); if (container == NULL) { /* Not yet done DMA. Wait done */ dqbuf_wait_flg = &type_inf->wait_dma.dqbuf_wait_flg; /* Loop until semaphore is unlocked by DMA done or DQCANCEL */ do { if (buf->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { /* If start DMA condition is satisfied, start DMA */ flags = enter_critical_section(); next_video_state = estimate_next_video_state (vmng, CAUSE_VIDEO_DQBUF); change_video_state(vmng, next_video_state); leave_critical_section(flags); } nxsem_wait(dqbuf_wait_flg); } while (type_inf->wait_dma.waitend_cause == VIDEO_WAITEND_CAUSE_STILLSTOP); container = type_inf->wait_dma.done_container; if (!container) { /* Waking up without DMA data means abort. * Therefore, Check cause. */ if (type_inf->wait_dma.waitend_cause == VIDEO_WAITEND_CAUSE_DQCANCEL) { return -ECANCELED; } } type_inf->wait_dma.done_container = NULL; } memcpy(buf, &container->buf, sizeof(struct v4l2_buffer)); video_framebuff_free_container(&type_inf->bufinf, container); return OK; } static int video_cancel_dqbuf(FAR struct video_mng_s *vmng, enum v4l2_buf_type type) { FAR video_type_inf_t *type_inf; type_inf = get_video_type_inf(vmng, type); if (type_inf == NULL) { return -EINVAL; } if (!is_sem_waited(&type_inf->wait_dma.dqbuf_wait_flg)) { /* In not waiting DQBUF case, return OK */ return OK; } type_inf->wait_dma.waitend_cause = VIDEO_WAITEND_CAUSE_DQCANCEL; /* If DMA is done before nxsem_post, cause is overwritten */ nxsem_post(&type_inf->wait_dma.dqbuf_wait_flg); return OK; } static int video_enum_fmt(FAR struct v4l2_fmtdesc *fmt) { int ret; if ((g_video_devops == NULL) || (g_video_devops->get_range_of_fmt == NULL)) { return -EINVAL; } ret = g_video_devops->get_range_of_fmt(fmt); return ret; } static int video_enum_framesizes(FAR struct v4l2_frmsizeenum *frmsize) { int ret; if ((g_video_devops == NULL) || (g_video_devops->get_range_of_framesize == NULL)) { return -EINVAL; } ret = g_video_devops->get_range_of_framesize(frmsize); return ret; } static int video_try_fmt(FAR struct v4l2_format *fmt) { int ret; if ((g_video_devops == NULL) || (g_video_devops->try_format == NULL)) { return -EINVAL; } ret = g_video_devops->try_format(fmt); return ret; } static int video_s_fmt(FAR struct video_mng_s *priv, FAR struct v4l2_format *fmt) { int ret; if ((g_video_devops == NULL) || (g_video_devops->set_format == NULL)) { return -EINVAL; } ret = g_video_devops->set_format(fmt); return ret; } static int video_enum_frameintervals(FAR struct v4l2_frmivalenum *frmival) { int ret; if ((g_video_devops == NULL) || (g_video_devops->get_range_of_frameinterval == NULL)) { return -EINVAL; } ret = g_video_devops->get_range_of_frameinterval(frmival); return ret; } static int video_s_parm(FAR struct video_mng_s *priv, FAR struct v4l2_streamparm *parm) { int ret; if ((g_video_devops == NULL) || (g_video_devops->set_frameinterval == NULL)) { return -EINVAL; } ret = g_video_devops->set_frameinterval(parm); return ret; } static int video_streamon(FAR struct video_mng_s *vmng, FAR enum v4l2_buf_type *type) { FAR video_type_inf_t *type_inf; enum video_state_e next_video_state; int ret = OK; if ((vmng == NULL) || (type == NULL)) { return -EINVAL; } type_inf = get_video_type_inf(vmng, *type); if (type_inf == NULL) { return -EINVAL; } if (*type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { /* No procedure for VIDIOC_STREAMON(STILL_CAPTURE) */ return OK; } video_lock(&type_inf->lock_state); if (type_inf->state != VIDEO_STATE_STREAMOFF) { ret = -EPERM; } else { next_video_state = estimate_next_video_state (vmng, CAUSE_VIDEO_START); change_video_state(vmng, next_video_state); } video_unlock(&type_inf->lock_state); return ret; } static int video_streamoff(FAR struct video_mng_s *vmng, FAR enum v4l2_buf_type *type) { FAR video_type_inf_t *type_inf; enum video_state_e next_video_state; irqstate_t flags; int ret = OK; if ((vmng == NULL) || (type == NULL)) { return -EINVAL; } type_inf = get_video_type_inf(vmng, *type); if (type_inf == NULL) { return -EINVAL; } if (*type != V4L2_BUF_TYPE_VIDEO_CAPTURE) { /* No procedure for VIDIOC_STREAMOFF(STILL_CAPTURE) */ return OK; } flags = enter_critical_section(); if (type_inf->state == VIDEO_STATE_STREAMOFF) { ret = -EPERM; } else { next_video_state = estimate_next_video_state (vmng, CAUSE_VIDEO_STOP); change_video_state(vmng, next_video_state); } leave_critical_section(flags); return ret; } static int video_do_halfpush(bool enable) { if ((g_video_devops == NULL) || (g_video_devops->do_halfpush == NULL)) { return -EINVAL; } return g_video_devops->do_halfpush(enable); } static int video_takepict_start(FAR struct video_mng_s *vmng, int32_t capture_num) { irqstate_t flags; enum video_state_e next_video_state; FAR vbuf_container_t *dma_container; int ret = OK; if (vmng == NULL) { return -EINVAL; } video_lock(&vmng->still_inf.lock_state); if (vmng->still_inf.state != VIDEO_STATE_STREAMOFF) { ret = -EPERM; } else { if (capture_num > 0) { vmng->still_inf.remaining_capnum = capture_num; } else { vmng->still_inf.remaining_capnum = VIDEO_REMAINING_CAPNUM_INFINITY; } /* Control video stream prior to still stream */ flags = enter_critical_section(); next_video_state = estimate_next_video_state(vmng, CAUSE_STILL_START); change_video_state(vmng, next_video_state); leave_critical_section(flags); dma_container = video_framebuff_get_dma_container (&vmng->still_inf.bufinf); if (dma_container) { /* Start video stream DMA */ g_video_devops->set_buftype(V4L2_BUF_TYPE_STILL_CAPTURE); g_video_devops->set_buf(dma_container->buf.m.userptr, dma_container->buf.length); vmng->still_inf.state = VIDEO_STATE_DMA; } else { vmng->still_inf.state = VIDEO_STATE_STREAMON; } } video_unlock(&vmng->still_inf.lock_state); return ret; } static int video_takepict_stop(FAR struct video_mng_s *vmng, bool halfpush) { int ret = OK; irqstate_t flags; enum video_state_e next_video_state; if (vmng == NULL) { return -EINVAL; } video_lock(&vmng->still_inf.lock_state); if ((vmng->still_inf.state == VIDEO_STATE_STREAMOFF) && (vmng->still_inf.remaining_capnum == VIDEO_REMAINING_CAPNUM_INFINITY)) { ret = -EPERM; } else { flags = enter_critical_section(); if (vmng->still_inf.state == VIDEO_STATE_DMA) { g_video_devops->cancel_dma(); } leave_critical_section(flags); vmng->still_inf.state = VIDEO_STATE_STREAMOFF; vmng->still_inf.remaining_capnum = VIDEO_REMAINING_CAPNUM_INFINITY; /* Control video stream */ video_lock(&vmng->video_inf.lock_state); next_video_state = estimate_next_video_state(vmng, CAUSE_STILL_STOP); change_video_state(vmng, next_video_state); video_unlock(&vmng->video_inf.lock_state); } video_unlock(&vmng->still_inf.lock_state); return ret; } static int video_queryctrl(FAR struct v4l2_queryctrl *ctrl) { int ret; struct v4l2_query_ext_ctrl ext_ctrl; if (ctrl == NULL) { return -EINVAL; } /* Replace to VIDIOC_QUERY_EXT_CTRL format */ ext_ctrl.ctrl_class = ctrl->ctrl_class; ext_ctrl.id = ctrl->id; ext_ctrl.type = ctrl->type; ext_ctrl.minimum = ctrl->minimum; ext_ctrl.maximum = ctrl->maximum; ext_ctrl.step = ctrl->step; ext_ctrl.default_value = ctrl->default_value; ext_ctrl.flags = ctrl->flags; ret = video_query_ext_ctrl(&ext_ctrl); if (ret != OK) { return ret; } if ((ext_ctrl.type == V4L2_CTRL_TYPE_INTEGER64) || (ext_ctrl.type == V4L2_CTRL_TYPE_U8) || (ext_ctrl.type == V4L2_CTRL_TYPE_U16) || (ext_ctrl.type == V4L2_CTRL_TYPE_U32)) { /* Unsupported type in VIDIOC_QUERYCTRL */ return -EINVAL; } /* Replace gotten value to VIDIOC_QUERYCTRL */ ctrl->type = ext_ctrl.type; ctrl->minimum = ext_ctrl.minimum; ctrl->maximum = ext_ctrl.maximum; ctrl->step = ext_ctrl.step; ctrl->default_value = ext_ctrl.default_value; ctrl->flags = ext_ctrl.flags; strncpy(ctrl->name, ext_ctrl.name, sizeof(ctrl->name)); return OK; } static int video_query_ext_ctrl(FAR struct v4l2_query_ext_ctrl *ctrl) { int ret; if ((g_video_devops == NULL) || (g_video_devops->get_range_of_ctrlvalue == NULL)) { return -EINVAL; } ret = g_video_devops->get_range_of_ctrlvalue(ctrl); return ret; } static int video_querymenu(FAR struct v4l2_querymenu *menu) { int ret; if ((g_video_devops == NULL) || (g_video_devops->get_menu_of_ctrlvalue == NULL)) { return -EINVAL; } ret = g_video_devops->get_menu_of_ctrlvalue(menu); return ret; } static int video_g_ctrl(FAR struct video_mng_s *priv, FAR struct v4l2_control *ctrl) { int ret; struct v4l2_ext_controls ext_controls; struct v4l2_ext_control control; if (ctrl == NULL) { return -EINVAL; } /* Replace to VIDIOC_G_EXT_CTRLS format */ control.id = ctrl->id; ext_controls.ctrl_class = V4L2_CTRL_CLASS_USER; ext_controls.count = 1; ext_controls.controls = &control; /* Execute VIDIOC_G_EXT_CTRLS */ ret = video_g_ext_ctrls(priv, &ext_controls); if (ret == OK) { /* Replace gotten value to VIDIOC_G_CTRL parameter */ ctrl->value = control.value; } return ret; } static int video_s_ctrl(FAR struct video_mng_s *priv, FAR struct v4l2_control *ctrl) { int ret; struct v4l2_ext_controls ext_controls; struct v4l2_ext_control control; if (ctrl == NULL) { return -EINVAL; } /* Replace to VIDIOC_S_EXT_CTRLS format */ control.id = ctrl->id; control.value = ctrl->value; ext_controls.ctrl_class = V4L2_CTRL_CLASS_USER; ext_controls.count = 1; ext_controls.controls = &control; /* Execute VIDIOC_S_EXT_CTRLS */ ret = video_s_ext_ctrls(priv, &ext_controls); return ret; } static int video_g_ext_ctrls(FAR struct video_mng_s *priv, FAR struct v4l2_ext_controls *ctrls) { int ret = OK; int cnt; FAR struct v4l2_ext_control *control; if ((priv == NULL) || (ctrls == NULL)) { return -EINVAL; } for (cnt = 0, control = ctrls->controls; cnt < ctrls->count; cnt++, control++) { ret = g_video_devops->get_ctrlvalue(ctrls->ctrl_class, control); if (ret < 0) { /* Set cnt in that error occurred */ ctrls->error_idx = cnt; return ret; } } return ret; } static int video_s_ext_ctrls(FAR struct video_mng_s *priv, FAR struct v4l2_ext_controls *ctrls) { int ret = OK; int cnt; FAR struct v4l2_ext_control *control; if ((priv == NULL) || (ctrls == NULL)) { return -EINVAL; } for (cnt = 0, control = ctrls->controls; cnt < ctrls->count; cnt++, control++) { ret = g_video_devops->set_ctrlvalue(ctrls->ctrl_class, control); if (ret < 0) { /* Set cnt in that error occurred */ ctrls->error_idx = cnt; return ret; } } return ret; } /**************************************************************************** * Name: video_ioctl * * Description: * Standard character driver ioctl method. * ****************************************************************************/ static int video_ioctl(FAR struct file *filep, int cmd, unsigned long arg) { FAR struct inode *inode = filep->f_inode; FAR video_mng_t *priv = (FAR video_mng_t *)inode->i_private; int ret = OK; switch (cmd) { case VIDIOC_REQBUFS: ret = video_reqbufs(priv, (FAR struct v4l2_requestbuffers *)arg); break; case VIDIOC_QBUF: ret = video_qbuf(priv, (FAR struct v4l2_buffer *)arg); break; case VIDIOC_DQBUF: ret = video_dqbuf(priv, (FAR struct v4l2_buffer *)arg); break; case VIDIOC_CANCEL_DQBUF: ret = video_cancel_dqbuf(priv, (FAR enum v4l2_buf_type)arg); break; case VIDIOC_STREAMON: ret = video_streamon(priv, (FAR enum v4l2_buf_type *)arg); break; case VIDIOC_STREAMOFF: ret = video_streamoff(priv, (FAR enum v4l2_buf_type *)arg); break; case VIDIOC_DO_HALFPUSH: ret = video_do_halfpush(arg); break; case VIDIOC_TAKEPICT_START: ret = video_takepict_start(priv, (int32_t)arg); break; case VIDIOC_TAKEPICT_STOP: ret = video_takepict_stop(priv, arg); break; case VIDIOC_ENUM_FMT: ret = video_enum_fmt((FAR struct v4l2_fmtdesc *)arg); break; case VIDIOC_ENUM_FRAMESIZES: ret = video_enum_framesizes((FAR struct v4l2_frmsizeenum *)arg); break; case VIDIOC_TRY_FMT: ret = video_try_fmt((FAR struct v4l2_format *)arg); break; case VIDIOC_S_FMT: ret = video_s_fmt(priv, (FAR struct v4l2_format *)arg); break; case VIDIOC_ENUM_FRAMEINTERVALS: ret = video_enum_frameintervals((FAR struct v4l2_frmivalenum *)arg); break; case VIDIOC_S_PARM: ret = video_s_parm(priv, (FAR struct v4l2_streamparm *)arg); break; case VIDIOC_QUERYCTRL: ret = video_queryctrl((FAR struct v4l2_queryctrl *)arg); break; case VIDIOC_QUERY_EXT_CTRL: ret = video_query_ext_ctrl((FAR struct v4l2_query_ext_ctrl *)arg); break; case VIDIOC_QUERYMENU: ret = video_querymenu((FAR struct v4l2_querymenu *)arg); break; case VIDIOC_G_CTRL: ret = video_g_ctrl(priv, (FAR struct v4l2_control *)arg); break; case VIDIOC_S_CTRL: ret = video_s_ctrl(priv, (FAR struct v4l2_control *)arg); break; case VIDIOC_G_EXT_CTRLS: ret = video_g_ext_ctrls(priv, (FAR struct v4l2_ext_controls *)arg); break; case VIDIOC_S_EXT_CTRLS: ret = video_s_ext_ctrls(priv, (FAR struct v4l2_ext_controls *)arg); break; default: videoerr("Unrecognized cmd: %d\n", cmd); ret = - ENOTTY; break; } return ret; } static int video_poll_setup(FAR struct video_mng_s *priv, FAR struct pollfd *fds) { if ((fds->events & POLLIN) == 0) { return -EDEADLK; } /* TODO: If data exists, get and nxsem_post If no data, wait dma */ return OK; } static int video_poll_teardown(FAR struct video_mng_s *priv, FAR struct pollfd *fds) { /* TODO: Delete poll wait information */ return OK; } static int video_poll(FAR struct file *filep, FAR struct pollfd *fds, bool setup) { FAR struct inode *inode = filep->f_inode; FAR video_mng_t *priv = inode->i_private; if (setup) { return video_poll_setup(priv, fds); } else { return video_poll_teardown(priv, fds); } return OK; } static FAR void *video_register(FAR const char *devpath) { FAR video_mng_t *priv; int ret; size_t allocsize; /* Input devpath Error Check */ if (!devpath) { return NULL; } allocsize = strnlen(devpath, MAX_VIDEO_FILE_PATH - 1/* Space for '\0' */); if ((allocsize < 2) || (devpath[0] != '/') || ((allocsize == (MAX_VIDEO_FILE_PATH - 1)) && (devpath[MAX_VIDEO_FILE_PATH] != '\0'))) { return NULL; } /* Initialize video device structure */ priv = (FAR video_mng_t *)kmm_malloc(sizeof(video_mng_t)); if (!priv) { videoerr("Failed to allocate instance\n"); return NULL; } memset(priv, 0, sizeof(video_mng_t)); /* Save device path */ priv->devpath = (FAR char *)kmm_malloc(allocsize + 1); if (!priv->devpath) { kmm_free(priv); return NULL; } memcpy(priv->devpath, devpath, allocsize); priv->devpath[allocsize] = '\0'; /* Initialize semaphore */ nxsem_init(&priv->lock_open_num, 0, 1); /* Register the character driver */ ret = register_driver(priv->devpath, &g_video_fops, 0666, priv); if (ret < 0) { videoerr("Failed to register driver: %d\n", ret); kmm_free(priv->devpath); kmm_free(priv); return NULL; } return (FAR void *)priv; } static int video_unregister(FAR video_mng_t *v_mgr) { int ret = OK; if (!v_mgr) { ret = -ENODEV; } else { nxsem_destroy(&v_mgr->lock_open_num); unregister_driver((const char *)v_mgr->devpath); kmm_free(v_mgr->devpath); kmm_free(v_mgr); } return ret; } /**************************************************************************** * Public Functions ****************************************************************************/ int video_initialize(FAR const char *devpath, FAR const struct video_devops_s *devops) { if (is_initialized) { return OK; } video_handler = video_register(devpath); g_video_devops = devops; is_initialized = true; return OK; } int video_uninitialize(void) { if (is_initialized) { return OK; } video_unregister(video_handler); g_video_devops = NULL; is_initialized = false; return OK; } int video_common_notify_dma_done(uint8_t err_code, uint32_t buf_type, uint32_t datasize, FAR void *priv) { FAR video_mng_t *vmng = (FAR video_mng_t *)priv; FAR video_type_inf_t *type_inf; FAR vbuf_container_t *container = NULL; type_inf = get_video_type_inf(vmng, buf_type); if (type_inf == NULL) { return -EINVAL; } if (err_code == 0) { type_inf->bufinf.vbuf_dma->buf.flags = 0; if (type_inf->remaining_capnum > 0) { type_inf->remaining_capnum--; } } else { type_inf->bufinf.vbuf_dma->buf.flags = V4L2_BUF_FLAG_ERROR; } type_inf->bufinf.vbuf_dma->buf.bytesused = datasize; video_framebuff_dma_done(&type_inf->bufinf); if (is_sem_waited(&type_inf->wait_dma.dqbuf_wait_flg)) { /* If waiting DMA done in DQBUF, * get/save container and unlock wait */ type_inf->wait_dma.done_container = video_framebuff_pop_curr_container(&type_inf->bufinf); type_inf->wait_dma.waitend_cause = VIDEO_WAITEND_CAUSE_DMADONE; nxsem_post(&type_inf->wait_dma.dqbuf_wait_flg); /* TODO: in poll wait, unlock wait */ } if (type_inf->remaining_capnum == 0) { g_video_devops->cancel_dma(); type_inf->state = VIDEO_STATE_STREAMOFF; /* If stop still stream, notify it to video stream */ if ((buf_type == V4L2_BUF_TYPE_STILL_CAPTURE) && is_sem_waited(&vmng->video_inf.wait_dma.dqbuf_wait_flg)) { vmng->video_inf.wait_dma.waitend_cause = VIDEO_WAITEND_CAUSE_STILLSTOP; nxsem_post(&vmng->video_inf.wait_dma.dqbuf_wait_flg); } } else { container = video_framebuff_get_dma_container(&type_inf->bufinf); if (!container) { g_video_devops->cancel_dma(); type_inf->state = VIDEO_STATE_STREAMON; } else { g_video_devops->set_buf(container->buf.m.userptr, container->buf.length); } } return OK; }
12,234
https://github.com/Hellena42/testproject/blob/master/resources/views/blocks/header/logo.blade.php
Github Open Source
Open Source
MIT
null
testproject
Hellena42
PHP
Code
10
59
<div class="header-logotype"> <a class="header-logotype__link"><img class="header-logotype-image" src="img/logo.png" width="195" height="37" alt="Test"></a> </div>
28,235
https://github.com/kadhirvelm/out-of-step/blob/master/packages/backend/src/cronJobs/instantiateAllCronJobs.ts
Github Open Source
Open Source
MIT
null
out-of-step
kadhirvelm
TypeScript
Code
243
822
/* eslint-disable @typescript-eslint/quotes */ import _ from "lodash"; import { scheduleJob } from "node-schedule"; import dayjs from "dayjs"; import { getNextTimeWithinMarketHours } from "@stochastic-exchange/utils"; import { postgresPool } from "../utils/getPostgresPool"; import { pricingStocksCronJob } from "./stocks/pricingStocksCronJob"; import { handleLimitOrders } from "./stocks/limitOrders/handleLimitOrders"; const MINIMUM_MINUTES_FROM_NOW = 10; const MAXIMUM_MINUTES_FROM_NOW = 45; async function maybeGetExistingCronJob() { try { const date = await postgresPool.query<{ date: string }>('SELECT * FROM "nextCronJob"'); const parsedDate = dayjs(date.rows[0]?.date); if (date.rows[0] === undefined || parsedDate.valueOf() < Date.now()) { return undefined; } return parsedDate; } catch { return undefined; } } const getRandomTimeBetweenMinutesFromNow = (minimumMinutes: number, maximumMinutes: number) => { return dayjs(Date.now() + _.random(minimumMinutes, maximumMinutes) * 1000 * 60); }; async function scheduleNextStocksCronJob() { await postgresPool.query('DELETE FROM "nextCronJob"'); const nextDate = getNextTimeWithinMarketHours( getRandomTimeBetweenMinutesFromNow(MINIMUM_MINUTES_FROM_NOW, MAXIMUM_MINUTES_FROM_NOW), ); await postgresPool.query('INSERT INTO "nextCronJob" (date) VALUES ($1)', [nextDate]); return nextDate; } async function getNextStocksCronJobDate(): Promise<dayjs.Dayjs> { const existingCronJobDate = await maybeGetExistingCronJob(); if (existingCronJobDate !== undefined) { return existingCronJobDate; } return scheduleNextStocksCronJob(); } let isJobRunning = false; export async function priceAllStocks() { await pricingStocksCronJob(); // eslint-disable-next-line no-console console.log("Priced stocks at: ", new Date().toLocaleString()); await handleLimitOrders(); // eslint-disable-next-line no-console console.log("Ran limit orders at: ", new Date().toLocaleString()); } function instantiateStocksCronJob() { if (isJobRunning) { return; } // Give the system a second to catch up from the last file write setTimeout(async () => { isJobRunning = true; scheduleJob((await getNextStocksCronJobDate()).valueOf(), async () => { await priceAllStocks(); isJobRunning = false; scheduleNextStocksCronJob(); instantiateStocksCronJob(); }); }, 1000); } export function instantiateAllCronJobs() { instantiateStocksCronJob(); }
33,599
https://github.com/roblillack/tack/blob/master/commands/serve.go
Github Open Source
Open Source
MIT
2,021
tack
roblillack
Go
Code
225
848
package commands import ( "fmt" "log" "net/http" "path/filepath" "sync" "time" "github.com/roblillack/tack/core" ) var noCacheHeaders = map[string]string{ "Cache-Control": "no-cache, no-store, no-transform, must-revalidate, private, max-age=0", "Expires": time.Unix(0, 0).Format(time.RFC1123), "Pragma": "no-cache", } func init() { RegisterCommand("serve", "Runs a minimal HTTP server", Serve) } func ServeError(w http.ResponseWriter, req *http.Request, err error) { w.WriteHeader(500) w.Write([]byte(fmt.Sprintf("Error: %s\n", err.Error()))) log.Printf("%s %s://%s%s%s -> ERROR: %s\n", req.Method, "http", req.Host, req.URL.Port(), req.RequestURI, err.Error()) } func Serve(args ...string) error { tacker, err := newTackerWithArgs(args...) if err != nil { return err } if err := tacker.Tack(); err != nil { log.Println(err) } tacker.Logger = nil var lastCheck time.Time var checkpoint *core.Checkpoint var mutex sync.Mutex htmlDir := filepath.Join(tacker.BaseDir, core.TargetDir) log.Printf("Serving from %s, listening on port 8080 …\n", htmlDir) server := http.FileServer(http.Dir(htmlDir)) return http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { start := time.Now() mutex.Lock() defer mutex.Unlock() if time.Since(lastCheck) >= 3*time.Second { rebuild, newCheckpoint, err := tacker.HasChanges(checkpoint) if err != nil { ServeError(w, req, err) return } if rebuild { tackStart := time.Now() if err := tacker.Reload(); err != nil { ServeError(w, req, err) return } if err := tacker.Tack(); err != nil { ServeError(w, req, err) return } if !lastCheck.IsZero() { log.Printf("Changes detected. Re-tacked in %s.\n", time.Since(tackStart)) } checkpoint = newCheckpoint } lastCheck = time.Now() } for k, v := range noCacheHeaders { w.Header().Set(k, v) } server.ServeHTTP(w, req) log.Printf("%s %s://%s%s%s (%s)\n", req.Method, "http", req.Host, req.URL.Port(), req.RequestURI, time.Since(start)) })) }
14,416
https://github.com/tonfonka/UpToTrain2/blob/master/resources/views/schedule.blade.php
Github Open Source
Open Source
MIT
null
UpToTrain2
tonfonka
PHP
Code
272
1,488
@extends('layouts.layout') @section('content') <!-- newedit About Section --> <!--<section id="about" align="center" padding-top= "50%">--> <div align="right"> <!--<button type="button" class="btn btn-default btn-lg"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Close </button>--> </div> <!--<div class="container">--> <div class="container" id="about" align="center"> <div class="row"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>{{ $trip->trips_name }}</h2> <!--<p class="item-intro text-muted">จังหวัด<br>โดย "$บริษัททัวร์"</p>--> <p>ระยะเวลา {{ $trip->trip_nday }} วัน {{ $trip->trip_nnight }} คืน</p> <img class="img-responsive img-centered" src="/img/portfolio/trip1_00.jpg" alt=""> <p>{{$trip->trip_description}}</p> <br><br> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Schedule</h2> <h3 class="section-subheading text-muted">" ไปไหนบ้างนะ "</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <ul class="timeline"> <!--ถ้าเลขคู่ ตรง li จะเพิ่ม class='timeline-inverted'--> @foreach($schedules as $schedule) <h3>{{$loop->iteration}}</h3> @if($loop->iteration %2 == 0) <li class="timeline-inverted"> @else <li> @endif <div class="timeline-image"> <img class="img-circle img-responsive" src="/img/about/1.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>วันที่ {{ $schedule->schedule_day }} เวลา {{ $schedule->schedule_time }}</h4> <h4 class="subheading">{{ $schedule->schedule_place }}</h4> </div> <div class="timeline-body"> <p class="text-muted">{{ $schedule->schedule_description }}</p> </div> </div> </li> @endforeach <li class="timeline-inverted"> <div class="timeline-image"> <h4>Booking <br><br>Now! </h4> </div> </li> </ul> </div> </div> <br><br> <!--<ul class="list-inline"> <li>Travel Agency: abc company</li> <li>Date: ?วัน ?คืน</li> <li>Cost: ? baht</li> </ul>--> <!-- ADD table round --> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <ul class="list-inline"> <table class="table"> <tr> <th>รอบวันที่</th> <th>ราคาผู้ใหญ่</th> <th>ราคาเด็ก</th> <th>จำนวนที่ว่าง</th> </tr> <!-- edit add loop select for db --> @foreach($triprounds as $tripround) <tr> <td>{{ $tripround->start_date }}</td> <td>{{$tripround->price_adult}}</td> <td>{{$tripround->price_child}}</td> <td>{{$tripround->amount_seats}}</td> </tr> @endforeach </table> <!-- end loop --> </ul> </div> <div class="col-md-3"></div> </div> <a class="btn btn-primary" href={{ url( '/search') }}> <i class="fa fa-times"></i> Close This</a> </div> </div> </div> </div> <!--</section>--> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js" integrity="sha384-mE6eXfrb8jxl0rzJDBRanYqgBxtJ6Unn4/1F7q4xRRyIw7Vdg9jP4ycT7x1iVsgb" crossorigin="anonymous"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Theme JavaScript --> <script src="js/agency.min.js"></script> </body> </html> @endsection('content')
21,820
https://github.com/anpint/azure-sdk-for-net/blob/master/sdk/securityinsights/Azure.ResourceManager.SecurityInsights/src/Generated/Models/BookmarkTimelineItem.Serialization.cs
Github Open Source
Open Source
LicenseRef-scancode-generic-cla, MIT, LGPL-2.1-or-later, Apache-2.0
2,022
azure-sdk-for-net
anpint
C#
Code
223
880
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.SecurityInsights.Models { public partial class BookmarkTimelineItem { internal static BookmarkTimelineItem DeserializeBookmarkTimelineItem(JsonElement element) { string azureResourceId = default; Optional<string> displayName = default; Optional<string> notes = default; Optional<DateTimeOffset> endTimeUtc = default; Optional<DateTimeOffset> startTimeUtc = default; Optional<DateTimeOffset> eventTime = default; Optional<UserInfo> createdBy = default; Optional<IReadOnlyList<string>> labels = default; EntityTimelineKind kind = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("azureResourceId")) { azureResourceId = property.Value.GetString(); continue; } if (property.NameEquals("displayName")) { displayName = property.Value.GetString(); continue; } if (property.NameEquals("notes")) { notes = property.Value.GetString(); continue; } if (property.NameEquals("endTimeUtc")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } endTimeUtc = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("startTimeUtc")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } startTimeUtc = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("eventTime")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } eventTime = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("createdBy")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } createdBy = UserInfo.DeserializeUserInfo(property.Value); continue; } if (property.NameEquals("labels")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<string> array = new List<string>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(item.GetString()); } labels = array; continue; } if (property.NameEquals("kind")) { kind = new EntityTimelineKind(property.Value.GetString()); continue; } } return new BookmarkTimelineItem(kind, azureResourceId, displayName.Value, notes.Value, Optional.ToNullable(endTimeUtc), Optional.ToNullable(startTimeUtc), Optional.ToNullable(eventTime), createdBy.Value, Optional.ToList(labels)); } } }
40,722
https://github.com/Baytul163-15/Nogoraion/blob/master/config/weather.php
Github Open Source
Open Source
MIT
null
Nogoraion
Baytul163-15
PHP
Code
162
479
<?php return [ 'setting' => [ 'api_key' => '18103825fb389181de986d249211193c', // Api key 'units' => 'metric', // Units of measurement. standard, metric and imperial units are available. ], 'citys' => [ 'Dhaka' => [ 'city' => null, 'lat' => 23.81, 'lon' => 90.41 ], 'Rajshahi' => [ 'city' => null, 'lat' => 24.37, 'lon' => 88.60 ], 'Chittagong' => [ 'city' => null, 'lat' => 22.36, 'lon' => 91.78 ], 'Khulna' => [ 'city' => null, 'lat' => 22.85, 'lon' => 89.54 ], 'Rangpur' => [ 'city' => null, 'lat' => 25.74, 'lon' => 89.27 ], 'Kurigram' => [ 'city' => null, 'lat' => 25.81, 'lon' => 89.65 ], 'Panchagarh' => [ 'city' => null, 'lat' => 26.34, 'lon' => 88.55 ], 'Barisal' => [ 'city' => null, 'lat' => 22.70, 'lon' => 90.35 ], 'Mymensingh' => [ 'city' => null, 'lat' => 24.75, 'lon' => 90.42 ], 'Sylhet' => [ 'city' => null, 'lat' => 24.89, 'lon' => 91.87 ] ] ];
7,435
https://github.com/OxCom/SymfonyRollbarBundle/blob/master/Provider/Api/Filter.php
Github Open Source
Open Source
MIT
2,021
SymfonyRollbarBundle
OxCom
PHP
Code
72
162
<?php namespace SymfonyRollbarBundle\Provider\Api; /** * Class Validator * * Before calls to API we have to check some restrictions on Rollbar side to avoid drops of request * * @package SymfonyRollbarBundle\Provider\Api */ class Filter { /** * @param mixed $value * @param string $filterName * @param array $options * * @return mixed */ public static function process($value, $filterName = '', $options = []) { $filter = new $filterName($options); return $filter($value); } }
19,862
https://github.com/Mhithrandir/go-cms/blob/master/www/templates/app/website/src/app/classes/user.ts
Github Open Source
Open Source
MIT
2,021
go-cms
Mhithrandir
TypeScript
Code
46
113
import { BasicTable } from "./basic-table"; import { UserType } from "./user-type"; export class User extends BasicTable { public Username!: string; public Password!: string; public LastLogin!: Date; public DatePassword!: Date; public PasswordDuration!: number; public IDUserType!: number; public CodeResetPassword!: string; public IsPasswordExpired!: boolean; public UserType!: UserType; }
9,033
https://github.com/kongaraju/antkorp/blob/master/3party/dtl-1.18/test/comparators.hpp
Github Open Source
Open Source
CC-BY-3.0, Apache-2.0
2,015
antkorp
kongaraju
C++
Code
66
195
#ifndef DTL_COMPARATORS #define DTL_COMPARATORS class CaseInsensitive: public dtl::Compare<char> { public: virtual bool impl(const char& a, const char& b) const { return tolower(a) == tolower(b); } }; class StringCaseInsensitive: public dtl::Compare<string> { public: virtual bool impl(string& a, string& b) const { if (a.length() == b.length()) { bool equal = (strncasecmp(a.c_str(), b.c_str(), a.length()) == 0); return equal; } else { return false; } } }; #endif // DTL_COMPARATORS
20,667
https://github.com/I-Enderlord-I/CCTweaks/blob/master/src/test/java/org/squiddev/cctweaks/core/network/PacketTest.java
Github Open Source
Open Source
MIT
2,016
CCTweaks
I-Enderlord-I
Java
Code
286
1,098
package org.squiddev.cctweaks.core.network; import com.google.gson.Gson; import dan200.computercraft.api.network.IPacketSender; import dan200.computercraft.api.network.Packet; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.squiddev.cctweaks.api.network.IWorldNetworkNode; import org.squiddev.cctweaks.api.network.IWorldNetworkNodeHost; import org.squiddev.cctweaks.core.network.mock.BasicNetwork; import org.squiddev.cctweaks.core.network.mock.KeyedNetworkNode; import org.squiddev.cctweaks.core.network.mock.NodeTile; import javax.annotation.Nonnull; import java.io.InputStreamReader; import java.util.Map; import static org.junit.Assert.assertEquals; /** * Tests various facts about the network visitor */ @RunWith(Parameterized.class) public class PacketTest { private final TestData data; public PacketTest(String name, TestData data) { this.data = data; } @Parameterized.Parameters(name = "{0}") public static Object[][] data() { TestData[] data = new Gson().fromJson( new InputStreamReader(PacketTest.class.getResourceAsStream("data.json")), TestData[].class ); Object[][] result = new Object[data.length][]; for (int i = 0; i < data.length; i++) { TestData item = data[i]; result[i] = new Object[]{ item.name, item }; } return result; } @Test public void testCounts() { if (data.counts == null) return; BasicNetwork network = new BasicNetwork(data); network.reset(); ((NodeTile) network.getTileEntity(0, 0, 0)).node.doInvalidate(); for (Map.Entry<BlockPos, KeyedNetworkNode> location : network) { Integer count = data.counts.get(location.getValue().key); if (count != null) { assertEquals("Location " + location, count.intValue(), location.getValue().invalidated()); } } } @Test public void testDistance() { if (data.distance == null) return; BasicNetwork network = new BasicNetwork(data); network.reset(); IWorldNetworkNode node = ((IWorldNetworkNodeHost) network.getTileEntity(0, 0, 0)).getNode(); node.getAttachedNetwork().transmitPacket(node, new Packet(0, 0, null, new Sender(node))); for (Map.Entry<BlockPos, KeyedNetworkNode> location : network) { Integer distance = data.distance.get(location.getValue().key); if (distance != null) { assertEquals("Location " + location, distance, location.getValue().distance(), 0.01); } } } public final class TestData { public String name; public String[] map; public Map<String, Integer> counts; public Map<String, Integer> distance; } public final class Sender implements IPacketSender { private final IWorldNetworkNode node; public Sender(IWorldNetworkNode node) { this.node = node; } @Nonnull @Override public World getWorld() { return (World) node.getPosition().getBlockAccess(); } @Nonnull @Override public Vec3d getPosition() { return new Vec3d(node.getPosition().getPosition()); } @Nonnull @Override public String getSenderID() { return node.toString(); } } }
43,041
https://github.com/ricardodalarme/CryBits/blob/master/Client.Framework/Audio/Sound.cs
Github Open Source
Open Source
MIT
2,023
CryBits
ricardodalarme
C#
Code
94
261
using CryBits.Client.Framework.Constants; using SFML.Audio; namespace CryBits.Client.Framework.Audio; public static class Sound { // Dispositivo sonoro public static readonly Dictionary<string, SFML.Audio.Sound> List = new(); public static void Load() { var files = Directories.Sounds.GetFiles(); // Carrega todos os arquivos e os adiciona a lista foreach (var file in files) List.Add(file.Name, new SFML.Audio.Sound(new SoundBuffer(file.FullName))); } public static void Play(string sound, bool loop = false) { if (!List.ContainsKey(sound)) return; // Reproduz o áudio List[sound].Volume = 20; List[sound].Loop = loop; List[sound].Play(); } public static void StopAll() { // Para todos os sons foreach (var sound in List) sound.Value.Stop(); } }
3,642
https://github.com/il3n/PodTest/blob/master/PodTest/PodTest/Shared/Person.m
Github Open Source
Open Source
MIT
2,016
PodTest
il3n
Objective-C
Code
26
72
// // Person.m // PodTest // // Created by lijun on 16/11/23. // // #import "Person.h" @implementation Person -(void) sayHello { NSLog(@"Hello from Pod"); } @end
31,958
https://github.com/robertsundstrom/PointOfSale/blob/master/WebApi/WebApi/Catalog/Models.cs
Github Open Source
Open Source
MIT
2,021
PointOfSale
robertsundstrom
C#
Code
183
451
namespace WebApi.Catalog; using System.Runtime.Serialization; using Newtonsoft.Json; using WebApi.Hal; using WebApi.Shared; public class Items : Resource<ItemsEmbedded> { public int Count { get; set; } public int Total { get; set; } } public class ItemsEmbedded { [JsonProperty("items", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<Item>? Items { get; set; } } public class Item : Resource<ItemEmbedded> { public string Id { get; set; } = null!; public string Name { get; set; } = null!; public string Description { get; set; } = null!; public string? Unit { get; set; } public decimal Price { get; set; } public double VatRate { get; set; } [JsonExtensionData] public Dictionary<string, object>? CustomFields { get; set; } } public class ItemEmbedded { [JsonProperty("charges", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<ItemCharge>? Charges { get; set; } [JsonProperty("customFields", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<CustomField>? CustomFields { get; set; } } public class ItemCharge : Resource { public Guid Id { get; set; } public string Name { get; set; } = null!; [JsonProperty("amount", NullValueHandling = NullValueHandling.Ignore)] public decimal? Amount { get; set; } [JsonProperty("percent", NullValueHandling = NullValueHandling.Ignore)] public double? Percent { get; set; } }
3,046
https://github.com/theemack/webumenia.sk/blob/master/app/Harvest/Harvesters/ItemHarvester.php
Github Open Source
Open Source
MIT, LicenseRef-scancode-proprietary-license, LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-public-domain
2,020
webumenia.sk
theemack
PHP
Code
283
1,079
<?php namespace App\Harvest\Harvesters; use App\Harvest\Importers\ItemImporter; use App\Harvest\Repositories\ItemRepository; use App\Harvest\Result; use App\Item; use App\SpiceHarvesterRecord; use Illuminate\Support\Str; use Monolog\Logger; class ItemHarvester extends AbstractHarvester { /** @var array */ protected $excludePrefix = ['x']; /** @var Logger */ protected $logger; public function __construct(ItemRepository $repository, ItemImporter $importer) { parent::__construct($repository, $importer); $this->logger = new Logger('oai_harvest'); } protected function harvestSingle(SpiceHarvesterRecord $record, Result $result, array $row = null) { if ($row === null) { $row = $this->repository->getRow($record); } // @todo responsibility of repository? $iipimgUrls = $this->fetchItemImageIipimgUrls($row); $row['images'] = []; foreach ($iipimgUrls as $iipimgUrl) { $row['images'][] = [ 'iipimg_url' => [$iipimgUrl], ]; } if ($record->harvest->collection) { $row['collections'] = [ ['id' => $record->harvest->collection->id], ]; } /** @var Item $item */ $item = parent::harvestSingle($record, $result, $row); if (!$item) { return; } if ($item->img_url) { $this->trySaveImage($item); } // index with updated relations $item->index(); return $item; } protected function trySaveImage(Item $item) { try { $item->saveImage($item->img_url); } catch (\Exception $e) { $error = sprintf('%s: %s', $item->img_url, $e->getMessage()); $this->logger->addError($error); app('sentry')->captureException($e); } } protected function isExcluded(array $row) { $id = $this->importer->getModelId($row); $prefix = substr($id, strpos($id, '.') + 1, 1); $prefix = Str::lower($prefix); return in_array($prefix, $this->excludePrefix); } /** * @param array $row * @return string[] */ protected function fetchItemImageIipimgUrls(array $row) { $url = array_first($row['identifier'], function ($identifier) { return str_contains($identifier, 'L2_WEB'); }); if ($url === null) { return []; } return $this->parseItemImageIipimgUrls(file_get_contents($url)); } /** * @param string $iipimgUrls * @return string[] */ protected function parseItemImageIipimgUrls($iipimgUrls) { $iipimgUrls = strip_tags($iipimgUrls, '<br>'); $iipimgUrls = explode('<br>', $iipimgUrls); $iipimgUrls = array_filter($iipimgUrls, function ($iipimgUrl) { return str_contains($iipimgUrl, '.jp2'); }); sort($iipimgUrls); return array_map(function($iipimgUrl) { $iipimgUrl = substr($iipimgUrl, strpos($iipimgUrl, '?FIF=') + 5); $iipimgUrl = substr($iipimgUrl, 0, strpos($iipimgUrl, '.jp2') + 4); return $iipimgUrl; }, $iipimgUrls); } protected function isForDeletion(array $row) { return parent::isForDeletion($row) || (isset($row['rights'][0]) && !$row['rights'][0]); } }
47,196
https://github.com/classicsunny/grafana/blob/master/public/app/features/dashboard/services/DashboardLoaderSrv.ts
Github Open Source
Open Source
Apache-2.0
2,017
grafana
classicsunny
TypeScript
Code
365
1,177
import angular from 'angular'; import moment from 'moment'; // eslint-disable-line no-restricted-imports import _ from 'lodash'; import $ from 'jquery'; import kbn from 'app/core/utils/kbn'; import { AppEvents, dateMath, UrlQueryValue } from '@grafana/data'; import impressionSrv from 'app/core/services/impression_srv'; import { backendSrv } from 'app/core/services/backend_srv'; import { DashboardSrv } from './DashboardSrv'; import DatasourceSrv from 'app/features/plugins/datasource_srv'; import { GrafanaRootScope } from 'app/routes/GrafanaCtrl'; export class DashboardLoaderSrv { /** @ngInject */ constructor( private dashboardSrv: DashboardSrv, private datasourceSrv: DatasourceSrv, private $http: any, private $timeout: any, contextSrv: any, private $routeParams: any, private $rootScope: GrafanaRootScope ) {} _dashboardLoadFailed(title: string, snapshot?: boolean) { snapshot = snapshot || false; return { meta: { canStar: false, isSnapshot: snapshot, canDelete: false, canSave: false, canEdit: false, dashboardNotFound: true, }, dashboard: { title }, }; } loadDashboard(type: UrlQueryValue, slug: any, uid: any) { let promise; if (type === 'script') { promise = this._loadScriptedDashboard(slug); } else if (type === 'snapshot') { promise = backendSrv.get('/api/snapshots/' + slug).catch(() => { return this._dashboardLoadFailed('Snapshot not found', true); }); } else { promise = backendSrv .getDashboardByUid(uid) .then((result: any) => { if (result.meta.isFolder) { this.$rootScope.appEvent(AppEvents.alertError, ['Dashboard not found']); throw new Error('Dashboard not found'); } return result; }) .catch(() => { return this._dashboardLoadFailed('Not found', true); }); } promise.then((result: any) => { if (result.meta.dashboardNotFound !== true) { impressionSrv.addDashboardImpression(result.dashboard.id); } return result; }); return promise; } _loadScriptedDashboard(file: string) { const url = 'public/dashboards/' + file.replace(/\.(?!js)/, '/') + '?' + new Date().getTime(); return this.$http({ url: url, method: 'GET' }) .then(this._executeScript.bind(this)) .then( (result: any) => { return { meta: { fromScript: true, canDelete: false, canSave: false, canStar: false, }, dashboard: result.data, }; }, (err: any) => { console.log('Script dashboard error ' + err); this.$rootScope.appEvent(AppEvents.alertError, [ 'Script Error', 'Please make sure it exists and returns a valid dashboard', ]); return this._dashboardLoadFailed('Scripted dashboard'); } ); } _executeScript(result: any) { const services = { dashboardSrv: this.dashboardSrv, datasourceSrv: this.datasourceSrv, }; const scriptFunc = new Function( 'ARGS', 'kbn', 'dateMath', '_', 'moment', 'window', 'document', '$', 'jQuery', 'services', result.data ); const scriptResult = scriptFunc(this.$routeParams, kbn, dateMath, _, moment, window, document, $, $, services); // Handle async dashboard scripts if (_.isFunction(scriptResult)) { return new Promise(resolve => { scriptResult((dashboard: any) => { this.$timeout(() => { resolve({ data: dashboard }); }); }); }); } return { data: scriptResult }; } } angular.module('grafana.services').service('dashboardLoaderSrv', DashboardLoaderSrv);
32,618
https://github.com/sbcmadn1/Have-a-pet/blob/master/有宠ZJZ离线测试版/有宠ZJZ/Classes/Share(分享)/View/CZStatuseCell.h
Github Open Source
Open Source
MIT
2,015
Have-a-pet
sbcmadn1
Objective-C
Code
35
279
// // CZStatuseCell.h // 15-微博案例(屏幕适配) // #import <UIKit/UIKit.h> @class CZStatuse; @interface CZStatuseCell : UITableViewCell @property (nonatomic,strong) CZStatuse *statuse; /** * 1.如果采用连线方式使指针对象指向一个同类型的对象,可以使用weak属性,因为这时候被连线的对象是全局的 * 2.如果采用写代码创建一个同类型的对象,并赋值给该对象的话,属性必须是strong,因为代码创建的对象是局部的,必须用一个强指针执行,不然出了方法体就会被释放 */ //@property (weak, nonatomic) IBOutlet UILabel *textView; @property (nonatomic,assign) CGFloat pictureHeight; @end
240
https://github.com/itfuyun/jeebud/blob/master/jeebud-modules/module-upms/src/main/java/com/jeebud/module/upms/controller/LogController.java
Github Open Source
Open Source
MIT
2,021
jeebud
itfuyun
Java
Code
212
1,089
package com.jeebud.module.upms.controller; import com.jeebud.core.web.RestEntity; import com.jeebud.core.log.OpTypeEnum; import com.jeebud.core.log.Operation; import com.jeebud.module.upms.model.entity.LoginLog; import com.jeebud.module.upms.model.entity.OperationLog; import com.jeebud.module.upms.model.param.log.LoginLogPageQuery; import com.jeebud.module.upms.model.param.log.OperationLogPageQuery; import com.jeebud.module.upms.service.LogService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * <p>Description: </p> * <p>Copyright (c) www.jeebud.com Inc. All Rights Reserved.</p> * * @author Tanxh(itfuyun@gmail.com) */ @Controller @RequestMapping("${jeebud.sys.serverCtx}/sys/log") public class LogController { /** * 模板前缀 */ private static final String TPL_PATH = "admin/modules/sys/log"; @Autowired LogService logService; /** * 操作日志列表页 * * @return */ @RequiresPermissions("p:sys:log:operation:list") @GetMapping("/operation/pageList") public String operationLogPageList() { return TPL_PATH + "/operationLogList"; } /** * 操作日志列表 * * @param query * @return */ @RequiresPermissions("i:sys:log:operation:list") @GetMapping("/operation/list") @ResponseBody public RestEntity<Page<OperationLog>> operationLogList(OperationLogPageQuery query) { Page<OperationLog> operationLogPage = logService.operationLogPage(query); return RestEntity.ok().data(operationLogPage); } /** * 清空操作日志 * * @return */ @Operation(module = "日志模块", opType = OpTypeEnum.UPDATE, info = "清空操作日志") @RequiresPermissions("i:sys:log:operation:clear") @PostMapping("/operation/clear") @ResponseBody public RestEntity clearOperationLog() { logService.clearOperationLog(); return RestEntity.ok(); } /** * 登录日志列表页 * * @return */ @RequiresPermissions("p:sys:log:login:list") @GetMapping("/login/pageList") public String loginPageList() { return TPL_PATH + "/loginLogList"; } /** * 登录日志列表 * * @param query * @return */ @RequiresPermissions("i:sys:log:login:list") @GetMapping("/login/list") @ResponseBody public RestEntity<Page<LoginLog>> loginLogList(LoginLogPageQuery query) { Page<LoginLog> loginLogPage = logService.loginLogPage(query); return RestEntity.ok().data(loginLogPage); } /** * 清空登录日志 * * @return */ @Operation(module = "日志模块", opType = OpTypeEnum.UPDATE, info = "清空登录日志") @RequiresPermissions("i:sys:log:login:clear") @PostMapping("/login/clear") @ResponseBody public RestEntity clearLoginLog() { logService.clearLoginLog(); return RestEntity.ok(); } }
46,182
https://github.com/sanshishen/webgl-first/blob/master/public/assets/js/sun.js
Github Open Source
Open Source
MIT
null
webgl-first
sanshishen
JavaScript
Code
191
749
/** * sun * @date 2018-05-29 11:59:17 * @version 1.0.0 */ define(['sim/sim', 'js/static'], function(Sim, STATIC) { function Sun() { Sim.Object.call(this); } Sun.prototype = new Sim.Object(); Sun.prototype.init = function() { var sunGroup = new THREE.Object3D(), sunMap = '/assets/images/sun_surface.jpg', texture = new THREE.TextureLoader().load(sunMap), material = new THREE.MeshLambertMaterial({map: texture, color: 0xffff00}), geometry = new THREE.SphereGeometry(STATIC.Sun.SIZE_IN_EARTHS, 64, 64), sunMesh = new THREE.Mesh(geometry, material); var light = new THREE.PointLight(0xffffff, 1.2, 1000); sunGroup.add(sunMesh); sunGroup.add(light); this.setObject3D(sunGroup); /* var sunGroup = new THREE.Object3D(); var SUNMAP = '/assets/images/lavatile.jpg', NOISEMAP = '/assets/images/cloud.png', textureLoader = new THREE.TextureLoader(), uniforms = { time: { type: 'f', value: 1.0 }, texture1: { type: 'f', value: 0, texture: textureLoader.load(NOISEMAP) }, texture2: { type: 'f', value: 1, texture: textureLoader.load(SUNMAP) } }; uniforms.texture1.texture.wrapS = uniforms.texture1.texture.wrapT = THREE.Repeat; uniforms.texture2.texture.wrapS = uniforms.texture2.texture.wrapT = THREE.Repeat; var material = new THREE.ShaderMaterial({ uniforms: uniforms, vertexShader: document.querySelector('#vertexShader').textContent, fragmentShader: document.querySelector('#fragmentShader').textContent }); var geometry = new THREE.SphereGeometry(STATIC.Sun.SIZE_IN_EARTHS, 64, 64), sunMesh = new THREE.Mesh(geometry, material); this.uniforms = uniforms; // 开启一个时钟驱动动画 this.clock = new THREE.Clock(); var light = new THREE.PointLight(0xffffff, 1.2, 100000); sunGroup.add(sunMesh); sunGroup.add(light); this.setObject3D(sunGroup); */ }; Sun.prototype.update = function() { /* var delta = this.clock.getDelta(); this.uniforms.time.value += delta; */ Sim.Object.prototype.update.call(this); this.object3D.rotation.y -= 0.001; }; return Sun; })
5,437
https://github.com/aqkhan/weconnect-demo/blob/master/src/components/footer.js
Github Open Source
Open Source
MIT
null
weconnect-demo
aqkhan
JavaScript
Code
100
490
import React from "react" const footer = () => { return ( <footer> <div className="container"> <div className="row"> <div className="col-md-4"> <img src="/images/logo_footer.webp" alt=""/> <p className="email lato-regular"> info@weconnectrecovery.com </p> <p className="number lato-regular">720.661.2231</p> </div> <div className="col-md-2"> <h1 className="lato-regular">Useful Links</h1> <ul> <li className="lato-regular"> Home</li> <li className="lato-regular">Families</li> <li className="lato-regular">Providers</li> <li className="lato-regular">Research</li> <li className="lato-regular">Download Apps</li> <li className="lato-regular">Press</li> </ul> </div> <div className="col-md-2"> <h1 className="lato-regular">About us</h1> <ul> <li className="lato-regular">About us</li> <li className="lato-regular">Team</li> <li className="lato-regular">Investors</li> <li className="lato-regular">Cereers</li> <li className="lato-regular">Contact</li> </ul> </div> <div className="col-md-4"> <h1 className="lato-regular">Our Address</h1> <p className="lato-regular adress"> Galvanize 111 S Jackson St. ,<br/> Seattle, WA 98104, US </p> </div> </div> </div> </footer> ) } export default footer;
7,424
https://github.com/lihaochen910/RPGMakerProject/blob/master/js/ecs/component.js
Github Open Source
Open Source
MIT
null
RPGMakerProject
lihaochen910
JavaScript
Code
1,102
2,596
const ComponentRefs = require ( './componentrefs' ); const UUID = require ( 'uuid/v1' ); const CoreProperties = new Set ( [ 'ecs', 'entity', 'type', '_values', '_ready', 'id', 'updated', 'constructor', 'stringify', 'clone', 'getObject' ] ); class BaseComponent { constructor ( ecs, entity, initialValues ) { Object.defineProperty ( this, 'ecs', { enumerable: false, value: ecs } ); Object.defineProperty ( this, 'entity', { enumerable: true, value: entity } ); Object.defineProperty ( this, 'type', { enumerable: false, value: this.constructor.name } ); Object.defineProperty ( this, '_values', { enumerable: false, value: {} } ); Object.defineProperty ( this, '_refs', { enumerable: false, value: {} } ); Object.defineProperty ( this, '_ready', { writable: true, enumerable: false, value: false } ); Object.defineProperty ( this, 'id', { enumerable: true, value: initialValues.id || UUID () } ); Object.defineProperty ( this, 'updated', { enumerable: false, writable: true, value: this.ecs.ticks } ); //loop through inheritance by way of prototypes //avoiding constructor->super() boilerplate for every component //also avoiding proxies just for a simple setter on properties const definitions = []; for ( var c = this.constructor; c !== null; c = Object.getPrototypeOf ( c ) ) { if ( !c.definition ) continue; definitions.push ( c.definition ); } //we want to inherit deep prototype defintions first definitions.reverse (); for ( let idx = 0, l = definitions.length; idx < l; idx++ ) { const definition = definitions[ idx ]; // set component properties from Component.properties if ( !definition.properties ) { continue; } const properties = definition.properties; const keys = Object.keys ( properties ); for ( let idx = 0, l = keys.length; idx < l; idx++ ) { const property = keys[ idx ]; if ( CoreProperties.has ( property ) ) { throw new Error ( `Cannot override property in Component definition: ${ property }` ); } const value = properties[ property ]; if ( this._values.hasOwnProperty ( property ) ) { this[ property ] = value; continue; } switch ( value ) { case '<EntitySet>': Object.defineProperty ( this, property, { //writable: true, enumerable: true, set: ( value ) => { Reflect.set ( this._values, property, ComponentRefs.EntitySet ( value, this, property ) ); }, get: () => { return Reflect.get ( this._values, property ); } } ); //this._refs[property] = this[property]; this[ property ] = []; break; case '<EntityObject>': Object.defineProperty ( this, property, { writable: false, enumerable: true, value: ComponentRefs.EntityObject ( {}, this, property ) } ); this._refs[ property ] = this[ property ]; break; case '<Entity>': Object.defineProperty ( this, property, { enumerable: true, writeable: true, set: ( value ) => { if ( value && value.id ) { value = value.id; } const old = Reflect.get ( this._values, property ); if ( old && old !== value ) { this.ecs.deleteRef ( old, this.entity.id, this.id, property ); } if ( value && value !== old ) { this.ecs.addRef ( value, this.entity.id, this.id, property ); } const result = Reflect.set ( this._values, property, value ); this.ecs._sendChange ( this, 'setEntity', property, old, value ); return result; }, get: () => { return this.ecs.getEntity ( this._values[ property ] ); } } ); this._values[ property ] = null; break; case '<ComponentObject>': Object.defineProperty ( this, property, { writable: false, enumerable: true, value: ComponentRefs.ComponentObject ( {}, this ) } ); this._refs[ property ] = this[ property ]; break; case '<ComponentSet>': Object.defineProperty ( this, property, { //writable: true, enumerable: true, set: ( value ) => { Reflect.set ( this._values, property, ComponentRefs.ComponentSet ( value, this, property ) ); }, get: () => { return Reflect.get ( this._values, property ); } } ); //this._refs[property] = this[property]; this[ property ] = []; break; case '<Component>': Object.defineProperty ( this, property, { enumerable: true, writeable: true, set: ( value ) => { if ( typeof value === 'object' ) { value = value.id; } const old = Reflect.get ( this._values, property ); const result = Reflect.set ( this._values, property, value ); this.ecs._sendChange ( this, 'setComponent', property, old, value ); return result; }, get: () => { return this.entity.componentMap[ this._values[ property ] ]; } } ); this._values[ property ] = null; break; default: let reflect = null; if ( typeof value === 'string' && value.startsWith ( '<Pointer ' ) ) { reflect = value.substring ( 9, value.length - 1 ).trim ().split ( '.' ) } Object.defineProperty ( this, property, { enumerable: true, writeable: true, set: ( value ) => { const old = Reflect.get ( this._values, property, value ); const result = Reflect.set ( this._values, property, value ); if ( reflect ) { let node = this; let fail = false; for ( let i = 0; i < reflect.length - 1; i++ ) { const subprop = reflect[ i ]; /* $lab:coverage:off$ */ if ( typeof node === 'object' && node !== null && node.hasOwnProperty ( subprop ) ) { /* $lab:coverage:on */ node = node[ subprop ]; } else { fail = true; } } if ( !fail ) { Reflect.set ( node, reflect[ reflect.length - 1 ], value ); node = value; } } this.ecs._sendChange ( this, 'set', property, old, value ); return result; }, get: () => { if ( !reflect ) { return Reflect.get ( this._values, property ); } let node = this; let fail = false; for ( let i = 0; i < reflect.length - 1; i++ ) { const subprop = reflect[ i ]; /* $lab:coverage:off$ */ if ( typeof node === 'object' && node !== null && node.hasOwnProperty ( subprop ) ) { /* $lab:coverage:on */ node = node[ subprop ]; } else { fail = true; } } if ( !fail ) { return Reflect.get ( node, reflect[ reflect.length - 1 ] ); } else { return Reflect.get ( this._values, property ); } } } ); this._values[ property ] = value; break; } } } // don't allow new properties Object.seal ( this ); Object.seal ( this._values ); const values = { ...initialValues }; delete values.type; delete values.entity; delete values.id; Object.assign ( this, values ); this.ecs._sendChange ( this, 'addComponent' ); this._ready = true; } stringify () { return JSON.stringify ( this.getObject () ); } getObject () { const serialize = this.constructor.definition.serialize; let values = this._values; if ( serialize ) { /* $lab:coverage:off$ */ if ( serialize.skip ) return undefined; /* $lab:coverage:on$ */ if ( serialize.ignore.length > 0 ) { values = {} const props = new Set ( [ ...serialize.ignore ] ); for ( const prop of Object.keys ( this._values ).filter ( prop => !props.has ( prop ) ) ) { values[ prop ] = this._values[ prop ]; } } } return Object.assign ( { id: this.id, type: this.type }, values, this._refs ); } } BaseComponent.definition = { properties: {}, multiset: false, serialize: { skip: false, ignore: [], } }; module.exports = BaseComponent;
23,943
https://github.com/aszecsei/Crimson/blob/master/Crimson.UI/Flags.cs
Github Open Source
Open Source
MIT
null
Crimson
aszecsei
C#
Code
350
749
using System; namespace Crimson.UI { [Flags] public enum Align { None = 0, CenterX = 1 << 0, CenterY = 1 << 1, Top = 1 << 2, Bottom = 1 << 3, Left = 1 << 4, Right = 1 << 5, TopLeft = Top | Left, TopCenter = Top | CenterX, TopRight = Top | Right, CenterLeft = CenterY | Left, Center = CenterY | CenterX, CenterRight = CenterY | Right, BottomLeft = Bottom | Left, BottomCenter = Bottom | CenterX, BottomRight = Bottom | Right, } /// <summary> /// Controls clipping of widgets. /// </summary> public enum WidgetClipping { /// <summary> /// This widget does not clip children, it and all children inherit /// the clipping area of the last widget that clipped. /// </summary> Inherit, /// <summary> /// This widget clips content to the bounds of the widget. /// </summary> ClipToBounds, /// <summary> /// This widget clips to its bounds when its Desired Size is larger than the allocated geometry the widget is given. /// </summary> OnDemand, } public enum FlowDirectionPreference { /// <summary> /// Inherits the flow direction set by the parent widget. /// </summary> Inherit, /// <summary> /// Begins laying out widgets using the current culture's layout direction preference, flipping the directionality of flows. /// </summary> Culture, /// <summary> /// Forces a Left to Right layout flow. /// </summary> LeftToRight, /// <summary> /// Forces a Right to Left layout flow. /// </summary> RightToLeft, } public enum Visibility { /// <summary> /// Visible and hit-testable (can interact with cursor). Default value. /// </summary> Visible, /// <summary> /// Not visible and takes up no space in the layout (obviously not hit-testable). /// </summary> Collapsed, /// <summary> /// Not visible but occupies layout space (obviously not hit-testable). /// </summary> Hidden, /// <summary> /// Visible but not hit-testable (cannot interact with cursor) and children in the hierarchy (if any) are also not hit-testable. /// </summary> HitTestInvisible, /// <summary> /// Visible but not hit-testable (cannot interact with cursor) and doesn't affect hit-testing on children (if any). /// </summary> SelfHitTestInvisible } public enum WidgetState { Normal, MouseOver, MouseDown } }
13,269
https://github.com/oursky/eslint-oursky/blob/master/.gitignore
Github Open Source
Open Source
Apache-2.0
2,023
eslint-oursky
oursky
Ignore List
Code
5
24
node_modules/ *.log dist/ .parcel-cache/ .DS_Store
31,660
https://github.com/Ortus-Solutions/ColdCukes/blob/master/index.cfm
Github Open Source
Open Source
MIT
2,021
ColdCukes
Ortus-Solutions
ColdFusion
Code
564
1,944
<cfscript> /* start here to make changes to how the stub files are generated */ // this is where your *.feature files (Gherkin formatted text) should live param name="form.featuresDir" type="string" default='#expandPath(".") & "\testData"#'; // this is your stub files results param name="form.outputDir" type="string" default='#expandPath(".") & "\tests\stubs"#'; response = ''; if (structKeyExists(form, "submitted")) { function cleanSlashes(str) { str = Replace(str, "/", "\", "ALL"); var ret = str; var hasTrailingSlash = right(str,1) is '\'; if (hasTrailingSlash) { ret = left(str, Len(str) - 1 ); } return ret; } featuresDir = cleanSlashes( form.featuresDir.Trim() ); outputDir = cleanSlashes( form.outputDir.Trim() ); // grab all the directories and subdirectories, and files within qFilesAndDirectories = DirectoryList(featuresDir, true, "query"); // clear the directory so we have fresh files and delete out ones where the matching Gherkin feature file was deleted if (DirectoryExists( outputDir )) { DirectoryDelete( outputDir, true ); } // filter to only the directories q = new query(); q.setName("qDirectories"); q.setDBType("query"); q.setAttributes(sourceQuery=qFilesAndDirectories); qDirectories = q.execute(sql="SELECT * FROM sourceQuery WHERE type = 'Dir'").getResult(); //writeDump(qDirectories); // loop through the directories and create TestBox Gherkin style BDD test file stubs for (featureDir in qDirectories) { // start using the ColdCukes obj for parsing obj = new ColdCukes(); // get the feature sub folder if it exists if (featureDir.directory == featuresDir) { subDir = "\"; } else { subDir = replaceNoCase(featureDir.directory, featuresDir, "") & "\"; } // test if this dir has any feature files directly in it currentFeatureDir = featureDir.directory & "\" & featureDir.name; qFeatureFiles = DirectoryList(currentFeatureDir, false, "query"); q = new query(); q.setName("qFeatureFiles"); q.setDBType("query"); q.setAttributes(sourceQuery=qFeatureFiles); qFeatureFiles = q.execute(sql="SELECT * FROM sourceQuery WHERE type = 'File' AND Name LIKE '%.feature'").getResult(); //writeDump(qFeatureFiles); // only create the Test file if there are feature files in current directory if (qFeatureFiles.RecordCount) { obj.setFeaturesDirectory( currentFeatureDir ); obj.setOutputDirectory( outputDir & subDir ); // optionally pass in different break or tab characters for the outputted code //obj.setLineBreakCharacters( chr(13) & chr(10) ); //obj.setTabCharacters( chr(9) ); // run it and see the file that was returned, which is auto-generated (including the dir) if not there already outputFile = obj.generateGherkinTests(); // you should be able to run the resulting files via TestBox with no errors response &= "generated Gherkin tests in '#outputFile#' successfully!<br>"; } } } </cfscript> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>ColdCukes Generator</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <cfoutput> <div class="container"> <h1 class="text-info">ColdCukes Generator</h1> <form action="#CGI.SCRIPT_NAME#" method="post"> <input type="hidden" name="submitted"> <div class="form-group"> <label for="featuresDir">Feature Directory</label> <input type="text" class="form-control" id="featuresDir" value="#featuresDir#" placeholder="#featuresDir#" name="featuresDir"> </div> <div class="form-group"> <label for="outputDir">Output Directory</label> <input type="text" class="form-control" id="outputDir" value="#outputDir#" placeholder="#outputDir#" name="outputDir"> </div> <button type="submit" class="btn btn-primary">Generate Gherkin Stubs</button> </form> <br> <cfif structKeyExists(form, "submitted")> <cfif Len(response)> <div class="alert alert-success" role="alert">#response#</div> <cfelse> <div class="alert alert-warning" role="alert">No Feature files found in the Feature Directory above</div> </cfif> </cfif> </div> </cfoutput> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </body> </html>
47,623
https://github.com/yunfandev/AlbiteREADER-WindowsPhone/blob/master/Albite.Reader.Core/Test/IsolatedContainerTest.cs
Github Open Source
Open Source
Apache-2.0
2,016
AlbiteREADER-WindowsPhone
yunfandev
C#
Code
96
293
using Albite.Reader.Core.IO; using Albite.Reader.Core.Test; using System.IO; namespace Albite.Reader.Core.Test { public class IsolatedContainerTest : TestCase { string basePath; string[] entityNames; public IsolatedContainerTest(string basePath, string[] entityNames) { this.basePath = basePath; this.entityNames = entityNames; } protected override void TestImplementation() { using (IsolatedContainer container = new IsolatedContainer(basePath)) { foreach (string entityName in entityNames) { byte[] buffer = new byte[IsolatedStorage.BufferSize]; using (Stream stream = container.Stream(entityName)) { int readBytes; int readBytesTotal = 0; while ((readBytes = stream.Read(buffer, 0, buffer.Length)) > 0) { readBytesTotal += readBytes; } Log("Read {0} bytes for {1} : {2}", readBytesTotal, basePath, entityName); } } } } } }
14,149
https://github.com/luxonis/depthai-hardware/blob/master/OSHW_KiCad_Community/Footprints/Altium Transfer Archive/OSHW_CAP_Altium_Vault_Generic_20201223.pretty/CAPC1005(2512)165_N.kicad_mod
Github Open Source
Open Source
MIT
2,023
depthai-hardware
luxonis
KiCad Layout
Code
194
730
(module "CAPC1005(2512)165_N" (layer F.Cu) (tedit 5B0D3C36) (fp_line (start -0.05000 -0.65000) (end 0.05000 -0.65000) (layer Cmts.User) (width 0.2)) (fp_line (start -0.05000 0.65000) (end 0.05000 0.65000) (layer Cmts.User) (width 0.2)) (fp_line (start -2.05000 0.65000) (end -2.05000 -0.65000) (layer Cmts.User) (width 0.2)) (fp_line (start -0.50000 0.00000) (end 0.50000 0.00000) (layer Cmts.User) (width 0.05)) (fp_line (start 0.00000 0.50000) (end 0.00000 -0.50000) (layer Cmts.User) (width 0.05)) (fp_line (start -2.00000 1.00000) (end 2.00000 1.00000) (layer Cmts.User) (width 0.05)) (fp_line (start -2.00000 -1.00000) (end 2.00000 -1.00000) (layer Cmts.User) (width 0.05)) (fp_line (start 2.00000 1.00000) (end 2.00000 -1.00000) (layer Cmts.User) (width 0.05)) (fp_line (start -2.00000 1.00000) (end -2.00000 -1.00000) (layer Cmts.User) (width 0.05)) (fp_line (start -1.45000 -0.82500) (end 1.45000 -0.82500) (layer Cmts.User) (width 0.1)) (fp_line (start -1.45000 0.82500) (end 1.45000 0.82500) (layer Cmts.User) (width 0.1)) (fp_line (start 1.45000 0.82500) (end 1.45000 -0.82500) (layer Cmts.User) (width 0.1)) (fp_line (start -1.45000 0.82500) (end -1.45000 -0.82500) (layer Cmts.User) (width 0.1)) (fp_line (start -2.00000 1.00000) (end -2.00000 -1.00000) (layer Cmts.User) (width 0.1)) (fp_line (start 2.00000 1.00000) (end 2.00000 -1.00000) (layer Cmts.User) (width 0.1)) (fp_line (start -2.00000 1.00000) (end 2.00000 1.00000) (layer Cmts.User) (width 0.1)) (fp_line (start -2.00000 -1.00000) (end 2.00000 -1.00000) (layer Cmts.User) (width 0.1)) )
16,773
https://github.com/787917909/lottery/blob/master/app/src/main/java/com/example/qiang/adapter/LotteryAdapter.java
Github Open Source
Open Source
Apache-2.0
null
lottery
787917909
Java
Code
285
1,092
package com.example.qiang.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.qiang.R; import com.example.qiang.activity.LotteryActivity; import com.example.qiang.entity.Mainlottery; import com.example.qiang.entity.Theme; import com.example.qiang.tool.BundleTemp; import java.util.ArrayList; import java.util.List; public class LotteryAdapter extends RecyclerView.Adapter<LotteryAdapter.ViewHolder> implements Filterable { private Context mContext; private List<Theme> mThemeList; private List<Theme> noteListFiltered ; @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (mContext == null){ mContext = parent.getContext(); } View view = LayoutInflater.from(mContext).inflate(R.layout.lottery_item,parent,false); final ViewHolder holder = new ViewHolder(view); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, LotteryActivity.class); intent.putExtras(BundleTemp.ThemeIdBundle(mThemeList.get(holder.getAdapterPosition()).getId(),mThemeList.get(holder.getAdapterPosition()).getTheme())); mContext.startActivity(intent); } }); return holder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Theme Theme = noteListFiltered.get(position); holder.Theme.setText(Theme.getTheme()); holder.Date.setText(Theme.getDate().split(" ")[0]); Glide.with(mContext).load(Theme.getImageid()).into(holder.ThemeImage); } @Override public int getItemCount() { return noteListFiltered.size(); } public Theme getNote(int position) { return mThemeList.get(position); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence charSequence) { String charString = charSequence.toString(); if (charString.isEmpty()) { noteListFiltered = mThemeList; } else { List<Theme> filteredList = new ArrayList<>(); for (Theme row : mThemeList) { // name match condition. this might differ depending on your requirement // here we are looking for name or phone number match if (row.getTheme().contains(charString)) { filteredList.add(row); } } noteListFiltered = filteredList; } FilterResults filterResults = new FilterResults(); filterResults.values = noteListFiltered; return filterResults; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { noteListFiltered = (ArrayList<Theme>) filterResults.values; notifyDataSetChanged(); } }; } static class ViewHolder extends RecyclerView.ViewHolder{ CardView cardView; ImageView ThemeImage; TextView Theme; TextView Date; public ViewHolder(View view){ super(view); cardView = (CardView) view; ThemeImage = view.findViewById(R.id.lottery_image); Theme = view.findViewById(R.id.lottery_name); Date = view.findViewById(R.id.lottery_date); } } public LotteryAdapter(List<Theme> ThemeList){ mThemeList = ThemeList; this.noteListFiltered = ThemeList; } }
21,032
https://github.com/sparsetech/pine/blob/master/src/test/scala-js/pine/dom/DOMSpec.scala
Github Open Source
Open Source
Apache-2.0
2,020
pine
sparsetech
Scala
Code
1,056
4,364
package pine.dom import org.scalajs.dom import org.scalatest.funsuite.AnyFunSuite import pine._ import scala.collection.mutable.ListBuffer import scala.scalajs.js class DOMSpec extends AnyFunSuite { /* test("Render node with one-way binding") { val title = Var("test") val span = html"""<div id="text"></div>""" span.setChildren(Seq(title)) val html = span.toDom.map(_.outerHTML).mkString assert(html, """<div id="text">test</div>""") title := "test2" val html2 = span.toDom.map(_.outerHTML).mkString assert(html2, """<div id="text">test2</div>""") } test("Update `value` attribute of `input` node") { val input = html"""<input type="text" />""" val node = input.toDom.head.asInstanceOf[dom.html.Input] assert(node.value, "") input.setAttribute("value", "Hello world") assert(node.value, "Hello world") } test("Update `href` attribute of `a` node") { val input = html"""<a>Action</a>""" val node = input.toDom.head.asInstanceOf[dom.html.Anchor] assert(node.href, "") input.attribute("href") := "http://github.com/" assert(node.href, "http://github.com/") } test("Get updated `value` attribute of `input` node") { ignore("Detecting changes in externally modified DOM nodes") val input = html"""<input type="text" />""" val node = input.toDom.head.asInstanceOf[dom.html.Input] assert(input.attribute("value").get, ()) node.value = "Hello world" assert(input.attribute("value").get, "Hello world") } test("Listen to attribute `value` on `input` node") { val input = html"""<input type="text" />""" val node = input.toDom.head.asInstanceOf[dom.html.Input] val value = Var("") input.attribute("value").asInstanceOf[StateChannel[String]].subscribe(value) assert(node.value, "") assert(input.attribute("value").get, "") value := "Hello world" assert(node.value, "Hello world") assert(input.attribute("value").get, "Hello world") } test("Listen to attribute `disabled` on `input` node") { val input = html"""<input type="text" />""" val node = input.toDom.head.asInstanceOf[dom.html.Input] val value = Var(false) input.attribute("disabled").asInstanceOf[StateChannel[Boolean]].subscribe(value) assert(node.disabled, false) value := true assert(node.disabled, true) value := false assert(node.disabled, false) } test("Listen to child channel on `span` node") { val span = html"""<span></span>""" val node = span.toDom.head val text = Var("Hello world") span.subscribe(text) assert(node.outerHTML, "<span>Hello world</span>") text := "42" assert(node.outerHTML, "<span>42</span>") } test("Render node with two-way binding") { val text = Var("") val input = html"""<input type="text" />""" input.attribute("value").bind(text.asInstanceOf[Channel[Any]]) val domElement = input.toDom.head.asInstanceOf[dom.html.Input] domElement.value = "Hello World" assert(text.get, "") val event = js.Dynamic.newInstance(js.Dynamic.global.Event)("change") .asInstanceOf[dom.raw.Event] domElement.dispatchEvent(event) assert(text.get, "Hello World") text := "42" assert(domElement.value, "42") } test("Set `class` attribute on nodes") { val div = html"""<div id="a" class="b c"></div>""" val node = div.toDom.head assert(node.outerHTML, """<div class="b c" id="a"></div>""") } test("Set `style` attribute on nodes") { val div = html"""<div></div>""" val node = div.toDom.head div.attribute("style") := "display: none" assert(node.outerHTML, """<div style="display: none"></div>""") } test("Listen to text value changes") { val text = Var("Initial value") val div = html"""<div></div>""" div.setChildren(Seq(text)) val node = div.toDom.head assert(node.outerHTML, """<div>Initial value</div>""") text := "Changed value" assert(node.outerHTML, """<div>Changed value</div>""") }*/ test("Obtain `options` from `select` node") { val select = html"""<select id="type"> <option value="opt1">Option 1</option> <option value="opt2" selected="true">Option 2</option> </select>""".as[tag.Select] val node = select.toDom assert(node.options(node.selectedIndex).value == "opt2") } test("Convert DOM node") { val node = dom.document.createElement("span") node.setAttribute("id", "test") node.appendChild(dom.document.createTextNode("Hello world")) val s = DOM.toTree(node).asInstanceOf[Tag[tag.Span]] assert(s.children.size == 1) s.children.head match { case t: Text => assert(t.text == "Hello world") case _ => fail() } } test("Convert DOM node (2)") { val node = dom.document.createElement("span") val node2 = dom.document.createTextNode("Hello world") node.appendChild(node2) val test = DOM.toTree(node).asInstanceOf[Tag[tag.Span]] assert(test.children.nonEmpty) val text = test.children.head.asInstanceOf[Text] assert(text.text == "Hello world") } test("Convert DOM node with Boolean attribute") { val node = dom.document.createElement("span") node.setAttribute("id", "test") val node2 = dom.document.createElement("input") node2.setAttribute("checked", "") node.appendChild(node2) val test = DOM.toTree(node).asInstanceOf[Tag[tag.Span]] assert(test.id() == "test") assert(test.children.nonEmpty) val input = test.children.head.asInstanceOf[Tag[tag.Input]] assert(input.checked()) assert(node.childNodes.length == 1) assert(node2.childNodes.length == 0) } test("Replace first occurrence") { val div = html"""<div id="test"><span id="hello">Hello</span></div>""".toDom dom.document.body.appendChild(div) val ref = TagRef[tag.Span] DOM.render { implicit ctx => ref.replace(html"<div>World</div>") } assert( DOM.toTree(dom.document.getElementById("test")).toHtml == """<div id="test"><div>World</div></div>""") dom.document.body.removeChild(div) } test("Replace first occurrence with multiple children") { val div = html"""<div id="test"><span id="hello">Hello</span></div>""".toDom dom.document.body.appendChild(div) val ref = TagRef[tag.Span] DOM.render { implicit ctx => ref.replace(List(html"<div>Hello</div>", html"<div>World</div>")) } assert( DOM.toTree(dom.document.getElementById("test")).toHtml == """<div id="test"><div>Hello</div><div>World</div></div>""") dom.document.body.removeChild(div) } test("Replace all occurrences") { val div = html"""<div id="test"><span></span><span></span></div>""".toDom dom.document.body.appendChild(div) val ref = TagRef[tag.Span] DOM.render { implicit ctx => ref.each.replace(html"<div>test</div>") } assert( DOM.toTree(dom.document.getElementById("test")).toHtml == """<div id="test"><div>test</div><div>test</div></div>""") dom.document.body.removeChild(div) } /* test("Remove child from attached DOM node") { val node = dom.document.createElement("span") val node2 = dom.document.createTextNode("Hello world") node.appendChild(node2) val test = DOM.toTree[tag.Span](node) assert(test.toHtml == "<span>Hello world</span>") test -= test.children.head assert(node.outerHTML, "<span></span>") } test("Set attribute on attached DOM node") { val node = dom.document.createElement("span") val node2 = dom.document.createElement("div") node2.setAttribute("id", "node2") node2.setAttribute("class", "test") node.appendChild(node2) val test = DOM.toTree[tag.Span](node) test.byId[tag.Div]("node2").`class` := "changed" assert(node2.asInstanceOf[js.Dynamic].className, "changed") }*/ test("Find elements by class") { val div = html"""<div><span class="a test"></span><span class="b test"></span></div>""".as[tag.Div] val node = div.toDom dom.document.body.appendChild(node) val input = TagRef.byClass[tag.Span]("test").each assert(input.dom.isInstanceOf[List[dom.html.Span]]) assert(input.dom.length == 2) DOM.render(implicit ctx => input.`class`.clear()) assert(DOM.toTree(node).toHtml == "<div><span></span><span></span></div>") dom.document.body.removeChild(node) } test("Listen to `onfocus` on `input` node") { val input = html"""<input type="text" />""".as[tag.Input] val node = input.toDom dom.document.body.appendChild(node) var eventTriggered = 0 TagRef[tag.Input].focus := { eventTriggered += 1 } node.focus() assert(eventTriggered == 1) dom.document.body.removeChild(node) } test("Resolve optional node") { val span = html"""<span></span>""".as[tag.Span] val node = span.toDom dom.document.body.appendChild(node) val ref = TagRef[tag.Span].opt assert(ref.dom.isInstanceOf[Option[_]]) assert(ref.dom.contains(node)) dom.document.body.removeChild(node) } test("Resolve optional node (2)") { val span = html"""<span></span>""".as[tag.Span] val node = span.toDom dom.document.body.appendChild(node) val ref = TagRef[tag.Input].opt assert(ref.dom.isInstanceOf[Option[_]]) assert(ref.dom.isEmpty) dom.document.body.removeChild(node) } test("Listen to `onclick` on `input` nodes") { val div = html"""<div><input type="text" /><input type="test" /></div>""".as[tag.Div] val node = div.toDom dom.document.body.appendChild(node) val input = TagRef[tag.Input].each assert(input.dom.length == 2) var eventTriggered = 0 input.click := { eventTriggered += 1 } input.dom.foreach(_.click()) assert(eventTriggered == 2) dom.document.body.removeChild(node) } test("Listen to `onclick` on `button` node") { val input = html"""<button />""".as[tag.Button] val node = input.toDom dom.document.body.appendChild(node) var eventTriggered = 0 TagRef[tag.Button].click := { eventTriggered += 1 } // TODO Support `new dom.Event("change")` in scala-js-dom val event = js.Dynamic.newInstance(js.Dynamic.global.Event)("click") .asInstanceOf[dom.raw.Event] node.dispatchEvent(event) assert(eventTriggered == 1) dom.document.body.removeChild(node) } test("Override event handler") { val input = html"""<button />""".as[tag.Button] val node = input.toDom dom.document.body.appendChild(node) val eventTriggered = ListBuffer.empty[Int] TagRef[tag.Button].click := { _ => eventTriggered += 23 } TagRef[tag.Button].click := { _ => eventTriggered += 42 } val event = js.Dynamic.newInstance(js.Dynamic.global.Event)("click") .asInstanceOf[dom.raw.Event] node.dispatchEvent(event) assert(eventTriggered == Seq(42)) dom.document.body.removeChild(node) } test("Update `disabled` attribute of `input` node") { val input = html"""<input type="text" />""".as[tag.Input] val node = input.toDom dom.document.body.appendChild(node) assert(!node.disabled) DOM.render { implicit ctx => TagRef[tag.Input].disabled := true } assert(node.disabled) dom.document.body.removeChild(node) } test("Render attributes in a namespace") { val node = tag.Div.setAttr("a:b:c", "test").toDom assert(node.getAttribute("a:b:c") == "test") assert(node.getAttributeNS("a:b", "c") == null) } test("Render SVG node") { val input = xml""" <svg viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="test"> <circle pn:id="circle" a:b:c="test" cx="50" cy="50" r="40" fill="blue" /> </svg> """.as[tag.Svg] val node = input.toDom assert(node.getAttribute("xmlns") == "http://www.w3.org/2000/svg") assert(node.getAttribute("xmlns:xlink") == "http://www.w3.org/1999/xlink") assert(node.getAttributeNS("xmlns", "xlink") == null) // TODO These two assertions were commented out because jsdom's behaviour // diverges from Chromium's // assert(node.getAttributeNS(null, "xmlns") == null) // assert(node.getAttributeNS(null, "xmlns:xlink") == null) assert(node.getAttribute("class") == "test") assert(node.getAttributeNS(null, "class") == "test") assert(node.getAttributeNS(null, "viewBox") == "0 0 300 100") assert(node .getElementsByTagNameNS(null, "circle") .length == 0) val circle = node .getElementsByTagNameNS("http://www.w3.org/2000/svg", "circle") .item(0) assert(circle.getAttributeNS(null, "cx") == "50") assert(circle.getAttribute("pn:id") == "circle") assert(circle.getAttributeNS("pn", "id") == null) assert(circle.getAttribute("a:b:c") == "test") assert(circle.getAttributeNS("a:b", "c") == null) } }
44,386
https://github.com/pagupasoft/NEOPAGUPA/blob/master/resources/views/admin/citasMedicas/atencionCitas/individualPlano.blade.php
Github Open Source
Open Source
MIT
null
NEOPAGUPA
pagupasoft
PHP
Code
253
1,412
@extends ('admin.layouts.admin') @section('principal') <div class="card card-secondary"> <div class="card-header"> <h3 class="card-title">Informe Individual de Clientes</h3> </div> <!-- /.card-header --> <div class="card-body"> <form class="form-horizontal" method="get" action="{{ url("informeindividualplano") }}"> @csrf <div class="col-md-12"> <div class="form-group row"> <div class="col-sm-12"> <div class="row mb-2"> <label for="fecha_desde" class="col-sm-1 col-form-label text-right">Desde :</label> <div class="col-sm-3"> <input type="date" class="form-control" id="fecha_desde" name="fecha_desde" value='<?php if(isset($fDesde)){echo $fDesde;}else{ echo(date("Y")."-".date("m")."-01");} ?>' required> </div> <label for="fecha_hasta" class="col-sm-1 col-form-label text-right">Hasta :</label> <div class="col-sm-3"> <input type="date" class="form-control" id="fecha_hasta" name="fecha_hasta" value='<?php if(isset($fHasta)){echo $fHasta;}else{ echo(date("Y")."-".date("m")."-".date("d"));} ?>' required> </div> <!--div class="custom-control custom-checkbox col-sm2 pt-2"> <input class="custom-control-input" type="checkbox" id="incluirFechas" name="incluirFechas" value="1" <?php if(isset($fechasI)) echo "checked"; ?>> <label for="incluirFechas" class="custom-control-label">Todo</label> </div--> </div> </div> </div> <div class="row"> <label for="fecha_desde" class="col-sm-1 col-form-label text-right">Sucursal :</label> <div class="col-sm-3"> <select class="form-control" name="sucursal"> @foreach($sucursales as $sucursal) <option value={{$sucursal->sucursal_id}} @if($sucursal_id==$sucursal->sucursal_id) selected @endif>{{$sucursal->sucursal_nombre}}</option> @endforeach </select> </div> </div> <div class="text-right"> <input class="btn btn-success" type="submit" value="Buscar"> </div> </div> </div> <form id="my_form" action="{{ url('generarindividualplano') }}" method="post"></form> <table class="table table-bordered table-hover table-responsive sin-salto"> <thead> <tr class="text-center neo-fondo-tabla"> <th>Identificación</th> <th>Cliente</th> <th>Fecha de Nacimiento</th> <th>Sexo</th> <th>Acción</th> </tr> </thead> <tbody> @if(isset($ordenes)) <?php $i=0 ?> @foreach($ordenes as $orden) <?php $agregar=true; for($j=0; $j<=$i; $j++){ if($ordenes[$j]->paciente->paciente_cedula==$orden->paciente->paciente_cedula && $j!=$i){ $agregar=false; break; } } $i++; ?> @if($agregar) <tr> <td>{{ $orden->paciente->paciente_cedula }}</td> <td>{{ $orden->paciente->paciente_apellidos }} {{ $orden->paciente->paciente_nombres }}</td> <td>{{ $orden->paciente->paciente_fecha_nacimiento }}</td> <td>{{ $orden->paciente->paciente_sexo }}</td> <td> <input form="" type="hidden" class="form-control" id="fecha_desde" name="fechaA" value='<?php if(isset($fDesde)){echo $fDesde;}else{ echo(date("Y")."-".date("m")."-".date("d"));} ?>' required> <input type="hidden" class="form-control" id="fecha_hasta" name="fechaB" value='<?php if(isset($fHasta)){echo $fHasta;}else{ echo(date("Y")."-".date("m")."-".date("d"));} ?>' required> <input type="hidden" name="paciente_id" value="{{ $orden->paciente->paciente_id }}"> <a target="_blank" href="{{ url('/generarindividualplano') }}?fechaA={{ $fDesde }}&fechaB={{ $fHasta }}&paciente_id={{ $orden->paciente_id }}&sucursal_id={{$sucursal_id}}" class="btn btn-primary">Descargar</a> </td> </tr> @endif @endforeach @endif </tbody> </table> </div> <!-- /.modal --> @endsection
16,978
https://github.com/blongz/elfinder-2.x-servlet/blob/master/src/main/java/org/grapheco/elfinder/util/FsServiceUtils.java
Github Open Source
Open Source
BSD-2-Clause
2,022
elfinder-2.x-servlet
blongz
Java
Code
43
176
package org.grapheco.elfinder.util; import java.io.IOException; import org.grapheco.elfinder.controller.executor.FsItemEx; import org.grapheco.elfinder.service.FsItem; import org.grapheco.elfinder.service.FsService; public abstract class FsServiceUtils { public static FsItemEx findItem(FsService fsService, String hash) throws IOException { FsItem fsi = fsService.fromHash(hash); if (fsi == null) { return null; } return new FsItemEx(fsi, fsService); } }
32,889
https://github.com/akiles987/cursoslaravel/blob/master/app/Http/Controllers/ProfesoreController.php
Github Open Source
Open Source
MIT
null
cursoslaravel
akiles987
PHP
Code
152
585
<?php namespace App\Http\Controllers; use App\Models\Profesore; use Illuminate\Http\Request; use PDF; use App\Rules\Validardni; class ProfesoreController extends Controller { public function index() { $profesores = Profesore::all(); return view('profesores.index', compact('profesores')); } public function create() { //mostrar el formulario de creación return view('profesores.create'); } public function store(Request $request) { $validated = $request->validate([ 'nombre' => 'required', 'apellidos' => 'required', 'email' => 'required', 'f_nacimiento' => 'required|date', 'telefono' => 'required', 'dni' => ['required',new Validardni], 'curso' => 'required', ]); Profesore::create($request->all()); return redirect()->route('profesores.index'); } public function show($id) { // } public function edit($id) { $profesore = Profesore::find($id); return view('profesores.edit', compact('profesore')); } public function update(Request $request, $id) { $validated = $request->validate([ 'nombre' => 'required', 'apellidos' => 'required', 'dni' => ['required',new Validardni], ]); $profesore = Profesore::find($id); $profesore->update($request->all()); return redirect()->route('profesores.index'); } public function destroy($id) { Profesore::find($id)->delete(); // return redirect('/profesores'); //estas dos instrucciones hacen lo mismo return redirect()->route('profesores.index'); } public function imprimir(){ $profesores = Profesore::all(); $data = compact('profesores'); $pdf = \PDF::loadView('pdf.profesores', $data); return $pdf->download('primerpdf.pdf'); } }
15,540
https://github.com/shark8me/kubeapps/blob/master/dashboard/src/components/ChartList/ChartListItem.tsx
Github Open Source
Open Source
Apache-2.0
null
kubeapps
shark8me
TypeScript
Code
126
447
import * as React from "react"; import { Link } from "react-router-dom"; import placeholder from "../../placeholder.png"; import { IChart } from "../../shared/types"; import Card, { CardContent, CardIcon } from "../Card"; import "./ChartListItem.css"; interface IChartListItemProps { chart: IChart; } class ChartListItem extends React.Component<IChartListItemProps> { public render() { const { chart } = this.props; const { icon, name, repo } = chart.attributes; const iconSrc = icon ? `/api/chartsvc/${icon}` : placeholder; const latestAppVersion = chart.relationships.latestChartVersion.data.app_version; return ( <Card key={`${repo}/${name}`} responsive={true} className="ChartListItem"> <Link to={`/charts/` + chart.id} title={name}> <CardIcon icon={iconSrc} /> <CardContent> <div className="ChartListItem__content"> <h3 className="ChartListItem__content__title type-big">{name}</h3> <div className="ChartListItem__content__info"> <p className="ChartListItem__content__info_version margin-reset type-small padding-t-tiny type-color-light-blue"> {latestAppVersion || "-"} </p> <span className={`ChartListItem__content__info_repo ${ repo.name } type-small padding-t-tiny padding-h-normal`} > {repo.name} </span> </div> </div> </CardContent> </Link> </Card> ); } } export default ChartListItem;
49,288
https://github.com/rkausch/opensphere-desktop/blob/master/open-sphere-plugins/wps/src/main/java/io/opensphere/wps/ui/detail/WpsDetailPanel.java
Github Open Source
Open Source
LicenseRef-scancode-free-unknown, Apache-2.0, LicenseRef-scancode-public-domain
2,020
opensphere-desktop
rkausch
Java
Code
655
2,493
package io.opensphere.wps.ui.detail; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import io.opensphere.controlpanels.DetailPane; import io.opensphere.core.Toolbox; import io.opensphere.core.util.collections.New; import io.opensphere.core.util.collections.StreamUtilities; import io.opensphere.core.util.image.IconUtil; import io.opensphere.core.util.image.IconUtil.IconType; import io.opensphere.core.util.lang.StringUtilities; import io.opensphere.mantle.data.DataGroupInfo; import io.opensphere.mantle.data.DataTypeInfo; import io.opensphere.mantle.data.impl.GroupCategorizationUtilities; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.image.ImageView; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; /** * An implementation of the {@link DetailPane} in which a WPS preview / editor * is defined. */ public class WpsDetailPanel extends DetailPane { /** * The field in which the provider information is entered. */ private final Label myProviderField; /** * The field in which the type information is entered. */ private final Label myTypeField; /** * The field in which the description information is entered. */ private final Label myDescriptionField; /** * The field in which the URL information is entered. */ private final Label myUrlField; /** * The field in which the provider information is entered. */ private final Label myTagsField; /** * The button used to clone the WPS process configuration. */ private final Button myCloneButton; /** * The button used to reset deviations from the saved configuration values. */ private final Button myResetButton; /** * The button used to save deviations from the saved configuration values. */ private final Button mySaveButton; /** * The bar component in which the {@link #mySaveButton} and * {@link #myResetButton}s are rendered. */ private final ButtonBar myButtonBar; /** * The area in which the form is displayed. */ private final GridPane myParameterFormArea; /** * The model in which detail data is contained for the U/I. */ private final WpsProcessModel myModel; /** * Creates a new panel. * * @param pToolbox the toolbox through which application interactions occur. */ @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") public WpsDetailPanel(Toolbox pToolbox) { super(pToolbox); myModel = new WpsProcessModel(); GridPane grid = createContainer(); myProviderField = new Label(); myProviderField.textProperty().bind(myModel.getProvider()); grid.addRow(0, new Label("Provider:"), myProviderField); myTypeField = new Label(); myTypeField.textProperty().bind(myModel.getTypes()); grid.addRow(1, new Label("Type:"), myTypeField); myDescriptionField = new Label(); myDescriptionField.textProperty().bind(myModel.getDescription()); myDescriptionField.setWrapText(true); myDescriptionField.setFont( Font.font(myDescriptionField.getFont().getName(), FontPosture.ITALIC, myDescriptionField.getFont().getSize())); myDescriptionField.setPadding(new Insets(2, 2, 2, 2)); ScrollPane descriptionPane = new ScrollPane(myDescriptionField); descriptionPane.setHbarPolicy(ScrollBarPolicy.NEVER); descriptionPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); descriptionPane.setFitToWidth(true); grid.add(descriptionPane, 0, 2, 2, 1); GridPane.setFillWidth(descriptionPane, Boolean.TRUE); GridPane.setHgrow(descriptionPane, Priority.ALWAYS); GridPane.setVgrow(descriptionPane, Priority.SOMETIMES); myTagsField = new Label(); myTagsField.textProperty().bind(myModel.getTags()); grid.addRow(3, new Label("Tags:"), myTagsField); myUrlField = new Label(); myUrlField.textProperty().bind(myModel.getUrl()); grid.addRow(4, new Label("URL(s):"), myUrlField); myCloneButton = new Button("Clone", new ImageView(IconUtil.getResource(IconType.COPY))); grid.addRow(5, myCloneButton); myParameterFormArea = createProcessEditor(); myParameterFormArea.setStyle("-fx-border-color: #676767; -fx-border-style: solid inside line-join miter;"); GridPane.setFillHeight(myParameterFormArea, Boolean.TRUE); GridPane.setHgrow(myParameterFormArea, Priority.ALWAYS); GridPane.setVgrow(myParameterFormArea, Priority.ALWAYS); grid.add(myParameterFormArea, 0, 6, 2, 1); myButtonBar = new ButtonBar(); myResetButton = new Button("Reset", new ImageView(IconUtil.getResource(IconType.RELOAD))); mySaveButton = new Button("Save", new ImageView(IconUtil.getResource(IconType.DISK))); myButtonBar.getButtons().add(myResetButton); myButtonBar.getButtons().add(mySaveButton); grid.add(myButtonBar, 0, 7, 2, 1); setCenter(grid); } /** * Creates and configures a GridPane into which all content will be added. * * @return a new GridPane into which all content will be added. */ protected GridPane createContainer() { GridPane grid = new GridPane(); grid.setVgap(5); ColumnConstraints columnConstraints1 = new ColumnConstraints(); columnConstraints1.setHgrow(Priority.NEVER); ColumnConstraints columnConstraints2 = new ColumnConstraints(); columnConstraints2.setFillWidth(true); columnConstraints2.setHgrow(Priority.ALWAYS); grid.getColumnConstraints().add(columnConstraints1); grid.getColumnConstraints().add(columnConstraints2); return grid; } /** * Creates an implementation specific editor, in which a panel tied to a * specific WPS process is rendered. * * @return a new editor, configured for a specific WPS process. */ protected GridPane createProcessEditor() { return new GridPane(); } /** * Gets the value of the {@link #myParameterFormArea} field. * * @return the value stored in the {@link #myParameterFormArea} field. */ public GridPane getParameterFormArea() { return myParameterFormArea; } /** * {@inheritDoc} * * @see io.opensphere.controlpanels.DetailPane#populate(io.opensphere.mantle.data.DataGroupInfo) */ @Override public void populate(DataGroupInfo pDataGroup) { myModel.getTagList().clear(); myModel.getTypeList().clear(); myParameterFormArea.getChildren().clear(); myModel.getProvider().set(pDataGroup.getTopParentDisplayName()); myModel.getTypeList().addAll(StreamUtilities.map(GroupCategorizationUtilities.getGroupCategories(pDataGroup, false), input -> StringUtilities.trim(input, 's'))); myModel.getDescription().set(pDataGroup.getSummaryDescription()); Collection<String> tags = New.set(); Collection<String> descriptions = New.insertionOrderSet(); Collection<DataTypeInfo> members = pDataGroup.getMembers(true); Collection<String> urls = New.list(members.size()); if (!members.isEmpty()) { List<DataTypeInfo> memberList = New.list(members); Collections.sort(memberList, DataTypeInfo.DISPLAY_NAME_COMPARATOR); for (DataTypeInfo member : memberList) { tags.addAll(member.getTags()); if (!StringUtils.isBlank(member.getDescription())) { descriptions.add(member.getDescription()); } if (member.getUrl() != null) { urls.add(member.getUrl()); } } } // Sort the tags if (!tags.isEmpty()) { List<String> tagList = New.list(tags); Collections.sort(tagList); tags = tagList; } myModel.getTagList().addAll(tags); StringBuilder descriptionText = new StringBuilder(); StringUtilities.join(descriptionText, "\n\n", descriptions); myModel.getDescription().set(descriptionText.toString()); StringBuilder urlText = new StringBuilder(); StringUtilities.join(urlText, "\n", urls); myModel.getUrl().set(urlText.toString()); } }
18,884
https://github.com/trowik/document-merge-service/blob/master/document_merge_service/api/tests/test_template.py
Github Open Source
Open Source
MIT
2,019
document-merge-service
trowik
Python
Code
654
2,935
import io import pytest from django.core.exceptions import ImproperlyConfigured from django.urls import reverse from docx import Document from lxml import etree from rest_framework import status from .. import models from ..views import walk_nested from .data import django_file @pytest.mark.parametrize( "template__group,group_access_only,size", [(None, False, 2), ("admin", True, 2), ("unknown", True, 1), ("unknown", False, 2)], ) def test_template_list_group_access( db, admin_client, template, template_factory, snapshot, size, group_access_only, settings, ): settings.GROUP_ACCESS_ONLY = group_access_only url = reverse("template-list") # add a global template (no group) template_factory() response = admin_client.get(url) assert response.status_code == status.HTTP_200_OK assert response.json()["count"] == size @pytest.mark.parametrize("template__description", ["test description"]) @pytest.mark.parametrize( "query_params,size", [ ({"description__icontains": "test"}, 1), ({"description__search": "test"}, 1), ({"description__icontains": "unknown"}, 0), ({"description__search": "unknown"}, 0), ], ) def test_template_list_query_params( db, admin_client, template, snapshot, size, query_params ): url = reverse("template-list") response = admin_client.get(url, data=query_params) assert response.status_code == status.HTTP_200_OK assert response.json()["count"] == size def test_template_detail(db, client, template): url = reverse("template-detail", args=[template.pk]) response = client.get(url) assert response.status_code == status.HTTP_200_OK @pytest.mark.parametrize( "template_name,status_code,group,require_authentication,authenticated", [ ("docx-template.docx", status.HTTP_201_CREATED, None, False, False), ("docx-template.docx", status.HTTP_201_CREATED, None, True, True), ("docx-template.docx", status.HTTP_401_UNAUTHORIZED, None, True, False), ("docx-template.docx", status.HTTP_400_BAD_REQUEST, "unknown", True, True), ("docx-template.docx", status.HTTP_201_CREATED, "admin", True, True), ("test.txt", status.HTTP_400_BAD_REQUEST, None, False, False), ], ) def test_template_create( db, client, admin_client, template_name, status_code, group, require_authentication, settings, authenticated, ): if authenticated: client = admin_client settings.REQUIRE_AUTHENTICATION = require_authentication url = reverse("template-list") template_file = django_file(template_name) data = { "slug": "test-slug", "template": template_file.file, "engine": models.Template.DOCX_TEMPLATE, } if group: data["group"] = group response = client.post(url, data=data, format="multipart") assert response.status_code == status_code if status_code == status.HTTP_201_CREATED: data = response.json() template_link = data["template"] response = client.get(template_link) assert response.status_code == status.HTTP_200_OK Document(io.BytesIO(response.content)) @pytest.mark.parametrize( "template_name,status_code", [ ("docx-template.docx", status.HTTP_200_OK), ("test.txt", status.HTTP_400_BAD_REQUEST), ], ) def test_template_update(db, client, template, template_name, status_code): url = reverse("template-detail", args=[template.pk]) template_file = django_file(template_name) data = {"description": "Test description", "template": template_file.file} response = client.patch(url, data=data, format="multipart") assert response.status_code == status_code if status_code == status.HTTP_200_OK: template.refresh_from_db() assert template.description == "Test description" def test_template_destroy(db, client, template): url = reverse("template-detail", args=[template.pk]) response = client.delete(url) assert response.status_code == status.HTTP_204_NO_CONTENT @pytest.mark.parametrize( "template__slug,template__engine,template__template", [ ( "TestNameTemplate", models.Template.DOCX_TEMPLATE, django_file("docx-template.docx"), ), ( "TestNameMailMerge", models.Template.DOCX_MAILMERGE, django_file("docx-mailmerge.docx"), ), ], ) def test_template_merge_docx(db, client, template, snapshot): url = reverse("template-merge", args=[template.pk]) response = client.post(url, data={"data": {"test": "Test input"}}, format="json") assert response.status_code == status.HTTP_200_OK assert ( response._headers["content-type"][1] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) docx = Document(io.BytesIO(response.content)) xml = etree.tostring(docx._element.body, encoding="unicode", pretty_print=True) try: snapshot.assert_match(xml) except AssertionError: # pragma: no cover with open(f"/tmp/{template.slug}.docx", "wb") as output: output.write(response.content) print("Template output changed. Check file at %s" % output.name) raise # This needs a strange parametrization. If `unoconv_local` is in a separate # `parametrize()`, the template filename in the second test will be appended with a # hash and the test fails @pytest.mark.parametrize( "template__engine,template__template,unoconv_local", [ (models.Template.DOCX_TEMPLATE, django_file("docx-template.docx"), True), (models.Template.DOCX_TEMPLATE, django_file("docx-template.docx"), False), ], ) def test_template_merge_as_pdf(db, settings, unoconv_local, client, template): settings.UNOCONV_LOCAL = unoconv_local settings.UNOCONV_URL = "" if unoconv_local else "http://unoconv:3000" url = reverse("template-merge", args=[template.pk]) response = client.post( url, data={"data": {"test": "Test input"}, "convert": "pdf"}, format="json" ) assert response.status_code == status.HTTP_200_OK assert response["Content-Type"] == "application/pdf" assert f"{template.pk}.pdf" in response["Content-Disposition"] assert response.content[0:4] == b"%PDF" @pytest.mark.parametrize( "template__engine,template__template", [(models.Template.DOCX_TEMPLATE, django_file("docx-template.docx"))], ) def test_template_merge_as_pdf_without_unoconv(db, client, template, settings): settings.UNOCONV_URL = None url = reverse("template-merge", args=[template.pk]) with pytest.raises(ImproperlyConfigured): client.post( url, data={"data": {"test": "Test input"}, "convert": "pdf"}, format="json" ) @pytest.mark.parametrize( "template__engine,template__template", [(models.Template.DOCX_TEMPLATE, django_file("docx-template-loopcontrols.docx"))], ) def test_template_merge_jinja_extensions_docx(db, client, template, settings, snapshot): settings.DOCXTEMPLATE_JINJA_EXTENSIONS = ["jinja2.ext.loopcontrols"] url = reverse("template-merge", args=[template.pk]) response = client.post(url, data={"data": {"test": "Test input"}}, format="json") assert response.status_code == status.HTTP_200_OK assert ( response._headers["content-type"][1] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) docx = Document(io.BytesIO(response.content)) xml = etree.tostring(docx._element.body, encoding="unicode", pretty_print=True) snapshot.assert_match(xml) @pytest.mark.parametrize( "template__engine,template__template", [(models.Template.DOCX_TEMPLATE, django_file("docx-template-filters.docx"))], ) def test_template_merge_jinja_filters_docx(db, client, template, snapshot, settings): settings.LANGUAGE_CODE = "de-ch" url = reverse("template-merge", args=[template.pk]) data = { "data": { "test_date": "1984-09-15", "test_time": "23:24", "test_datetime": "1984-09-15 23:23", "test_datetime2": "23:23-1984-09-15", "test_none": None, "test_richtext": {"nested": "This is\na test."}, } } response = client.post(url, data=data, format="json") assert response.status_code == status.HTTP_200_OK assert ( response._headers["content-type"][1] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) docx = Document(io.BytesIO(response.content)) xml = etree.tostring(docx._element.body, encoding="unicode", pretty_print=True) snapshot.assert_match(xml) def test_walk_nested_datastructure(): assert walk_nested({"x": "y", "foo": {"baz": "buzz"}}, lambda x: x.upper()) == { "x": "Y", "foo": {"baz": "BUZZ"}, } assert walk_nested( {"x": "y", "foo": ["bar", {"baz": "buzz"}]}, lambda x: x.upper() ) == {"x": "Y", "foo": ["BAR", {"baz": "BUZZ"}]}
5,649
https://github.com/datenreisender/dotfiles/blob/master/bin/off
Github Open Source
Open Source
MIT
2,023
dotfiles
datenreisender
Shell
Code
17
65
#!/bin/sh resize "" $(longest_line < ~/downloads.txt) caffeinate bash -c " cat ~/downloads.txt && otr-fetch && (otr-decode-move; otr-print-failures)"
19,449
https://github.com/Kleidukos/haddock/blob/master/html-test/src/PR643.hs
Github Open Source
Open Source
BSD-2-Clause
2,023
haddock
Kleidukos
Haskell
Code
10
29
{-# LANGUAGE Haskell2010 #-} module PR643 (test) where import PR643_1
21,232
https://github.com/reverofx/rv6/blob/master/user/usys.pl
Github Open Source
Open Source
MIT-0
2,022
rv6
reverofx
Perl
Code
134
478
#!/usr/bin/perl -w # Generate usys.S, the stubs for syscalls. print "# generated by usys.pl - do not edit\n"; print "#include \"kernel/syscall.h\"\n"; $target = $ENV{'TARGET'}; if($target eq "riscv") { *entry = sub { my $name = shift; print ".global $name\n"; print "${name}:\n"; print " li a7, SYS_${name}\n"; print " ecall\n"; print " ret\n"; } } elsif($target eq "arm") { *entry = sub { my $name = shift; print ".global $name\n"; print "${name}:\n"; print " STR x7, [sp, #-0x08]!\n"; print " MOV x7, #SYS_${name}\n"; print " SVC 0x00\n"; print " LDR x7, [sp], #0x08\n"; print " br x30; //lr = x30\n"; } } else { exit(1); } entry("fork"); entry("exit"); entry("wait"); entry("pipe"); entry("read"); entry("write"); entry("close"); entry("kill"); entry("exec"); entry("open"); entry("mknod"); entry("unlink"); entry("fstat"); entry("link"); entry("mkdir"); entry("chdir"); entry("dup"); entry("getpid"); entry("sbrk"); entry("sleep"); entry("uptime"); entry("poweroff"); entry("select"); entry("getpagesize"); entry("waitpid"); entry("getppid"); entry("lseek"); entry("uptime_as_micro"); entry("clock");
19,023
https://github.com/chandrab/steampipe_alchemy/blob/master/tests/main/test_steampipe_alchemy.py
Github Open Source
Open Source
BSD-3-Clause
2,021
steampipe_alchemy
chandrab
Python
Code
238
1,138
#!/usr/bin/env python """ Tests for `steampipe_alchemy` package. For testing we grab lists of values via boto3 and compare that to what we get from steampipe-alchemy. This requires AWS credentials to be set in the environment, because of this these tests only run when merged. The credentials used for https://github.com/RyanJarv/steampipe_alchemy are limited to only the permissions required here and run in an isolated account. If anything is added these permissions need to be updated. """ import pytest import boto3 import steampipe_alchemy from steampipe_alchemy.models import AwsVpc regions = ['us-east-1', 'us-east-2', 'us-west-2', 'us-west-1'] @pytest.fixture(scope='module') def steam_class() -> steampipe_alchemy.SteamPipe: return steampipe_alchemy.SteamPipe() @pytest.fixture(scope='module') def steam(steam_class) -> steampipe_alchemy.SteamPipe: steam_class.install(['aws']) steam_class.update_config(aws={ "plugin": "aws", "regions": regions, }) status: steampipe_alchemy.ServiceStatus = steam_class.start() assert status.state == status.state.RUNNING return steam_class @pytest.fixture(scope='module') def steam_install_plugin(steam_class) -> steampipe_alchemy.SteamPipe: steam_class.install() steam_class.install_plugin('aws') steam_class.update_config(aws={ "plugin": "aws", "regions": regions, }) status: steampipe_alchemy.ServiceStatus = steam_class.start() assert status.state == status.state.RUNNING return steam_class def test_steam_install_plugin(steam_install_plugin): for i in steam_install_plugin.query(AwsVpc.vpc_id): print(i) @pytest.fixture(scope='module') def query_deprecated() -> steampipe_alchemy.query: steampipe_alchemy.install(['aws']) steampipe_alchemy.update_config(aws={ "plugin": "aws", "regions": regions, }) status: steampipe_alchemy.ServiceStatus = steampipe_alchemy.start() assert status.state == steampipe_alchemy.ServiceState.RUNNING return steampipe_alchemy.query @pytest.fixture(scope='module') def vpc_ids_deprecated(query_deprecated: steampipe_alchemy.query): for i in query_deprecated(AwsVpc.vpc_id): print(i) return [vpc_id for (vpc_id,) in query_deprecated(AwsVpc.vpc_id)] @pytest.mark.parametrize("region", regions) def test_this_deprecated(region, vpc_ids_deprecated): for vpc in boto3.resource('ec2', region_name=region).vpcs.all(): assert vpc.id in sorted(vpc_ids_deprecated) @pytest.fixture(scope='module') def vpc_ids(steam: steampipe_alchemy.SteamPipe): return [vpc_id for (vpc_id,) in steam.query(AwsVpc.vpc_id)] @pytest.mark.parametrize("region", regions) def test_this(region, vpc_ids): for vpc in boto3.resource('ec2', region_name=region).vpcs.all(): assert vpc.id in sorted(vpc_ids) def test_deprecated_function_prints_warning(): steampipe_alchemy.query(AwsVpc.vpc_id) # TODO: # def test_status_configures_dbconn_when_postgres_is_running() # def test_status_does_not_configure_dbconn_when_postgres_is_stopped() # def test_status_does_not_configure_dbconn_when_postgres_is_in_unknown_state()
33,701
https://github.com/bjqiwei/unimrcp/blob/master/libs/sofia-sip/utils/apps_utils.h
Github Open Source
Open Source
Apache-2.0
null
unimrcp
bjqiwei
C
Code
425
1,466
#ifndef APPS_UTILS_H /** Defined when apps_utils.h has been included. */ #define APPS_UTILS_H /** * @nofile apps_utils.h * @brief * * Copyright (C) 2005 Nokia Corporation. * * Written by Pekka Pessi <pekka -dot pessi -at- nokia -dot- com> * * @STARTLGPL@ * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * @ENDLGPL@ * * @date Created: Thu Apr 8 15:55:15 2004 ppessi * */ SOFIA_BEGIN_DECLS static inline int proxy_authenticate(context_t *c, nta_outgoing_t *oreq, sip_t const *sip, nta_response_f response_function) { if (sip && sip->sip_status->st_status == 407 && sip->sip_proxy_authenticate && c->c_proxy_auth_retries++ < 3 && c->c_proxy && c->c_proxy->url_user && c->c_proxy->url_password) { url_t *u = c->c_proxy; msg_t *rmsg = nta_outgoing_getrequest(oreq); sip_t *rsip = sip_object(rmsg); if (auc_challenge(&c->c_proxy_auth, c->c_home, sip->sip_proxy_authenticate, sip_proxy_authorization_class) >= 0 && auc_all_credentials(&c->c_proxy_auth, NULL, NULL, u->url_user, u->url_password) > 0 && auc_authorization(&c->c_proxy_auth, rmsg, (msg_pub_t *)rsip, rsip->sip_request->rq_method_name, rsip->sip_request->rq_url, rsip->sip_payload) > 0) { nta_outgoing_destroy(c->c_orq); sip_header_remove(rmsg, rsip, (sip_header_t *)rsip->sip_via); nta_msg_request_complete(rmsg, c->c_leg, 0, NULL, NULL); c->c_orq = nta_outgoing_tmcreate(c->c_agent, response_function, c, NULL, rmsg, TAG_END()); return 1; } } return 0; } static inline int server_authenticate(context_t *c, nta_outgoing_t *oreq, sip_t const *sip, nta_response_f response_function) { if (sip && sip->sip_status->st_status == 401 && sip->sip_www_authenticate && c->c_auth_retries++ < 3 && c->c_password && c->c_username) { msg_t *rmsg = nta_outgoing_getrequest(oreq); sip_t *rsip = sip_object(rmsg); if (auc_challenge(&c->c_auth, c->c_home, sip->sip_www_authenticate, sip_authorization_class) >= 0 && auc_all_credentials(&c->c_auth, NULL, NULL, c->c_username, c->c_password) > 0 && auc_authorization(&c->c_auth, rmsg, (msg_pub_t *)rsip, rsip->sip_request->rq_method_name, rsip->sip_request->rq_url, rsip->sip_payload) > 0) { nta_outgoing_destroy(c->c_orq); sip_header_remove(rmsg, rsip, (sip_header_t *)rsip->sip_via); nta_msg_request_complete(rmsg, c->c_leg, 0, NULL, NULL); c->c_orq = nta_outgoing_tmcreate(c->c_agent, response_function, c, NULL, rmsg, TAG_END()); return 1; } } return 0; } static inline int tag_from_header(nta_agent_t *nta, su_home_t *home, sip_from_t *f) { char *env = getenv("SIPTAG"); char *t = (void *)nta_agent_newtag(home, NULL, nta); int retval; if (env) { char *t1 = su_sprintf(home, "tag=%s-%s", env, t); su_free(home, t); t = t1; } retval = sip_from_tag(home, f, t); su_free(home, t); return retval; } SOFIA_END_DECLS #endif /* !defined APPS_UTILS_H */
10,930