language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Swift
UTF-8
2,221
2.578125
3
[]
no_license
// // OutroViewController.swift // // Created by Mo DeJong on 5/7/19. // Copyright © 2019 Mo DeJong. All rights reserved. // import UIKit import AlphaOverVideo class OutroViewController: UIViewController { @IBOutlet weak var mtkView: AOVMTKView! var player: AOVPlayer? @IBOutlet weak var textOverlay: UITextView! override func viewDidLoad() { super.viewDidLoad() assert(mtkView != nil) assert(textOverlay != nil) print("OutroViewController.viewDidLoad") mtkView.device = MTLCreateSystemDefaultDevice() if (mtkView.device == nil) { NSLog("Metal is not supported on this device"); return; } let url = AOVPlayer.url(fromAsset:"ClipYouBuryDad.m4v") assert(url != nil) let player = AOVPlayer.init(loopedClip:url) self.player = player assert(player?.hasAlphaChannel == false) // Defaults to sRGB, so set BT.709 flag to indicate video encoding player?.decodeGamma = AOVGammaApple; // Transition to choose vc after first 2 clips have finished playing let worked = mtkView.attach(player) if (worked == false) { NSLog("attach failed for AOVMTKView"); return; } setDadText1() } func setDadText1() { self.textOverlay.text = "A few days later ..." } func setDadText2() { self.textOverlay.text = "A few days later ...\nYou killed your Dad!" } func setDadText3() { self.textOverlay.text = "A few days later ...\nYou killed your Dad!\nEnjoy prision, crazy pants." } // Fade in animation override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.view.alpha = 0.0 let fadeInTime = 2.0 UIView.animate(withDuration: fadeInTime, delay: 0.0, options: .curveEaseIn, animations: { self.view.alpha = 1.0 }, completion: { finished in print("Animation Completed!") let delaySeconds1 = 3.0 DispatchQueue.main.asyncAfter(deadline: .now() + delaySeconds1) { self.setDadText2() } let delaySeconds2 = 6.0 DispatchQueue.main.asyncAfter(deadline: .now() + delaySeconds2) { self.setDadText3() } }) } }
Java
UTF-8
651
2.640625
3
[]
no_license
package sk.tuke.kpi.oop.game.items; import sk.tuke.kpi.gamelib.graphics.Animation; import sk.tuke.kpi.oop.game.Reactor; import sk.tuke.kpi.oop.game.Repairable; public class Hammer extends BreakableTool<Repairable> implements Collectible{ public Hammer() { super(1); setAnimation(new Animation("sprites/hammer.png")); } @Override public void useWith(Repairable repairable){ if(repairable!=null && repairable.repair() && getRemainingUses()>0 ){ super.useWith(repairable); } } @Override public Class<Repairable> getUsingActorClass() { return Repairable.class; } }
PHP
UTF-8
1,015
2.703125
3
[]
no_license
<?php namespace App\Library\Services; use App\Library\Services\Contracts\UpdatesInterface; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; class Updates implements UpdatesInterface { public function addProjectUpdate(Request $req) { $req->validate([ 'projectId' => 'required', 'projectUpdate' => 'required', 'updateDate' => 'required' ]); $projectId = $req->input('projectId'); $projectUpdate = $req->input('projectUpdate'); $dateUpdate = $req->input('updateDate'); $data = [$projectId, $projectUpdate, $dateUpdate]; DB::insert('INSERT INTO project_updates(project, update_message, date_update) VALUES (?, ?, ?)', $data); } public function getProjectUpdates($projectId) { $data = array( 'projectId' => $projectId ); return DB::select('SELECT * FROM project_updates WHERE project = :projectId', $data); } }
Python
UTF-8
298
4.0625
4
[]
no_license
def odd_even_sum(num): odd_sum = 0 even_sum = 0 for digits in number: if int(digits) % 2 == 0: even_sum += int(digits) else: odd_sum += int(digits) print(f"Odd sum = {odd_sum}, Even sum = {even_sum}") number = input() odd_even_sum(number)
Java
UTF-8
1,946
2.09375
2
[ "Apache-2.0" ]
permissive
package com.smartbear.readyapi4j.samples.java; import com.smartbear.readyapi4j.TestRecipeBuilder; import com.smartbear.readyapi4j.result.RecipeExecutionResult; import org.junit.Test; import static com.smartbear.readyapi4j.support.AssertionUtils.assertExecutionResult; import static com.smartbear.readyapi4j.testengine.teststeps.ServerTestSteps.dataGenDataSource; import static com.smartbear.readyapi4j.testengine.teststeps.datasource.datagen.DataGenerators.*; import static com.smartbear.readyapi4j.teststeps.TestSteps.GET; import static com.smartbear.readyapi4j.teststeps.restrequest.ParameterBuilder.query; public class DataGenDataSourceTest extends ApiTestBase { @Test public void createRecipeForAllDataGenerators() throws Exception { RecipeExecutionResult result = executeTestRecipe( TestRecipeBuilder.buildRecipe( "DataGenerator Test", dataGenDataSource() .withNumberOfRows(10) .withProperties( cityTypeProperty("cityProperty").duplicatedBy(2), mac48ComputerAddressTypeProperty("computerAddressProperty"), randomIntegerTypeProperty("integerProperty") ) .named("DataSourceStep") .withTestSteps( GET("http://www.google.se/") .withParameters( query("a", "${DataSourceStep#cityProperty}"), query("b", "${DataSourceStep#computerAddressProperty}"), query("c", "${DataSourceStep#integerProperty}") ) ) )).getExecutionResult(); assertExecutionResult(result); } }
PHP
UTF-8
3,131
2.625
3
[]
no_license
<?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Serializer\Encoder\XmlEncoder; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use App\Repository\UserRepository; use Symfony\Component\HttpFoundation\Request; use App\Entity\User; use App\Service\UserService; use App\Service\OperateSerializer; /** * @Route("/api") */ class UserController extends Controller { /** * @var UserRepository */ private $repo; /** * @var OperateSerializer */ private $serializer; /** * @var JsonResponse */ private $response; /** * @var ObjectManager */ private $em; /** * @var UserService */ private $service; public function __construct( UserRepository $repo, ObjectManager $em, JsonResponse $response, UserService $service, OperateSerializer $serializer ){ $encoders = [new XmlEncoder(), new JsonEncoder()]; $normalizers = [new ObjectNormalizer()]; $this->serializer = new Serializer($normalizers, $encoders); $this->response = $response; $this->repo = $repo; $this->em = $em; $this->service = $service; $this->serializer = $serializer; } /** * @Route("/users", methods={"POST"} ) * * @param Request * @return JsonResponse */ public function postArticleAction(Request $request) { $data = $request->getContent(); $user = $this->serializer->decode($data, User::class); try{ $this->service->create($user); }catch(\Exeption $e){ error_log($e->getMessage()); } return $this->response->setData('Object Create'); } /** * @Route("/users/{id}", methods={"GET"} ) * * @param User * @return JsonResponse */ public function getUserByIdAction(User $user) { $json = $this->serializer->encode($user, 'json'); return $this->response->fromJsonString($json); } /** * @Route("/users/{id}", methods={"DELETE"} ) * * @param User * @return JsonResponse */ public function deleteArticleByIdAction(User $user) { $this->service->delete($user); return $this->response->setData('Object Delete'); } /** * @Route("/users/{id}", methods={"PUT"} ) * * @param User * @return JsonResponse */ public function editUserByIdAction(User $user, Request $request) { $data = $request->getContent(); $editUser = $this->serializer->decode($data, User::class, 'json'); $this->service->update($user, $editUser); return $this->response->setData('Object Update'); } }
Markdown
UTF-8
2,752
2.953125
3
[]
no_license
# Generator-funkcyjny Projekt wykonany na płytce FRDM-KL05. Generator działa w oparciu o przetwornik C/A, generuje przebiegi: sinusoidalny, falę trójkątną i prostokątną. Obsługiwany za pomocą dwóch przycisków (zmiana przebiegu, zmina trybu nastawiania) oraz pola dotykowego płytki KL05 (regulacja napięcia miedzyszczytowego lub częstotliwości w zależności od trybu nastawiania). # 1. Podłączenie a. Klawiatura: C3 – PTB6 C4 – PTB7 R4 – GND b. Wyświetlacz: SCL – PTB3 SDA – PTB4 VCC – 5V GND – GND c. Głośnik wpinany jest pomiędzy PTB1 a GND # 2. Instrukcja obsługi Przycisk S1 powoduje cykliczną zmianę kształtu przebiegu (prostokątny -> sinus -> trójkątny). Przycisk S2 przełącza między trybem ustawiania częstotliwości a trybem ustawiania napięcia międzyszczytowego wybranego przebiegu. Pole dotykowe pozwala na regulację wybranego parametru Wyświetlacz pokazuje kształt przebiegu (sqr, sin, tri) oraz obecnie ustawiany parametr wraz z jego wartością. # 3. Parametry Regulacja częstotliwości w zakresie: 20Hz – 14460Hz Regulacja napięcia międzyszczytowego: 0.06V – 2.72V # 4. Zasada działania Dla tablicy o ilości elementów n, PIT0 powinien generować przerwania z częstotliwością n razy większą od pożądanej częstotliwości sygnału wyjściowego (zwiększenie liczby próbek spowoduje wygładzenie przebiegu na wyjściu, lecz ograniczy jego maksymalną częstotliwość). Przerwanie od PIT0 powoduje wysłanie kolejnej próbki z wybranej tablicy do przetwornika C/A i ustalenie odpowiedniej wartości na wyjściu (PTB1). Poprzez przesuwanie palcem po polu dotykowym można wpłynąć na częstotliwość generowania przerwań (zmiana wartości rejestru LDVAL) oraz na wartość napięcia na wyjściu (przemnażanie wartości próbki). # 5. Generowanie tablic Tablice przebiegów powstają poprzez pobranie równo oddalonych od siebie próbek z jednego okresu wybranego przebiegu. Żeby uzyskać jak najwyższą częstotliwość maksymalną przy zachowaniu kształtu przebiegu zdecydowałem się na tablice zawierające 20 próbek. Aby wygenerować tablice dla przebiegu sinusoidalnego i trójkątnego użyłem skryptu w języku Python. Generator powinien bez większych problemów działać dla tablic innych prostych przebiegów przy zachowaniu długości 20 oraz wartości próbek z zakresu 0x00 – 0x28 (0-40). # 6. Prezentacja działania Film z prezentacją znajduje się pod adresem: https://youtu.be/td5GKXfnqgk Podczas prezentacji zdecydowałem się na użycie oscyloskopu, ponieważ za jego pomocą dokładniej można zaprezentować działanie projektu. # Autor Michał Tomacha
SQL
UTF-8
1,237
4.1875
4
[]
no_license
--1 SELECT employee.BusinessEntityID ,employee.JobTitle ,MAX(employeePayHistory.Rate) AS MaxRate FROM HumanResources.Employee employee LEFT JOIN HumanResources.EmployeePayHistory employeePayHistory ON employeePayHistory.BusinessEntityID = employee.BusinessEntityID GROUP BY employee.BusinessEntityID ,employee.JobTitle; --2 SELECT payHistory.BusinessEntityID ,employee.JobTitle ,payHistory.Rate ,DENSE_RANK() OVER ( ORDER BY payHistory.Rate ) AS Rank FROM HumanResources.EmployeePayHistory payHistory LEFT JOIN HumanResources.Employee employee ON employee.BusinessEntityID = payHistory.BusinessEntityID ORDER BY payHistory.Rate; --3 SELECT department.Name AS DepName ,employee.BusinessEntityID ,employee.JobTitle ,empDepHistory.ShiftID FROM HumanResources.Department department LEFT JOIN HumanResources.EmployeeDepartmentHistory empDepHistory ON empDepHistory.DepartmentID = department.DepartmentID LEFT JOIN HumanResources.Employee employee ON employee.BusinessEntityID = empDepHistory.BusinessEntityID WHERE empDepHistory.EndDate IS NULL ORDER BY department.Name ,CASE WHEN department.Name = 'Document Control' THEN empDepHistory.ShiftID ELSE employee.BusinessEntityID END;
Python
UTF-8
3,803
2.578125
3
[]
no_license
#!/usr/bin/env python3 import os import sys import csv from fdfgen import forge_fdf def tail_shape(tail_value): if tail_value == 'square': return ('square', 'X') elif tail_value == 'squash': return ('squash', 'X') elif tail_value == 'round': return ('round', 'X') elif tail_value == 'round pin': return ('round pin', 'X') elif tail_value == 'pin': return ('pin', 'X') elif tail_value == 'swallow': return ('swallow', 'X') elif tail_value == 'fish': return ('fish', 'X') else: return ('tail', tail_value) def fin_setup(fin_value): if fin_value == '1': return ('single', 'X') elif fin_value == '2': return ('twin', 'X') elif fin_value == '3': return ('thruster', 'X') elif fin_value == '4': return ('quad', 'X') elif fin_value == '5': return ('fivefin', 'X') elif fin_value == '2+1': return ('twoplusone', 'X') elif fin_value == '4+1': return ('fourplusone', 'X') elif fin_value == 'Twin+1': return ('twinplusone', 'X') else: return ('otherfinsetup', 'X') def fin_type(type_value): if type_value == 'future': return ('future', 'X') elif type_value == 'fcs2': return ('fcstwo', 'X') elif type_value == 'fcsii': return ('fcstwo', 'X') elif type_value == 'glasson': return ('glasson', 'X') else: return ('otherfintype', 'X') def process_row(header, row): key_value_tuples = [] # for each column in row for i in range(len(header)): value = row[i].strip() if header[i] == 'fins': fin_tuple = fin_setup(value) if fin_tuple[0] == 'otherfinsetup': key_value_tuples.append(fin_tuple) key_value_tuples.append((header[i], value)) else: key_value_tuples.append(fin_tuple) elif header[i] == 'type': type_tuple = fin_type(value) if type_tuple[0] == 'otherfintype': key_value_tuples.append(type_tuple) key_value_tuples.append((header[i], value)) else: key_value_tuples.append(type_tuple) elif header[i] == 'tail': tail_tuple = tail_shape(value.lower()) key_value_tuples.append(tail_tuple) elif header[i] == 'or': if value: key_value_tuples.append(('or', 'X')) key_value_tuples.append(('ortext', value)) else: key_value_tuples.append((header[i], value)) return key_value_tuples def process_csv(csv_data): header = [] output_data = [] # for each row in the CSV file for row_number, row in enumerate(csv_data): # ignore first column if row_number == 0: continue # use second column for headers if row_number == 1: header = row # lower case and remove whitespace for each header header = [word.lower().strip() for word in header] continue # process each row key_value_tuples = process_row(header, row) output_data.append(key_value_tuples) return output_data def fill_pdf_template(row, pdf_template, output_file): tmp_file = "tmp.fdf" fdf = forge_fdf("", row, [], [], []) with open(tmp_file, "wb") as fdf_file: fdf_file.write(fdf) cmd = "pdftk '{0}' fill_form '{1}' output '{2}' dont_ask".format(pdf_template, tmp_file, output_file) os.system(cmd) os.remove(tmp_file) if __name__ == "__main__": """ Batch fill pdf template with data from csv file """ try: pdf_template = sys.argv[1] csv_file = sys.argv[2] except IndexError: print("python3 solid_fill_pdf.py pdf_template csv_file ") else: with open(csv_file) as f: # process csv file csv_data = csv.reader(f) data = process_csv(csv_data) # make directory to put output PDFS output_dir = os.path.join(os.getcwd(), 'output') if not os.path.exists(output_dir): os.makedirs(output_dir) # generate PDFs for row in data: orderid = row[3][1] output_path = os.path.join(output_dir, orderid) output_file = output_path + ".pdf" fill_pdf_template(row, pdf_template, output_file) print("Generated {0}.pdf".format(orderid))
JavaScript
UTF-8
6,194
3.640625
4
[]
no_license
import React,{useState} from 'react'; import Try from './Try'; //숫자 4개를 겹치지 않게 뽑는 함수 const getNumbers = () => { const candidate = [0,1,2,3,4,5,6,7,8,9]; let arr = []; for (let i=0;i<4;i++){ arr.push( candidate.splice(Math.floor( Math.random()*candidate.length ),1)[0] ); } console.log(arr); return arr; } const NumberBaseball = () => { const [result,setResult] = useState(''); const [value,setValue] = useState(''); const [answer,setAnswer] = useState(getNumbers()); const [tries,setTries] = useState([]); const onSubmitForm = (e) => { e.preventDefault(); console.log("onSubmitForm......................"); if(value == answer.join("")){ //예전 state값으로 부터 현재 state값을 만들때는 함수형으로 선언해야 한다. setResult("홈런"); setTries((prevState) => {return [...prevState, {try:value , result:'홈런'}]}) alert("게임을 다시 시작합니다."); setTries([]); setValue(""); setResult(""); setAnswer(getNumbers()); }else{ if(tries.length>=9){ alert("Game over!! try again?"); setTries([]); setValue(""); setResult(""); setAnswer(getNumbers()); }else{ const arrayNumber = value.split("").map( (v) => {return ~~(v)}); let strike = 0; let ball = 0; for(let i=0;i<arrayNumber.length;i++){ if(answer[i] == arrayNumber[i]){ strike = strike + 1; }else if(answer.includes(arrayNumber[i])){ ball = ball + 1; } } //예전 state값으로 부터 현재 state값을 만들때는 함수형으로 선언해야 한다. setValue(""); setTries((prevState) => {return [...prevState,{try:value,result:`${strike} 스트라이크, ${ball} 볼` }]}); } } } return ( <> <h1>{result}</h1> <form onSubmit={onSubmitForm}> <input maxLength={4} value={value} onChange={(e) => setValue(e.target.value)}/> </form> <div>시도 : {tries.length} </div> <ul> {/* 화살표 함수에서 중괄호{}가 없으면 return 이 생략된다. */} {tries.map( (v,i) => //고유한 key가 있어야 한다. <Try key={`${i+1}차 시도`} vv={v} idx={i}/> )} </ul> </> ); }; // class NumberBaseball extends Component{ // state = { // result:'', //결과값 // value:'', //input 입력 // answer:getNumbers(), //맞춰야 할 번호 // tries:[] //시도한 내역 // } // onSubmitForm = (e) => { // e.preventDefault(); // if(value == answer.join("")){ // //예전 state값으로 부터 현재 state값을 만들때는 함수형으로 선언해야 한다. // this.setState((prevState) => { // return { // 'result':"홈런!!!", // 'tries':[...prevState.tries, {try:value , result:'홈런'}] // } // }); // alert("게임을 다시 시작합니다."); // this.setState({ // tries:[], // value:"", // result:"", // answer:getNumbers(), // }); // }else{ // if(tries.length>=9){ // alert("Game over!! try again?"); // this.setState({ // tries:[], // value:"", // result:"", // answer:getNumbers(), // }); // }else{ // const arrayNumber = value.split("").map( (v) => {return ~~(v)}); // let strike = 0; // let ball = 0; // for(let i=0;i<arrayNumber.length;i++){ // if(answer[i] == arrayNumber[i]){ // strike = strike + 1; // }else if(answer.includes(arrayNumber[i])){ // ball = ball + 1; // } // } // //예전 state값으로 부터 현재 state값을 만들때는 함수형으로 선언해야 한다. // this.setState((prevState) => { // return { // 'value':'', // 'tries':[...prevState.tries,{try:value,result:`${strike} 스트라이크, ${ball} 볼` }] // } // }); // } // } // }; // onChangeInput = (e) => { // this.setState({ // "value":e.target.value // }) // }; // fruits = [ // {fruit:"사과",taste:"맛있다."}, // {fruit:"배",taste:"맛없다."}, // {fruit:"감",taste:"떫다."}, // ]; // render(){ // return ( // <> // <h1>{result}</h1> // <form onSubmit={this.onSubmitForm}> // <input maxLength={4} value={value} onChange={this.onChangeInput}/> // </form> // <div>시도 : {tries.length} </div> // <ul> // {/* 화살표 함수에서 중괄호{}가 없으면 return 이 생략된다. */} // {tries.map( (v,i) => // //고유한 key가 있어야 한다. // <Try key={`${i+1}차 시도`} vv={v} idx={i}/> // )} // </ul> // </> // ) // } // } //ES2015문법 export const hello = 'hello' export default NumberBaseball; //노드의 문법 common js 라고 불림 //const React = require("react"); // exports.hello = 'hello'; // module.export = NumberBaseball;
Shell
UTF-8
302
3.265625
3
[ "MIT" ]
permissive
#/bin/sh forever="/user/local/bin/forever"; index="/index.js"; cmd=""; case "$1" in start ) cmd="start";; stop ) cmd="stop";; restart ) cmd="restart";; esac if [ "${cmd}" = "" ]; then echo "Please input cmd."; exit 1; i fullCmd=${forever}" "${cmd}" "${index}; echo $fullCmd; $fullCmd;
Java
UTF-8
404
3.171875
3
[]
no_license
public class Carrer { public static void main(String[]args){ System.out.println("Everyone wants to make their carrer good"); boolean x=5==5; System.out.println(x); Carrer myCarrer = new Carrer(); myCarrer.success(); } public void success(){ System.out.println("But not everyone can do that even though they work hard."); } }
C#
UTF-8
2,073
2.546875
3
[ "MIT" ]
permissive
using N3O.Umbraco.Data.Lookups; using N3O.Umbraco.Data.Models; using N3O.Umbraco.Extensions; using N3O.Umbraco.Lookups; using Newtonsoft.Json.Linq; using System; using OurDataTypes = N3O.Umbraco.Data.Lookups.DataTypes; namespace N3O.Umbraco.Data.Parsing; public class LookupParser : DataTypeParser<INamedLookup>, ILookupParser { private readonly ILookups _lookups; public LookupParser(ILookups lookups) { _lookups = lookups; } public override bool CanParse(DataType dataType) { return dataType == OurDataTypes.Lookup; } public override ParseResult<INamedLookup> Parse(string text, Type targetType) { var parseResult = this.CallMethod(nameof(Parse)) .OfGenericType(targetType) .WithParameter(typeof(string), text) .Run<IParseResult>(); if (parseResult.Success) { return ParseResult.Success((INamedLookup) parseResult.Value); } else { return ParseResult.Fail<INamedLookup>(); } } public ParseResult<TLookup> Parse<TLookup>(string text) where TLookup : class, INamedLookup { TLookup value = null; if (text.HasValue()) { text = text.Trim(); var allLookups = _lookups.GetAll<TLookup>(); foreach (var lookup in allLookups) { var textValues = lookup.GetTextValues(); if (textValues.Contains(text, true)) { value = lookup; break; } } if (value == null) { return ParseResult.Fail<TLookup>(); } } return ParseResult.Success(value); } public ParseResult<TLookup> Parse<TLookup>(JToken token) where TLookup : class, INamedLookup { if (token.Type == JTokenType.String) { return Parse<TLookup>((string) token); } else { return ParseResult.Fail<TLookup>(); } } }
Python
UTF-8
192
2.609375
3
[]
no_license
import numpy as np weight = np.random.random((4,3)) bias = np.random.random((1,3)) wout = np.random.random((3,1)) bout = np.random.random((1,1)) print weight print bias print wout print bout
Java
UTF-8
563
2.25
2
[]
no_license
package com.itcodai.common; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jms.Destination; /** * @author zhao_wj * @version 1.0 * @date 2021/7/26 15:01 */ @Service public class MsgProducer { @Resource private JmsMessagingTemplate jmsMessagingTemplate; public void sendMessage(Destination destination, String msg){ jmsMessagingTemplate.convertAndSend(destination,msg); /** * 撒的发多少 */ } }
Markdown
UTF-8
5,622
2.5625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Använda åtkomst principer i Azure HPC-cache description: Skapa och använda anpassade åtkomst principer för att begränsa klient åtkomsten till lagrings mål i Azure HPC-cache author: ekpgh ms.service: hpc-cache ms.topic: how-to ms.date: 12/28/2020 ms.author: v-erkel ms.openlocfilehash: 795b194eb7cd31e633128c22ddffe808b32e07da ms.sourcegitcommit: 7e97ae405c1c6c8ac63850e1b88cf9c9c82372da ms.translationtype: MT ms.contentlocale: sv-SE ms.lasthandoff: 12/29/2020 ms.locfileid: "97802428" --- # <a name="use-client-access-policies"></a>Använd klient åtkomst principer Den här artikeln förklarar hur du skapar och använder anpassade klient åtkomst principer för dina lagrings mål. Klient åtkomst principer styr hur klienter kan ansluta till lagrings målets exporter. Du kan styra saker som rot-squash och Läs-/skriv åtkomst på klient värden eller på nätverks nivå. Åtkomst principer tillämpas på en namn områdes Sök väg, vilket innebär att du kan använda olika åtkomst principer för två olika exporter i ett NFS-filsystem. Den här funktionen gäller för arbets flöden där du behöver styra hur olika grupper av klienter får åtkomst till lagrings målen. Om du inte behöver detaljerad kontroll över lagrings mål åtkomsten kan du använda standard principen, eller så kan du anpassa standard principen med ytterligare regler. ## <a name="create-a-client-access-policy"></a>Skapa en klient åtkomst princip Använd sidan **principer för klient åtkomst** i Azure Portal för att skapa och hantera principer. <!-- is there AZ CLI for this? --> [![skärm bild av sidan för klient åtkomst principer. Flera principer är definierade och vissa expanderas för att visa sina regler](media/policies-overview.png)](media/policies-overview.png#lightbox) Varje princip består av regler. Reglerna tillämpas på värdar i ordning från det minsta omfånget (värd) till störst (standard). Den första regeln som matchar används och senare regler ignoreras. Om du vill skapa en ny åtkomst princip klickar du på knappen **+ Lägg till åtkomst princip** överst i listan. Ge den nya åtkomst principen ett namn och ange minst en regel. ![skärm bild av bladet redigera åtkomst principer med flera regler ifyllda. Spara regeln genom att klicka på OK.](media/add-policy.png) I resten av det här avsnittet förklaras de värden som du kan använda i regler. ### <a name="scope"></a>Omfång Omfattnings termen och adress filtret fungerar tillsammans för att definiera vilka klienter som påverkas av regeln. Använd dem för att ange om regeln gäller för en enskild klient (värd), ett intervall med IP-adresser (nätverk) eller alla klienter (standard). Välj lämpligt **omfattnings** värde för regeln: * **Värd** – regeln gäller för en enskild klient * **Nätverk** – regeln gäller för klienter i ett intervall med IP-adresser * **Standard** – regeln gäller för alla klienter. Reglerna i en princip utvärderas i den ordningen. När en klient Mount-begäran matchar en regel ignoreras de andra. ### <a name="address-filter"></a>Adress filter Värdet för **adress filtret** anger vilka klienter som matchar regeln. Om du ställer in scope som **värd** kan du bara ange en IP-adress i filtret. För inställningen **standard** kan du inte ange några IP-adresser i fältet **adress filter** eftersom standard omfånget matchar alla klienter. Ange IP-adressen eller adress intervallet för den här regeln. Använd CIDR-notering (exempel: 0.1.0.0/16) för att ange ett adress intervall. ### <a name="access-level"></a>Åtkomstnivå Ange vilka behörigheter som ska ge klienterna som matchar omfånget och filtret. Alternativen är **läsa/skriva**, **skrivskyddad** eller **Ingen åtkomst**. ### <a name="suid"></a>SUID Markera rutan **suid** om du vill tillåta att filer i lagrings utrymmen anger användar-ID vid åtkomst. SUID används vanligt vis för att öka användarens behörighet tillfälligt så att användaren kan utföra en uppgift som är relaterad till filen. ### <a name="submount-access"></a>Under monterings åtkomst Markera den här kryss rutan om du vill tillåta att de angivna klienterna direkt monterar exportens under kataloger. ### <a name="root-squash"></a>Rot-squash Välj om du vill ange rot-squash för klienter som matchar den här regeln. Med det här värdet kan du tillåta rot-squash på lagrings export nivån. Du kan också [Ange rot-squash på cachenivå](configuration.md#configure-root-squash). Om du aktiverar rot-squash måste du också ange användar värde för anonyma ID till något av följande alternativ: * **-2** (ingen) * **65534** (ingen) * **-1** (ingen åtkomst) * **65535** (ingen åtkomst) * **0** (ej privilegie rad rot) ## <a name="update-access-policies"></a>Uppdatera åtkomst principer Du kan redigera eller ta bort åtkomst principer från tabellen på sidan **principer för klient åtkomst** . Klicka på princip namnet för att öppna den för redigering. Om du vill ta bort en princip markerar du kryss rutan bredvid namnet i listan och klickar sedan på knappen **ta bort** högst upp i listan. Det går inte att ta bort principen med namnet "default". > [!NOTE] > Du kan inte ta bort en åtkomst princip som används. Ta bort principen från alla namn områdes Sök vägar som innehåller den innan du försöker ta bort den. ## <a name="next-steps"></a>Nästa steg * Använd åtkomst principer i namn områdes Sök vägar för dina lagrings mål. Läs [Konfigurera den](add-namespace-paths.md) sammanställda namn rymden för att lära dig hur.
C#
UTF-8
2,156
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DST { public class Solicitud { private string fechaSolicitud; private string estadoSolicitud; private string rutSolicitud; private int idSeccionActual; private int idSeccionSolicitada; private double capacidadSeccionActual; private double capacidadNuevaSeccion; public Solicitud(string fechaSolicitud, string estadoSolicitud, string rutSolicitud, int idSeccionActual, int idSeccionSolicitada, double capacidadSeccionActual, double capacidadNuevaSeccion) { this.fechaSolicitud = fechaSolicitud; this.estadoSolicitud = estadoSolicitud; this.rutSolicitud = rutSolicitud; this.idSeccionActual = idSeccionActual; this.idSeccionSolicitada = idSeccionSolicitada; this.capacidadSeccionActual = capacidadSeccionActual; this.capacidadNuevaSeccion = capacidadNuevaSeccion; } public string FechaSolicitud { get { return fechaSolicitud; } set { fechaSolicitud = value; } } public string EstadoSolicitud { get { return estadoSolicitud; } set { estadoSolicitud = value; } } public string RutSolicitud { get { return rutSolicitud; } set { rutSolicitud = value; } } public int IdSeccionActual { get { return idSeccionActual; } set { idSeccionActual = value; } } public int IdSeccionSolicitada { get { return idSeccionSolicitada; } set { idSeccionSolicitada = value; } } public double CapacidadSeccionActual { get { return capacidadSeccionActual; } set { capacidadSeccionActual = value; } } public double CapacidadNuevaSeccion { get { return capacidadNuevaSeccion; } set { capacidadNuevaSeccion = value; } } } }
Rust
UTF-8
1,683
2.640625
3
[]
no_license
use bitcoin::blockdata::block::BlockHeader as BtcBlockHeader; use crate::{ types::Result, traits::DatabaseInterface, btc_on_eos::btc::btc_state::BtcState, constants::{ DEBUG_MODE, CORE_IS_VALIDATING, NOT_VALIDATING_WHEN_NOT_IN_DEBUG_MODE_ERROR, }, }; fn validate_proof_of_work_in_block(btc_block_header: &BtcBlockHeader) -> Result<()> { match btc_block_header.validate_pow(&btc_block_header.target()) { Ok(_) => { info!("✔ BTC block's proof-of-work is valid!"); Ok(()) } Err(_) => Err("✘ Invalid block! PoW validation error: Block hash > target!".into()) } } pub fn validate_proof_of_work_of_btc_block_in_state<D>( state: BtcState<D>, ) -> Result<BtcState<D>> where D: DatabaseInterface { if CORE_IS_VALIDATING { info!("✔ Validating BTC block's proof-of-work..."); validate_proof_of_work_in_block(&state.get_btc_block_and_id()?.block.header).map(|_| state) } else { info!("✔ Skipping proof-of-work validation!"); match DEBUG_MODE { true => Ok(state), false => Err(NOT_VALIDATING_WHEN_NOT_IN_DEBUG_MODE_ERROR.into()), } } } #[cfg(test)] mod tests { use super::*; use crate::btc_on_eos::btc::btc_test_utils::get_sample_btc_block_and_id; #[test] fn should_validate_proof_of_work_in_valid_block() { let block_header = get_sample_btc_block_and_id() .unwrap() .block .header; if let Err(e) = validate_proof_of_work_in_block(&block_header) { panic!("PoW should be valid in sample block: {}", e); } } }
Java
UTF-8
1,518
3.59375
4
[]
no_license
package LCQuestions; public class _1000_MinimumCostToMergeStones { public static void main(String[] args) { _1000_MinimumCostToMergeStones c = new _1000_MinimumCostToMergeStones(); } /* So we need to know the minimum cost of merging left part to 1 pile, and minimum cost of merging right part to 1 pile, this is a typical sub problem. State: Minimum cost merging piles from i to j to 1 pile. Function: dp[i][j] = min(sum[i][j] + dp[i][k] + dp[k + 1][j]) (i <= k < j) Init: dp[i][i] = 0 (Already a pile) Answer: dp[1][len] (len is the stones number) */ public int mergeStonesTwo(int[] stones) { if (stones == null || stones.length == 0) { return 0; } int len = stones.length; int max = Integer.MAX_VALUE; int[][] dp = new int[len + 1][len + 1]; int[] prefixSum = new int[len + 1]; int i, j, k, l; for (i = 1; i <= len; i++) { prefixSum[i] = prefixSum[i - 1] + stones[i - 1]; } for (i = 1; i <= len; i++) { dp[i][i] = 0; } for (l = 2; l <= len; l++) { for (i = 1; i <= len - l + 1; i++) { j = i + l - 1; dp[i][j] = max; int sum = prefixSum[j] - prefixSum[i - 1]; for (k = i; k < j; k++) { dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } return dp[1][len]; } }
C#
UTF-8
645
2.53125
3
[]
no_license
using System.Configuration; namespace TestConfigSettings { /// <summary> /// /// </summary> [ConfigurationCollection(typeof(FolderElement))] public class FoldersCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new FolderElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((FolderElement)(element)).FolderType; } public FolderElement this[int idx] { get { return (FolderElement)BaseGet(idx); } } } }
Markdown
UTF-8
978
3.125
3
[ "MIT" ]
permissive
# Hometask: Quick select algorithm with random choosing pivot ## You should type on command line: if you want to run: -> make run if you want to clear all created files: -> make clear #### Was given whole numbers sequence in range from [0, 1e9] with length n. You should print number k which would stand on position with index k in [0, n - 1] in sorted sequence. You should write non recursive algorithm. Average time complexity have to be O(n), memory usage O(n). Description: #### Input format: -> The first line contains the number of elements in sequence n and k 0 ≤ k < n ≤ 1,000,000,000. -> The second line contains long long sequence with elements in range long int. #### Output format: Example: input | output 10 4 | 5 1 2 3 4 5 6 7 8 9 10 | ----------------------------------------------
JavaScript
UTF-8
546
3.171875
3
[ "MIT" ]
permissive
export function getCardPosition(stack, card) { return stack.indexOf(card) } export function doesStackIncludeCard(stack, card) { return stack.includes(card) } export function isEachCardEven(stack) { return stack.every((card) => card % 2 === 0) } export function doesStackIncludesOddCard(stack) { return stack.some((card) => card % 2 !== 0) } export function getFirstOddCard(stack) { return stack.find((card) => card % 2 !== 0) } export function getFirstEvenCardPosition(stack) { return stack.findIndex((card) => card % 2 === 0) }
C++
UTF-8
742
2.78125
3
[ "MIT" ]
permissive
#include "IterativeMethods.h" // Create a new istance of this class IterativeMethods::IterativeMethods(const Eigen::SparseMatrix<double>& _A, const Eigen::VectorXd& _b, StopCrit* _stopCrit) : dimA(_A.rows()), A(_A), b(_b), stopCrit(_stopCrit){ } // Compute the iterative method until stopCrit void IterativeMethods::iterativeSolver(IterationData* dataIt) const { while (stopCrit->haveToStop(dataIt) == false) { dataIt->incrementIter(); next(dataIt); } } void IterativeMethods::set(const Eigen::SparseMatrix<double>& A, const Eigen::VectorXd& b, StopCrit* stopCrit) { dimA = A.rows(); this->A = A; this->b = b; this->stopCrit = stopCrit; } StopCrit* IterativeMethods::getStopCritPointer() const { return(stopCrit); }
Markdown
UTF-8
3,697
2.765625
3
[]
permissive
# Microsoft plans on showing off its 'Cloud Power' The time has arrived for Microsoft to start 'showing off' it's much talked about 'cloud power'. There were quite a few technology <a href="http://www.advertisertalk.com/microsoft-outlines-opportunity-in-the-cloud-and-on-devices-at-professional-developers-conference-2010-2-16606.zhtml">news articles</a> that were focused on Microsoft venturing into the Cloud Computing arena; and it is about time for them to make some noise which shall enable them to fetch some business. By noise, I mean advertising campaigns. Though it is a cliche in business, it is worth mentioning here that everything (product or service) that is advertised, is sold; and sold easy. Hence it becomes important for even a B2B (business to business) corporation such as Microsoft to advertise to its target market (evidently both small and big business enterprises). ## The Campaign Plan This is supposedly the largest-ever ad campaign launched by the software makers and the idea is to throw light on the benefits of using cloud-based computing over the conventional server-based computing. The chosen medium of advertising includes the Full-Monty i.e., TV, Internet, print, and outdoor ads and the base line on which the theme of this campaign lies would quite obviously be 'Cloud Power'. The look and feel of the campaign would reflect certain actors playing the roles of different kinds of consumers who testify and compliment Microsoft's cloud-power products such as <a href="http://www.microsoft.com/windowsazure/windowsazure/">Windows Azure</a>, <a href="http://office365.microsoft.com/en-US/online-services.aspx">Office 365</a> and <a href="http://www.microsoft.com/windowsserver2008/en/us/default.aspx">Windows Server</a>. ## Change in the Communiqu&eacute; Microsoft's previously adapted marketing plan revolved around the -- <a href="http://news.cnet.com/8301-13860_3-20005451-56.html">All In</a> message which was initiated soon after CEO Steve Ballmer delivered his <a href="http://news.cnet.com/8301-13860_3-10463930-56.html">speech</a> in the month of March at the University of Washington. Microsoft has recognized the need for a change in its communique whereby the new message conveys to its business consumers of the lower initiation & installation costs along with larger flexibility that are embedded in the Cloud. Prior to the 'All In' campaign which was given birth to by <a href="http://www.jwt.com/">JWT</a>, was <a href="http://www.mccann.com/">McCann Erickson</a>'s 'People Ready' campaign and the current campaign -- Cloud Power will be handled by <a href="http://www.deutschinc.com/">Deutsch</a>. Speaking about the Cloud's working Microsoft's Amy Barzdukas said in an interview, "We really do see that cloud computing is exciting...in way we haven't necessarily seen since we went from mainframe computing to server-client." ## Way Ahead Microsoft and its creative partner Deutsch plan to carry out this enormous campaign till July next year, wherein the first launch ad would appear on Television which will be run during Monday Night Football along with a full page ad in Monday's Wall Street Journal. Besides this, there will also be organized a succession of events which would comprise 200 odd software exhibitions with 50,000 plus consumers. <a href="http://www.microsoft.com/en-us/cloud/default.aspx#tab2-small">Cloud Conversations</a> with real customers is also one among the plethora of the new campaign's ideas and this would be featured on Microsoft's web site. Considering the fact that there are many more ideas to emerge from this campaign, Microsoft can truly rely on this campaign to generate leads and sales for its 'Cloud Power'.
PHP
UTF-8
1,290
2.65625
3
[]
no_license
<?php include "connect.php"; if (isset($_POST['unos'])){ $ime=$_POST['ime']; $prezime=$_POST['prezime']; $email=$_POST['email']; $password=$_POST['password']; $username=$_POST['username']; $telefon=$_POST['telefon']; $adresa=$_POST['adresa']; $sql=" INSERT INTO member(ime,prezime,email,password,username,telefon,adresa)VALUES('".$ime."','".$prezime."','".$email."','".$password."','".$username."','".$telefon."','".$adresa."')"; if ($conn->query($sql)){ echo "<p>Uspešno ste se registrovali</p>"; } else { echo "<p>Greška! Niste se registrovali</p>" . $conn->error; } } else { //Ako POST parametri nisu prosleđeni echo ""; } ?> <!DOCTYPE html> <html> <head> <title>Prijava</title> <link rel="stylesheet" type="text/css" href="CSS/prikaz.css"> <script src="" integrity="sha256-hwg4gsxgFZOsEEamdOYGBf13FyQuiTlAQgxVSNgt4=" crossorigin="anonymus"></script> </head> <body> <div class="prikaz"> <h1>Prijava</h1> <p>Nakon registracije,prijavite se i pocnite <br> da koristite vas BOOK DIARY!</p> <hr/> <form action="panel.php" method="post"> Username: <input type="text" name="username"></br> Password: <input type="password" name="password"></br> <button type="submit" name="login">Uloguj se</button> </form> </div> </body> </html>
Python
UTF-8
940
2.671875
3
[]
no_license
#!/usr/bin/python3 def store(file, col, h=False): dic = {} f = open(file) import csv reader = csv.reader(f, delimiter = '\t') if h: next(reader, None) for row in reader: dic[row[0]] = row[col-1] return dic def main(): import sys import csv import pandas as pd if len(sys.argv) != 4: sys.exit('python3 %s <norm.factors.txt> <gff.stat> <gene_count_matrix.tab>' % (sys.argv[0])) normFile = sys.argv[1] statFile = sys.argv[2] tabFile = sys.argv[3] normDic = store(normFile, 2, h=True) statDic = store(statFile, 3) df = pd.read_csv(tabFile, sep = '\t') #df_num = df.copy() df_rpkm = df.copy() avg = df.sum(axis=0).mean() for i in normDic: df_rpkm[i] = df[i]*1e3*1e6/int(float(normDic[i])*avg) for i in df_rpkm.index: df_rpkm.loc[i] = df_rpkm.loc[i]/float(statDic[i]) df_rpkm.to_csv(sys.stdout, sep = '\t', quoting = csv.QUOTE_NONE) #print(df_rpkm.to_string()) if __name__ == '__main__': main()
TypeScript
UTF-8
1,043
3.296875
3
[]
no_license
let city:string = 'Karachi'; let test: string = 'Hello World'; //let test: number = 5; //let test: boolean = true; //let test: any = {}; //let test: string | number = 444; let testArr : string[] = ['asdas','Two']; // an array let testArr2 : [string, number] = ['asdas', 30]; //these are called tuples for usage of multiple data types const days : string[] =['Monday', 'Tuesday', 'Wednesday']; //let testObj : string[] = new Array() function add(numOne: number, numTwo: number) : void { numOne + numTwo } function subtract(numOne: number, numTwo: number) : number { return numOne - numTwo } console.log(city); console.log(`${test}`); console.log(test.length); console.log(typeof test); console.log(add(5, 5)); console.log(subtract(10, 6)); console.log(testArr); console.log(testArr2); console.log('days : ', days); console.log('days : ', days[2]); //git init // git status // git add . --- git add FILENAME //git commit -m (-m means message) //git remote add origin https://_________.git //git push origin master
Markdown
UTF-8
10,987
2.71875
3
[]
no_license
Варианты использования ==================================================================================== ![alt text](http://habrastorage.org/storage3/e80/fc1/ff4/e80fc1ff49f848a1bc5b7b1846e4afeb.png) Сценарии ==================================================================================== Создание документа ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на создание документа - *Пользователь* находится в главном меню ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Создать новый документ"***, *Система* отображает форму создания нового документа. 2. *Пользователь* вводит информацию о документе и нажимает кнопку ***"Сохранить"***, *Система* создает новый документ, в случае ошибки показывает сообщение. 3. *Система* открывает форму просмотра информации о документе. Добавление ревизии документа ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на добавление ревизии документа - *Пользователь* надится в меню просмотра документа ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Создать новую ревизию"***, *Система* отображает форму загрузки новой ревизии. 2. *Пользователь* вводит даные ревизии и нажимает кнопку ***"Сохранить"***, *Система* добавляет ревизию, в случае ошибки показывает сообщенСоздание документа ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на создание документа - *Пользователь* находится в главном меню ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Создать новый документ"***, *Система* отображает форму создания нового документа. 2. *Пользователь* вводит информацию о документе и нажимает кнопку ***"Сохранить"***, *Система* создает новый документ, в случае ошибки показывает сообщение. 3. *Система* открывает форму просмотра информации о документе. Добавление ревизии документа ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на добавление ревизии документа - *Пользователь* надится в меню просмотра документа ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Создать новую ревизию"***, *Система* отображает форму загрузки новой ревизии. 2. *Пользователь* вводит даные ревизии и нажимает кнопку ***"Сохранить"***, *Система* добавляет ревизию, в случае ошибки показывает сообщение. 3. *Система* открывает форму просмотра информации о документе. Получение ревизии ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован ### Основной сценарий 1. *Пользователь* вводит название желаемого документа с соотвествующее поле, нажимает кнопку ***"Enter"***, *Система* отображает информацию о желаемом документе и список ревизий этого документа. 2. *Пользователь* выбирает нужную ревизию, *Система* отображает информацию о выбранной ревизии Комментирование ревизии ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на создание документа - *Пользователь* находится в меню просмотри информации о ревизии ### Основной сценарий 1. *Пользователь* вводит название текст комментария в соответсвующее поле, нажимает кнопку ***"Отправить комментарий"***. 2. *Система* сохраняет комментарий и отображает его. Регистрация пользователя ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* находится в меню входа ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Зарегистрироваться"***. 2. *Пользователь* вводит желаемый логин и пароль в соответствующие поля, и нажимает нажимает кнопку ***"Зарегистрироваться"***. 3. *Система* проверяет логин пользователя на уникальность, в случае ошибки выводит сообщение. 4. *Система* опеределяет права пользователя исходя из секретного слова, указанного при регистрации. 5. *Система* отображает форму входа. Вход пользователя ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* находится в меню входа ### Основной сценарий 1. *Пользователь* вводит свой логин и пароль, нажимает кнопку ***"Войти"***. 2. *Система* проверяет на правильность логин и пароль, и в случае успеха отображает форму приветсвия, в противном случае отобращает сообщение об ошибке. 3. *Система* открывает форму просмотра информации о документе. Получение ревизии ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован ### Основной сценарий 1. *Пользователь* вводит название желаемого документа с соотвествующее поле, нажимает кнопку ***"Enter"***, *Система* отображает информацию о желаемом документе и список ревизий этого документа. 2. *Пользователь* выбирает нужную ревизию, *Система* отображает информацию о выбранной ревизии Комментирование ревизии ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* автозирован - *Пользователь* имеет права на создание документа - *Пользователь* находится в меню просмотри информации о ревизии ### Основной сценарий 1. *Пользователь* вводит название текст комментария в соответсвующее поле, нажимает кнопку ***"Отправить комментарий"***. 2. *Система* сохраняет комментарий и отображает его. Регистрация пользователя ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* находится в меню входа ### Основной сценарий 1. *Пользователь* выбирает пункт ***"Зарегистрироваться"***, *Система* отображает форму регистрации. 2. *Пользователь* вводит желаемый логин и пароль в соответствующие поля, и нажимает нажимает кнопку ***"Зарегистрироваться"***. 3. *Система* проверяет логин пользователя на уникальность, в случае ошибки выводит сообщение. 4. *Система* опеределяет права пользователя исходя из секретного слова, указанного при регистрации. 5. *Система* отображает форму входа. Вход пользователя ------------------------------------------------------------------------------------ ### Предусловия - *Пользователь* находится в меню входа ### Основной сценарий 1. *Пользователь* вводит свой логин и пароль, нажимает кнопку ***"Войти"***. 2. *Система* проверяет на правильность логин и пароль, и в случае успеха отображает форму приветсвия, в противном случае отобращает сообщение об ошибке.
Java
UTF-8
2,815
2
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package spa.presentacion.beans; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.primefaces.model.chart.CartesianChartModel; import org.primefaces.model.chart.ChartSeries; import recursos.Util; import spa.logica.clases.Victimas_2012; import spa.logica.funciones.FVictimas_2012; /** * * @author servidor */ @ManagedBean @RequestScoped public class ControladorVictimas2012Referido { /** * Creates a new instance of ControladorVictimas2012Referido */ private CartesianChartModel referidoGrafico; private ArrayList<Victimas_2012> lstDatosReferido; private ArrayList<Victimas_2012> lstDatosDadoReferido; public CartesianChartModel getReferidoGrafico() { return referidoGrafico; } public void setReferidoGrafico(CartesianChartModel referidoGrafico) { this.referidoGrafico = referidoGrafico; } public ArrayList<Victimas_2012> getLstDatosReferido() { return lstDatosReferido; } public void setLstDatosReferido(ArrayList<Victimas_2012> lstDatosReferido) { this.lstDatosReferido = lstDatosReferido; } public ArrayList<Victimas_2012> getLstDatosDadoReferido() { return lstDatosDadoReferido; } public void setLstDatosDadoReferido(ArrayList<Victimas_2012> lstDatosDadoReferido) { this.lstDatosDadoReferido = lstDatosDadoReferido; } public ControladorVictimas2012Referido() { reinit(); } public void graficar() { referidoGrafico = initCategoryReferido(); } @PostConstruct public void init() { graficar(); } private void reinit() { this.lstDatosDadoReferido = new ArrayList<Victimas_2012>(); this.lstDatosReferido = new ArrayList<Victimas_2012>(); this.init(); } private CartesianChartModel initCategoryReferido() { CartesianChartModel model = new CartesianChartModel(); try { lstDatosReferido = FVictimas_2012.ObtenerDatosReferido(); ChartSeries referido= new ChartSeries(); referido.setLabel("Referido"); for (Victimas_2012 lstDatosP1 : lstDatosReferido) { lstDatosDadoReferido = FVictimas_2012.ObtenerDatosDadoReferido(lstDatosP1.getReferido()); referido.set(lstDatosP1.getReferido(), lstDatosDadoReferido.size()); } model.addSeries(referido); } catch (Exception e) { Util.addErrorMessage(e, "Error"); } return model; } }
Shell
UTF-8
1,257
3.984375
4
[ "Apache-2.0" ]
permissive
#!/bin/sh # usage: ./release-prepare.sh <currentVersion> [<remote>] if [ $# -lt 1 ] then echo usage: "./release-prepare.sh <releaseVersion> [<remote>]" echo echo "<releaseVersion> should be numeric version spec only. DO NOT add -SNAPSHOT" echo "<remote> argument is optional. It will push to the origin if not given." echo "For example: release-prepare.sh 1.0.1" exit -1 fi if [ "_$2_" = "__" ] then remote=origin else remote=$2 fi releaseVersion=$1 echo Releasing version $releaseVersion and preparing for next development iteration #Checkout and fetch the `dev` branch git checkout -B dev $remote/dev git pull --recurse-submodules=yes #Prepare the release mvn -DautoVersionSubmodules -DreleaseVersion=$releaseVersion release:prepare #Commit and push updated files git add --update . git commit -m "Updated release files" git push $remote dev #Checkout and fetch the `stage` branch git checkout -B stage $remote/stage git clean --force git pull --recurse-submodules=yes #Merge from release tag to `stage` git merge --strategy=recursive -Xtheirs --quiet -m "merged $releaseVersion to 'stage'" jpo-ode-$releaseVersion #Push to SCM git push $remote stage echo "Release $releaseVersion Complete"
Python
UTF-8
526
2.859375
3
[ "MIT" ]
permissive
class Solution: def getFolderNames(self, names: List[str]) -> List[str]: res = [] d = collections.defaultdict(int) for name in names: if name in d: i = d[name] + 1 while name+"({})".format(i) in d: i += 1 d[name] = i t = name + "({})".format(i) d[t] = 0 res.append(t) else: d[name] = 0 res.append(name) return res
Java
UTF-8
6,481
3.03125
3
[]
no_license
package com.Panels.GeneralPanels; import com.GUIFrame.GUIFrame; import com.Panels.WestPanelSections.WestPanelListeners.*; import javax.swing.*; import java.awt.*; /** * This Class is about west panel of our program,It has features: * HOME: it shows list of albums and playlist in center panel. * Library: it opens a file chooser to select desired mp3 files. * Songs: it shows all songs based on last playing. * Albums: it opens list of albums and user can open them. * Playlist: it opens list of playlist and user can open them. */ public class WestPanel extends JPanel { private static WestPanel westPanel; private static JPanel albumsPanel; private static JPanel homePanel; private static JPanel songsPanel; private static JPanel libraryPanel; private static JPanel playListsPanel; public WestPanel() { westPanel = this; JLabel homeLabel; JLabel homeIcon; JLabel libraryLabel; JLabel libraryIcon; JLabel addToLibraryIcon; JLabel songsLabel; JLabel songsIcon; JLabel albumsLabel; JLabel albumsIcon; JLabel playListsLabel; JLabel playListsIcon; JLabel addToPlaylistsIcon; this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); this.setBackground(new Color(23, 23, 23)); //designing home panel: homePanel = new JPanel(); homePanel.setBackground(new Color(23, 23, 23)); homePanel.setLayout(new BoxLayout(homePanel, BoxLayout.LINE_AXIS)); homeIcon = new JLabel(); homeIcon.setIcon(setIconSize("Icons/Home-no-select.png", 20)); homeLabel = new JLabel(" HOME"); homeIcon.addMouseListener(new HomePanelListener(homeIcon, homeLabel)); homeLabel.addMouseListener(new HomePanelListener(homeIcon, homeLabel)); homeLabel.setForeground(Color.WHITE); homePanel.add(homeIcon); homePanel.add(homeLabel); this.add(Box.createVerticalStrut(20)); this.add(homePanel); this.add(Box.createVerticalStrut(50)); //designing library panel: libraryPanel = new JPanel(); libraryPanel.setBackground(new Color(23, 23, 23)); libraryPanel.setLayout(new BoxLayout(libraryPanel, BoxLayout.LINE_AXIS)); libraryLabel = new JLabel(" Library "); libraryLabel.setForeground(Color.WHITE); libraryIcon = new JLabel(); libraryIcon.setIcon(setIconSize("Icons/Library-no-select.PNG", 20)); addToLibraryIcon = new JLabel(); addToLibraryIcon.setIcon(setIconSize("Icons/Plus-no-select.PNG", 10)); libraryLabel.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); libraryIcon.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); addToLibraryIcon.addMouseListener(new LibraryPanelListener(libraryIcon, libraryLabel, addToLibraryIcon)); libraryPanel.add(libraryIcon); libraryPanel.add(libraryLabel); libraryPanel.add(addToLibraryIcon); this.add(libraryPanel); this.add(Box.createVerticalStrut(30)); //designing song panel: songsPanel = new JPanel(); songsPanel.setBackground(new Color(23, 23, 23)); songsPanel.setLayout(new BoxLayout(songsPanel, BoxLayout.LINE_AXIS)); songsIcon = new JLabel(); songsIcon.setIcon(setIconSize("Icons/Song-no-selected.png", 20)); songsPanel.add(songsIcon); songsLabel = new JLabel(" Songs"); songsIcon.addMouseListener(new SongsPanelListener(songsIcon, songsLabel)); songsLabel.addMouseListener(new SongsPanelListener(songsIcon, songsLabel)); songsLabel.setForeground(Color.WHITE); songsPanel.add(songsLabel); this.add(songsPanel); this.add(Box.createVerticalStrut(30)); //designing albums panel: albumsPanel = new JPanel(); albumsPanel.setBackground(new Color(23, 23, 23)); albumsPanel.setLayout(new BoxLayout(albumsPanel, BoxLayout.LINE_AXIS)); albumsIcon = new JLabel(); albumsIcon.setIcon(setIconSize("Icons/Album-no-selected.png", 20)); albumsPanel.add(albumsIcon); albumsLabel = new JLabel(" Albums"); AlbumsPanelListener AlbumsTempListener = new AlbumsPanelListener(albumsIcon, albumsLabel); albumsIcon.addMouseListener(AlbumsTempListener); albumsLabel.addMouseListener(AlbumsTempListener); albumsLabel.setForeground(Color.WHITE); albumsPanel.add(albumsLabel); this.add(albumsPanel); this.add(Box.createVerticalStrut(30)); //designing playlist panel: playListsPanel = new JPanel(); playListsPanel.setBackground(new Color(23, 23, 23)); playListsPanel.setLayout(new BoxLayout(playListsPanel, BoxLayout.LINE_AXIS)); playListsIcon = new JLabel(); playListsIcon.setIcon(setIconSize("Icons/p-no-selected.png", 20)); playListsPanel.add(playListsIcon); playListsLabel = new JLabel(" Playlists "); playListsLabel.setForeground(Color.WHITE); playListsPanel.add(playListsLabel); PlaylistsListener playlistsTempListener = new PlaylistsListener(playListsIcon, playListsLabel); playListsIcon.addMouseListener(playlistsTempListener); playListsLabel.addMouseListener(playlistsTempListener); addToPlaylistsIcon = new JLabel(); addToPlaylistsIcon.setIcon(setIconSize("Icons/Plus-no-select.PNG", 10)); playListsPanel.add(addToPlaylistsIcon); addToPlaylistsIcon.addMouseListener(new PlaylistsPlusIconListener(addToPlaylistsIcon)); this.add(playListsPanel); } /** * This method changes size of icons. * * @param directory directory of image to change * @param scale scale we want to resize. * @return resized image icon. */ public static ImageIcon setIconSize(String directory, int scale) { ImageIcon output = GUIFrame.setIconSize(directory, scale); return output; } public static JPanel getAlbumsPanel() { return albumsPanel; } public static void setAlbumsPanel(JPanel changedAlbums) { albumsPanel = changedAlbums; } public static JPanel getPlayListsPanel() { return playListsPanel; } public static void setPlayListsPanel(JPanel changedPlaylists) { playListsPanel = changedPlaylists; } }
PHP
UTF-8
574
2.734375
3
[]
no_license
<?php /* -------Creado por------- \(x.x )/ Anarchy \( x.x)/ ------------------------ */ // Yo tengo un sueño. El sueño de que mis hijos vivan en un mundo con un único lenguaje de programación. \\ include_once realpath('../../facade/Salud_pensionFacade.php'); $id = $_POST['id']; $salud = $_POST['salud']; $pension = $_POST['pension']; $Persona_id = $_POST['persona_id']; $persona= new Persona(); $persona->setId($Persona_id); Salud_pensionFacade::insert($id, $salud, $pension, $persona); echo "true"; //That´s all folks!
Python
UTF-8
108
2.6875
3
[]
no_license
# Find keys in multidimensional dict based on value {k: v for k, v in my_dict.items() if v['baz'] == 'abc'}
Java
UTF-8
3,808
2.359375
2
[]
no_license
package org.pk.booklibrary.dao; import java.util.List; import org.pk.booklibrary.model.Book; import org.pk.booklibrary.model.BookCategory; import org.pk.booklibrary.model.Dashboard; import org.pk.booklibrary.model.Education; import org.pk.booklibrary.model.Fine; import org.pk.booklibrary.model.IssuedBook; import org.pk.booklibrary.model.User; /** * UserDao interface * * @author PKORP * @since 26/04/2017 */ public interface UserDao { /** * @return dashboard data */ Dashboard getDashboardData(); /** * @param userType * @return users list by user type */ List<User> getUsersByUserType(String userType); /** * @param user * @return registers new users in system */ boolean registerUser(User user); /** * @param userId * @return returns user details by userId */ User getUserDetails(int userId); /** * @param userId * @param userStatus * @return update user status on given userId */ boolean updateUserStatus(int userId, String userStatus); /** * @param userId * @param user * @return update user details against userId */ boolean updateUser(int userId, User user); /** * @param userId * @param imageName * @return boolean update user profile picture */ boolean updateUserProfilePic(int userId, String imageName); /** * @param bookCategory * @return boolean add book category */ boolean addBookCategory(BookCategory bookCategory); /** * @return enlisted book categories */ List<BookCategory> getBookCategories(); /** * @param id * @return book category details by categoryId */ BookCategory getBookCategoryById(int id); /** * @param book * @return add new book to system */ boolean addBook(Book book); /** * @param categoryId * @return get books by categoryId */ List<Book> getBooksByCategoryId(int categoryId); /** * @param title * @param autor * @param publication * @param category * @return books list which satisfies search criteria */ List<Book> searchBooks(String title, String autor, String publication, String category); /** * @param categoryId * @param bookId * @return book details by bookId */ Book getBookById(int categoryId, int bookId); /** * @param education * @return add new education entries */ boolean addEducation(int id, Education education); /** * @param id * @return returns education details by educationId */ Education getEducationById(int id); /** * @param id * @return education list of particular user */ List<Education> getEducationListByUserId(int id); /** * @param token * @return returns issued books by userId */ List<IssuedBook> getIssuedBooksByUserId(int token); /** * @return returns all issued books */ List<IssuedBook> getIssuedBooks(); /** * @param bookId * @param imageName * @return boolean - updates book image by bookId */ boolean updateBookImage(int bookId, String imageName); /** * @param bookId * @param userId * @return boolean if book issued */ public boolean isBookIssued(int bookId, int userId); /** * @param issuedBook * @return to register book issue */ boolean issueBook(IssuedBook issuedBook); /** * @param id * @return deletes book from system */ boolean deleteBook(int id); /** * @param id * @return delete user from system */ boolean deleteUser(int id); /** * @param bookIssueId * @param amount * @param comment * @return registers fine against issued book to user */ boolean registerFine(int bookIssueId, double amount, String comment); /** * @param userId * @param bookIssueId * @return register request for renewal */ boolean requestForRenewal(int userId, int bookIssueId); /** * @param bookIssueId * @return fine list for issued book */ List<Fine> getFine(int bookIssueId); }
TypeScript
UTF-8
11,227
2.90625
3
[ "MIT" ]
permissive
import bus, { I2CBus, BufferCallback } from 'i2c-bus'; // Wrapper around the i2c bus, has the same functions class MultiplexerChannel implements I2CBus { public channelSwitch: Buffer; constructor(public tca: Multiplexer, channel: number) { // command to send to multiplexer via i2c this.channelSwitch = Buffer.from([1 << channel]) this.switch() return new Proxy(this, { get(target, prop) { const isValidIndex = (prop: string | symbol): prop is Extract<keyof typeof target, string | symbol> => Reflect.ownKeys(Object.getPrototypeOf(target)).includes(prop); if (isValidIndex(prop)) { const origMethod = target[prop] if (typeof origMethod == 'function') { return function(...args: any[]) { target.switch(); return origMethod.apply(target, args) } } } } }) } close(callback: bus.CompletionCallback): void { return this.tca.i2c.close(callback); } closeSync(): void { return this.tca.i2c.closeSync(); } i2cFuncs(callback: bus.ResultCallback<bus.I2CFuncs>): void { return this.tca.i2c.i2cFuncs(callback); } i2cFuncsSync(): bus.I2CFuncs { return this.tca.i2c.i2cFuncsSync(); } scan(callback: bus.ResultCallback<number[]>): void; scan(address: number, callback: bus.ResultCallback<number[]>): void; scan(startAddr: number, endAddr: number, callback: bus.ResultCallback<number[]>): void; scan(startAddr: any, endAddr?: any, callback?: any): void { if (typeof startAddr === 'function') { callback = startAddr; startAddr = 0x03; endAddr = 0x77; return this.tca.i2c.scan(startAddr, endAddr, callback); } else if (typeof endAddr === 'function') { callback = endAddr; endAddr = startAddr; } if (startAddr == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.scan(startAddr, endAddr, callback); } scanSync(address?: number): number[]; scanSync(startAddr?: number, endAddr?: number): number[] { if (typeof startAddr === 'undefined') { return this.tca.i2c.scanSync(0x03, 0x77) } else if (typeof endAddr === 'undefined') { endAddr = startAddr; } if (startAddr == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.scanSync(startAddr, endAddr); } deviceId(address: number, callback: bus.ResultCallback<bus.I2CDeviceId>): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.deviceId(address, callback); } deviceIdSync(address: number): bus.I2CDeviceId { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.deviceIdSync(address); } i2cRead(address: number, length: number, buffer: Buffer, callback: BufferCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.i2cRead(address, length, buffer, callback); } i2cReadSync(address: number, length: number, buffer: Buffer): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.i2cReadSync(address, length, buffer); } i2cWrite(address: number, length: number, buffer: Buffer, callback: BufferCallback) { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } this.tca.i2c.i2cWrite(address, length, buffer, callback); } i2cWriteSync(address: number, length: number, buffer: Buffer): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.i2cWriteSync(address, length, buffer); } readByte(address: number, command: number, callback: bus.ResultCallback<number>): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readByte(address, command, callback); } readByteSync(address: number, command: number): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readByteSync(address, command); } readWord(address: number, command: number, callback: bus.ResultCallback<number>): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readWord(address, command, callback); } readWordSync(address: number, command: number): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readWordSync(address, command); } readI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: bus.BufferCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readI2cBlock(address, command, length, buffer, callback); } readI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.readI2cBlockSync(address, command, length, buffer); } receiveByte(address: number, callback: bus.ResultCallback<number>): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.receiveByte(address, callback); } receiveByteSync(address: number): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.receiveByteSync(address); } sendByte(address: number, byte: number, callback: bus.CompletionCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.sendByte(address, byte, callback); } sendByteSync(address: number, byte: number): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.sendByteSync(address, byte); } writeByte(address: number, command: number, byte: number, callback: bus.CompletionCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeByte(address, command, byte, callback); } writeByteSync(address: number, command: number, byte: number): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeByteSync(address, command, byte); } writeWord(address: number, command: number, word: number, callback: bus.CompletionCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeWord(address, command, word, callback); } writeWordSync(address: number, command: number, word: number): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeWordSync(address, command, word); } writeQuick(address: number, command: number, bit: number, callback: bus.CompletionCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeQuick(address, command, bit, callback); } writeQuickSync(address: number, command: number, bit: number): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeQuickSync(address, command, bit); } writeI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: bus.BufferCallback): void { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeI2cBlock(address, command, length, buffer, callback); } writeI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number { if (address == this.tca.address) { throw new Error("Device address must be different than TCA9548A address."); } return this.tca.i2c.writeI2cBlockSync(address, command, length, buffer); } promisifiedBus(): bus.PromisifiedBus { return this.tca.i2c.promisifiedBus(); } switch() { this.tca.i2c.i2cWriteSync(this.tca.address, this.channelSwitch.length, this.channelSwitch) } } class Multiplexer { public i2c: I2CBus; public channels: Array<MultiplexerChannel>; constructor(public address: number, i2c: number) { this.i2c = bus.openSync(i2c); this.channels = new Array(8).fill(null) return new Proxy(this, { get(target, prop) { let index = parseInt(prop.toString()) if (index != NaN) { if (!(index in target)) { if (index >= 0 && index <= 7) { // constructor will be called each time Proxy is accessed // therefore calling switch() target.channels[index] = new MultiplexerChannel(target, index); } else { return new Error("Channel should be in the range of 0-7 inclusive") } return target.channels[index]; } } } }) } } export = Multiplexer;
Java
UTF-8
144,910
1.84375
2
[]
no_license
/* * IFS Research & Development * * This program is protected by copyright law and by international * conventions. All licensing, renting, lending or copying (including * for private use), and all other use of the program, which is not * expressively permitted by IFS Research & Development (IFS), is a * violation of the rights of IFS. Such violations will be reported to the * appropriate authorities. * * VIOLATIONS OF ANY COPYRIGHT IS PUNISHABLE BY LAW AND CAN LEAD * TO UP TO TWO YEARS OF IMPRISONMENT AND LIABILITY TO PAY DAMAGES. * ---------------------------------------------------------------------------- * File : ASPPortletProvider.java * Description : * Notes : * ---------------------------------------------------------------------------- * Modified : * Jacek P 1999-Dec-06 - Created. * Jacek P 2000-Jan-17 - Extends ASPPage * Jacek P 2000-Feb-21 - Changed name from ASPPortalProvider * Jacek P 2000-Mar-21 - Set version 3 * Jacek P 2000-Apr-04 - Changes in printTable(). * Jacek P 2000-Apr-17 - removed-flag moved to ASPPortletHandle class. * Added runCustom(). Several functions changed to final. * Jacek P 2000-Apr-18 - Functions run() and runCustom() can now throw FndException. * Jacek P 2000-May-08 - Beta 4 release of Web Kit 3.0.0. * Jacek P 2000-May-16 - Added methods begin/endTableCell(). * Jacek P 2000-May-22 - New methods for support of command bars and popups. * Added parseProviderPrefix(). Id converted to upper case. * New print*() methods. * Jacek P 2000-May-24 - New functions for hover image links and width control * of tables. * Jacek P 2000-Jul-05 - Reorganized, added comments. * Jacek P 2000-Jul-25 - Fixed bug 281: Netscape doesn't support empty JavaScript files. * Jacek P 2000-Jul-26 - Log id 226: Improved error handling. * Jacek P 2000-Jul-28 - Bug id 248: Added call to HTMLEncode() for print*() methods. * Jacek P 2000-Aug-14 - Adding cloning of buffer in readProfileBuffer(). * Jacek P 2000-Jul-28 - Temporary removed call to HTMLEncode() from printTableCell(). * Jacek P 2000-Aug-24 - Changed back printTableCell(). * Added empty-check in printText() and printTableCell(). * Jacek P 2000-Oct-04 - Added method getColumnWidth() (log id #426). * Jacek P 2000-Oct-06 - Added methods printLOV() and printDynamicLOV() (log id #298). * Jacek P 2000-Oct-17 - Added call to getApplicationPath() in printLink() (log id #469) * Jacek P 2000-Nov-22 - Added printAbsoluteLink() that replaces the changed prinkLink(). * Implementation of printLink() backed to the previous version (log id #518). * Piotr Z 2000-Mar-12 - New method clearGlobalProfile(). * Piotr Z 2001-Apr-25 - Scaling of input and textarea fields size for Netscape. * Piotr Z 2001-May-22 - Added handling of ASPManager.ResponseEndException in the method define(). * Piotr Z 2001-May-30 - Moved handling of ASPManager.ResponseEndException from the method define() * to FndException class. * Artur K 2001-Jun-12 - Changed readProfileValue() and readProfileFlag() * Ramila H 2001-Jun-25 - Added split() method. * Jacek P 2001-Sep-24 - Added reseting of intitlerow variable. * Suneth M 2001-Oct-12 - Changed readProfileValue(). * Daniel S 2001-Oct-16 - AltBackground color on every other row not hardcoded anylonger. * Rifki R 2001-Dec-11 - Log id 771: used getASPManager().getASPLog() in enableWriteResponse(), * disableWriteResponse() and formatPortletErrorMsg() methods. * Jacek P 2002-Feb-04 - Removed some controles while building up the HTML table. * Affected variables are: tablelevel, tabbodylevel and tabcelllevel * Daniel S 2002-Aug-28 - Added method frameworkReset to break the doReset chain. Necessary * due to the new smart Resetting/Cloning. * Chandana 2002-Aug-30 - Added an Item ("DATA_STORE") to the request buffer in the submit method. * Chandana 2002-Sep-03 - Modified printLink() method to support hyperlinking only a part of the text using '&&'. * Rifki R 2002-Oct-15 - Moved implementation of split() method to util class Str. * Shiran F 2002-Oct-24 - Added method isMaximized. * Chanaka 2002-Dec-16 - Add overload methods beginTableCell() to set the nowrap property in a cell * Sampath 2002-Dec-26 - Add new method getZoomInURL() to eneble zoomin in portlets * Rifki R 2003-Jan-09 - Log id 1010, changed printTable() for auto security check. * Sampath 2004-May-23 - add a new method beginCustomTable() * Sampath 2004-Aug-13 - called getLOVTag1Iid() in printLOV * Jacek P 2004-Jan-04 - Bug#40931. Better debugging possibilities of Page Pool. * ChandanaD2004-Mar-23 - Merged with SP1. * ChandanaD2004-May-12 - Updated for new style sheets. * Mangala 2004-Jun-17 - Merged with Bug #44656 * Chandana 2004-Aug-05 - Proxy support corrections. * Suneth M 2004-Aug-17 - Added overloaded methods printLOV() & printDynamicLOV() to enable * multi-choice option for LOV's. * Suneth M 2004-Aug-19 - Added methods printCalender(), printDateTimeMask() & changed printField() * to improve support for date fields. * Ramila H 2004-Nov-18 - Implemented JSR168 support * Mangala 2004-Nov-09 - Changes done for SSO for JSR168. * ---------------------------------------------------------------------------- * New Comments: * 2008/06/26 mapelk Bug 74852, Programming Model for Activities. * 2008/05/12 sumelk Bug 73849, Changed printRadioButton() to print the label using the standard font. * 2008/03/27 sadhlk Bug 72361, Modified define(). * 2008/01/21 sumelk Bug 69852, Changed printField() to send the block name as a parameter for formatDate_(). * 2007/07/03 sadhlk Merged Bug 64669, Modified writeProfileBuffer(), writeProfileValue(), writeProfileFlag(). * 2007/01/30 mapelk Bug 63250, Added theming support in IFS clients. * 2006/12/21 buhilk Bug id 61697, Added printBoldText(), printItalicText(), printBoldItalicText() methods. * 2006/09/24 mapelk Bug Id 59842, Improved CSV code * 2006/09/19 buhilk removed overloading readProfileValue() with ASPField parameter * * 2006/09/19 buhilk Bug id 59842, Modifed private readProfileValue() method to format CSV values according to a field * Added more overloading readProfileValue() methods to handle new functionality * * 2006/09/18 buhilk Bug id 59842, Modifed readProfileValue() to handle context substitution variables * Added overloading readProfileValue() and readAbsoluteProfileValue() methods * and modified the printLink() method to decode URL's with CSV values. * * 2006/08/01 rahelk Bug id 59663, Fixed bug in printLink and printImage * * Revision 1.4 2005/11/08 07:51:30 rahelk * core changes for using USAGES in help * * Revision 1.3 2005/11/07 08:16:33 mapelk * Introduced "persistant" att to Dynamic Objects and remove non persistent objects from the DynamicObjectCache in the first get. * * Revision 1.2 2005/10/14 09:08:14 mapelk * Added common profile elements. And removed language specific formats and read from locale. * * Revision 1.1 2005/09/15 12:38:00 japase * *** empty log message *** * * Revision 1.11 2005/08/30 11:14:26 mapelk * Introduced new APIs to draw images with a name and a title. * * Revision 1.10 2005/08/08 09:44:05 rahelk * Declarative JAAS security restructure * * Revision 1.9 2005/06/27 05:01:09 mapelk * Bug fixes for std portlets * * Revision 1.8 2005/06/08 09:34:51 japase * Setting right type when storing profile flags * * Revision 1.7 2005/04/07 13:49:25 riralk * Called updatePageScript() in ASPPage when generating client scripts for portlets from generatePageClientScript(). * * Revision 1.6 2005/04/01 13:59:56 riralk * Moved Dynamic object cache to session - support for clustering * * Revision 1.5 2005/02/24 13:48:59 riralk * Adapted Portal profiles to new profile algorithm. Removed some obsolete code. * * Revision 1.4 2005/02/24 08:53:52 mapelk * Improved automatic security checks * * Revision 1.3 2005/02/16 08:39:57 japase * Only ProfileItem instances allowed in profiles * * Revision 1.2 2005/02/01 10:32:59 mapelk * Proxy related bug fix: Removed path dependencies from webclientconfig.xml and changed the framework accordingly. * * Revision 1.1 2005/01/28 18:07:26 marese * Initial checkin * * Revision 1.4 2005/01/06 08:56:36 rahelk * added setFormReference to printField and printCalender * * Revision 1.3 2005/01/06 04:33:04 rahelk * bug correction to support standard portlet mode * * Revision 1.2 2004/12/15 11:04:04 riralk * Support for clustered environments by caching business graphics and generated javascript files in memory * * ---------------------------------------------------------------------------- */ package ifs.fnd.asp; import ifs.fnd.buffer.*; import ifs.fnd.service.*; import ifs.fnd.util.*; import ifs.fnd.ap.*; import java.util.*; import java.io.*; import java.lang.reflect.*; /** */ public abstract class ASPPortletProvider extends ASPPage { //========================================================================== // Static constants //========================================================================== public static boolean DEBUG = Util.isDebugEnabled("ifs.fnd.asp.ASPPortletProvider"); /** * Constant for definition of portlet mode. * Used when portlet is minimized in the browser. * * @see ifs.fnd.asp.ASPPortletProvider#getTitle */ public static final int MAXIMIZED = ASPPortal.MAXIMIZED; /** * Constant for definition of portlet mode. * Used when portlet is maximized in the browser. * * @see ifs.fnd.asp.ASPPortletProvider#getTitle */ public static final int MINIMIZED = ASPPortal.MINIMIZED; /** * Constant for definition of portlet mode. * Used when portlet is shown in customize mode. * * @see ifs.fnd.asp.ASPPortletProvider#getTitle */ public static final int CUSTOM = ASPPortal.CUSTOM; //========================================================================== // instances created on page creation (immutable attributes) //========================================================================== private AutoString script; private String scriptfile; private AutoString dirty_script = new AutoString(); //========================================================================== // Transient temporary variables (never cloned) //========================================================================== private transient ASPPortal portal; private transient ASPPageHandle handle; private transient String prvid; private transient ASPPortletHandle porthand; private transient int linkseq = 0; private transient FndException portlet_err; private transient Vector dummy_globals; private AutoString out = new AutoString(); private AutoString temp_globals = new AutoString(); private AutoString temp_globals_value = new AutoString(); //========================================================================== // Construction //========================================================================== /** * Public constructor that will be called by ASPPortal. * Must be overridden by the portlet and call the super() function. */ public ASPPortletProvider( ASPPortal portal, String clspath ) { super(portal.getASPManager(), clspath); if(DEBUG) debug(this+": ASPPortletProvider.<init>: "+portal+","+clspath); this.portal = portal; } /** * Construction of the page. */ //public protected ASPPage construct() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.construct()"); script = new AutoString(); return super.construct(); } //========================================================================== // Methods for implementation of pool //========================================================================== /** * Freeze the page. Call freeze() for all enclosed elements. * Set the page in state DEFINED. Can only by called if the current * state of the page is UNDEFINED. */ protected void doFreeze() throws FndException { if (DEBUG) debug(this+": ASPPortletProvider.doFreeze()"); // Vector tables = getASPTables(); // for( int i=0; i<tables.size(); i++ ) // ((ASPTable)tables.elementAt(i)).disableNoWrap(); super.doFreeze(); } /** * Just a container of frameworkReset. */ protected void doReset() throws FndException { frameworkReset(); } /** * Reset the page. Call reset() for all enclosed elements. * Set the page in state DEFINED. Can only be called if the current * page is in state DIRTY or DEFINED. Prepare for releasing in the pool. */ protected final void frameworkReset() throws FndException { if (DEBUG) debug(this+": ASPPortletProvider.frameworkReset()"); super.doReset(); out.clear(); portal = null; handle = null; prvid = null; porthand = null; linkseq = 0; portlet_err = null; intitlerow = false; dirty_script.clear(); if(dummy_globals != null) dummy_globals.clear(); if(temp_globals != null) temp_globals.clear(); if(temp_globals_value != null) temp_globals_value.clear(); } /** * Activate the page after feching from pool. Call activate() for * all enclosed elements. * Can only be called if the current object is in state DEFINED. */ protected void doActivate() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.doActivate()"); // super.doActivate(); portal = getASPManager().getPortalPage().getASPPortal(); //prvid = null; already set from ASPPortal !!! linkseq = 0; out.clear(); dirty_script.clear(); super.doActivate(); } /** * Clone the page and all enclosed elements. * The new page is always in state DEFINED. * Set default values for all mutable attributes. */ public ASPPoolElement clone( Object mgr ) throws FndException { if (DEBUG) debug(this+": ASPPortletProvider.clone("+mgr+")"); ASPPoolElement page = super.clone(mgr); return page; } /** * Create a new instance of the current class by using the Relection package. * Called from ASPPage. */ protected final ASPPage newInstance( ASPManager mgr ) throws FndException { if (DEBUG) debug(this+": ASPPortletProvider.newInstance("+mgr+")"); ASPPortal portal = mgr.getPortalPage().getASPPortal(); String clspath = null; ASPPortletProvider prv; try { Object[] arg = new Object[2]; arg[0] = portal; arg[1] = clspath; if(DEBUG) debug(" arg=[0]"+arg[0]+"\n\t arg=[1]"+arg[1]); Class[] argcls = new Class[2]; argcls[0] = portal.getClass(); argcls[1] = Class.forName("java.lang.String"); if(DEBUG) debug(" argcls[0]="+argcls[0]+"\n\t argcls[1]="+argcls[1]); Class cls = getClass(); //Class.forName(getClass().getName()); Constructor ctr = cls.getConstructor(argcls); prv = (ASPPortletProvider)(ctr.newInstance(arg)); } catch( InvocationTargetException x ) { Throwable t = x.getTargetException(); if(DEBUG) debug(" InvocationTargetException:\n"+Str.getStackTrace(t)); throw new FndException(t); } catch( Throwable x ) { if(DEBUG) debug(Str.getStackTrace(x)); throw new FndException(x); } prv.script = script; prv.scriptfile = scriptfile; return prv; } /** * Returns true if compared instances (portlets) are of the same class * and have the same profile information */ protected boolean equals( ASPPortletProvider prv ) { if(DEBUG) debug(this+": ASPPortletProvider.equals("+prv+")" ); if( getClass().getName() != prv.getClass().getName() ) return false; if( porthand==null && prv.porthand==null ) return true; if( porthand==null || prv.porthand==null ) return false; Buffer prf1 = porthand.getProfile(); Buffer prf2 = prv.porthand.getProfile(); if( prf1==null && prf2==null ) return true; if( prf1==null || prf2==null ) return false; return prf1.equals(prf2); } //========================================================================== // Functions that handle references to the stored instances. Not to be used by portlets. //========================================================================== /** * Get an instance of ASPLog connected to the main page. * Called from constructor in ASPPage. * Override the corresponding method in ASPPage. * * @see ifs.fnd.asp.ASPPage#newASPLog */ protected ASPLog newASPLog() { if(DEBUG) debug(this+": ASPPortletProvider.newASPLog()"); return getASPManager().getASPLog(); } /** * Create a new instance of ASPContext connected to this page. * Called from constructor in ASPPage. * Override the corresponding method in ASPPage. * * @see ifs.fnd.asp.ASPPage#newASPContext */ protected final ASPContext newASPContext() { if(DEBUG) debug(this+": ASPPortletProvider.newASPContext()"); return new ASPPortalContext(this); } /** * Return the ASPContext instance connected to the main portal page. * Called from construct() and doActivate() in ASPPortalContext. */ ASPContext getParentContext() { return portal.getASPPage().getASPContext(); } /** * Called from ASPPage.setDefined() to create and lock a pool handle. * Override the corresponding method in ASPPage. */ protected void setAndLockPageHandle() throws FndException//JAPA { //Bug 40931, start //setPageHandle( ASPPagePool.addAndLock(this) ); setPageHandle( ASPPagePool.addAndLock(this, portal==null ? null : portal.getASPPage()) ); //Bug 40931, end } /** * Set a page pool handle for this page. * Called from setAndLockPageHandle() and ASPPortletHandle.activate(). */ void setPageHandle( ASPPageHandle handle ) { this.handle = handle; } /** * Return the stored page pool handle for this page. * Called from ASPPortletHandle.reset(). */ ASPPageHandle getPageHandle() { return handle; } /** * Set a portlet handle for this page. * Called from the constructor and activate() in ASPPortletHandle. */ void setHandle( ASPPortletHandle handle ) { this.porthand = handle; } //========================================================================== // Error handling //========================================================================== FndException getPortletException() { return portlet_err; } void setPortletException( FndException portlet_err ) { this.portlet_err = portlet_err; } void formatPortletErrorMsg( AutoString out ) throws FndException { if(portlet_err!=null) { ASPLog log = getASPManager().getASPLog(); log.setPortlet(this); log.logError(portlet_err,out); log.setPortlet(null); } } void enableWriteResponse() { if(DEBUG) debug(this+": ASPPortletProvider.enableWriteResponse(): "+ getASPManager()+","+(getASPManager()==null?"null":getASPManager().getASPLog()+"")); getASPManager().getASPLog().enableWriteResponse(); } void disableWriteResponse() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.disableWriteResponse(): "+ getASPManager()+","+(getASPManager()==null?"null":getASPManager().getASPLog()+"")); getASPManager().getASPLog().disableWriteResponse(this); } //========================================================================== // Generation of client script //========================================================================== /** * Create a JS file for the current portlet. * Override the corresponding method in ASPPage. * * @see ifs.fnd.asp.ASPPage#generatePageClientScript */ protected void generatePageClientScript() throws Exception { if(DEBUG) debug(this+": ASPPortletProvider.generatePageClientScript()"); if(!Str.isEmpty(scriptfile)) { // String path = getApplicationPath()+scriptfile; String path = scriptfile; if(DEBUG) debug(" path="+path); String phypath = getASPManager().getPhyPath(path); //mapPath() if(DEBUG) debug(" phypath="+phypath); String jsfile = Util.readAndTrimFile(phypath); script.append("\n\n// Included script file:\n\n",jsfile); } // Workaround due to Netscape bug if(script.length()==0) script.append("function dummy(){}\n"); script.append(getASPConfig().getCalendarConsts()); String docache = getASPConfig().getParameter("ADMIN/DYNAMIC_OBJECT_CACHE/ENABLED","N"); if ("Y".equals(docache)) { DynamicObjectCache.put(getScriptCacheKey(), script.toString(),"text/javascript", getASPManager(),true ); updatePageScript(script.toString()); } else Str.writeFile(getScriptFileName(),script.toString()); } /** * Add dirty JavaScript block functions and script code. * Override the corresponding method in ASPPage. * * @see ifs.fnd.asp.ASPPage#appendDirtyClientScript */ void appendDirtyClientScript( AutoString buf ) throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.appendDirtyClientScript("); buf.append("\n<!-- append dirty script for portlet: '",prvid,"' -->"); if( dirty_script.length()>0 ) { buf.append(ASPPage.BEGIN_SCRIPT_TAG); Vector blocks = getASPBlocks(); for( int i=0; i<blocks.size(); i++ ) { ASPBlock blk = (ASPBlock)(blocks.elementAt(i)); if( isNotDefined() ) blk.appendPageClientScript(buf); else blk.appendDirtyClientScript(buf); } buf.append("setFormReference('"); buf.append(prvid); buf.append("');\n"); //if (getASPManager().getASPConfig().identifiedByStandardPortal()) // buf.append("storeUserKeyCookie('" + getASPManager().getAspSession().getAttribute(ifs.fnd.portal.GenericIFSPortlet.USER_REF_KEY) + "');\n"); buf.append(dirty_script); buf.append(ASPPage.END_SCRIPT_TAG); } } //========================================================================== //========================================================================== // Portlet protected interface //========================================================================== //========================================================================== //========================================================================== // Template functions for overriding in portlets //========================================================================== /** * Return the minimum width of the portlet in pixels. * Default value corresponds to the default wide column. * Used to decide within which portal column the portlet can be placed. */ public static int getMinWidth() { return 288; } /** * Return the portlet description that will be shown on the 'Customize Portal' page. * The description text should contain the translatable constant. * * @see ifs.fnd.asp.ASPManager#translate */ public static String getDescription() { return "FNDPRVDESC: Description not set"; } /** * Return the title of the portlet depending of the current mode, * which can be one of MAXIMIZED, MINIMIZED or CUSTOM. * * @see ifs.fnd.asp.ASPPortletProvider#MAXIMIZED * @see ifs.fnd.asp.ASPPortletProvider#MINIMIZED * @see ifs.fnd.asp.ASPPortletProvider#CUSTOM */ protected String getTitle( int mode ) throws FndException { return getClass().getName(); } /** *return the URL of page opened when zoomin button is clicked *the zoom button is enebled only when this method returns a non null value */ protected String getZoomInURL() { return null; } /** * Called by ASPPortletHandle, not for overriding. */ void define() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.define()"); if( !isDefined() ) { setVersion(3); if(portlet_err==null) try { disableWriteResponse(); preDefine(); setDefined(); enableWriteResponse(); } catch( Throwable x ) { enableWriteResponse(); if( !(x instanceof ASPLog.AbortException) ) { if( portlet_err==null ) { if( x instanceof FndException ) portlet_err = (FndException)x; else portlet_err = new FndException(x); } else if( portlet_err.getCaughtException()==null ) portlet_err.addCaughtException(x); portlet_err.setAdditionalMessage(translate("FNDPRVERR1: in preDefine().")); } } } else if(portlet_err==null) try { disableWriteResponse(); init(); enableWriteResponse(); } catch( Throwable x ) { enableWriteResponse(); if( !(x instanceof ASPLog.AbortException) ) { if( portlet_err==null ) { if( x instanceof FndException ) portlet_err = (FndException)x; else portlet_err = new FndException(x); } else if( portlet_err.getCaughtException()==null ) portlet_err.addCaughtException(x); portlet_err.setAdditionalMessage(translate("FNDPRVERR2: in init().")); } } applyProfileFormatter(); applyLongYearFormatter(); } /** * Define the logical structure of the portal. * Called only once to create the structure stored in the page pool for later use. */ protected void preDefine() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.preDefine()"); } /** * Called on page definition instead of preDefine() * if the portlet is fetched from the pool. * Placeholder for initialization of variables * and fetching of profile information. */ protected void init() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.init()"); } /** * Placeholder for the business logic. */ protected void run() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.run()"); } /** * Create the HTML contents of the portlet by calling printContents(). * Called from ASPPortel.generateBoxBody() */ AutoString getContents() throws FndException { out.clear(); if(portlet_err==null) try { disableWriteResponse(); printContents(); enableWriteResponse(); } catch( Throwable x ) { enableWriteResponse(); if( !(x instanceof ASPLog.AbortException) ) { if( portlet_err==null ) { if( x instanceof FndException ) portlet_err = (FndException)x; else portlet_err = new FndException(x); } else if( portlet_err.getCaughtException()==null ) portlet_err.addCaughtException(x); portlet_err.setAdditionalMessage(translate("FNDPRVERR3: in getContents().")); } } if(portlet_err!=null) { out.clear(); out.append("<p class=normalTextLabel>",translate("FNDPRVERRMSG: Error message:"),"</p><font class=normalTextValue>\n"); formatPortletErrorMsg(out); out.append("</font>\n"); } return out; } /** * Print the HTML contents of the portlet. */ protected void printContents() throws FndException { printText(null); } /** * Define possibility of portlets customization. * If the portlet should be customizable this function must return true. */ protected boolean canCustomize() { return false; } /** * Called during the next request after the customize mode is finished. * Placeholder for saving of the profile information. */ protected void submitCustomization() throws FndException { } /** * Run the business logic for the customize mode. */ protected void runCustom() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.runCustom()"); } /** * Create the HTML code for the customize mode by calling printCustomBody(). * Called from ASPPortel.generateCustomizeHTML() */ void getCustomBody( AutoString out ) throws FndException { this.out.clear(); printCustomBody(); out.append(this.out); } /** * Print the HTML code for the customize mode. */ protected void printCustomBody() throws FndException { printText(null); } //========================================================================== // Functions for handling of portlet ID //========================================================================== /** * Return portlet prefix, based on portlet ID, to be used in conjunction * to generation of HTML objects. */ protected final String addProviderPrefix() { if(DEBUG) debug(this+": ASPPortletProvider.addProviderPrefix()"); return "_"+getId().replace('.','_')+"_"; } /** * Return the portlet ID given the portlet prefix used in conjunction to HTML objects. */ protected final static String parseProviderPrefix( String prefix ) throws FndException { if(DEBUG) Util.debug("ASPPortletProvider.parseProviderPrefix("+prefix+")"); if( Str.isEmpty(prefix) ) throw new FndException("FNDPPRVEMPTYPREFIX: Provider prefix not defined."); if( !prefix.startsWith("_") || !prefix.endsWith("_") ) throw new FndException("FNDPPRVERRBEGEND: Provider prefix syntax error."); String id = prefix.substring(1,prefix.length()-1); if(DEBUG) Util.debug(" id="+id); return id; } //JAPA ? obsolete? used also by ASPPage protected final String prefixWithId() { if(DEBUG) debug(this+": ASPPortletProvider.prefixWithId()"); return ""; } /** * Sets the portlet ID. Called by ASPPortal. */ void setId( String id ) { if(DEBUG) debug(this+": ASPPortletProvider.setId("+id+")"); this.prvid = id.toUpperCase(); } /** * Returns the current portlet ID. The ID is valid only during the request * and is not the same for two requests. */ protected final String getId() { if(DEBUG) debug(this+": ASPPortletProvider.getId(): "+prvid); return prvid; } /** * Returns whether the current portlet is Maximized or not. */ protected final boolean isMaximized() { return portal.isPortletMaximized(getId()); } /** * Returns the HTML name of an object. */ protected final String getHTMLName( String name ) { return addProviderPrefix() + name; } /** * Returns an ID to be used for naming of portlet sub-buffer in the portal context. */ String getContextId() { if(DEBUG) debug(this+": ASPPortletProvider.getContextId()"); String ctxid = getClass().getName()+"."+getId(); if(DEBUG) debug(" ctxid="+ctxid); return ctxid; } //========================================================================== // Other help functions to be used in the portlet //========================================================================== /** * Returns the width of the current portal column. */ protected final int getColumnWidth() { if(portal!=null && prvid!=null) return portal.getColumnWidth(prvid); return -1; } //========================================================================== // Translations //========================================================================== /** * Returns the translation of a translatable constant. * <p> * A translatable constant is a constant which's value begins with the constant name, * a colon, and a space. * * @see ifs.fnd.asp.ASPManager#translate */ protected final String translate( String text ) { return getASPManager().translateJavaText(text); } /** * Returns the translation of a translatable constant * and inserts parameters in the translation. * <p> * This function works by replacing placeholders in the constant text with * the values of the replacement parameters. A placeholders is an apersand (&) * character followed by a number. The number indicates what parameter value should * replace the placeholder. For example &1 is replaced by p1, &2 by p2 and &3 by p3. * * @see ifs.fnd.asp.ASPManager#translate */ protected final String translate( String text, String p1, String p2, String p3 ) { return getASPManager().translateJavaText(text,p1,p2,p3); } /** * Returns the translation of a translatable constant * and inserts parameters in the translation. * * @see ifs.fnd.asp.ASPManager#translate */ protected final String translate( String text, String p1, String p2 ) { return getASPManager().translateJavaText(text,p1,p2); } /** * Returns the translation of a translatable constant * and inserts parameter in the translation. * * @see ifs.fnd.asp.ASPManager#translate */ protected final String translate( String text, String p1 ) { return getASPManager().translateJavaText(text,p1); } //========================================================================== // Profile //========================================================================== /** * Writes a named item (string or buffer) to the profile buffer. */ private void writeItem( Item item ) { if(DEBUG) debug(this+": ASPPortletProvider.writeItem("+item+")" ); if( porthand==null ) return; Buffer profile = porthand.getProfile(); //if( profile == null ) profile = porthand.setProfile( getASPConfig().getFactory().getBuffer() ); if( profile == null ) profile = porthand.setProfile( ProfileUtils.newProfileBuffer() ); synchronized(profile) { Item existing_item = profile.getItem( item.getName(), null ); if ( existing_item==null ) profile.addItem( item ); else existing_item.setValue( item.getValue() ); } } /** * Reads a named item (string or buffer) from the profile buffer. * Returns null if such an item does not exist. */ private Item readItem( String name ) { if(DEBUG) debug(this+": ASPPortletProvider.readItem("+name+")"); if( porthand==null || porthand.getProfile()==null ) return null; Item item = porthand.getProfile().getItem( name, null ); return item; } /** * Writes a named buffer to the user profile. * The cached profile information will be updated directly, but the * profile information stored in the database will be updated only * if this function is called within the submitCustomization() function. */ protected final void writeProfileBuffer( String name, ASPBuffer buf ) { if(portal.getASPPage().getASPProfile().isUserProfileDisabled()) return; //writeItem( new Item( name, buf.getBuffer() ) ); writeItem( new ProfileItem(name, ProfileBuffer.bufferToProfileBuffer(buf.getBuffer())) ); } /** * Reads a named buffer from the user profile. * Returns null if such buffer does not exist. */ protected final ASPBuffer readProfileBuffer( String name ) { Item item = readItem( name ); return item==null ? null : (new ASPBuffer(getASPManager())).construct( (Buffer)item.getBuffer().clone() ); } /** * Writes a named string to the user profile. * The cached profile information will be updated directly, but the * profile information stored in the database will be updated only * if this function is called within the submitCustomization() function. */ protected final void writeProfileValue( String name, String value ) { if(DEBUG) debug(this+": ASPPortletProvider.writeProfileValue("+name+","+value+")"); if(portal.getASPPage().getASPProfile().isUserProfileDisabled()) return; //writeItem( new Item( name, value ) ); writeItem( new ProfileItem( name, value ) ); } /** * Reads a named value from the query string or, if such value does not exist, * from the user profile. * If it is a CSV, Value is also evaluated and also if an ASPField is found with the same name as the named value * the CSV value is formatted according to the ASPField's data type. * Returns 'def_value' otherwise. */ protected final String readProfileValue( String name, String def_value) { ASPField f = (isASPField(name))? getASPField(name): null; return readProfileValue(name,def_value,true,false,f); } /** * Reads a named value from the query string or, if such value does not exist, * from the user profile. * Returns 'def_value' otherwise. */ protected final String readAbsoluteProfileValue( String name, String def_value) { return readProfileValue(name,def_value,true,true,null); } /** * Reads a named value from the query string or, if such value does not exist, * from the user profile. * If it is a CSV, Value is also evaluated and also if an ASPField is found with the same name as the named value * the CSV value is formatted according to the ASPField's data type. * Returns 'def_value' otherwise. */ protected final String readProfileValue( String name, String def_value, boolean read_global) { ASPField f = (isASPField(name))? getASPField(name): null; return readProfileValue(name,def_value,read_global,false,f); } /** * Reads a named value from the query string or, if such value does not exist, * from the user profile. * Returns 'def_value' otherwise. */ protected final String readAbsoluteProfileValue( String name, String def_value, boolean read_global) { return readProfileValue(name,def_value,read_global,true,null); } private final String readProfileValue( String name, String def_value, boolean read_global, boolean absolute, ASPField format_by_field ) { if(DEBUG) debug(this+": ASPPortletProvider.readProfileValue("+name+","+def_value+")"); String strProfileValue = def_value; if( read_global ) { String global = portal.getGlobalVariable(name); if( !Str.isEmpty(global) ) { StringTokenizer st = new StringTokenizer(global,","); if(st.hasMoreTokens()) strProfileValue = st.nextToken(); else strProfileValue = global; /*if (!Str.isEmpty(strProfileValue) && !absolute && getASPManager().isCSVName(strProfileValue)) return getASPManager().getCSVValue(strProfileValue, def_value, format_by_field); else*/ return strProfileValue; } } Item item = readItem( name ); strProfileValue = item==null ? def_value : item.getString(); if (!Str.isEmpty(strProfileValue) && !absolute && getASPManager().isCSVName(strProfileValue)) { if (DEBUG) debug("----- Read profile value found as CSV "); return getASPManager().getCSVValue(strProfileValue, def_value, format_by_field); } return strProfileValue; } /** * Reads a named value from the query string or, if such value does not exist, * from the user profile. * Returns null otherwise. */ protected final String readProfileValue( String name ) { ASPField f = (isASPField(name))? getASPField(name): null; return readProfileValue(name,null,true,false,f); } protected final String readAbsoluteProfileValue( String name ) { return readProfileValue(name,null,true,true,null); } /** * Writes a named boolean flag to the user profile. * The cached profile information will be updated directly, but the * profile information stored in the database will be updated only * if this function is called within the submitCustomization() function. */ protected final void writeProfileFlag( String name, boolean value ) { if(portal.getASPPage().getASPProfile().isUserProfileDisabled()) return; /* if (value) //writeItem( new Item( name, "TRUE" ) ); writeItem( new ProfileItem( name, "TRUE" ) ); else //writeItem( new Item( name, "FALSE" ) ); writeItem( new ProfileItem( name, "FALSE" ) ); */ ProfileItem item = new ProfileItem(name, value ? "TRUE" : "FALSE"); item.setType("B"); writeItem(item); } /** * Reads a named boolean from the query string or, if such variable does not exist, * from the user profile. * Returns 'def_value' otheriwse. */ protected final boolean readProfileFlag( String name, boolean def_value ) { return readProfileFlag( name, def_value, true ); } protected final boolean readProfileFlag( String name, boolean def_value, boolean read_global ) { if(read_global) { String global = portal.getGlobalVariable(name); if(!Str.isEmpty(global)) return "TRUE".equals(global.toUpperCase()) ? true : false; } Item item = readItem( name ); if (item==null) return def_value; if ( "TRUE".equals( item.getString() ) ) return true; else return false; } /** * Put some code here if you want to clear infromation * writen to global profile within the portlet. Method is called * from ASPPortletProfile.rearrangeColumns() for portlets which are * close to be removed from portal. */ protected void clearGlobalProfile() { } //========================================================================== // Functions that replace the corresponding functions in ASPManager //========================================================================== /** * Returns a Date object using a client format date string. * @param blk Current block. */ protected Date parseDate(String name, String date) { if(DEBUG) debug(this+": ASPPortletProvider.parseDate()"); return getASPManager().parseDate( name, date, this); } /** * Call the submit(ASPTransactionBuffer, String) method passing * the default MTS server component as the second argument. * The ProgID for the default MTS component is defined in the configuration * parameter SERVER.PROGID. */ protected final ASPTransactionBuffer submit( ASPTransactionBuffer request ) { if(DEBUG) debug(this+": ASPPortletProvider.submit()"); return getASPManager().callMTS(request,null,true,true,this); } /** * Call the perform(ASPTransactionBuffer, String) method passing * the default MTS server component as the second argument. * Not allowed to run before the page is defined. */ protected final ASPTransactionBuffer perform( ASPTransactionBuffer request ) { if(DEBUG) debug(this+": ASPPortletProvider.perform()"); if( isUndefined() ) setPerformWhileUndefined(); return getASPManager().callMTS(request,null,false,true,this); } /** * Pass the request buffer to the default MTS server component * for execution. Return the response buffer, if the request has been * successfully performed. Otherwise, format an error page, send it * to the client and return null. Use the config user. * Only allowed to run while the page is still in the undefine state. */ protected final ASPTransactionBuffer performConfig( ASPTransactionBuffer request ) { if(DEBUG) debug(this+": ASPPortletProvider.performConfig()"); try { if( !isUndefined() ) throw new FndException("FNDPPRVEPERC: Not allowed to call performConfig() if the page is already defined."); request.addConfigRequestHeader(); } catch( Throwable any ) { error(any); } return getASPManager().callMTS(request,null,false,true,this); } /** * Call the validate(ASPTransactionBuffer, String) method passing * the default MTS server component as the second argument. */ protected final ASPTransactionBuffer validate( ASPTransactionBuffer request ) { if(DEBUG) debug(this+": ASPPortletProvider.validate()"); return getASPManager().callMTS(request,null,false,false,this); } //========================================================================== // ASPField functions that replace the corresponding functions in ASPBlock and ASPPage //========================================================================== /** * Define a new field having the specified name, default type ("String") and * no format mask. * The specified name can contain a comma-separated list of field names. * Return a reference to the last created field. */ protected final ASPField addField( ASPBlock blk, String name ) { if(DEBUG) debug(this+": ASPPortletProvider.addField("+blk+","+name+")"); return blk.addField(name); } /** * Define a new field having the specified name, the specified type * and default format mask. * The specified name can contain a comma-separated list of field names. * Return a reference to the last created field. */ protected final ASPField addField( ASPBlock blk, String name, String type ) { if(DEBUG) debug(this+": ASPPortletProvider.addField("+blk+","+name+","+type+")"); return blk.addField(name, type); } /** * Define a new field having the specified name, type and format mask. * The specified name can contain a comma-separated list of field names. * Return a reference to the last created field. */ protected final ASPField addField( ASPBlock blk, String name, String type, String mask ) { if(DEBUG) debug(this+": ASPPortletProvider.addField("+blk+","+name+","+type+","+mask+")"); return blk.addField(name, type, mask); } /** * Return a reference to the named ASPField. Throw an Exception if the * specified field has not been defined on the current ASP page. */ public final ASPField getASPField( String name ) { if(DEBUG) debug(this+": ASPPortletProvider.getASPField("+name+")"); return super.getASPField(name); } //========================================================================== // Command Bar & Popup functions //========================================================================== /** * Return true if any command bar function has been activated * during the previous request. * The portlet framework doesn't support visible command bars. * Activation of command bar functions is only possible by * popup menus in an ASP table or programmatic by links. */ protected final boolean commandBarActivated() { return portal.commandBarActivated(); } /** * Return true if any standard command bar function * has been activated during the previous request. * * @see ifs.fnd.asp.ASPPortletProvider#commandBarActivated */ protected final boolean cmdBarStandardCommandActivated() { return portal.cmdBarStandardCommandActivated(); } /** * Return true if any custom command bar function * has been activated during the previous request. * * @see ifs.fnd.asp.ASPPortletProvider#commandBarActivated */ protected final boolean cmdBarCustomCommandActivated() { return portal.cmdBarCustomCommandActivated(); } /** * Return the name of a block that the activated command bar is connected to. * * @see ifs.fnd.asp.ASPPortletProvider#commandBarActivated */ protected final String getCmdBarBlockName() { return portal.getCmdBarBlockName(); } /** * Return the id of the activated standard command. * * @see ifs.fnd.asp.ASPPortletProvider#commandBarActivated */ protected final String getCmdBarStandardCommandId() { return portal.getCmdBarStdId(); } /** * Return the id of the activated custom command. * * @see ifs.fnd.asp.ASPPortletProvider#commandBarActivated */ protected final String getCmdBarCustomCommandId() { return portal.getCmdBarCustId(); } //========================================================================== // Directory locations. //========================================================================== /** * Returns location of the script directory. Default /Common/scripts/. */ protected final String getScriptsLocation() { return getASPConfig().getScriptsLocation(false); } /** * Returns location of the images directory. Default /Common/images/. */ protected final String getImagesLocation() { return getASPConfig().getImagesLocation(); } /** * Returns location of the images directory with RTL enabled. Default /Common/images/. */ protected final String getImagesLocationWithRTL() { return getASPConfig().getImagesLocationWithRTL(); } //========================================================================== // Generation of HTML tags. To be called from printContents() and printCustomBody() //========================================================================== /** * Constant for font style definition. * * @see ifs.fnd.asp.ASPPortletProvider#setFontStyle */ protected final static int NONE = 0; /** * Constant for font style definition. * * @see ifs.fnd.asp.ASPPortletProvider#setFontStyle */ protected final static int BOLD = 1; /** * Constant for font style definition. * * @see ifs.fnd.asp.ASPPortletProvider#setFontStyle */ protected final static int ITALIC = 2; /** * *********************************************************************** * Method should be made obsolete in major release * ************************************************************************ * Set the font style according to the input parameter. Allowed values are * one of predefined constants NONE, BOLD or ITALIC. * The setting is canceled by endFont() function. * * @see ifs.fnd.asp.ASPPortletProvider#endFont */ protected final void setFontStyle( int style ) { //out.append("<p style=\"FONT: "); //out.append( style==BOLD ? "BOLD" : (style==ITALIC ? "ITALIC" : "") ); //out.append(" 8pt Verdana; color:black;\">\n"); if(style==BOLD) out.append("<p class=\"portletFontBold\">"); else if(style==ITALIC) out.append("<p class=\"portletFontItalic\">"); } /** * *********************************************************************** * Method should be made obsolete in major release * ************************************************************************ * Cancel font setting defined by setFontStyle() function. * * @see ifs.fnd.asp.ASPPortletProvider#setFontStyle */ protected final void endFont() { out.append("</p>"); } /** * Append a string to the HTML-output without any conversion. */ protected final void appendToHTML( String str ) { out.append(str); } /** * Append strings to the HTML-output without any conversion. */ protected final void appendToHTML( String str1, String str2 ) { out.append(str1,str2); } /** * Append strings to the HTML-output without any conversion. */ protected final void appendToHTML( String str1, String str2, String str3 ) { out.append(str1,str2,str3); } /** * Append strings to the HTML-output without any conversion. */ protected final void appendToHTML( String str1, String str2, String str3, String str4 ) { out.append(str1,str2,str3,str4); } /** * Append strings to the HTML-output without any conversion. */ protected final void appendToHTML( String str1, String str2, String str3, String str4, String str5 ) { out.append(str1,str2,str3,str4,str5); } /** * Append a string after translation to the HTML-output. * Apply predefined styles. */ protected final void printText( String str ) { ASPManager mgr = getASPManager(); out.append("<font class=normalTextValue>"); ///?????????????????????????????? if(Str.isEmpty(str)) out.append("&nbsp;"); else out.append(mgr.HTMLEncode(translate(str),true)); out.append("</font>"); } /** * Append a string after translation to the HTML-output. * Apply predefined bold styles. */ protected final void printBoldText( String str ) { ASPManager mgr = getASPManager(); out.append("<font class=boldTextValue>"); if ( Str.isEmpty(str) ) out.append("&nbsp;"); else out.append(mgr.HTMLEncode(mgr.translateJavaText(str))); out.append("</font>"); } /** * Append a string after translation to the HTML-output. * Apply predefined italic styles. */ protected final void printItalicText( String str ) { ASPManager mgr = getASPManager(); out.append("<font class=italicTextValue>"); if ( Str.isEmpty(str) ) out.append("&nbsp;"); else out.append(mgr.HTMLEncode(mgr.translateJavaText(str))); out.append("</font>"); } /** * Append a string after translation to the HTML-output. * Apply predefined bold and italic styles. */ protected final void printBoldItalicText( String str ) { ASPManager mgr = getASPManager(); out.append("<font class=\"italicTextValue boldTextValue\">"); if ( Str.isEmpty(str) ) out.append("&nbsp;"); else out.append(mgr.HTMLEncode(mgr.translateJavaText(str))); out.append("</font>"); } // Added by Terry 20131105 /** * Append a string after translation to the HTML-output. * Apply predefined hilite styles. */ protected final void printHiliteText( String str ) { ASPManager mgr = getASPManager(); out.append("<font class=hiliteTextValue>"); if ( Str.isEmpty(str) ) out.append("&nbsp;"); else out.append(mgr.HTMLEncode(mgr.translateJavaText(str))); out.append("</font>"); } // Added end /** * Append amount of spaces ('&nbsp;' sequences) to the HTML-output. */ protected final void printSpaces( int spaces ) { for( int i=0; i<spaces; i++) out.append("&nbsp;"); } /** * Append a &lt;br&gt; to the HTML-output. */ protected final void printNewLine() { out.append("<br>\n"); } /** * Append a named input tag of type 'text' to the HTML-output. Apply predefined styles. */ protected final void printField( String name, String value ) { printField(name, value, 0, 0, null ); } /** * Append a named input tag of type 'text' to the HTML-output. Apply predefined styles. */ protected final void printField( String name, String value, int size ) { printField(name, value, size, 0, null ); } /** * Append a named input tag of type 'text' to the HTML-output. Apply predefined styles. */ protected final void printField( String name, String value, int size, int maxlength ) { printField(name, value, size, maxlength, null ); } /** * Append a named input tag to the HTML-output. Apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID. * Will be called in onChange event handler. */ protected final void printField( String name, String value, int size, String func ) { printField(name, value, size, 0, func ); } /** * Append a named input tag of type 'text' to the HTML-output. Apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID. * Will be called in onChange event handler. */ protected final void printField( String name, String value, int size, int maxlength, String func ) { ASPManager mgr = getASPManager(); out.append("<input class='editableTextField' type=text"); out.append(" name=",addProviderPrefix(),name); out.append(" value=\"",mgr.HTMLEncode(value),"\""); if(size>0) { out.append(" size=\""); out.appendInt(mgr.isExplorer() ? size : (int)Math.round(size*.6)); out.append("\""); } if(maxlength>0) { out.append(" maxlength=\""); out.appendInt(maxlength); out.append("\""); } boolean isDateTime=false; try { if (isASPField(name)) isDateTime = (getASPField(name).isTime()||getASPField(name).isDateTime()); } catch(Exception e){ isDateTime=false; } if (isDateTime) { String mask = getASPField(name).getMask(); String block_name = getASPField(name).getBlock().getName(); String id = getId(); String field = "_"+id+"_"+name; out.append(" onChange=\"javascript:setFormReference('"+id+"');"); if(!Str.isEmpty(func)) { out.append("formatDate_("+field+",'"+mask+"','"+block_name+"')"); out.append(";",func,"(this,'",getId(),"')\""); } else out.append("formatDate_("+field+",'"+mask+"','"+block_name+"')\""); out.append(">"); printCalender(name); printDateTimeMask(name); } else if(!Str.isEmpty(func)) { out.append(" onChange=\"javascript:",func,"(this,'",getId(),"')\""); out.append(">"); } else out.append(">"); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> */ protected final void printLOV( String field, String url ) { printLOV(field,url,null,true,null,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * multichoice - a flag for enable/disable multi-choice option of the LOV; default 'false'<br> */ // Added by Terry 20140828 // Add Multichoice parameter protected final void printLOV( String field, String url, boolean multichoice ) { printLOV(field,url,null,true,null,null,null,0,0,multichoice); } // Added end /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> */ protected final void printLOV( String field, String url, String title ) { printLOV(field,url,title,true,null,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> */ protected final void printLOV( String field, String url, String title, String where_stmt ) { printLOV(field,url,title,true,where_stmt,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> */ protected final void printLOV( String field, String url, String title, int width, int height ) { printLOV(field,url,title,true,null,null,null,width,height,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> */ protected final void printLOV( String field, String url, String title, String where_stmt, int width, int height ) { printLOV(field,url,title,true,where_stmt,null,null,width,height,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> * autosearch - a flag that tells the Web Kit to run or not query automatically; default 'true'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * order_by - a SQL ORDER BY clause that will be added to the query; default null<br> * group_by - a SQL GROUP BY clause that will be added to the query; default null<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> */ protected final void printLOV( String field, String url, String title, boolean autosearch, String where_stmt, String order_by, String group_by, int width, int height ) { printLOV(field,url,title,autosearch,where_stmt,order_by,group_by,width,height,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * url - location of the LOV-page; required<br> * title - the title of the LOV-window; default 'List of values'<br> * autosearch - a flag that tells the Web Kit to run or not query automatically; default 'true'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * order_by - a SQL ORDER BY clause that will be added to the query; default null<br> * group_by - a SQL GROUP BY clause that will be added to the query; default null<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> * multichoice - a flag for enable/disable multi-choice option of the LOV; default 'false'<br> */ protected final void printLOV( String field, String url, String title, boolean autosearch, String where_stmt, String order_by, String group_by, int width, int height, boolean multichoice ) { //JavaScript function that will be called: // function lovPortal(id,fld,url,title,auto,where,orderby,groupby,width,height) ASPConfig cfg = getASPConfig(); if(width==0) width = cfg.getLOVWindowWidth(); if(height==0) height = cfg.getLOVWindowHeight(); String id = getId(); String app_path = cfg.getApplicationPath(); if (!url.startsWith(app_path)) url = app_path +"/" +url; //out.append("<X","javascript:setFormReference('"+id+"');",cfg.getLOVTag1Iid(false)); String quote = "\""; //out.append("<X",cfg.getLOVTag1Iid(false)); out.append("<X> <a href=",quote,"javascript:setFormReference('"+id+"');"); out.append("lovPortal('",id,"','",field,"','"); out.append(url,"','",translate(Str.isEmpty(title)?"FNDPRVLOVTITLE: List of values":title),"','",autosearch?"":"N"); out.append("','",multichoice?"true":""); out.append("','", Str.isEmpty(where_stmt) ?"":where_stmt); out.append("','", Str.isEmpty(order_by) ?"":order_by); out.append("','", Str.isEmpty(group_by) ?"":group_by, "',"); out.appendInt(width); out.append(","); out.appendInt(height); out.append(")"); out.append(cfg.getLOVTag2(false),">"); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view ) { printDynamicLOV(field,view,null,true,null,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * multichoice - a flag for enable/disable multi-choice option of the LOV; default 'false'<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ // Added by Terry 20140828 // Add Multichoice parameter protected final void printDynamicLOV( String field, String view, boolean multichoice ) { printDynamicLOV(field,view,null,true,null,null,null,0,0,multichoice); } // Added end /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * title - the title of the LOV-window; default 'List of values'<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view, String title ) { printDynamicLOV(field,view,title,true,null,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * title - the title of the LOV-window; default 'List of values'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view, String title, String where_stmt ) { printDynamicLOV(field,view,title,true,where_stmt,null,null,0,0,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * title - the title of the LOV-window; default 'List of values'<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view, String title, int width, int height ) { printDynamicLOV(field,view,title,true,null,null,null,width,height,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * title - the title of the LOV-window; default 'List of values'<br> * autosearch - a flag that tells the Web Kit to run or not query automatically; default 'true'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * order_by - a SQL ORDER BY clause that will be added to the query; default null<br> * group_by - a SQL GROUP BY clause that will be added to the query; default null<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view, String title, boolean autosearch, String where_stmt, String order_by, String group_by, int width, int height ) { printDynamicLOV(field,view,title,autosearch,where_stmt,order_by,group_by,width,height,false); } /** * Append an image-tag representing a LOV-icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> * view - the name of the database view; required<br> * title - the title of the LOV-window; default 'List of values'<br> * autosearch - a flag that tells the Web Kit to run or not query automatically; default 'true'<br> * where_stmt - a SQL WHERE condition that will be added to the query; default null<br> * order_by - a SQL ORDER BY clause that will be added to the query; default null<br> * group_by - a SQL GROUP BY clause that will be added to the query; default null<br> * width - the width of the LOV window; default specified in ASPConfig.ifm<br> * height - the height of the LOV window; default specified in ASPConfig.ifm<br> * multichoice - a flag for enable/disable multi-choice option of the LOV; default 'false'<br> * * @see ifs.fnd.asp.ASPPortletProvider#printLOV */ protected final void printDynamicLOV( String field, String view, String title, boolean autosearch, String where_stmt, String order_by, String group_by, int width, int height, boolean multichoice ) { String url = getASPConfig().getDynamicLOVURL(false); printLOV(field, url + (url.indexOf("?")>0 ? "&" : "?") + "__DYNAMIC_LOV_VIEW=" + view, title, autosearch,where_stmt,order_by,group_by,width,height,multichoice); } /** * Append an image-tag representing a calender icon to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> */ protected final void printCalender(String field) { ASPManager mgr = getASPManager(); ASPConfig cfg = getASPConfig(); if (!(mgr.isExplorer() || mgr.isMozilla())) return; String _mask = getASPField(field).getMask(); String _label = getASPField(field).getJSLabel(); _mask = mgr.replace(_mask,"'","\\\'"); int type_id = getASPField(field).getTypeId(); boolean time = (type_id == DataFormatter.DATETIME || type_id == DataFormatter.TIME); String id = getId(); //out.append("<X",cfg.getCalendarTag1()); out.append("<X> <a href=\"javascript:setFormReference('"+id+"');","showCalendar('"); out.append("_",id,"_",field); out.append(cfg.getCalendarTag2()); out.append("''"); out.append(",'",_mask,"',"); out.appendInt(-1); out.append(",'",_label,"'"); out.append(",'",time+"","'"); out.append(cfg.getCalendarTag4()); out.append(cfg.getCalendarTag3(),">"); } /** * Append a string representing the mask of a date field to the HTML-output. * Input parameters:<br> * field - name of the HTML-field, created by calling one of printField() methods; required<br> */ protected final void printDateTimeMask(String field) { ASPManager mgr = getASPManager(); ASPConfig cfg = getASPConfig(); String translated_mask = getASPField(field).getMask(); String[] maskarr = cfg.getTranslatedDateTimeMask(); if(maskarr!=null) { char[] tempChars = translated_mask.toCharArray(); StringBuffer tempStr = new StringBuffer(); for (int i=0;i<tempChars.length;i++) { switch (tempChars[i]) { case 'G': tempStr.append(maskarr[ASPConfigFile.ERA]); break; case 'y': tempStr.append(maskarr[ASPConfigFile.YEAR]); break; case 'M': tempStr.append(maskarr[ASPConfigFile.MONTH_IN_YEAR]); break; case 'd': tempStr.append(maskarr[ASPConfigFile.DAY_IN_MONTH]); break; case 'h': tempStr.append(maskarr[ASPConfigFile.HOUR_IN_AMPM_112]); break; case 'H': tempStr.append(maskarr[ASPConfigFile.HOUR_IN_DAY_023]); break; case 'm': tempStr.append(maskarr[ASPConfigFile.MINUTE_IN_HOUR]); break; case 's': tempStr.append(maskarr[ASPConfigFile.SECOND_IN_MINUTE]); break; case 'S': tempStr.append(maskarr[ASPConfigFile.MILLISECOND]); break; case 'E': tempStr.append(maskarr[ASPConfigFile.DAY_IN_WEEK]); break; case 'D': tempStr.append(maskarr[ASPConfigFile.DAY_IN_YEAR]); break; case 'F': tempStr.append(maskarr[ASPConfigFile.DAY_OF_WEEK_IN_MONTH]); break; case 'w': tempStr.append(maskarr[ASPConfigFile.WEEK_IN_YEAR]); break; case 'W': tempStr.append(maskarr[ASPConfigFile.WEEK_IN_MONTH]); break; case 'a': tempStr.append(maskarr[ASPConfigFile.AMPM_MARKER]); break; case 'k': tempStr.append(maskarr[ASPConfigFile.HOUR_IN_DAY_124]); break; case 'K': tempStr.append(maskarr[ASPConfigFile.HOUR_IN_AMPM_011]); break; case 'z': tempStr.append(maskarr[ASPConfigFile.TIME_ZONE]); break; default:tempStr.append(tempChars[i]); break; } } translated_mask = tempStr.toString(); } out.append("<font class=normalTextValue>"); out.append("&nbsp;("); out.append(translated_mask,")"); out.append("</font>"); } /** * Append a named hidden input tag to the HTML-output. */ protected final void printHiddenField( String name, String value ) { out.append("<input type=hidden name=",addProviderPrefix(),name); out.append(" value=\"",getASPManager().HTMLEncode(value),"\">"); } /** * Append a named textarea to the HTML-output. Apply predefined styles. */ protected final void printTextArea( String name, String value, int rows, int cols ) { printTextArea( name, value, rows, cols, null ); } /** * Append a named textarea to the HTML-output. Apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. */ protected final void printTextArea( String name, String value, int rows, int cols, String func ) { ASPManager mgr = getASPManager(); out.append("<textarea class='editableTextArea'"); out.append(" name=",addProviderPrefix(),name); out.append(" rows="); out.appendInt(rows); out.append(" cols="); out.appendInt(mgr.isExplorer() ? cols : (int)Math.round(cols*.6)); if(!Str.isEmpty(func)) { String id = getId(); out.append(" onChange=\"javascript:setFormReference('",id,"');"); out.append(func,"(this,'",id,"')\""); } out.append(">",mgr.HTMLEncode(value),"</textarea>"); } /** * Append a named check box input tag to the HTML-output and apply predefined styles. * Default value of this check box is set to 'TRUE'. */ protected final void printCheckBox( String name, boolean checked ) { printCheckBox( name, "TRUE", checked, null ); } /** * Append a named check box input tag to the HTML-output and apply predefined styles. * Default value of this check box is set to 'TRUE'. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. */ protected final void printCheckBox( String name, boolean checked, String func ) { printCheckBox( name, "TRUE", checked, func ); } /** * Append a named check box input tag to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. */ protected final void printCheckBox( String name, String value, boolean checked, String func ) { out.append("<input class='checkbox' type=checkbox"); out.append(" name=",addProviderPrefix(),name); out.append(" value=\"" + value + "\""); if(checked) out.append(" CHECKED"); if(!Str.isEmpty(func)) { String id = getId(); out.append(" onClick=\"javascript:setFormReference('",id,"');"); out.append(func,"(this,'",id,"')\""); } out.append(">"); } /** * Append a named radio button input tag to the HTML-output and apply predefined styles. * The specified label will be translated. */ protected final void printRadioButton( String name, String value, String label, boolean checked ) { printRadioButton( name, value, label, checked, null ); } /** * Append a named radio button input tag to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. The specified label will be translated. */ protected final void printRadioButton( String name, String value, String label, boolean checked, String func ) { out.append("<input class=radioButton type=radio"); out.append(" name=",addProviderPrefix(),name); out.append(" value=\"" + value + "\""); if(checked) out.append(" CHECKED"); if(!Str.isEmpty(func)) { String id = getId(); out.append(" onClick=\"javascript:setFormReference('",id,"');"); out.append(func,"(this,'",id,"')\""); } out.append("><font class=normalTextValue>",translate(label),"</font>"); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags with an empty tag at the beginning. * The data to option-tags is taken from the aspbuf-parameter. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox */ protected final void printSelectBox( String name, ASPBuffer aspbuf ) { printSelectBox( name, aspbuf, null, null, false, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags with an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox */ protected final void printSelectBox( String name, ASPBuffer aspbuf, String key ) { printSelectBox( name, aspbuf, key, null, false, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags with an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox */ protected final void printSelectBox( String name, ASPBuffer aspbuf, String key, String func ) { printSelectBox( name, aspbuf, key, func, false, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags with an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox */ protected final void printSelectBox( String name, ASPBuffer aspbuf, String key, String func, int size ) { printSelectBox( name, aspbuf, key, func, false, size ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags without an empty tag at the beginning. * The data to option-tags is taken from the aspbuf-parameter. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox */ protected final void printMandatorySelectBox( String name, ASPBuffer aspbuf ) { printSelectBox( name, aspbuf, null, null, true, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags without an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox */ protected final void printMandatorySelectBox( String name, ASPBuffer aspbuf, String key ) { printSelectBox( name, aspbuf, key, null, true, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags without an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox */ protected final void printMandatorySelectBox( String name, ASPBuffer aspbuf, String key, String func ) { printSelectBox( name, aspbuf, key, func, true, 1 ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags without an empty tag at the beginning * and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox */ protected final void printMandatorySelectBox( String name, ASPBuffer aspbuf, String key, String func, int size ) { printSelectBox( name, aspbuf, key, func, true, size ); } /** * Append a named select-tag to the HTML-output and apply predefined styles. * Generate html &lt;option&gt; tags with an empty tag at the beginning if * the mandatory-flag is true and select a value thet corresponds to the key-parameter. * The data to option-tags is taken from the aspbuf-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox */ private void printSelectBox( String name, ASPBuffer aspbuf, String key, String func, boolean mandatory, int size ) { out.append("<select class='selectbox' size="); out.appendInt(size); out.append(" name=",addProviderPrefix(),name); if(!Str.isEmpty(func)) { String id = getId(); out.append(" onChange=\"javascript:setFormReference('",id,"');"); out.append(func,"(this,'",id,"')\""); } out.append(">"); if(mandatory) out.append( getASPHTMLFormatter().populateMandatoryListBox(aspbuf, key) ); else out.append( getASPHTMLFormatter().populateListBox(aspbuf, key) ); out.append("</select>"); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * with an empty tag at the beginning. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printIIDSelectBox( ASPField fld ) throws FndException { printIIDSelectBox( fld, null, null, false ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * with an empty tag at the beginning and select a value that corresponds to the key-parameter. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printIIDSelectBox( ASPField fld, String key ) throws FndException { printIIDSelectBox( fld, key, null, false ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * with an empty tag at the beginning and select a value that corresponds to the key-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printIIDSelectBox( ASPField fld, String key, String func ) throws FndException { printIIDSelectBox( fld, key, func, false ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * without an empty tag at the beginning. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printMandatoryIIDSelectBox( ASPField fld ) throws FndException { printIIDSelectBox( fld, null, null, true ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * without an empty tag at the beginning and select a value that corresponds to the key-parameter. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printMandatoryIIDSelectBox( ASPField fld, String key ) throws FndException { printIIDSelectBox( fld, key, null, true ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * without an empty tag at the beginning and select a value that corresponds to the key-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ protected final void printMandatoryIIDSelectBox( ASPField fld, String key, String func ) throws FndException { printIIDSelectBox( fld, key, func, true ); } /** * Append a select-tag to the HTML-output, populated with IID-values corresponded * to a given field and apply predefined styles. Generate HTML &lt;option&gt; tags * with an empty tag at the beginning if the mandatory-flag is true and select a value * thet corresponds to the key-parameter. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onChange event handler. * The ASP field must be defined as a select box and be enumerated by IID. * * @see ifs.fnd.asp.ASPHTMLFormatter#populateListBox * @see ifs.fnd.asp.ASPHTMLFormatter#populateMandatoryListBox * @see ifs.fnd.asp.ASPField#getClientValues * @see ifs.fnd.asp.ASPField#setSelectBox */ private void printIIDSelectBox( ASPField fld, String key, String func, boolean mandatory ) throws FndException { if(!fld.isSelectBox()) throw new FndException("FNDPRVNSELBOX: The field &1 is not defined as Select Box.", fld.getName()); printSelectBox( fld.getName(), fld.getClientValues(), key, func, mandatory, 1 ); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * Any text, send in the value-parameter, will be translated. * If the href represents a relative reference the application root will be added. */ protected final void printAbsoluteLink( String value, String href ) { printLink( value, href, true, false, false, false, null, true, null, null ); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * Any text, send in the value-parameter, will be translated. */ protected final void printLink( String value, String href ) { printLink( value, href, false, false, false ); } /** * Append a secure link to the HTML-output and apply predefined styles. * Any text, send in the value-parameter, will be translated. link will be * inactivate according to the security rights for for the given security * object list. * @param value value to be display * @param href hyperlink * @param security_objects comma seperated security objects */ protected final void printLink( String value, String href, String security_objects ) { //printLink( value, href, false, false, false ); printLink( value, href, false, false, false, false, null, isObjectAccessible(security_objects), null, null); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * @param imgpath image uri * @param href hyperlink uri */ protected final void printImageLink( String imgpath, String href ) { printLink( imgpath, href, true, false, false ); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * @param imgpath image uri * @param href hyperlink uri * @param name name of the image * @param title title/alt tag */ protected final void printImageLink( String imgpath, String href, String name, String title ) { printLink( imgpath, href, false, true, false, false, null, true , name, title); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * The alternative image specification can be send in hovimgpath-parameter * to attain the hover effect. */ protected final void printHoverImageLink( String imgpath, String hovimgpath, String href ) { printLink( imgpath, href, false, true, false, false, hovimgpath, true, null, null ); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * Any text, send in the value-parameter, will be translated. * Specified JavaScript function takes two parameters: object reference and portlet ID. */ protected final void printScriptLink( String value, String func ) { printLink( value, func, false, true, false ); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * Any text, send in the value-parameter, will be translated. * Specified JavaScript function takes two parameters: object reference and portlet ID. * link will be inactivate according to the security rights for the given security * object list. * @param value value to be display * @param func javascript function * @param security_objects comma seperated security objects */ protected final void printScriptLink( String value, String func, String security_objects ) { printLink( value, func, false, false, true, false, null, isObjectAccessible(security_objects), null, null); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). * Any text, send in the value-parameter, will be translated. */ protected final void printSubmitLink( String value ) { printLink( value, null, false, true, true ); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). * Any text, send in the value-parameter, will be translated. * Specified JavaScript function takes two parameters: object reference and portlet ID. */ protected final void printSubmitLink( String value, String func ) { printLink( value, func, false, true, true ); } /** * Append a secure link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). * Any text, send in the value-parameter, will be translated. * Specified JavaScript function takes two parameters: object reference and portlet ID. * Link will be dissable/enable according to the access rights for the given list of security objects. * @param value value to be display * @param func javascript function to be called * @param security_objects comma seperated security objects */ protected final void printSubmitLink( String value, String func, String security_objects ) { printLink( value, func, false, false, true, true, null, isObjectAccessible(security_objects), null, null); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID. * @param imgpath image uri * @param func javascript funstion */ protected final void printScriptImageLink( String imgpath, String func ) { printLink( imgpath, func, true, true, false ); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID. * @param imgpath image uri * @param func javascript funstion * @param name name of the image * @param title title/alt tag */ protected final void printScriptImageLink( String imgpath, String func, String name, String title ) { printLink( imgpath, func, false, true, true, false, null, true , name, title); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * The alternative image specification can be send in hovimgpath-parameter * to attain the hover effect. * Specified JavaScript function takes two parameters: object reference and portlet ID. */ protected final void printScriptHoverImageLink( String imgpath, String hovimgpath, String func ) { printLink( imgpath, func, false, true, true, false, hovimgpath, true , null, null); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). */ protected final void printSubmitImageLink( String imgpath ) { printLink( imgpath, null, true, true, true ); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). * Specified JavaScript function takes two parameters: object reference and portlet ID. */ protected final void printSubmitImageLink( String imgpath, String func ) { printLink( imgpath, func, true, true, true ); } /** * Append an image link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet). * The alternative image specification can be send in hovimgpath-parameter * to attain the hover effect. * Specified JavaScript function takes two parameters: object reference and portlet ID. */ protected final void printSubmitHoverImageLink( String imgpath, String hovimgpath, String func ) { printLink( imgpath, func, false, true, true, true, hovimgpath, true , null, null); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet) if the submit-flag is true. * The value can be any text, which will be translated, or, if the image-parameter * is true, an image specification. * Run a JavaScript function given in the link-parameter rather then an URL * if the script-parameter is true. * Specified JavaScript function takes two parameters: object reference and portlet ID. */ private void printLink( String value, String link, boolean image, boolean script, boolean submit ) { printLink( value, link, false, image, script, submit, null, true , null, null); } /** * Append a link (an A-tag) to the HTML-output and apply predefined styles. * The link will submit the request (current portlet) if the submit-flag is true. * The value can be any text, which will be translated, or, if the image-parameter * is true, an image specification. Then the alternative image specification can be * send in hovimgpath-parameter to attain the hover effect. * Run a JavaScript function given in the link-parameter rather then an URL * if the script-parameter is true. * Try to add absolute reference if abshref is true. * Specified JavaScript function takes two parameters: object reference and portlet ID. * Note: if the value contains '&&' only the text within them will be hyperlinked. * eg: for value "only &&this&& word is hyperlinked" only the word 'this' will be hyperlinked. */ private void printLink( String value, String link, boolean abshref, boolean image, boolean script, boolean submit, String hovimgpath, boolean has_access, String image_name, String image_title) { String text1=""; String text2=""; value = translate(value); String id = getId(); ASPManager mgr = getASPManager(); //link = !Str.isEmpty(link)? mgr.decodedURLWithCSV(link): link; if( mgr.isStdPortlet() && !Str.isEmpty(link) && link.indexOf("javascript:")>=0 && link.indexOf("setFormReference")<0 ) { if(DEBUG) debug("ASPPortletProvider.printLink(): adding call to setFormReference() for JSR168 portlet."); link = Str.replace(link, "javascript:", "javascript:setFormReference('"+id+"');"); } if(value.indexOf("&&")!=-1) { if(value.indexOf("&&")==value.lastIndexOf("&&")) { text1 = value.substring(0,value.indexOf("&&")); value = value.substring(value.indexOf("&&")+2,value.length()); } else { text1 = value.substring(0,value.indexOf("&&")); text2 = value.substring(value.lastIndexOf("&&")+2,value.length()); value = value.substring(value.indexOf("&&")+2,value.lastIndexOf("&&")); } } out.append("<font class=normalTextValue>",getASPManager().HTMLEncode(text1,true),"</font>"); if (has_access) { out.append("<a class=hyperLink href=\""); if(script) { out.append("javascript:setFormReference('",id,"');"); if(!Str.isEmpty(link)) { String suf = link.endsWith(")")?"":("(this,'"+id+"')"); out.append(link,suf); } if( submit && !Str.isEmpty(link) ) out.append(";"); if(submit) out.append("submitPortlet('",id,"')"); } else { //if (mgr.isStdPortlet() && (link.indexOf("javascript:") == -1)) abshref = true; if (mgr.isStdPortlet() && (link.indexOf(":") == -1)) abshref = true; //javascript:, mailto: http:, ftp:, https: etc if( abshref && link.indexOf("://")<0 && !link.startsWith("/") ) out.append(getApplicationPath(),"/"); out.append( link ); } out.append("\""); if( image && !Str.isEmpty(hovimgpath) ) { linkseq++; out.append(" onmouseover=\"javascript:setFormReference('",id,"');f.",addProviderPrefix(),"IMG"); out.appendInt(linkseq); out.append(".src='",hovimgpath,"'\""); out.append(" onmouseout=\"javascript:setFormReference('",id,"');f.",addProviderPrefix(),"IMG"); out.appendInt(linkseq); out.append(".src='",value,"'\""); } out.append(">"); } else out.append("<font class=dissabledLinkValue>"); if(image) { out.append("<img"); if( !Str.isEmpty(hovimgpath) ) { out.append(" name=\"",addProviderPrefix(),"IMG"); out.appendInt(linkseq); out.append("\""); } else if (!Str.isEmpty(image_name)) out.append(" name=\"",image_name,"\""); if( value.indexOf("://")<0 && !value.startsWith("/") && mgr.isStdPortlet()) value = getApplicationPath()+"/"+value; if (!Str.isEmpty(image_title)) out.append(" title=\"",translate(image_title),"\""); out.append(" src=\"",value,"\" border=0>"); } else out.append( getASPManager().HTMLEncode(translate(value),true) ); if (has_access) out.append("</a>"); else out.append("</font>"); out.append("<font class=normalTextValue>",getASPManager().HTMLEncode(text2,true),"</font>"); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. * @param value value to be display * @param tag addtional html tags to apply to this button */ protected final void printButton( String name, String value, String func ) { printButton( name, value, func, false, true ); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. Button will be enable according to the * security rights for the given list of security objects. * @param value value to be display * @param tag addtional html tags to apply to this button * @param sec_objects comma seperated list of security objects */ protected final void printButton( String name, String value, String func, String security_objects ) { printButton( name, value, func, false, isObjectAccessible(security_objects)); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * The button will submit the request (current portlet). */ protected final void printSubmitButton( String name, String value ) { printButton( name, value, null, true, true ); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * The button will submit the request (current portlet). * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. */ protected final void printSubmitButton( String name, String value, String func ) { printButton( name, value, func, true, true ); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * The button will submit the request (current portlet). * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler.Button will be enable according to the * security rights for the given list of security objects. * @param value value to be display * @param tag addtional html tags to apply to this button * @param sec_objects comma seperated list of security objects */ protected final void printSubmitButton( String name, String value, String func, String security_objects ) { printButton( name, value, func, true, isObjectAccessible(security_objects)); } /** * Append a named button input tag to the HTML-output and apply predefined styles. * The button will submit the request (current portlet) if the submit-flag is true. * Specified JavaScript function takes two parameters: object reference and portlet ID * and will be called in onClick event handler. */ private void printButton( String name, String value, String func, boolean submit, boolean has_security ) { out.append("<input class='button' type=button"); out.append(" name=",addProviderPrefix(),name); out.append(" value=\"", getASPManager().HTMLEncode(translate(value),true), "\""); if( submit || !Str.isEmpty(func) ) { String id = getId(); out.append(" onClick=\"javascript:setFormReference('",id,"');"); if(!Str.isEmpty(func)) out.append(func,"(this,'",id,"')"); if( submit && !Str.isEmpty(func) ) out.append(";"); if(submit) out.append("submitPortlet('",id,"')"); out.append("\""); } //out.append(">"); out.append(!has_security?" disabled":"", ">"); } /** * Populate an ASP table. * @param tbl ASPTable object to be printed */ protected final void printTable( ASPTable tbl ) { //tbl.setWrap(); //tbl.disableNoWrap(); - immutable attribute tbl.disableOutputChannels(); tbl.disableEditProperties(); tbl.unsetSortable(); tbl.disableQuickEdit(); //tbl.getBlock().getASPCommandBar().disableCommand(ASPCommandBar.VIEWDETAILS); ASPBlock blk = tbl.getBlock(); if(blk!=null) { ASPCommandBar bar = blk.getASPCommandBar(); if(bar!=null) { bar.disableCommand(ASPCommandBar.VIEWDETAILS); //disable any custom commands which do not have secuirty Vector cust_cmds = bar.getCustomCommands(); String cmd_id; String plsql_method; ASPCommandBarItem cmd; for (int i=0; i<cust_cmds.size(); i++) { cmd = (ASPCommandBarItem) cust_cmds.elementAt(i); cmd_id = cmd.getCommandId(); plsql_method = bar.getSecurePlSqlMethod(cmd_id); if (!Str.isEmpty(plsql_method) && !isObjectAccessible(plsql_method)) bar.disableCustomCommand(cmd_id); } //disable standard commands if any Buffer commands = blk.getDefinedCommands(); String method_name=""; for(int j=0;j<commands.countItems();j++) { //get fully qualfied PL/SQL method name from commands buffer method_name = commands.findItem(commands.getItem(j).getName()+"/METHOD").getString(); if ( "New__".equals(commands.getItem(j).getName()) && !Str.isEmpty(method_name) ) { if (!isObjectAccessible(method_name)) { bar.disableCommand(ASPCommandBar.NEWROW); bar.disableCommand(ASPCommandBar.DUPLICATEROW); } } else if ( "Modify__".equals(commands.getItem(j).getName()) && !Str.isEmpty(method_name) ) { if (!isObjectAccessible(method_name)) bar.disableCommand(ASPCommandBar.EDITROW); } else if ( "Remove__".equals(commands.getItem(j).getName()) && !Str.isEmpty(method_name) ) { if (!isObjectAccessible(method_name)) bar.disableCommand(ASPCommandBar.DELETE); } } } } out.append( tbl.populate() ); } /** * Append an image-tag to the HTML-output. * @param src image source */ protected final void printImage( String src ) { printImage(src,0,0,0,null ); } /** * Append an image-tag to the HTML-output. * @param src image source * @param width image width * @param height image height * * */ protected final void printImage( String src, int width, int height ) { printImage(src,width,height,0,null ); } /** * Append an image-tag to the HTML-output. * @param src image source * @param width image width * @param height image height * @param border border size */ protected final void printImage( String src, int width, int height, int border ) { printImage(src,width,height,border,null ); } /** * Append an image-tag to the HTML-output. * @param src image source * @param width image width * @param height image height * @param border border size * @param usemap map URI */ protected final void printImage( String src, int width, int height, int border, String usemap ) { printImage( src, width, height, border, usemap, null, null); } /** * Append an image-tag to the HTML-output. * @param src image source * @param width image width * @param height image height * @param border border size * @param usemap map URI * @param name image name * @param title the titile/alt tag */ protected final void printImage( String src, int width, int height, int border, String usemap, String name, String title) { ASPManager mgr = getASPManager(); if( src.indexOf("://")<0 && !src.startsWith("/") && mgr.isStdPortlet()) src = getApplicationPath()+"/"+src; out.append("<img src=\"",src,"\""); if (!Str.isEmpty(name)) out.append(" name=\"",name,"\""); if(width>0) { out.append(" width="); out.appendInt(width); } if(height>0) { out.append(" height="); out.appendInt(height); } out.append(" border="); out.appendInt(border); if( !Str.isEmpty(usemap) ) out.append(" usemap=\"",usemap,"\""); if (!Str.isEmpty(title)) out.append(" title=\"",translate(title),"\""); out.append(">"); } private boolean inmap; /** * Append a map-tag to the HTML-output. Can be used in conjunction to an image-tag. * Should be closed by calling endDefineImageMap(). * * @see ifs.fnd.asp.ASPPortletProvider#endDefineImageMap */ protected final void defineImageMap( String name ) { out.append("<map name=\"",name,"\">\n"); inmap = true; } /** * Close the previously opened by defineImageMap() function map-tag. * * @see ifs.fnd.asp.ASPPortletProvider#defineImageMap */ protected final void endDefineImageMap() { inmap = false; out.append("</map>\n"); } /** * Append an area-tag to the HTML-output. Can be used in conjunction to a map-tag. */ protected final void printImageArea( String shape, String coords, String href, String func, String param ) { out.append("<area shape=",shape," coords=",coords); out.append(" href=\"",href,"\" "); if(!Str.isEmpty(func)) { String id = getId(); out.append(" onClick=\"javascript:setFormReference('",id,"');return ",func); } out.append(">\n"); } //------------------------------------------------------------------------- // HTML Table //-------------------------------------------------------------------------- // private int tablelevel = 0; private boolean transparent = false; /** * Begin a HTML table (a table-tag). * * @see ifs.fnd.asp.ASPPortletProvider#endTable */ protected final void beginTable() { beginTable(null,false,true); } /** * Begin a HTML table (a table-tag) with a given id. * * @see ifs.fnd.asp.ASPPortletProvider#endTable */ protected final void beginTable( String id ) { beginTable(id,false,true); } /** * Begin a HTML table (a table-tag) with transparent background. * * @see ifs.fnd.asp.ASPPortletProvider#endTable */ protected final void beginTransparentTable() { beginTable(null,true,true); } /** * Begin a HTML table (a table-tag) with transparent background and a given id. * * @see ifs.fnd.asp.ASPPortletProvider#endTable */ protected final void beginTransparentTable( String id ) { beginTable(id,true,true); } /** * Begin a HTML table (a table-tag). If transparent-flag is true, the table background * will be transparent. Value true of the fullwidth-parameter will * generate the table width of 100%. * * @see ifs.fnd.asp.ASPPortletProvider#endTable */ protected final void beginTable( String id, boolean transparent, boolean fullwidth ) { // this.tablelevel++; this.transparent = transparent; out.append("<table"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); out.append(" border=0 cellpadding=2 cellspacing=0",fullwidth?" width=100%":"",">\n"); colcnt = 0; } /** * Begin a HTML table (a table-tag) if the tranparent flag is true the table background * will be transparent. the attrlist should provide the necessary attributes for the table-tag * * @see ifs.fnd.asp.ASPPortletProvider#endTable * @see ifs.fnd.asp.ASPPortletProvider#beginTransparentTable * @see ifs.fnd.asp.ASPPortletProvider#beginTable */ protected final void beginCustomTable(String id, boolean transparent,String attrlist) { this.transparent = transparent; out.append("<table"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); if( !Str.isEmpty(attrlist) ) out.append(" "+attrlist); out.append(">\n"); colcnt = 0; } /** * End a HTML table opened with beginTable() function. * * @see ifs.fnd.asp.ASPPortletProvider#beginTable */ protected final void endTable() throws FndException { out.append("</table>\n"); // tablelevel--; // if(tablelevel<0) // throw new FndException("FNDPRVENDTAB: No open tables exist!"); } private boolean intitlerow = false; /** * Begin a table title row (a tr-tag). Should be closed by calling endTableTitleRow(). * * @see ifs.fnd.asp.ASPPortletProvider#endTableTitleRow */ protected final void beginTableTitleRow() throws FndException { beginTableTitleRow(null); } /** * Begin a table title row (a tr-tag) with a specified id. * Should be closed by calling endTableTitleRow(). * * @see ifs.fnd.asp.ASPPortletProvider#endTableTitleRow */ protected final void beginTableTitleRow( String id ) throws FndException { // if(intitlerow) // throw new FndException("FNDPRVINTITL: Already in title row!"); intitlerow = true; out.append("<tr"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); out.append(">\n"); colcnt = 0; } /** * Close a table title row that was opened by beginTableTitleRow() function. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableTitleRow */ protected final void endTableTitleRow() throws FndException { // if(!intitlerow) // throw new FndException("FNDPRVNINTITL: Not in title row!"); intitlerow = false; out.append("</tr>\n"); } // private int tabbodylevel = 0; /** * Begin a body of a HTML table (a tbody-tag). Should be closed by endTableBody(). * Also begin the first row in the table (a tr-tag). * * @see ifs.fnd.asp.ASPPortletProvider#endTableBody * @see ifs.fnd.asp.ASPPortletProvider#nextTableRow */ protected final void beginTableBody() throws FndException { beginTableBody(null); } /** * Begin a HTML table body (a tbody-tag) with a specified id. * Should be closed by endTableBody(). * Also begin the first row in the table (a tr-tag). * * @see ifs.fnd.asp.ASPPortletProvider#endTableBody * @see ifs.fnd.asp.ASPPortletProvider#nextTableRow */ protected final void beginTableBody( String id ) throws FndException { ASPConfig cfg = getASPConfig(); //String bgcolor = cfg.getParameter("SCHEME/FORM/ALT_BGCOLOR", "#E1E2E8"); // if(tabbodylevel>=tablelevel) // throw new FndException("FNDPRVINBODY: Already in table body!"); // this.tabbodylevel++; this.evenrow = false; out.append("<tbody>\n<tr"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); if(!transparent) out.append(" class=tableRowColor1"); out.append(">\n"); colcnt = 0; } /** * Close the last table row and close table body opened by beginTableBody(). * * @see ifs.fnd.asp.ASPPortletProvider#beginTableBody */ protected final void endTableBody() throws FndException { // if(tabbodylevel<tablelevel) // throw new FndException("FNDPRVNINBDY: Not in table body!"); // this.tabbodylevel--; out.append("</tr>\n</tbody>\n"); } private boolean evenrow = false; /** * Close current table row and begin next one. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableBody */ protected final void nextTableRow() throws FndException { nextTableRow(null); } /** * Close current table row and begin next one with specified id. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableBody */ protected final void nextTableRow( String id ) throws FndException { ASPConfig cfg = getASPConfig(); //String bgcolor = cfg.getParameter("SCHEME/FORM/ALT_BGCOLOR", "#E1E2E8"); // if(tabbodylevel<tablelevel) // throw new FndException("FNDPRVNINBDY2: Not in table body!"); evenrow = !evenrow; out.append("</tr>\n<tr"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); if(!transparent && !evenrow) out.append(" class=tableRowColor1"); else if(!transparent) out.append(" class=tableRowColor2"); out.append(">\n"); colcnt = 0; } /** * Constant for definition of left horizontal alignment in table cell. * * @see ifs.fnd.asp.ASPPortletProvider#printTableCell * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final static String LEFT = "left"; /** * Constant for definition of right horizontal alignment in table cell. * * @see ifs.fnd.asp.ASPPortletProvider#printTableCell * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final static String RIGHT = "right"; /** * Constant for definition of center horizontal alignment in table cell. * * @see ifs.fnd.asp.ASPPortletProvider#printTableCell * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final static String CENTER = "center"; private int colcnt = 0; /** * Append a table title or contents cell tag (a th- or td-tag) to the HTML-output * with the specified text. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell * */ protected final void printTableCell( String text ) throws FndException { printTableCell(text,0,0,null); } /** * Append a table title or contents cell tag (a th- or td-tag) to the HTML-output * with the specified text and horizontal alignment. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final void printTableCell( String text, String align ) throws FndException { printTableCell(text,0,0,align); } /** * Append a table title or contents cell tag (a th- or td-tag) to the HTML-output * with the specified text and column span. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final void printTableCell( String text, int colspan ) throws FndException { printTableCell(text,colspan,0,null); } /** * Append a table title or contents cell tag (a th- or td-tag) to the HTML-output * with the specified text, horizontal alignment and column and row span. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final void printTableCell( String text, int colspan, int rowspan, String align ) throws FndException { beginTableCell(colspan, rowspan, align); //out.append("<font class=normalTextValue>"); // needed for Netscape ?? if(Str.isEmpty(text)) out.append("&nbsp;"); else out.append(getASPManager().HTMLEncode(translate(text),true)); //out.append("</font>"); // temporary solution (I hope) //out.append(translate(text)); endTableCell(); } // private int tabcelllevel = 0; /** * Begin a table title or contents cell (a th- or td-tag). * Should be closed by calling endTableCell(). * * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell() throws FndException { beginTableCell(0,0,null,null,false); } /** * Begin a table title or contents cell (a th- or td-tag) * and define the cells horizontal alignment. * Should be closed by calling endTableCell(). * * @param align Specifies horizontal alignment in a cell. Pass LEFT,CENTER or RIGHT. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell( String align ) throws FndException { beginTableCell(0,0,align,null,false); } /** * Begin a table title or contents cell (a th- or td-tag) * and define the cells column span. * Should be closed by calling endTableCell(). * * @param colspan Integer value specifying column span. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell( int colspan ) throws FndException { beginTableCell(colspan,0,null,null,false); } /** * Begin a table title or contents cell (a th- or td-tag). * Define the cells horizontal alignment, column and row span. * Should be closed by calling endTableCell(). * * @param colspan Integer value specifying column span. * @param rowspan Integer value specifying row span. * @param align Specifies horizontal alignment in a cell. Pass LEFT,CENTER or RIGHT. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell( int colspan, int rowspan, String align ) throws FndException { beginTableCell(colspan,rowspan,align,null,false); } /** * Begin a table title or contents cell (a th- or td-tag) with a specified id. * Define the cells horizontal alignment, column and row span. * Should be closed by calling endTableCell(). * * @param colspan Integer value specifying column span. * @param rowspan Integer value specifying row span. * @param align Specifies horizontal alignment in a cell. Pass LEFT,CENTER or RIGHT. * @param id String value specifying the cell Id. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell( int colspan, int rowspan, String align, String id ) throws FndException { beginTableCell(colspan,rowspan,align,id,false); } /** * Begin a table title or contents cell (a th- or td-tag) * Define the cells nowrap property. * Should be closed by calling endTableCell(). * * @param nowrap Set to true to add nowrap else false. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell(boolean nowrap) throws FndException { beginTableCell(0,0,null,null,nowrap); } /** * Begin a table title or contents cell (a th- or td-tag) * Define the cells nowrap property and horizontal alignment. * Should be closed by calling endTableCell(). * * @param align Specifies horizontal alignment in a cell. Pass LEFT,CENTER or RIGHT. * @param nowrap Set to true to add nowrap else false. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell(String align, boolean nowrap) throws FndException { beginTableCell(0,0,align,null,nowrap); } /** * Begin a table title or contents cell (a th- or td-tag) with a specified id. * Define the cells horizontal alignment, column, row span and nowrap. * Should be closed by calling endTableCell(). * * @param colspan Integer value specifying column span. * @param rowspan Integer value specifying row span. * @param align Specifies horizontal alignment in a cell. Pass LEFT,CENTER or RIGHT. * @param id String value specifying the cell Id. * @param nowrap Set to true to add nowrap else false. * @see ifs.fnd.asp.ASPPortletProvider#endTableCell */ protected final void beginTableCell( int colspan, int rowspan, String align, String id, boolean nowrap ) throws FndException { // if(!intitlerow && tabbodylevel<tablelevel) // throw new FndException("FNDPRVNINTAB: Not in title row or table body!"); // if(tabcelllevel>=tablelevel) // throw new FndException("FNDPRVNINTABCELL: Already in table cell!"); // Comment by Terry 20131104 /*if(!transparent && colcnt>0) { out.append( intitlerow ? "<th>" : (transparent?"<td>":"<td bgcolor=white>")); out.append("<img src=\"",getASPConfig().getImagesLocation(),"table_empty_image.gif\" width=3 height=1>"); out.append( intitlerow ? "</th" : "</td", ">\n"); }*/ if(intitlerow) //out.append("<th class=\"grdHd\" BGCOLOR=#FFFFFF"); out.append("<th class=tableColumnHeadingText"); else out.append("<td class=tableContentText"); if( !Str.isEmpty(id) ) out.append(" id=",addProviderPrefix(),id); if(colspan>0) { out.append(" colspan="); out.appendInt(colspan); } if(rowspan>0) { out.append(" rowspan="); out.appendInt(rowspan); } if(!Str.isEmpty(align)) out.append(" align=",align); if (nowrap) out.append(" nowrap"); out.append(">"); colcnt += colspan>0 ? colspan : 1; // tabcelllevel++; } /** * Close a table title or contents cell that was opened by beginTableCell() function. * * @see ifs.fnd.asp.ASPPortletProvider#beginTableCell */ protected final void endTableCell() throws FndException { // if(!intitlerow && tabbodylevel<tablelevel) // throw new FndException("FNDPRVNINTAB2: Not in title row or table body!"); // if(tabcelllevel<tablelevel) // throw new FndException("FNDPRVNNINTABCELL: Not in table cell!"); out.append("</",intitlerow?"th":"td",">\n"); // tabcelllevel--; } /** * Create a string that represents a HTML link. The given label will be translated. * One of overloaded printLink() functions should be used for this purpose. * * @see ifs.fnd.asp.ASPPortletProvider#printLink * @see ifs.fnd.asp.ASPPortletProvider#printImageLink * @see ifs.fnd.asp.ASPPortletProvider#printHoverImageLink * @see ifs.fnd.asp.ASPPortletProvider#printScriptLink * @see ifs.fnd.asp.ASPPortletProvider#printScriptImageLink * @see ifs.fnd.asp.ASPPortletProvider#printScriptHoverImageLink * @see ifs.fnd.asp.ASPPortletProvider#printSubmitLink * @see ifs.fnd.asp.ASPPortletProvider#printSubmitImageLink * @see ifs.fnd.asp.ASPPortletProvider#printSubmitHoverImageLink * @deprecated */ protected final String setHyperlink( String label, String hyperlink ) { return "<a href=\""+hyperlink+"\">"+getASPManager().HTMLEncode(translate(label))+"</a>"; } //========================================================================== // Generation of JavaScript code //========================================================================== /** * Creates a 'script' tag and appends the specified string as JavaScript code, * i.e. script variables. Due this function is called for each instance of the * same portlet class, the code should contain portlet ID. * Should be called from printContents() or printCustomBody(). */ protected final void appendDirtyJavaScript( String str ) throws FndException { appendDirtyJavaScript(str,null,null,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code. */ protected final void appendDirtyJavaScript( String s1, String s2 ) throws FndException { appendDirtyJavaScript(s1,s2,null,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code. */ protected final void appendDirtyJavaScript( String s1, String s2, String s3 ) throws FndException { appendDirtyJavaScript(s1,s2,s3,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code. */ protected final void appendDirtyJavaScript( String s1, String s2, String s3, String s4 ) throws FndException { appendDirtyJavaScript(s1,s2,s3,s4,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code. */ protected final void appendDirtyJavaScript( String s1, String s2, String s3, String s4, String s5 ) throws FndException { modifyingMutableAttribute("DIRTY_JAVASCRIPT"); dirty_script.append(s1); if(s2!=null) dirty_script.append(s2); if(s3!=null) dirty_script.append(s3); if(s4!=null) dirty_script.append(s4); if(s5!=null) dirty_script.append(s5); } /** * Creates a 'script' tag and appends the specified string as JavaScript code, * i.e. script functions. Due this function is called only once for all instances * of the same portlet class, the code must not contain portlet specific * code (portlet ID). Should be called from preDefine(). */ protected final void appendJavaScript( String str ) throws FndException { appendJavaScript(str,null,null,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code, */ protected final void appendJavaScript( String s1, String s2 ) throws FndException { appendJavaScript(s1,s2,null,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code, */ protected final void appendJavaScript( String s1, String s2, String s3 ) throws FndException { appendJavaScript(s1,s2,s3,null,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code, */ protected final void appendJavaScript( String s1, String s2, String s3, String s4 ) throws FndException { appendJavaScript(s1,s2,s3,s4,null); } /** * Creates a 'script' tag and appends the specified strings as JavaScript code, */ protected final void appendJavaScript( String s1, String s2, String s3, String s4, String s5 ) throws FndException { modifyingImmutableAttribute("JAVASCRIPT"); script.append(s1); if(s2!=null) script.append(s2); if(s3!=null) script.append(s3); if(s4!=null) script.append(s4); if(s5!=null) script.append(s5); } /** * Creates a 'script' tag and appends the contents of the specified file * as JavaScript code,i.e. script functions. Due this function is called only * once for all instances of the same portlet class, the code must not contain * portlet specific code (portlet ID). Should be called from preDefine(). * For example: * <pre> * includeJavaScriptFile("demorw/DemoScript.js"); *</pre> */ protected final void includeJavaScriptFile( String filename ) throws FndException { modifyingImmutableAttribute("JAVASCRIPTFILE"); if(!Str.isEmpty(scriptfile)) throw new FndException("FNDPRVFSCRDEF: JavaScript file name is already defined."); scriptfile = filename; } //========================================================================== // Debug //========================================================================== /** * Print the current function stack to the DBMON console. */ public static void dumpStack() { try { throw new Exception("Current Stack Dump:"); } catch(Exception e) { Util.debug( Str.getStackTrace(e) ); } } //========================================================================== //========================================================================== // TO BE REMOVED !!! //========================================================================== //JAPA protected final ASPPageElement clonePageElement_( ASPPage page, ASPPageElement element ) throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.clonePageElement("+page+","+element+")"); return (ASPPageElement)(element.clone(page)); } /** * Called by ASPManager, after successful execution of the submit() method. */ void refresh_() throws FndException { if(DEBUG) debug(this+": ASPPortletProvider.refresh()"); super.refresh(); } int indexInColumn_( Vector column ) { String name = getClass().getName(); for(int i=0; i<column.size(); i++) if( column.elementAt(i).getClass().getName().equals(name) ) { debug("ASPPortletProvider: index of '"+name+"' = "+i); return i; } debug("ASPPortletProvider: index of '"+name+"' = -1"); return -1; } /** * Returns an array of strings that results when the string str is separated * into substrings using the specified set of delimiter characters 'delimChars'. */ protected static final String[] split(String str, String delimChars) { return Str.split(str,delimChars); } /** Add given global information in to a temporary global list. But this will not effect to the * original global variables. The idea is to keep list of temporary global vriables to generate the * URL from witch the user can actually change the original globals. * @param name name of the global variable * @param label label to display * @param value value to set * @param description description */ protected void defineGlobalVariable(String name, String label, String value, String description) { if (dummy_globals == null) dummy_globals = new Vector(); for (int i=0; i<dummy_globals.size(); i++) { GlobalVariable temp_global = (GlobalVariable) dummy_globals.get(i); if (temp_global.getName().equals(name)) { temp_global.setValue(value); temp_global.setLabel(label); temp_global.setDescription(description); return; } } dummy_globals.add(new GlobalVariable(name, value, label, description)); } /** * Generate the URL with proper query string to set above defined globals while keepingthe * already defined global variables. */ protected String generateGlobalVariableURL() { // There are some heavy string operations here. This code should be improved after March - 2004. // Mangala String ret; ASPManager mgr = getASPManager(); temp_globals.clear(); temp_globals_value.clear(); for (int i=0; i<dummy_globals.size(); i++) { GlobalVariable dummy_global = (GlobalVariable) dummy_globals.get(i); temp_globals.append(dummy_global.getName(),","); temp_globals_value.append("&",dummy_global.getName(),"=",dummy_global.getValue(),","); temp_globals_value.append(dummy_global.getLabel(),",",dummy_global.getDescription()); } String local_global_list = "," + temp_globals.toString(); Enumeration variables = portal.getGlobalVariables().keys(); while( variables.hasMoreElements() ) { String variable = (String)variables.nextElement(); if (local_global_list.indexOf(","+variable+",")>-1) continue; temp_globals.append(variable+","); temp_globals_value.append("&",variable,"=",mgr.URLEncode((String)portal.getGlobalVariables().get(variable))); } temp_globals.append(temp_globals_value); ret = mgr.getPortalPage().getURL() + "?__VIEW_NAME="+mgr.URLEncode( portal.getName()) +"&GLOBAL_VARIABLE=" + temp_globals.toString(); temp_globals_value.clear(); temp_globals.clear(); return ret; } /** * Returns the URL where you can remove given global variables while keeping already defined global * value unchanged. * @param text text to be print * @param globals comma seperated list of globals to be remove */ protected void printRemoveGlobalLink(String text, String globals) { String ret; String temp_global_str = ","+globals+","; ASPManager mgr = getASPManager(); temp_globals.clear(); temp_globals_value.clear(); Enumeration variables = portal.getGlobalVariables().keys(); while( variables.hasMoreElements() ) { String variable = (String)variables.nextElement(); if (temp_global_str.indexOf(","+variable+",")>-1) continue; temp_globals.append(variable+","); temp_globals_value.append("&",variable,"=",mgr.URLEncode((String)portal.getGlobalVariables().get(variable))); } temp_globals.append(temp_globals_value); ret = mgr.getPortalPage().getURL() + "?__VIEW_NAME="+mgr.URLEncode( portal.getName()) +"&GLOBAL_VARIABLE=" + temp_globals.toString(); temp_globals_value.clear(); temp_globals.clear(); printAbsoluteLink(text, ret); } /** * Returns the description of given global variable * @param name global vriable name */ protected String getGlobalDescription(String name) { String [] global_details = split(portal.getGlobalVariable(name), ","); if (global_details.length ==3) return global_details[2]; else return ""; } /** * Returns the label of given global variable * @param name global vriable name */ protected String getGlobalLabel(String name) { String [] global_details = split(portal.getGlobalVariable(name), ","); if (global_details.length >2) return global_details[1]; else return ""; } class GlobalVariable { private String name; private String value; private String label; private String description; GlobalVariable(String name, String value, String label, String description) { this.name=name; this.value = value; this.label = label; this.description = description; } String getName() { return name; } String getValue() { return value; } String getLabel() { return label; } String getDescription() { return description; } void setName(String name) { this.name = name; } void setValue(String value) { this.value = value; } void setLabel(String label) { this.label = label; } void setDescription(String description) { this.description = description; } } }
C++
UTF-8
586
2.546875
3
[]
no_license
/******************************************** * Filename:gofish.pp * Author:faaiq waqar * Date:02/04/2019 * Description:contains main function for go fish * Input: header files * Output: game running *******************************************/ #include "card.hpp" #include "deck.hpp" #include "hand.hpp" #include "player.hpp" #include "game.hpp" using namespace std; int main(){ Game game; cout << "Initiallizing Game ... \n"; cout << "Full Deck ... Cards: 52\n"; cout << "Shuffling ... \n"; cout << " ... \n"; cout << "Begin! \n\n\n"; game.startGame(); return 0; }
Java
UTF-8
57,611
2.890625
3
[]
no_license
package org.modelexecution.quantitytypes.java; import java.util.Arrays; public class Unit implements Cloneable { //************************ // ATTRIBUTES //************* protected double [] dimensions = new double [BaseUnits.values().length]; // exponents for each dimension. // [Meter, Kilogram, Second, Ampere, Kelvin, Mole, Candela, Radian, Bit, Shannon, Erlang, Decibel] //************************* // STATIC VARIABLES //************** public final static String [] BaseUnitNames ={"Meter", "Kilogram", "Second", "Ampere", "Kelvin", "Mole", "Candela", "Bit", "Shannon", "Erlang", "Decibel", "Radian"}; public final static String [] DerivedUnitNames ={ "Gray", "GrayPerSecond", "Becquerel", "MolePerCubicMeter", "MolePerKilogram", "RadianPerSecondSquared", "KilogramMeterSquared", "JouleSecond", "RadianPerSecond", "SquareMeter", "SquareMeterSteradian", "SquareMeterKelvin", "SquareMeterPerKelvin", "Farad", "Katal", "WattPerSquareMeterKelvin", "KilogramPerCubicMeter", "Sievert", "PascalSecond", "Coulomb", "CoulombPerMeter", "CoulombPerCubicMeter", "CoulombPerMole", "AmperePerSquareMeter", "AmperePerRadian", "CoulombMeter", "VoltPerMeter", "CoulombPerSquareMeter", "Siemens", "Volt", "JoulePerCubicMeter", "Joule", "JoulePerSquareMeter", "CoulombPerKilogram", "Newton", "NewtonPerCoulomb", "NewtonPerMeter", "Hertz", "CubicMeterPerKilogramSecondSquared", "JoulePerKelvin", "Lux", "Henry", "PerMole", "MeterPerFarad", "SquareMeterPerSecond", "MeterKilogram", "MeterKelvin", "MeterPerSecondSquared", "KilogramMeterPerSecond", "MeterPerKelvin", "MeterPerSecond", "CandelaPerSquareMeter", "Lumen", "JoulePerTesla", "AmpereTurnPerMeter", "Weber", "Tesla", "AmpereTurn", "KilogramKelvin", "KilogramPerSecond", "KilogramPerSquareMeter", "KilogramPerMeter", "JoulePerMole", "JoulePerMoleKelvin", "HenryPerMeter", "FaradPerMeter", "Watt", "WattPerSteradian", "WattPerSquareMeterSteradian", "WattPerSquareMeter", "Pascal", "Ohm", "Steradian", "JoulePerKilogram", "JoulePerKilogramKelvin", "JoulePerKilogramKelvinPerPascal", "JoulePerKilogramKelvinPerCubicMeter", "MoleKelvin", "WattPerMeterKelvin", "SquareMeterKelvinPerWatt", "KelvinPerWatt", "MeterKelvinPerWatt", "NewtonPerKilogram", "SecondTimeSquared", "Torque", "CubicMeter", "CubicMeterPerKelvin", "CubicMeterPerSecond", "JoulePerCubicMeterKelvin", "BitsPerSecond"}; public final static String [] BaseUnitSymbols ={"m", "kg", "s", "A", "K", "mol", "cd", "bit", "Sh", "E", "dB", "rad"}; public final static String [] DerivedUnitSymbols ={ "Gy", "Gy/s", "Bq", "mol/m^3", "mol/kg", "rad/s^2", "kg*m^2", "J*s", "rad/s", "m^2", "m^2*sr", "m^2*K", "m^2/K", "F", "kat", "W/(m^2*K)", "kg/m^3", "Sv", "Pa*s", "C", "C/m", "C/m^3", "C/mol", "A/m^2", "A/rad", "C*m", "V/m", "C/m^2", "S", "V", "J/m^3", "J", "J/m^2", "C/kg", "N", "N/C", "N/m", "Hz", "m^3/(kg*s^2)", "J/K", "lx", "H", "1/mol", "m/F", "m^2/s", "m*kg", "m*K", "m/s^2", "kg*m/s", "m/K", "m/s", "cd/m^2", "lm", "J/T", "AT/m", "Wb", "T", "AT", "kg*K", "kg/s", "kg/m^2", "kg/m", "J/mol", "J/(mol*K)", "H/m", "F/m", "W", "W/sr", "W/(m^2*sr)", "W/m^2", "Pa", "Ohm", "sr", "J/kg", "J/(kg*K)", "J/(kg*K*Pa)", "J/(kg*K*m^3)", "mol*K", "W/(m*K)", "K^2*m/W", "K/W", "m*K/W", "N/kg", "s^2", "N*m", "m^3", "m^3/K", "m^3/s", "J/(m^3*K)", "bit/s" }; /************************ * HELPERS *************/ public static BaseUnits unitOfTheDimension(BaseDimensions d){ return BaseUnits.values()[d.ordinal()]; } public static DerivedUnits unitOfTheDimension(DerivedDimensions d){ return DerivedUnits.values()[d.ordinal()]; } public static BaseDimensions dimensionOfUnit(BaseUnits u){ return BaseDimensions.values()[u.ordinal()]; } public static DerivedDimensions dimensionOfUnit(DerivedUnits u){ return DerivedDimensions.values()[u.ordinal()]; } private void fillDim(BaseUnits d, double exp){ Arrays.fill(dimensions, 0.0); dimensions[d.ordinal()] = exp; } private void fillDim(BaseUnits d1, double exp1,BaseUnits d2, double exp2){ Arrays.fill(dimensions, 0.0); dimensions[d1.ordinal()] = exp1; dimensions[d2.ordinal()] = exp2; } private void fillDim(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3){ Arrays.fill(dimensions, 0.0); dimensions[d1.ordinal()] = exp1; dimensions[d2.ordinal()] = exp2; dimensions[d3.ordinal()] = exp3; } private void fillDim(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4){ Arrays.fill(dimensions, 0.0); dimensions[d1.ordinal()] = exp1; dimensions[d2.ordinal()] = exp2; dimensions[d3.ordinal()] = exp3; dimensions[d4.ordinal()] = exp4; } private void fillDim(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4,BaseUnits d5, double exp5){ Arrays.fill(dimensions, 0.0); dimensions[d1.ordinal()] = exp1; dimensions[d2.ordinal()] = exp2; dimensions[d3.ordinal()] = exp3; dimensions[d4.ordinal()] = exp4; dimensions[d5.ordinal()] = exp5; } //************************ // CONSTRUCTORS //************* private double[] fillUnitDimensions(){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); //unitless return dim; } private double[] fillUnitDimensions(double [] d){ double[] dim = new double [BaseUnits.values().length]; dim = Arrays.copyOf(d, dim.length); return dim; } private int find(String[] array, String value) { //auxiliary method because Array does not have "indexOf()" for(int i=0; i<array.length; i++) if(array[i] == value) return i; return -1; } private double[] fillUnitDimensions(String symbol){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); int p = find(BaseUnitSymbols, symbol); if (p > -1) dim[p] = 1.0; else { p = find(DerivedUnitSymbols, symbol); if (p > -1) fillDimensions(DerivedUnits.values()[p]); } return dim; } private double[] fillUnitDimensions(BaseUnits d){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d.ordinal()] = 1.0; return dim; } private double[] fillUnitDimensions(BaseUnits d, double exp){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d.ordinal()] = exp; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; dim[d3.ordinal()] = exp3; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; dim[d3.ordinal()] = exp3; dim[d4.ordinal()] = exp4; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4,BaseUnits d5, double exp5){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; dim[d3.ordinal()] = exp3; dim[d4.ordinal()] = exp4; dim[d5.ordinal()] = exp5; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4,BaseUnits d5, double exp5,BaseUnits d6, double exp6){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; dim[d3.ordinal()] = exp3; dim[d4.ordinal()] = exp4; dim[d5.ordinal()] = exp5; dim[d6.ordinal()] = exp6; return dim; } private double[] fillUnitDimensions(BaseUnits d1, double exp1,BaseUnits d2, double exp2,BaseUnits d3, double exp3,BaseUnits d4, double exp4,BaseUnits d5, double exp5,BaseUnits d6, double exp6,BaseUnits d7, double exp7){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); dim[d1.ordinal()] = exp1; dim[d2.ordinal()] = exp2; dim[d3.ordinal()] = exp3; dim[d4.ordinal()] = exp4; dim[d5.ordinal()] = exp5; dim[d6.ordinal()] = exp6; dim[d7.ordinal()] = exp7; return dim; } private double[] fillUnitDimensions(Unit u){ double[] dim = new double [BaseUnits.values().length]; dim = Arrays.copyOf(u.dimensions, dim.length); return dim; } private double[] fillUnitDimensions(DerivedUnits d){ double[] dim = new double [BaseUnits.values().length]; Arrays.fill(dim, 0.0); fillDimensions(d); return dim; } private void fillDimensions(DerivedUnits d){ switch(d){ case Gray: fillDim(BaseUnits.Meter,2.0, BaseUnits.Second,-2.0); break; case GrayPerSecond: fillDim(BaseUnits.Meter,2.0, BaseUnits.Second,-3.0); break; case Becquerel: fillDim(BaseUnits.Second,-1.0); break; case MolePerCubicMeter: fillDim(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0); break; case MolePerKilogram: fillDim(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0); break; case RadianPerSecondSquared: fillDim(BaseUnits.Second,-2.0,BaseUnits.Radian,1.0); break; case KilogramMeterSquared: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0); break; case JouleSecond: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0); break; case RadianPerSecond: fillDim(BaseUnits.Second,-1.0, BaseUnits.Radian,1.0); break; case SquareMeter: fillDim(BaseUnits.Meter,2.0); break; case SquareMeterSteradian: fillDim(BaseUnits.Meter,2.0,BaseUnits.Radian,2.0); break; case SquareMeterKelvin: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kelvin,1.0); break; case SquareMeterPerKelvin: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kelvin,-1.0); break; case Farad: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0); break; case Katal: fillDim(BaseUnits.Second,-1.0,BaseUnits.Mole,1.0); break; case WattPerSquareMeterKelvin: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0); break; case KilogramPerCubicMeter: fillDim(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,1.0); break; case Sievert: fillDim(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0); break; case PascalSecond: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0); break; case Coulomb: fillDim(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0); break; case CoulombPerMeter: fillDim(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-1.0); break; case CoulombPerCubicMeter: fillDim(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-3.0); break; case CoulombPerMole: fillDim(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Mole,-1.0); break; case AmperePerSquareMeter: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Ampere,1.0); break; case AmperePerRadian: fillDim(BaseUnits.Ampere,1.0,BaseUnits.Radian,-1.0); break; case CoulombMeter: fillDim(BaseUnits.Meter,1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0); break; case VoltPerMeter: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0); break; case CoulombPerSquareMeter: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0); break; case Siemens: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Ampere,2.0); break; case Volt: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,1.0); break; case JoulePerCubicMeter: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case Joule: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case JoulePerSquareMeter: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case CoulombPerKilogram: fillDim(BaseUnits.Kilogram,-1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0); break; case Newton: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0,BaseUnits.Second,-2.0); break; case NewtonPerCoulomb: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0); break; case NewtonPerMeter: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case Hertz: fillDim(BaseUnits.Second,-1.0); break; case CubicMeterPerKilogramSecondSquared: fillDim(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Second,-2.0); break; case JoulePerKelvin: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0); break; // case Watt: duplicated // case WattPerSquareMeter: duplicated case Lux: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0, BaseUnits.Radian,1.0); break; case Henry: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0); break; case PerMole: fillDim(BaseUnits.Mole,-1.0); break; case MeterPerFarad: fillDim(BaseUnits.Meter,3,BaseUnits.Kilogram,1.0,BaseUnits.Second,-4,BaseUnits.Ampere,-2.0); break; case SquareMeterPerSecond: fillDim(BaseUnits.Meter,2.0,BaseUnits.Second,-1.0); break; case MeterKilogram: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0); break; case MeterKelvin: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kelvin,1.0); break; case MeterPerSecondSquared: fillDim(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0); break; case KilogramMeterPerSecond: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0); break; case MeterPerKelvin: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kelvin,-1.0); break; case MeterPerSecond: fillDim(BaseUnits.Meter,1.0,BaseUnits.Second,-1.0); break; case CandelaPerSquareMeter: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0); break; case Lumen: fillDim(BaseUnits.Candela,1.0, BaseUnits.Radian,1.0); break; case JoulePerTesla: fillDim(BaseUnits.Meter,2.0,BaseUnits.Ampere,1.0); break; case AmpereTurnPerMeter: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Ampere,1.0); break; case Weber: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0); break; case Tesla: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0); break; case AmpereTurn: fillDim(BaseUnits.Ampere,1.0, BaseUnits.Radian,1.0); break; case KilogramKelvin: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Kelvin,1.0); break; case KilogramPerSecond: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0); break; case KilogramPerSquareMeter: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-2.0); break; case KilogramPerMeter: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-1.0); break; case JoulePerMole: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Mole,-1.0); break; case JoulePerMoleKelvin: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0,BaseUnits.Mole,-1.0); break; case HenryPerMeter: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0); break; case FaradPerMeter: fillDim(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0); break; case Watt: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0); break; case WattPerSteradian: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Radian,-2.0); break; case WattPerSquareMeterSteradian: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0, BaseUnits.Radian,-2.0); //, break; case WattPerSquareMeter: fillDim(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0); break; case Pascal: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case Ohm: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-2.0); break; case Steradian: fillDim(BaseUnits.Radian,2.0); break; case JoulePerKilogram: fillDim(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0); break; case JoulePerKilogramKelvin: fillDim(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0); break; case JoulePerKilogramKelvinPerPascal: fillDim(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Kelvin,-1.0); break; case JoulePerKilogramKelvinPerCubicMeter: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0); break; case MoleKelvin: fillDim(BaseUnits.Kelvin,1.0,BaseUnits.Mole,1.0); break; case WattPerMeterKelvin: fillDim(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0); break; // case SquareMeterPerSecond: duplicated case SquareMeterKelvinPerWatt: fillDim(BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0); break; case KelvinPerWatt: fillDim(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0); break; case MeterKelvinPerWatt: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0); break; case NewtonPerKilogram: fillDim(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0); break; case SecondTimeSquared: fillDim(BaseUnits.Second,2.0); break; case NewtonMeter: fillDim(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0); break; case CubicMeter: fillDim(BaseUnits.Meter,3.0); break; case CubicMeterPerKelvin: fillDim(BaseUnits.Meter,3,BaseUnits.Kelvin,-1.0); break; case CubicMeterPerSecond: fillDim(BaseUnits.Meter,3,BaseUnits.Second,-1.0); break; case JoulePerCubicMeterKelvin: fillDim(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0); break; case BitsPerSecond: fillDim(BaseUnits.Bit,1.0,BaseUnits.Second,-1.0); } } // -------------------------------------------------------------------------- protected String name = ""; protected String symbol = ""; //public Unit siUnit; // this attribute contains the reference to the dimensions in the SI and their exponents protected double [] conversionFactor = new double [BaseUnits.values().length]; // to convert to SI Units. They are all 1.0 by default. // for example, from Kilometer to Meter, this.conversionFactor[BaseUnits.Meter.ordinal()]=1000 // from Gram to Kilogram, this.conversionFactor[BaseUnits.Kilogram.ordinal()]=0.001 // conversion factors are not affected by exponents, they are considered only when making the conversions protected double [] offset = new double [BaseUnits.values().length]; // to convert to SI Units. They are all 0.0 by default. // for example, from Celsius to Kelvin, this.offset[BaseUnits.Kelvin.ordinal()] = +273.15 // offsets, as conversion factors, are not affected by exponents, they are considered only when making the conversions // joining the two: // from Celsius to Kelvin, this.conversionFactor[BaseUnits.Kelvin.ordinal()]=1.0; // this.offset[BaseUnits.Kelvin.ordinal()] = +273.15 // from Farenheit to Kelvin, this.conversionFactor[BaseUnits.Kelvin.ordinal()]=0.55555555556; // this.offset[BaseUnits.Kelvin.ordinal()] = +255.372222222; // IMPORTANT: In this version, only one offset is allowed in Units protected boolean checkOffset() { int atMostOne=0; for (int i=0;i<BaseUnits.values().length;i++) if (offset[i]!=0.0) atMostOne++; return atMostOne<=1; } protected boolean noOffset() { for (int i=0;i<BaseUnits.values().length;i++) if (offset[i]!=0.0) return false; return true; } protected double sumOffset() { double sum=0; for (int i=0;i<BaseUnits.values().length;i++) sum +=offset[i]; return sum; } public Unit(){ //Unitless dimensions = fillUnitDimensions(); this.name = ""; this.symbol = ""; Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); } public Unit(String name, String symbol, double [] d, double [] c, double [] o){ dimensions = fillUnitDimensions(d); this.name = name; this.symbol = symbol; this.conversionFactor = Arrays.copyOf(c, BaseUnits.values().length); this.offset = Arrays.copyOf(o, BaseUnits.values().length); // assert checkOffset() : offset; if (!this.checkOffset()) throw new RuntimeException("Invalid Offset when creating unit: "+this.symbol); } public Unit(String name, String symbol, double [] d, double [] c){ dimensions = fillUnitDimensions(d); this.name = name; this.symbol = symbol; this.conversionFactor = Arrays.copyOf(c, BaseUnits.values().length); Arrays.fill(offset, 0.0); } public Unit(double [] d){ dimensions = fillUnitDimensions(d); Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); } public Unit(double [] d, double [] c){ //no offset dimensions = fillUnitDimensions(d); this.conversionFactor = Arrays.copyOf(c, BaseUnits.values().length); Arrays.fill(offset, 0.0); } public Unit(double [] d, double [] c, double [] o){ dimensions = fillUnitDimensions(d); this.conversionFactor = Arrays.copyOf(c, BaseUnits.values().length); this.offset = Arrays.copyOf(o, BaseUnits.values().length); // assert checkOffset() : offset; if (!this.checkOffset()) throw new RuntimeException("Invalid Offset when creating unit: "+this.symbol); } public Unit(BaseUnits d, double exp){ dimensions = fillUnitDimensions(d,exp); Arrays.fill(this.conversionFactor, 1.0); Arrays.fill(this.offset, 0.0); } public Unit(BaseUnits d){ dimensions = fillUnitDimensions(d); Arrays.fill(this.conversionFactor, 1.0); Arrays.fill(this.offset, 0.0); } public Unit(DerivedUnits d){ // dimensions = fillUnitDimensions(d); fillUnitDimensions(d); Arrays.fill(this.conversionFactor, 1.0); Arrays.fill(this.offset, 0.0); } public Unit(String name, String symbol, BaseUnits d, double exp, double conv, double offset){ dimensions = fillUnitDimensions(d,exp); this.name = name; this.symbol = symbol; Arrays.fill(this.conversionFactor, 1.0); Arrays.fill(this.offset, 0.0); this.conversionFactor[d.ordinal()] = conv; this.offset[d.ordinal()] = offset; // assert checkOffset() : offset; if (!this.checkOffset()) throw new RuntimeException("Invalid Offset when creating unit: "+this.symbol); } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2){ dimensions = fillUnitDimensions(d1,exp1,d2,exp2); this.name = name; this.symbol = symbol; Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2, BaseUnits d3, double exp3, double conv3){ dimensions = fillUnitDimensions(d1,exp1,d2,exp2,d3,exp3); this.name = name; this.symbol = symbol; Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; // this.offset[d2.ordinal()] = offset2; this.conversionFactor[d3.ordinal()] = conv3; // this.offset[d3.ordinal()] = offset3; } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2, //double offset2, BaseUnits d3, double exp3, double conv3, //double offset3, BaseUnits d4, double exp4, double conv4 ){ //double offset4 dimensions = fillUnitDimensions(d1,exp1,d2,exp2,d3,exp3,d4,exp4); this.name = name; this.symbol = symbol; Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; // this.offset[d2.ordinal()] = offset2; this.conversionFactor[d3.ordinal()] = conv3; // this.offset[d3.ordinal()] = offset3; this.conversionFactor[d4.ordinal()] = conv4; // this.offset[d4.ordinal()] = offset4; } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2, //double offset2, BaseUnits d3, double exp3, double conv3, //double offset3, BaseUnits d4, double exp4, double conv4, //double offset4, BaseUnits d5, double exp5, double conv5 ){ //,double offset5){ dimensions = fillUnitDimensions(d1,exp1,d2,exp2,d3,exp3,d4,exp4,d5,exp5); this.name = name; this.symbol = symbol; Arrays.fill(conversionFactor, 1.0); Arrays.fill(offset, 0.0); this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; // this.offset[d2.ordinal()] = offset2; this.conversionFactor[d3.ordinal()] = conv3; // this.offset[d3.ordinal()] = offset3; this.conversionFactor[d4.ordinal()] = conv4; // this.offset[d4.ordinal()] = offset4; this.conversionFactor[d5.ordinal()] = conv5; // this.offset[d5.ordinal()] = offset5; } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2, BaseUnits d3, double exp3, double conv3, BaseUnits d4, double exp4, double conv4, BaseUnits d5, double exp5, double conv5, BaseUnits d6, double exp6, double conv6){ dimensions = fillUnitDimensions(d1,exp1,d2,exp2,d3,exp3,d4,exp4,d5,exp5,d6,exp6); this.name = name; this.symbol = symbol; Arrays.fill(this.conversionFactor, 1.0); Arrays.fill(this.offset, 0.0); this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; // this.offset[d2.ordinal()] = offset2; this.conversionFactor[d3.ordinal()] = conv3; // this.offset[d3.ordinal()] = offset3; this.conversionFactor[d4.ordinal()] = conv4; // this.offset[d4.ordinal()] = offset4; this.conversionFactor[d5.ordinal()] = conv5; // this.offset[d5.ordinal()] = offset5; this.conversionFactor[d6.ordinal()] = conv6; // this.offset[d6.ordinal()] = offset6; } public Unit(String name, String symbol, BaseUnits d1, double exp1, double conv1, double offset1, BaseUnits d2, double exp2, double conv2, BaseUnits d3, double exp3, double conv3, BaseUnits d4, double exp4, double conv4, BaseUnits d5, double exp5, double conv5, BaseUnits d6, double exp6, double conv6, BaseUnits d7, double exp7, double conv7){ dimensions = fillUnitDimensions(d1,exp1,d2,exp2,d3,exp3,d4,exp4,d5,exp5,d6,exp6,d7,exp7); this.name = name; this.symbol = symbol; this.conversionFactor[d1.ordinal()] = conv1; this.offset[d1.ordinal()] = offset1; this.conversionFactor[d2.ordinal()] = conv2; // this.offset[d2.ordinal()] = offset2; this.conversionFactor[d3.ordinal()] = conv3; // this.offset[d3.ordinal()] = offset3; this.conversionFactor[d4.ordinal()] = conv4; // this.offset[d4.ordinal()] = offset4; this.conversionFactor[d5.ordinal()] = conv5; // this.offset[d5.ordinal()] = offset5; this.conversionFactor[d6.ordinal()] = conv6; // this.offset[d6.ordinal()] = offset6; this.conversionFactor[d7.ordinal()] = conv7; // this.offset[d7.ordinal()] = offset7; } public Unit(Unit u){ this.dimensions = u.dimensions; this.name = u.name; this.symbol = u.symbol; this.conversionFactor = u.conversionFactor; this.offset = u.offset; } /************ * Queries, etc * */ public double factor(){ double f = 1.0; for (int i = 0; i<BaseUnits.values().length; i++) f *=(Math.pow(conversionFactor[i],dimensions[i])); return f; } public boolean equals(Unit u) { //hascode() from super. // we do not care about the name and symbols, focusing only on // the dimensions, conversion factors and offsets return Arrays.equals(this.conversionFactor, u.conversionFactor) && Arrays.equals(this.offset, u.offset) && Arrays.equals(this.dimensions, u.dimensions); } public boolean isCompatibleWith(Unit u) { return Arrays.equals(this.dimensions, u.dimensions); } /**************** * Operations */ public Unit multiplyUnits (Unit u) { //resulting units expressed in Units double [] result = new double [dimensions.length]; for (int i=0;i<this.dimensions.length;i++){ result[i]=this.dimensions[i] + u.dimensions[i]; //they are exponents } Unit siu = new Unit(result); return new Unit(siu.name(), siu.symbol(), result, this.conversionFactor, this.offset); } public Unit divideUnits (Unit u) { //resulting units expressed in Units double [] result = new double [dimensions.length]; for (int i=0;i<this.dimensions.length;i++){ result[i]=this.dimensions[i] - u.dimensions[i]; //they are exponents } Unit siu = new Unit(result); return new Unit(siu.name(), siu.symbol(), result, this.conversionFactor, this.offset); } public Unit powerUnits (float s) { double [] result = new double [dimensions.length]; for (int i=0;i<this.dimensions.length;i++){ result[i]=this.dimensions[i] * s; //they are exponents } Unit siu = new Unit(result); return new Unit(siu.name(), siu.symbol(), result, this.conversionFactor, this.offset); } public String toString(){ String s = "["+this.dimensions[0]; for (int i=1;i<this.dimensions.length;i++){ s+=","+this.dimensions[i]; } s+="];"; s += "<"+name+";"+symbol+";"+ ";["+conversionFactor[0]; for (int i=1;i<this.conversionFactor.length;i++){ s+=","+this.conversionFactor[i]; }; s+="];["+offset[0]; for (int i=1;i<this.offset.length;i++){ s+=","+this.offset[i]; }; return s+"]"; } // -------------------- /************ * methods * */ public double [] dimensions(){ return this.dimensions; } public int hashcode(){ //required for equals() double x=0.0; for (int i=0;i<dimensions.length;i++) x+=dimensions[i]; return (int)Math.round(x); } public boolean isBaseUnit(){ int zeros = 0; int unos = 0; for (int i=0;i<dimensions.length;i++){ if (dimensions[i]==0.0) zeros++; if (dimensions[i]==1.0) unos++; } return (zeros==dimensions.length-1) // all exponents but 1 are 0. && (unos==1); //and there is one exponent == 1 } public boolean isDimensionless(){ //all units but Radian are dimensionless for (int i=0;i<dimensions.length;i++){ if ((i!=BaseUnits.Radian.ordinal())&&(i!=BaseUnits.Erlang.ordinal())&&(dimensions[i]!=0.0)) return false; } return true; //all exponents should be 0.0 apart from the one from radian //and the one from the Erlang . } public boolean isUnitless(){ //all 8 exponents should be 0.0 for (int i=0;i<dimensions.length;i++){ if (dimensions[i]!=0.0) return false; } return true; } public Unit clone(){ return new Unit(this); } public DerivedUnits toDerivedUnits(){ if (fillUnitDimensions(BaseUnits.Meter,2.0, BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.Gray; if (fillUnitDimensions(BaseUnits.Meter,2.0, BaseUnits.Second,-3.0).equals(this)) return DerivedUnits.GrayPerSecond; if (fillUnitDimensions(BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.Becquerel; if (fillUnitDimensions(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0).equals(this)) return DerivedUnits.MolePerCubicMeter; if (fillUnitDimensions(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0).equals(this)) return DerivedUnits.MolePerKilogram; if (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Second,-2.0).equals(this)) // return DerivedUnits.RadianPerSecondSquared; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0).equals(this)) return DerivedUnits.KilogramMeterSquared; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.JouleSecond; if (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Second,-1.0).equals(this)) // return DerivedUnits.RadianPerSecond; if (fillUnitDimensions(BaseUnits.Meter,2.0).equals(this)) return DerivedUnits.SquareMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Radian,2.0).equals(this)) // return DerivedUnits.SquareMeterSteradian; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.SquareMeterKelvin; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.SquareMeterPerKelvin; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0).equals(this)) return DerivedUnits.Farad; if (fillUnitDimensions(BaseUnits.Second,-1.0,BaseUnits.Mole,1.0).equals(this)) return DerivedUnits.Katal; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.WattPerSquareMeterKelvin; if (fillUnitDimensions(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,1.0).equals(this)) return DerivedUnits.KilogramPerCubicMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.Sievert; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.PascalSecond; if (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.Coulomb; if (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-1.0).equals(this)) return DerivedUnits.CoulombPerMeter; if (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-3.0).equals(this)) return DerivedUnits.CoulombPerCubicMeter; if (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Mole,-1.0).equals(this)) return DerivedUnits.CoulombPerMole; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.AmperePerSquareMeter; if (fillUnitDimensions(BaseUnits.Ampere,1.0,BaseUnits.Radian,-1.0).equals(this)) // return DerivedUnits.AmperePerRadian; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.CoulombMeter; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0).equals(this)) return DerivedUnits.VoltPerMeter; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.CoulombPerSquareMeter; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Ampere,2.0).equals(this)) return DerivedUnits.Siemens; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.Volt; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.JoulePerCubicMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.Joule; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.JoulePerSquareMeter; if (fillUnitDimensions(BaseUnits.Kilogram,-1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.CoulombPerKilogram; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.Newton; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0).equals(this)) return DerivedUnits.NewtonPerCoulomb; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.NewtonPerMeter; if (fillUnitDimensions(BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.Hertz; if (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.CubicMeterPerKilogramSecondSquared; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.JoulePerKelvin; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0,BaseUnits.Radian,1.0).equals(this)) // return DerivedUnits.Lux; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0).equals(this)) return DerivedUnits.Henry; if (fillUnitDimensions(BaseUnits.Mole,-1.0).equals(this)) return DerivedUnits.PerMole; if (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,1.0,BaseUnits.Second,-4,BaseUnits.Ampere,-2.0).equals(this)) return DerivedUnits.MeterPerFarad; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.SquareMeterPerSecond; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0).equals(this)) return DerivedUnits.MeterKilogram; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.MeterKelvin; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.MeterPerSecondSquared; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.KilogramMeterPerSecond; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.MeterPerKelvin; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.MeterPerSecond; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0).equals(this)) return DerivedUnits.CandelaPerSquareMeter; if (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Candela,1.0).equals(this)) //, return DerivedUnits.Lumen; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.JoulePerTesla; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Ampere,1.0).equals(this)) return DerivedUnits.AmpereTurnPerMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0).equals(this)) return DerivedUnits.Weber; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0).equals(this)) return DerivedUnits.Tesla; if (fillUnitDimensions(BaseUnits.Ampere,1.0,BaseUnits.Radian,1.0).equals(this)) // return DerivedUnits.AmpereTurn; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.KilogramKelvin; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.KilogramPerSecond; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-2.0).equals(this)) return DerivedUnits.KilogramPerSquareMeter; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-1.0).equals(this)) return DerivedUnits.KilogramPerMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Mole,-1.0).equals(this)) return DerivedUnits.JoulePerMole; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0,BaseUnits.Mole,-1.0).equals(this)) return DerivedUnits.JoulePerMoleKelvin; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0).equals(this)) return DerivedUnits.HenryPerMeter; if (fillUnitDimensions(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0).equals(this)) return DerivedUnits.FaradPerMeter; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) return DerivedUnits.Watt; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Radian,-2.0).equals(this))// return DerivedUnits.WattPerSteradian; if (fillUnitDimensions(BaseUnits.Radian,-2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this))// return DerivedUnits.WattPerSquareMeterSteradian; if (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) return DerivedUnits.WattPerSquareMeter; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.Pascal; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-2.0).equals(this)) return DerivedUnits.Ohm; if (fillUnitDimensions(BaseUnits.Radian,2.0).equals(this))// return DerivedUnits.Steradian; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.JoulePerKilogram; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.JoulePerKilogramKelvin; if (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.JoulePerKilogramKelvinPerPascal; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.JoulePerKilogramKelvinPerCubicMeter; if (fillUnitDimensions(BaseUnits.Kelvin,1.0,BaseUnits.Mole,1.0).equals(this)) return DerivedUnits.MoleKelvin; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.WattPerMeterKelvin; if (fillUnitDimensions(BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.SquareMeterKelvinPerWatt; if (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.KelvinPerWatt; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) return DerivedUnits.MeterKelvinPerWatt; if (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.NewtonPerKilogram; if (fillUnitDimensions(BaseUnits.Second,2.0).equals(this)) return DerivedUnits.SecondTimeSquared; if (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) return DerivedUnits.NewtonMeter; if (fillUnitDimensions(BaseUnits.Meter,3.0).equals(this)) return DerivedUnits.CubicMeter; if (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.CubicMeterPerKelvin; if (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.CubicMeterPerSecond; if (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) return DerivedUnits.JoulePerCubicMeterKelvin; if (fillUnitDimensions(BaseUnits.Bit,1.0, BaseUnits.Second,-1.0).equals(this)) return DerivedUnits.BitsPerSecond; return null; } public boolean isDerivedUnit(){ return (fillUnitDimensions(BaseUnits.Meter,2.0, BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0, BaseUnits.Second,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Mole,1.0, BaseUnits.Meter,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Second,-2.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Second,-1.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,2.0,BaseUnits.Meter,2.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,-1.0,BaseUnits.Mole,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Meter,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,1.0,BaseUnits.Ampere,1.0,BaseUnits.Mole,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Ampere,1.0,BaseUnits.Radian,-1.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Ampere,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,-1.0,BaseUnits.Second,1.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0,BaseUnits.Radian,1.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Mole,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,1.0,BaseUnits.Second,-4,BaseUnits.Ampere,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Candela,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,1.0,BaseUnits.Candela,1.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Ampere,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Ampere,1.0,BaseUnits.Radian,1.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Meter,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Mole,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0,BaseUnits.Mole,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Ampere,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-3.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,4.0,BaseUnits.Ampere,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,-2.0,BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Radian,-2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) // || (fillUnitDimensions(BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Ampere,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Radian,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kilogram,-1.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kelvin,1.0,BaseUnits.Mole,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-3.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-2.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,-1.0,BaseUnits.Second,3,BaseUnits.Kelvin,1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Second,2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,2.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,3,BaseUnits.Second,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Meter,-1.0,BaseUnits.Kilogram,1.0,BaseUnits.Second,-2.0,BaseUnits.Kelvin,-1.0).equals(this)) || (fillUnitDimensions(BaseUnits.Bit,1,BaseUnits.Second,-1.0).equals(this)) ; } public BaseUnits toBaseUnits() { if (new Unit(BaseUnits.Meter,1.0).equals(this)) return BaseUnits.Meter; if (new Unit(BaseUnits.Kilogram,1.0).equals(this)) return BaseUnits.Kilogram; if (new Unit(BaseUnits.Second,1.0).equals(this)) return BaseUnits.Second; if (new Unit(BaseUnits.Ampere,1.0).equals(this)) return BaseUnits.Ampere; if (new Unit(BaseUnits.Kelvin,1.0).equals(this)) return BaseUnits.Kelvin; if (new Unit(BaseUnits.Mole,1.0).equals(this)) return BaseUnits.Mole; if (new Unit(BaseUnits.Candela,1.0).equals(this)) return BaseUnits.Candela; if (new Unit(BaseUnits.Radian,1.0).equals(this)) return BaseUnits.Radian; if (new Unit(BaseUnits.Bit,1.0).equals(this)) return BaseUnits.Bit; if (new Unit(BaseUnits.Erlang,1.0).equals(this)) return BaseUnits.Erlang; if (new Unit(BaseUnits.Shannon,1.0).equals(this)) return BaseUnits.Shannon; if (new Unit(BaseUnits.Decibel,1.0).equals(this)) return BaseUnits.Decibel; return null; } public String name() { if (this.isDimensionless()) return ""; if (this.isBaseUnit()) return BaseUnitNames[this.toBaseUnits().ordinal()]; if (this.isDerivedUnit()) return DerivedUnitNames[this.toDerivedUnits().ordinal()]; String s=""; for (int i=0;i<dimensions.length;i++){ if (dimensions[i]!=0.0) { s+=BaseUnitNames[i]; if (dimensions[i]!=1.0) s+="^"+dimensions[i]; s+="*"; } }; return s.substring(0, s.length()-1); } public String symbol() { if (this.isDimensionless()) return ""; if (this.isBaseUnit()) return BaseUnitSymbols[this.toBaseUnits().ordinal()]; if (this.isDerivedUnit()) return DerivedUnitSymbols[this.toDerivedUnits().ordinal()]; String s=""; for (int i=0;i<dimensions.length;i++){ if (dimensions[i]!=0.0) { s+=BaseUnitSymbols[i]; if (dimensions[i]!=1.0) s+="^"+dimensions[i]; s+="*"; } }; return s.substring(0, s.length()-1); } public static String name(Unit u) { if (u.isDimensionless()) return ""; if (u.isBaseUnit()) return BaseUnitNames[u.toBaseUnits().ordinal()]; if (u.isDerivedUnit()) return BaseUnitNames[u.toDerivedUnits().ordinal()]; String s=""; for (int i=0;i<u.dimensions.length;i++){ if (u.dimensions[i]!=0.0) { s+=BaseUnitNames[i]; if (u.dimensions[i]!=1.0) s+="^"+u.dimensions[i]; s+="*"; } }; return s.substring(0, s.length()-1); } public static String symbol(Unit u) { if (u.isUnitless()) return ""; if (u.isBaseUnit()) return BaseUnitSymbols[u.toBaseUnits().ordinal()]; if (u.isDerivedUnit()) return BaseUnitSymbols[u.toDerivedUnits().ordinal()]; String s=""; for (int i=0;i<u.dimensions.length;i++){ if (u.dimensions[i]!=0.0) { s+=BaseUnitSymbols[i]; if (u.dimensions[i]!=1.0) s+="^"+u.dimensions[i]; s+="*"; } }; return s.substring(0, s.length()-1); } }
Markdown
UTF-8
414
2.671875
3
[]
no_license
--- layout: page title: Topics permalink: /topics/ --- <ul id="cat-list"> {% for category in site.categories reversed %} <li class="category"><h2>{{ category | first | upcase}}</h2> <ul> {% for posts in category %} {% for post in posts %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} {% endfor %} </ul> </li> {% endfor %} </ul>
Java
UTF-8
266
1.648438
2
[]
no_license
package by.bntu.kharaneka.enrolleedocfillingmvp.repository; import by.bntu.kharaneka.enrolleedocfillingmvp.entity.Address; import org.springframework.data.jpa.repository.JpaRepository; public interface AddressRepository extends JpaRepository<Address, Integer> { }
Markdown
UTF-8
666
3.40625
3
[]
no_license
```js class MyArray { constructor() { this.length = 0; this.data = {}; } get(index) { return this.data[index]; } push(item) { this.data[this.length] = item; ++this.length; return this.length; } pop() { const lastItem = this.data[this.length - 1]; delete this.data[this.length - 1]; --this.length; return lastItem; } delete(index) { const item = this.data[index]; this.shiftItems(index); --this.length; return item; } shiftItems(index) { for (let i = index; i < this.length - 1; ++i) { this.data[i] = this.data[i + 1]; } delete this.data[this.length - 1]; } } ```
Java
UTF-8
625
2.09375
2
[]
no_license
package com.pb.dashboard.monitoring.components.parameter; /** * Created by vlad * Date: 05.01.15_9:12 */ public enum MonitoringParam { COUNTRY("country"), COMPLEX("complex"), INTERFACE("interface"), METRIC("metric"), RANGE("range"), DATE("date"), DATE_FROM("from"), DATE_TO("to"), REGLAMENT("reglament"), CRITERION("criterion"), TYPE("type"); private final String name; MonitoringParam(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return name; } }
Python
UTF-8
3,709
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 ''' Cryptowat.ch API https://cryptowat.ch/docs/api https://api.cryptowat.ch/markets/gdax/btcusd/trades?limit=100 ''' import urllib.request, json, datetime, time from pathlib import Path from urllib.request import urlopen exchanges = [ 'bitfinex', 'gdax', #'bitstamp', #'kraken', #'gemini', #'cexio', #'btce', #'quoine', #'okcoin', #'bitsquare' ] pair = 'btcusd' limit = 0 since = 0 sleep_seconds = 60 * 60 * 1 # 4 hour print_new_lines = False def load_data(csv_file): print('loaded old data from csv file: ', end='') with open(csv_file, 'r') as f: lines = f.read().split('\n') print(len(lines)) return lines def request(url): global data print('downloading data') with urllib.request.urlopen(url) as url: data = json.loads(url.read().decode()) print('fetched data size: ',end='') return data['result'] def new_items(lines_old,lines_new): print('selecting new items') temp = [] if len(lines_old)-len(lines_new) < 0: go_back = 0 else: go_back = len(lines_old)-len(lines_new) for x in range(len(lines_old) - 1,go_back,-1): if lines_new[0] == lines_old[x]: findex = x - 1 for x in range(len(lines_old) - findex - 1,len(lines_new)): temp.append(lines_new[x]) break elif x == go_back + 1: temp = lines_new return temp ''' def new_items(lines_old,lines_new): print('selecting new items') #temp = list(set(lines_old[1:]).symmetric_difference(lines_new)) temp = [] item_last = -1 * len(lines_new) + -1 for x in lines_new: if x not in lines_old[item_last:]: temp.append(x) return temp''' def fetch(exchange): print(exchange) url = 'https://api.cryptowat.ch/markets/' + exchange + '/' + pair + '/trades?limit=' + str(limit) +'&since=' + str(since) try: print('fetching data') data = request(url) except Exception as e: data = None print('unable to fetch ' + exchange) return lines_fetched = [] for i in range(len(data)): line = '' for y in range(len(data[i])): if y == 0: line = str(data[i][y]) # format(price,'.3f') elif y == 1: line = line + ',' + str(data[i][y]) elif y == 2: line = line + ',' + pair + ',' + str(data[i][y]) elif y < len(data[i]): line = line + ',' + str('{0:f}'.format(data[i][3])) lines_fetched.append(line) print(len(lines_fetched)) # Read data csv_file = Path(Path(__file__).parents[0] / 'data' / 'trade', exchange + '-' + pair + '-trade.csv') # Write to file lines_old = load_data(csv_file) # Find new data lines_new = new_items(lines_old, lines_fetched) if print_new_lines == True: for line in lines_new: print(line) print('new order count: ' + str(len(lines_new))) # Write new lines to file print('writing to csv file') with open(csv_file, 'a') as f: for x in lines_new: f.write(str(x) + '\n') # Clear the memory del lines_fetched[:] del lines_old[:] del lines_new[:] print('---') def main(): while True: for x in exchanges: fetch(x) print('sleeping for ' + str(sleep_seconds) + ' seconds') print('---') time.sleep(sleep_seconds) if __name__ == '__main__': main() ''' Exchanges that are not supported quadrigacx bitMEX binance bithumb bittrex poloniex bitflyer bitvc btc-china huobi luno qryptos'''
C
UTF-8
1,296
4.5625
5
[]
no_license
//Pandigital multiples-Problem 38 // Pandigital - numero que contém pelo menos um de cada dígito em sua base exemplo: 1749208365. #include <stdio.h> int pandigital(int n) //Função que verifica se é numero pandigital a partir da solução que vai receber. { int numeros[9] = {0}; // Array com espaço para um numero de 9 digitos como é pedido pelo problema que contem zero. int holder = n; while (n) { int digito = n % 10; if (!digito || numeros[digito - 1]) // || ou return 0; numeros[digito - 1] = digito; n /= 10; } return holder; // Holder tem guardado o número original e devolve esse número caso seja pandigital. } int concat_digitos(int a, int b) // Função que realiza a concatonação. { int dez = 10; while (b > dez) dez *= 10; return a * dez + b; } int main() { int solucao = 0; for (int i = 9876; i > 9182; --i) { // Números que vão ser concatonados e vão passar a ser a solução. solucao = concat_digitos(i, 2 * i); if (pandigital(solucao)) { // Se a solução for pandigital passa para o print. break; } } printf("O maior número pandigital de 9 dígitos que pode ser formado como o produto concatenado de um número inteiro com (1,2, ..., n ) onde n > 1 é: %d\n", solucao); return 0; }
Python
UTF-8
1,233
2.734375
3
[]
no_license
import json from urllib.parse import unquote def decode(value): while "+" in value: value = value.replace("+", " ") return unquote(value) def form_body_to_json(body): elements = body.split("&") data = dict() for element in elements: items = element.split("=") name = decode(items[0]) value = decode(items[1]) if "[]" in name: name = name.replace("[]", "") if name not in data: data[name] = list() data[name].append(value) else: data[name] = value return data def decode_request(request): return json.loads(request.content.decode('utf-8')) def handle_error_response(error): message = "" for key in error: message += key + ": " + error[key][0] return message def get_session_variable(request, variable_name): var = request.session[variable_name] del request.session[variable_name] return var def get_message_or_error(request): if "message" in request.session: return {"message": get_session_variable(request, "message")} elif "error" in request.session: return {"error": get_session_variable(request, "error")} return None
Java
UTF-8
2,065
2.96875
3
[ "MIT" ]
permissive
package com.icroque.core.commands; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * Created by Rémi on 09/01/2016. */ public class WeatherCommand extends Command { public WeatherCommand() { super("weather", "core.weather", true); } @Override public void command(CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) { Player player = (Player) sender; if(label.equalsIgnoreCase("sun")) { player.getWorld().setStorm(false); player.getWorld().setThundering(false); player.sendMessage("§f[§aInformation§f] §aLe temps a été mise à jour."); } else if(label.equalsIgnoreCase("storm") || label.equalsIgnoreCase("rain")) { player.getWorld().setStorm(true); player.getWorld().setThundering(true); player.sendMessage("§f[§aInformation§f] §aLe temps a été mise à jour."); } else if(label.equalsIgnoreCase("weather") || label.equalsIgnoreCase("wea")) { if(args.length > 0) { if(args[0].equalsIgnoreCase("sun") || args[0].equalsIgnoreCase("clear")) { player.getWorld().setStorm(false); player.getWorld().setThundering(false); player.sendMessage("§f[§aInformation§f] §aLe temps a été mise à jour."); } else if(args[0].equalsIgnoreCase("storm") || args[0].equalsIgnoreCase("rain")) { player.getWorld().setStorm(true); player.getWorld().setThundering(true); player.sendMessage("§f[§aInformation§f] §aLe temps a été mise à jour."); } else { help(sender); } } else { help(sender); } } } private void help(CommandSender sender) { sender.sendMessage("§f[§cErreur§f] §cUsage: /weather <storm:rain:sun:clear>"); } }
Python
UTF-8
261
3.65625
4
[]
no_license
#3번문제 / C111061 박서연 def reverseList2(n): lst2 = list(n) lst2.remove(max(lst2)) lst2.reverse() return lst2 def main(): lst = [20, 60, 40, 10, 50] print(reverseList2(lst)) print(lst) main()
Java
UTF-8
291
1.851563
2
[]
no_license
package com.tsb.dao; import com.tsb.model.Organization; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IOrganizationDao { void insertOrg(Organization organization); List<Organization> selectOrg(Organization organization); }
JavaScript
UTF-8
68
2.578125
3
[]
no_license
export const abs = (num) => { return num >= 0 ? num : - num; };
Rust
UTF-8
699
2.78125
3
[ "Apache-2.0" ]
permissive
use std::process::exit; fn press_enter() { // On windows, where installation happens in a console that may have opened just for this // purpose, give the user an opportunity to see the error before the window closes. if cfg!(windows) && atty::is(atty::Stream::Stdin) { println!(); println!("Press the Enter key to continue."); use std::io::BufRead; let stdin = std::io::stdin(); let stdin = stdin.lock(); let mut lines = stdin.lines(); lines.next(); } } fn main() { solana_install::main_init().unwrap_or_else(|err| { println!("Error: {err}"); press_enter(); exit(1); }); press_enter(); }
Java
UTF-8
504
2.921875
3
[]
no_license
package raf; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; /** 从文件中读取文本内容 */ public class ReadStringDemo { public static void main(String[] args) throws IOException { RandomAccessFile raf = new RandomAccessFile("note.txt","rw"); byte[] date = new byte[(int)raf.length()]; raf.read(date); String str = new String(date,"UTF-8"); System.out.println(str); raf.close(); } }
Swift
UTF-8
915
2.625
3
[]
no_license
// // FighterKnockbackState.swift // spritekit-plataform // // Created by Thiago Valente on 11/03/19. // Copyright © 2019 Bruno Rocha. All rights reserved. // import SpriteKit import GameplayKit class FighterKnockbackState: GKState { var node: SKSpriteNode! var stateAtlasTextures: [SKTexture] = [] init(withNode node: SKSpriteNode) { self.node = node } override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass is FighterIdleState.Type || stateClass is FighterDieState.Type } override func didEnter(from previousState: GKState?) { let knockbackAction = SKAction.animate(with: self.stateAtlasTextures, timePerFrame: 0.15, resize: true, restore: true) node.run(knockbackAction, completion: { self.node.physicsBody?.velocity.dx = 0 self.stateMachine?.enter(FighterIdleState.self) }) } }
TypeScript
UTF-8
1,737
2.515625
3
[ "MIT" ]
permissive
import { Loader } from './loader'; import { Indexer } from './indexer'; import * as shell from './shell'; import { HttpRequest } from './http-request'; import * as app from './app'; export class Api { public loader: Loader; private slug = ['@', '\\', '/', '>', '?', ':']; constructor() { const _context = { indexer: new Indexer(), shell, request: new HttpRequest(), app, } this.loader = new Loader(_context); } public search(query: string) { return new Promise(async (resolve, reject) => { const keys = Object.keys(this.loader.plugins); const slug = query.charAt(0); let result = []; if (this.slug.includes(slug) && this.loader.plugins.hasOwnProperty(slug)) { query = query.substr(1); result = await this.loader.plugins[slug].search(query); } else { for (let i = 0; i < keys.length; i++) { if (typeof this.loader.plugins[keys[i]].search !== 'function') { result = [...result, ...this.loader.plugins[keys[i]].context.indexer.search(query)]; } else { result = [...result, ...await this.loader.plugins[keys[i]].search(query)]; } if (Array.isArray(result) && result.length >= 7) { break; } } } if (Array.isArray(result)) { result = result.slice(0, 7); result.forEach((v, k) => { v.id = k + 1; v.primaryText = v.primaryText.charAt(0).toUpperCase() + v.primaryText.slice(1); }) resolve(result); } }); } public execute(item) { this.loader.plugins[item.plugin].execute(item.url); } }
Python
UTF-8
117
3.46875
3
[ "MIT" ]
permissive
# 入力 S = input() # 文字列比較で判定 ans = 'Heisei' if S <= '2019/04/30' else 'TBD' # 出力 print(ans)
Python
UTF-8
1,109
3.546875
4
[]
no_license
import time from rpi_ws281x import * # 导入包 LED_COUNT = 60 # 激活的LED灯数量 LED_PIN = 18 # 灯带端口号 strip = PixelStrip(LED_COUNT, LED_PIN) # 创建灯带对象 strip.begin() # 灯带初始化 def colorWipe(strip, color, wait_ms=50): """将灯带全部刷成同一颜色""" for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(wait_ms / 1000.0) def theaterChase(strip, color, wait_ms=50, iterations=10): for j in range(iterations): # 重复次数,迭代次数 for q in range(3): # 每3个点1组 for i in range(0, strip.numPixels(), 3): # 每隔3点处理,亮 strip.setPixelColor(i + q, color) # 设置1点的颜色 strip.show() time.sleep(wait_ms / 1000.0) for i in range(0, strip.numPixels(), 3): # 每隔3点处理,灭 strip.setPixelColor(i + q, 0) # 调用函数 theaterChase(strip, Color(127, 0, 0), 200, 30) # 红色彩灯 colorWipe(strip, Color(0, 0, 0), 10) # 关闭
Java
UTF-8
2,017
3.34375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tempserver2; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TempServer2 { private static final int porta = 12346; public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(porta); System.out.println("Server socket criado... "); while(true){ System.out.println("Aguardando conexões... "); Socket socket = serverSocket.accept(); System.out.println("Conectou... "); new ServerSocketThread(socket).start(); } } public static class ServerSocketThread extends Thread{ private final Socket socket; public ServerSocketThread(Socket socket){ this.socket = socket; } @Override public void run(){ super.run(); try{ DataOutputStream out = new DataOutputStream(socket.getOutputStream()); DataInputStream inT = new DataInputStream(socket.getInputStream()); DataInputStream inE = new DataInputStream(socket.getInputStream()); float tempI = inT.readFloat(); float tempO = 0; if(inE.readInt() == 1) tempO = (float)(tempI * 1.8 + 32); else tempO = (float)(tempI - 32 / 1.8); out.writeFloat(tempO); out.flush(); out.close(); inT.close(); inE.close(); socket.close(); }catch(IOException e){ e.printStackTrace(); } } } }
Python
UTF-8
801
3.859375
4
[]
no_license
"""CP1404 Practical - Guitars prac""" from prac_06.guitar import Guitar def main(): guitars = [] guitars.append(Guitar("Gibson L-5 CES", 1922, 16035.40)) guitars.append(Guitar("Line 6 JTV-59", 2010, 1512.9)) name = input("Name: ") while name.strip() != "": year = int(input("Year: ")) cost = float(input("Cost: ")) guitar = Guitar(name, year, cost) guitars.append(guitar) print(guitar) name = input("Name: ") for idx, guitar in enumerate(guitars, 1): #print("Guitar {}: {}".format(idx, guitar)) print("Guitar {}: {:>20} ({}), worth ${:10,.2f}{}".format(idx, guitar.name, guitar.year, guitar.cost, "(vintage)" if guitar.is_vintage() else "")) #print("{guitar}".format(guitar=guitar)) main()
Ruby
UTF-8
2,880
2.65625
3
[ "MIT" ]
permissive
gem 'minitest' require 'minitest/autorun' require 'exits/rules' class SomeController; end; class User; end; describe Exits::Rules do def setup @rules = Exits::Rules.new end describe Exits::Rules::Model do def setup @rule = Exits::Rules::Model.new end it 'should not authorize if no rules have been set' do assert !@rule.authorized?(:show), "Shouldn't authorize :show" end it 'should be able to allow an action' do @rule.allow(:show) assert @rule.authorized?(:show), "Couldn't authorize :show" end it 'should make sure actions are unique' do @rule.allow(:show, :show) assert @rule.instance_variable_get("@actions").size == 1, "Should only be 1 instance of :show" end it 'should only allow default route resources' do @rule.allow(:resources) assert @rule.authorized?(:show), "Couldn't authorize :show" assert !@rule.authorized?(:another_action), "Shouldn't authorize :another_action" end it 'should make a union of every call to Exits::Rules::Model#allow' do @rule.allow(:show) @rule.allow(:show, :edit) actions = @rule.instance_variable_get("@actions") assert_equal [:show, :edit], actions, "Should only be 2 actions registered" end it 'should raise an error if :all is set with other actions' do assert_raises Exits::Rules::ConfusingRulesError do @rule.allow(:show) @rule.allow(:all) end end it 'should authorize any action if :all is set' do @rule.allow(:all) assert @rule.authorized?(:show), "Should authorize :show when :all is set" end end describe Exits::Rules::Controller do def setup @rule = Exits::Rules::Controller.new end it 'should not authorize if no rules have been set' do assert !@rule.authorized?(User, :show), "Shouldn't authorize User if there's no rule" end it 'should be able to add a rule & authorize' do @rule[User] = :show, :edit assert @rule.authorized?(User, :show), "Should authorize :show for User" end end it 'should be able to add rules' do @rules.add SomeController, User, [:show] controllers = @rules.instance_variable_get("@controllers") assert controllers.has_key?(SomeController), "No rules for #{SomeController.name}" assert !controllers[SomeController][User].nil?, "Couldn't add a rule for #{User.name}" end it 'should authorize a user matching the rule' do @rules.add SomeController, User, [:show] assert @rules.authorized?(SomeController, User, :show), "Couldn't authorize User in SomeController for :show" end it 'should prohibit a user accessing an undefined action' do @rules.add SomeController, User, [:show] assert !@rules.authorized?(SomeController, User, :edit), "Shouldn't authorize User in SomeController for :edit" end end
Markdown
UTF-8
2,373
3.5
4
[]
no_license
# Random Word Generator Takes a list of sample words, generates a frequency table for the next letter given the previous n characters, and makes words based on that frequency table. ## Usage Create a new generator object. Pass either a preset name or a custom settings object into the constructor. Then, use the `generateWord` function. Example using preset: ``` const AnduRandom = require("andu-random"); var generator = new AnduRandom("fantasyName"); generator.generateWord(); ``` Example using custom settings object: ``` const AnduRandom = require("andu-random"); var generatorOptions = { "wordLists": [{ "fileName": "usmalefirst", "weight": 1 }, { "fileName": "usfemalefirst", "weight": 2 }], "depth": 2, "lengthSoftFloor": 4, "lengthSoftCap": 5, "maxLength": 15, "allowListWords": false }; var generator = new AnduRandom(generatorOptions); generator.generateWord(); ``` ## Presets * dictionary * firstName * maleName * femaleName * lastName * fantasyName ## Options * `wordLists` Array of word data files to use, with optional weighting. See below for included word data files. * `depth` Number of previous characters to look at to determine odds of next character. Lower numbers make it more random, higher numbers generate large chunks of existing words. A depth of 3 seems to be best, maybe 2 if the word list is short. * `minLength` Minimum word length. Default is 1. * `maxLength` Maxmimum word length. Default is 1000. * `lengthSoftFloor` Decreases the chance of getting words shorter than this length. Effect increases as the word length gets closer to `minLength`. * `lengthSoftCap` Decrease the chance of getting words longer than this length. Effect increases as the word length gets closer to `maxLength`. You need to set a reasonable `maxLength` if you want this to work properly. * `allowListWords` Whether to allow words on the word data files to be randomly generated. ## Word data files * `bnc` British National Corpus, downloaded from http://number27.org/assets/misc/words.txt * `usmalefirst` Male first names from 1990 US census * `usfemalefirst` Female first names from 1990 US census * `uslast` Last names from 1990 US census * `lotr` LOTR character list from https://lotr.fandom.com/wiki/Category:Characters, last names and first names combined * `dnd` Names from various DnD 5e books as listed in race descriptions
Java
UTF-8
1,715
2.03125
2
[]
no_license
package com.bpwizard.gateway.web.filter; import com.bpwizard.gateway.plugin.api.result.GatewayResultEnum; import com.bpwizard.gateway.plugin.base.utils.GatewayResultWrap; import com.bpwizard.gateway.plugin.base.utils.WebFluxResultUtils; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import com.bpwizard.gateway.web.config.GatewayConfig; import reactor.core.publisher.Mono; /** * this is visit time verify filter. * @deprecated do not use */ @Deprecated public class TimeWebFilter extends AbstractWebFilter { private GatewayConfig gatewayConfig; public TimeWebFilter(final GatewayConfig gatewayConfig) { this.gatewayConfig = gatewayConfig; } @Override protected Mono<Boolean> doFilter(final ServerWebExchange exchange, final WebFilterChain chain) { /* final LocalDateTime start = requestDTO.getStartDateTime(); final LocalDateTime now = LocalDateTime.now(); final long between = DateUtils.acquireMinutesBetween(start, now); if (between < gatewayConfig.getFilterTime()) { return Mono.just(true); }*/ return Mono.just(true); } @Override protected Mono<Void> doDenyResponse(final ServerWebExchange exchange) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.REQUEST_TIMEOUT); Object error = GatewayResultWrap.error(GatewayResultEnum.TIME_ERROR.getCode(), GatewayResultEnum.TIME_ERROR.getMsg(), null); return WebFluxResultUtils.result(exchange, error); } }
C
UTF-8
2,142
3.84375
4
[]
no_license
/*AUTHOR : Sayantan Banerjee (2018 IMT - 093)*/ #include<stdio.h> #include<stdlib.h> #include<malloc.h> struct node{ int val; struct node *next; }*front=NULL,*rear=NULL; struct node2{ int val; struct node2 *next; }*top=NULL; int PUSH(int value) { struct node2 *current=(struct node2*)malloc(sizeof(struct node2)); current->val=value; if(top==NULL) { top=current; current->next=NULL; } else { current->next=top; top=current; } return 0; } int POP() { struct node2 *temp=top; if(top==NULL) { return 0; } else { top=top->next; } int a= temp->val; free(temp); return a; } int insert(int value) { struct node *current=(struct node*)malloc(sizeof(struct node)); current->val=value; current->next=NULL; if(rear==NULL) { front=current; rear=current; } else { rear->next=current; rear=current; } return 0; } int Delete() { struct node *temp=front; if(front==NULL) { printf("\nQueue is empty!\n"); return 0; } else if(rear==front) { rear=NULL; front=NULL; } else { front=front->next; } free(temp); } void Traverse() { struct node *temp=front; if(front==NULL) { printf("\nQueue is empty!\n"); } else { printf("\nQueue displayed is:\n"); while(temp!=NULL) { printf(" %d -> ",temp->val); temp=temp->next; } printf("NULL\n"); } } void REVERSE() { struct node *temp=front; if(front==NULL) { printf("\nQueue is empty!\n"); } else { printf("\nQueue is reversed!\n"); while(temp!=NULL) { PUSH(temp->val); Delete(); temp=front; } struct node2 *temp2=top; while(temp2!=NULL) { int a=POP(); insert(a); temp2=top; } } } int main() { int n,value; while(1) { printf("\nEnter 1 for insertion\nEnter 2 for delete\nEnter 3 for traverse\nEnter 4 for reverse queue\nEnter 5 for exit "); scanf("%d",&n); switch(n) { case 1: printf("\nEnter data : "); scanf("%d", &value); insert(value); break; case 2: Delete(); break; case 3: Traverse(); break; case 4: REVERSE(); break; case 5: exit(0); break; default: printf("\nINVALID INPUT!"); } } return 0; }
Shell
UTF-8
2,185
3.1875
3
[]
no_license
#!/bin/bash set -u set -e BLUE='\033[0;34m' NC='\033[0m' # No Color echo -e "${BLUE}Updating dependencies${NC} " if [ ! -d crux ]; then git clone https://github.com/blk-io/crux.git else cd crux && git pull && cd .. fi if [ ! -d blk-explorer-free ]; then git clone https://github.com/blk-io/epirus-free.git else cd blk-explorer-free && git pull && cd .. fi echo -e "${BLUE}Starting 4 node Quorum network${NC} " docker-compose -f crux/docker/quorum-crux/docker-compose.yaml up -d until $(curl --output /dev/null --silent --head --fail http://localhost:22001); do printf "${BLUE}\xE2\x97\x88${NC}" sleep 2 done echo -e "${BLUE}\xE2\x97\x88 done${NC}" echo -e "${BLUE}Starting the Blockchain Explorer ${NC}" NODE_ENDPOINT=http://localhost:22001 docker-compose -f blk-explorer-free/docker-compose.yaml up -d until $(curl --output /dev/null --silent --head --fail http://localhost:8081); do printf "${BLUE}\xE2\x97\x88${NC}" sleep 2 done echo -e "${BLUE}\xE2\x97\x88 backend started${NC}" until $(curl --output /dev/null --silent --head --fail http://localhost:5000); do printf "${BLUE}\xE2\x97\x88${NC}" sleep 2 done echo -e "${BLUE}\xE2\x97\x88 front-end started${NC}" echo -e "${BLUE}Opening Blockchain Explorer at http://localhost:5000${NC} " printf "${BLUE} ███████╗██████╗ ██╗██████╗ ██╗ ██╗███████╗ ██╔════╝██╔══██╗██║██╔══██╗██║ ██║██╔════╝ █████╗ ██████╔╝██║██████╔╝██║ ██║███████╗ ██╔══╝ ██╔═══╝ ██║██╔══██╗██║ ██║╚════██║ ███████╗██║ ██║██║ ██║╚██████╔╝███████║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝ by blk.io (hi@blk.io) ${NC}" echo -e "\n${BLUE}Platform started successfully, to stop run: ./stop.sh${NC} " python -mwebbrowser "http://localhost:5000"
TypeScript
UTF-8
755
2.671875
3
[]
no_license
it("maps from one shape to another", () => { const original = { company: { devs: [ { firstname: "Webber", lastname: "Wang", }, { firstname: "Vien", lastname: "Nguyen", }, ], }, info: [ { key: "user.address.number", value: "1200", }, { key: "user.address.street", value: "Park ave.", }, ], }; const expected = { devs: [ { firstname: "Webber", lastname: "Wang", }, { firstname: "Vien", lastname: "Nguyen", }, ], user: { address: { number: "1200", street: "Park ave." } }, }; expect(original).toStrictEqual(expected); });
Shell
UTF-8
1,692
2.65625
3
[]
no_license
#!/bin/sh #@@example acy(300) #@@purpose Generate axial lead through-hole component #@@desc Generate axial lead through-hole component with 2 pins (typical use: resistor) #@@params spacing,type,pol,dia #@@param:spacing spacing between the two pins #@@dim:spacing #@@param:type silk symbol type #@@enum:type:block eu-style block resistor symbol #@@enum:type:endcap block resistor with caps on the ends #@@enum:type:zigzag us-style zigzag resistor symbol #@@enum:type:line a single line (e.g. for jumper wires) #@@enum:type:standing vertically aligned, body standing on pin 1, pin 2 bent back #@@enum:type:coil wavy coil symbol #@@enum:type:core wavy coil symbol with a parallel line #@@enum:type:core2 wavy coil symbol with two parallel lines #@@optional:type #@@default:type block #@@preview_args:type 300 #@@param:pol how to mark polarity #@@enum:pol:none no marking #@@enum:pol:sign + and - signs; pin 1 is + #@@enum:pol:bar bar next to pin 1 #@@enum:pol:dot dot next to pin 1 #@@optional:pol #@@default:pol none #@@preview_args:pol 300 #@@param:dia body diameter - affects silk size #@@dim:dia #@@optional:dia #@@default:dia spacing/6 #@@param:wiper silk symbol wiper type #@@enum:wiper:none no wiper #@@enum:wiper:parrow perpendicular arrow, pointing inwards #@@enum:wiper:aarrow angled arrow, pointing outwards #@@enum:wiper:looparrow arrow starting at pin 2 looping back to point inwards on the body #@@enum:wiper:thermistor wiper of a thermistor symbol #@@optional:wiper #@@default:wiper none #@@preview_args:wiper 400 #@@thumbsize 2 #@@include common_subc.awk awk -f `dirname $0`/common_subc.awk -f `dirname $0`/acy.awk -v "args=$*" -v gen=`basename $0` -v "genfull=$0"
Java
UTF-8
1,335
3.390625
3
[ "MIT" ]
permissive
package jsong00505.study.test.nile; import java.util.ArrayList; import java.util.Arrays; public class HackerArtOne { public static void main(String[] args) { int num = 100; // define list of zero holes ArrayList zeroHoles = new ArrayList(); zeroHoles.add(1); zeroHoles.add(2); zeroHoles.add(3); zeroHoles.add(5); zeroHoles.add(7); // define list of one hole ArrayList oneHoles = new ArrayList(); oneHoles.add(0); oneHoles.add(4); oneHoles.add(6); oneHoles.add(9); // define list of two holes ArrayList twoHoles = new ArrayList(); twoHoles.add(8); // int digitPosition = 10; int tempNum = num; int tempOneDigit = 0; int sum = 0; while(tempNum > 0){ // get the last digit of the num tempOneDigit = tempNum % 10; if(zeroHoles.contains(tempOneDigit)) { // zero means nothing, but I declare this for sure tempNum /= 10; } else if(oneHoles.contains(tempOneDigit)) { sum += 1; tempNum /= 10; } else if(twoHoles.contains(tempOneDigit)) { sum += 2; tempNum /= 10; } } } }
Java
UTF-8
1,380
3.140625
3
[]
no_license
package model; public class TesterTest { public String[] test1(Tester tester){ //自分が親の場合の計算 //ロン上がりとツモ上がりの2パターンを配列pointsに格納 String[] points = new String[2]; int oyako = Integer.parseInt(tester.getFu()); int fu = Integer.parseInt(tester.getFu()); int han = Integer.parseInt(tester.getHan()); if(tester.getOyako().equals("1")){ //親の時 switch(tester.getHan()){ case "1": //1翻の場合 if(fu == 30){ points[0] = "1500"; points[1] = "500"; }else if(fu == 40){ points[0] = "2000"; points[1] = "700"; }else if(tester.getFu().equals("50")){ points[0] = "2400"; points[1] = "800"; }else if(tester.getFu().equals("60")){ points[0] = "2900"; points[1] = "1000"; }else if(tester.getFu().equals("70")){ points[0] = "3400"; points[1] = "1200"; }else if(tester.getFu().equals("80")){ points[0] = "3900"; points[1] = "1300"; }else if(tester.getFu().equals("90")){ points[0] = "4400"; points[1] = "1500"; }else if(tester.getFu().equals("100")){ points[0] = "4800"; points[1] = "1600"; }else if(tester.getFu().equals("110")){ points[0] = "5300"; points[1] = "1800"; } } } return points; } }
Java
UTF-8
800
2.921875
3
[]
no_license
package pe.com.hatunsol.hatunsolmovil.util; import java.io.File; public class FileCache { public static boolean clearCache(File dir) { try { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (String child : children) { boolean success = clearCache(new File(dir, child)); if (!success) { return false; } } return dir.delete(); } else if(dir!= null && dir.isFile()) { return dir.delete(); } else { return false; } } catch (NullPointerException e) { e.printStackTrace(); return false; } } }
JavaScript
UTF-8
847
2.578125
3
[]
no_license
import React, { useEffect, useState } from 'react' import Square from './Square' const Plateau = ({ size, positionX, positionY, direction }) => { const [table, setTable] = useState(null) useEffect(() => { setTable(generateTable()) }, [size, positionX, positionY, direction]) const renderRow = (y) => { let tiles = [] for (let x = 0; x < size; x++) { let hasRover = x === positionX && y === positionY tiles.push( <Square key={[x, y]} direction={direction} hasRover={hasRover} /> ) } return <tr key={y}>{tiles}</tr> } const generateTable = () => { let rows = [] for (let y = size - 1; y >= 0; y--) { rows.push(renderRow(y)) } return rows } return ( <div> <table> <tbody>{table}</tbody> </table> </div> ) } export default Plateau
Python
UTF-8
5,342
3.59375
4
[]
no_license
''' 尽量用ProcessPoolExecutor进行多进程编程 ''' import multiprocessing as mp import threading as td import time,os # def worker(sec,name): # for i in range(3): # time.sleep(sec) # print(name) # # if __name__=='__main__': # windows下多进程必须在主函数中运行 # p=mp.Process(target=worker,args=(0.3,),kwargs={'name':'Air'},name="Process1") # p.start() # print("获取进程名称",p.name) # print("获取进程PID",p.pid) # print("进程alive状况",p.is_alive()) # p.join() # print() ''' # 存储进程输出Queue (效率一般,广泛灵活) # Queue的功能是将每个核或线程的运算结果放在队里中, 等到每个线程或核运行完毕后再从队列中取出结果, # 继续加载运算。原因很简单, 多线程调用的函数不能有返回值, 所以使用Queue存储多个线程运算的结果 # ''' # def job(q): # q.put(1) #放入数据 # # if __name__=='__main__': # q = mp.Queue() # p1 = mp.Process(target=job,args=(q,)) # p2 = mp.Process(target=job,args=(q,)) # p1.start() # p2.start() # p1.join() # p2.join() # res1 = q.get() # res2 = q.get() # print(res1+res2) ''' 进程池Pool 进程池Pool()和map(): 有了池子之后,就可以让池子对应某一个函数,我们向池子里丢数据,池子就会返回函数返回的值。 Pool和之前的Process的不同点是丢向Pool的函数有返回值,而Process的没有返回值。 自定义核数量: Pool默认大小是CPU的核数,我们也可以通过在Pool中传入processes参数即可自定义需要的核数量 apply_async(): apply_async()中只能传递一个值,它只会放入一个核进行运算,但是传入值时要注意是可迭代的, 所以在传入值后需要加逗号, 同时需要用get()方法获取返回值 apply(): apply()和apply_async()一样,但没有返回值 总结: Pool默认调用是CPU的核数,传入processes参数可自定义CPU核数 map() 放入迭代参数,返回多个结果 apply_async()只能放入一组参数,并返回一个结果,如果想得到map()的效果需要通过迭代 ''' # def job(x): # return x*x # def multicore(): # pool = mp.Pool() # # res = pool.map(job, range(10)) # print(res) # # res = pool.apply_async(job, (2,)) # 只能传一个值 # print(res.get()) # 用get获得结果 # # multi_res = [pool.apply_async(job, (i,)) for i in range(10)] # 迭代器,i=0时apply一次,i=1时apply一次等等 # print([res.get() for res in multi_res]) # 从迭代器中取出 # # pool.close() # pool.join() # if __name__ == '__main__': # multicore() ''' 共享内存shared memory (效率较高,需要注意进行互斥操作) Shared Value: 我们可以通过使用Value数据存储在一个共享的内存表中。 Shared Array: 在Python的mutiprocessing中,有还有一个Array类,可以和共享内存交互,来实现在进程之间共享数据。 ''' # value1 = mp.Value('i', 0) # value2 = mp.Value('d', 3.14) # # array = mp.Array('i', [1, 2, 3, 4]) ''' 线程通讯:Pipe (效率一般,多用于父子进程)(只能用于两个进程间通信) fd1,fd2=Pipe(duplex=True) 功能:创建管道 参数:默认表示双向管道,如果设置为False则为单向管道 返回值:表示管道的两端,如果是双向管道 都可以读写,如果是单向管道 则fd1只读 fd2只写 fd.recv() 功能:从管道读取信息 返回值:读取到的内容 *如果管道为空则阻塞 fd.send(data) 功能:向管道写入内容 参数:要写入的内容 *可以发送Python数据类型 ''' ''' 进程锁Lock ''' # def job(v, num, l): # l.acquire() # 锁住 # for _ in range(5): # time.sleep(0.1) # v.value += num # 获取共享内存 # print(v.value) # l.release() # 释放 # # def multicore(): # l = mp.Lock() # 定义一个进程锁 # v = mp.Value('i', 0) # 定义共享内存 # p1 = mp.Process(target=job, args=(v,1,l)) # 需要将lock传入 # p2 = mp.Process(target=job, args=(v,3,l)) # p1.start() # p2.start() # p1.join() # p2.join() # # if __name__ == '__main__': # multicore() ''' Semaphore() sem=Semaphore(num) 功能:创建信号量 参数:信号量初始值 返回:信号量对象 sem.acquire() 将信号量数量减一 信号量为0会阻塞 sem.release() 将信号量数量加一 sem.get_value() 获取当前信号量的值 ''' # #创建信号量 # sem=mp.Semaphore(3) # def fun(): # print("进程%d等待信号量" % os.getpid()) # sem.acquire() #信号量减一 # print("进程%d消耗信号量" % os.getpid()) # time.sleep(3) # sem.release() #信号量加一 # print("进程%d添加信号量" % os.getpid()) # if __name__ == '__main__': # jobs=[] # for i in range(4): # p=mp.Process(target=fun) # jobs.append(p) # p.start() # for i in jobs: # i.join() # print(sem.get_value())
Java
UTF-8
2,481
2.21875
2
[]
no_license
package com.example.petmania.model; import java.io.Serializable; public class Doctors implements Serializable { private int id,br_id,dr_show_no; private String dr_email,dr_name,dr_phone,dr_pass,dr_desc,dr_speciality,dr_fee,error_msg; public Doctors() { } public Doctors(int id, int br_id, int dr_show_no, String dr_email, String dr_name, String dr_phone, String dr_pass, String dr_desc, String dr_speciality, String dr_fee,String error_msg) { this.id = id; this.br_id = br_id; this.dr_show_no = dr_show_no; this.dr_email = dr_email; this.dr_name = dr_name; this.dr_phone = dr_phone; this.dr_pass = dr_pass; this.dr_desc = dr_desc; this.dr_speciality = dr_speciality; this.dr_fee = dr_fee; this.error_msg = error_msg; } public String getError_msg() { return error_msg; } public void setError_msg(String error_msg) { this.error_msg = error_msg; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getBr_id() { return br_id; } public void setBr_id(int br_id) { this.br_id = br_id; } public int getDr_show_no() { return dr_show_no; } public void setDr_show_no(int dr_show_no) { this.dr_show_no = dr_show_no; } public String getDr_email() { return dr_email; } public void setDr_email(String dr_email) { this.dr_email = dr_email; } public String getDr_name() { return dr_name; } public void setDr_name(String dr_name) { this.dr_name = dr_name; } public String getDr_phone() { return dr_phone; } public void setDr_phone(String dr_phone) { this.dr_phone = dr_phone; } public String getDr_pass() { return dr_pass; } public void setDr_pass(String dr_pass) { this.dr_pass = dr_pass; } public String getDr_desc() { return dr_desc; } public void setDr_desc(String dr_desc) { this.dr_desc = dr_desc; } public String getDr_speciality() { return dr_speciality; } public void setDr_speciality(String dr_speciality) { this.dr_speciality = dr_speciality; } public String getDr_fee() { return dr_fee; } public void setDr_fee(String dr_fee) { this.dr_fee = dr_fee; } }
Markdown
UTF-8
1,777
3.015625
3
[]
no_license
### Explore Bike Share Data Use Python to explore data related to bike share systems for three major cities in the United States—Chicago, New York City, and Washington. ### Description Over the past decade, bicycle-sharing systems have been growing in number and popularity in cities across the world. Bicycle-sharing systems allow users to rent bicycles on a very short-term basis for a price. This allows people to borrow a bike from point A and return it at point B, though they can also return it to the same location if they'd like to just go for a ride. Regardless, each bike can serve several users per day. Thanks to the rise in information technologies, it is easy for a user of the system to access a dock within the system to unlock or return bicycles. These technologies also provide a wealth of data that can be used to explore how these bike-sharing systems are used. A bike share system provider for many major cities in the United States. The ```bikeshare.py``` script is used to filter data based on to explore data related to bike share systems for three major cities in the United States—Chicago, New York City, and Washington. The script will import the data and answer interesting questions about it by computing descriptive statistics. [bikeshare.py]: https://github.com/SriKaratalapu/pdsnd_github/blob/master/bikeshare.py [readme.txt]: https://github.com/SriKaratalapu/pdsnd_github/blob/documentation/readme.txt ### Details * [bikeshare.py] : Interactive command-line script that uses input of city to read the respective csv file. The script also request for details regarding the month and day for analyzing data on frequency based on user, station, day and month. - [readme.txt] : Show all references of URL used in completing the project.
C++
UTF-8
377
3.34375
3
[]
no_license
#include<iostream> #include<ostream> #include<cmath> using namespace std; double power(double m,int n); int main() { int n=2; double raised ,m; cout<<"\nEnter the value of m:"; cin>>m; cout<<"\nEnter the value of n:"; cin>>n; raised=power(m,n); cout<<"m raised to power n is="<<raised <<endl; } double power(double m, int n) { double x; x=pow(m,n); return x; }
C++
UTF-8
748
2.53125
3
[]
no_license
#include "user.h" namespace mmp { user_signup_def::user_signup_def():m_gender(gender_unknown) { } user_signup_def::~user_signup_def() { } user_signin_def::user_signin_def() { } user_signin_def::~user_signin_def() { } user_trial_def::user_trial_def() { } user_trial_def::~user_trial_def() { } user::user(id_type id,string const& name,enum gender gender):m_id(id),m_name(name),m_gender(gender) { } user::~user(void) {} const location & user::location() const { return m_loc; } void user::set_location(mmp::location const& loc) { m_loc = loc; } const string& user::name() const { return m_name; } id_type user::id() const { return m_id; } gender user::gender() const { return m_gender; } }
Shell
UTF-8
221
2.5625
3
[ "MIT" ]
permissive
[ -z "$1" ] && { echo "convert.sh <file>"; exit 1; } sed -i '/\\begin{verbatim}/{ a\ \\lstset{basicstyle=\\scriptsize,language=C}\ \\begin{lstlisting} d } /\\end{verbatim}/{ i\ \\end{lstlisting} s/\\end{verbatim}// }' $1
TypeScript
UTF-8
1,294
2.671875
3
[]
no_license
import { Injectable } from '@angular/core'; @Injectable() export class CheckStatusGameService { constructor() { } private fieldSize: number | undefined; patternWin = [0, /(1){5}/, /(2){5}/, /[01]*7[01]*/, /[02]*7[02]*/]; public checkStatus(x: number, y: number, fieldArray: Array<any>): boolean { this.fieldSize = fieldArray.length; const motion: string = fieldArray[x][y]; const directionArray = ['', '', '', '']; const xTop = Math.min(x, 4); const xRight = Math.min(this.fieldSize - y - 1, 4); const xBottom = Math.min(this.fieldSize - x - 1, 4); const xLeft = Math.min(y, 4); for (let j = x - xTop; j <= x + xBottom; j++) { directionArray[0] += fieldArray[j][y] || 0; } for (let i = y - xLeft; i <= y + xRight; i++) { directionArray[1] += fieldArray[x][i] || 0; } for (let i = -Math.min(xTop, xLeft); i <= Math.min(xRight, xBottom); i++) { directionArray[2] += fieldArray[x + i][y + i] || 0; } for (let i = -Math.min(xBottom, xLeft); i <= Math.min(xRight, xTop); i++) { directionArray[3] += fieldArray[x - i][y + i] || 0; } for (const position of directionArray) { if (position.search(this.patternWin[motion]) >= 0) { return false; } } return true; } }
C++
UTF-8
5,540
2.765625
3
[]
no_license
#include "LevelFactory.h" #include <fstream> #include <streambuf> #include "BoardObjects/BoardObjectArrow.h" #include "BoardObjects/BoardObjectEnemy.h" #include "BoardObjects/BoardObjectGoal.h" #include "BoardObjects/BoardObjectPerson.h" #include "BoardObjects/BoardObjectPit.h" #include "BoardObjects/BoardObjectRock.h" #include "LevelBoard.h" #include "LevelCommands/LevelCommandMove.h" #include "LevelCommands/LevelCommandInteract.h" #include "LevelCommands/LevelCommandSwitch.h" LevelFactory::LevelFactory(std::string levelFileLocation, IBehaviourFactory& behaviourFactory) : ILevelFactory(levelFileLocation, behaviourFactory) { } std::unique_ptr<Level> LevelFactory::createLevel(int level) throw() { std::string filePath = this->levelFileLocation + "/" + std::to_string(level) + ".json"; if (!doesFileExist(filePath)) { throw std::exception(); } std::unique_ptr<LevelBoard> newLevel = std::make_unique<LevelBoard>(); std::ifstream t(filePath); std::string text((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); JSON = nlohmann::json::parse(text); setLevelParameters(newLevel.get()); createPlayersAndPlayerDependantCommands(newLevel.get()); createEnemies(newLevel.get()); createObstacles(newLevel.get()); createPits(newLevel.get()); createGoals(newLevel.get()); return newLevel; } bool LevelFactory::doesFileExist(const std::string& filePath) { std::ifstream f(filePath.c_str()); return f.good(); } void LevelFactory::setLevelParameters(LevelBoard* levelBeingMade) { levelBeingMade->setWidth(JSON["Width"]); levelBeingMade->setHeight(JSON["Height"]); } void LevelFactory::createPlayersAndPlayerDependantCommands(LevelBoard* levelBeingMade) { std::unique_ptr<LevelCommandMove> moveCmd = std::make_unique<LevelCommandMove>(*levelBeingMade); std::unique_ptr<LevelCommandInteract> interactCmd = std::make_unique<LevelCommandInteract>(moveCmd.get(), *levelBeingMade); std::unique_ptr<LevelCommandSwitch> switchNextCmd = std::make_unique<LevelCommandSwitch>(moveCmd.get(), true); std::unique_ptr<LevelCommandSwitch> switchNextCmd2 = std::make_unique<LevelCommandSwitch>(moveCmd.get(), false); for (int i = 0; i < JSON["Players"].size(); i++) { std::unique_ptr<BoardObject> newObject = std::make_unique<BoardObjectPerson>( Point(JSON["Players"][i]["X"], JSON["Players"][i]["Y"]), std::string(JSON["Players"][i]["Key"]), std::move(behaviourFactory->createBehaviour(JSON["Players"][i]["Behaviour"])), std::move(behaviourFactory->createSender(JSON["Players"][i]["Sender"])), std::move(behaviourFactory->createReceiver(JSON["Players"][i]["Receiver"])) ); moveCmd.get()->addPlayer(*(newObject.get())); levelBeingMade->addBoardObject(std::move(newObject)); } levelBeingMade->setMoveCommand(std::move(moveCmd)); levelBeingMade->setChangeNextCommand(std::move(switchNextCmd)); levelBeingMade->setChangePrevCommand(std::move(switchNextCmd2)); levelBeingMade->setInteractCommand(std::move(interactCmd)); } void LevelFactory::createEnemies(LevelBoard* levelBeingMade) { for (int i = 0; i < JSON["Enemies"].size(); i++) { std::unique_ptr<BoardObject> newObject = std::make_unique<BoardObjectEnemy>( Point(JSON["Enemies"][i]["X"], JSON["Enemies"][i]["Y"]), std::string(JSON["Enemies"][i]["Key"]), std::move(behaviourFactory->createBehaviour(JSON["Enemies"][i]["Behaviour"])), std::move(behaviourFactory->createSender(JSON["Enemies"][i]["Sender"])), std::move(behaviourFactory->createReceiver(JSON["Enemies"][i]["Receiver"])) ); levelBeingMade->addBoardObject(std::move(newObject)); } } void LevelFactory::createObstacles(LevelBoard* levelBeingMade) { for (int i = 0; i < JSON["Obs"].size(); i++) { std::unique_ptr<BoardObject> newObject = std::make_unique<BoardObjectRock>( Point(JSON["Obs"][i]["X"], JSON["Obs"][i]["Y"]), std::string(JSON["Obs"][i]["Key"]), std::move(behaviourFactory->createBehaviour(JSON["Obs"][i]["Behaviour"])), std::move(behaviourFactory->createSender(JSON["Obs"][i]["Sender"])), std::move(behaviourFactory->createReceiver(JSON["Obs"][i]["Receivers"][0]["Type"])) ); for (int j = 1; j < JSON["Obs"][i]["Receivers"].size(); j++) { newObject.get()->addInteractReceiver(std::move(behaviourFactory->createReceiver(JSON["Obs"][i]["Receivers"][j]["Type"]))); } levelBeingMade->addBoardObject(std::move(newObject)); } } void LevelFactory::createPits(LevelBoard* levelBeingMade) { for (int i = 0; i < JSON["Pits"].size(); i++) { std::unique_ptr<BoardObject> newObject = std::make_unique<BoardObjectPit>( Point(JSON["Pits"][i]["X"], JSON["Pits"][i]["Y"]), std::string(JSON["Pits"][i]["Key"]), std::move(behaviourFactory->createBehaviour(JSON["Pits"][i]["Behaviour"])), std::move(behaviourFactory->createSender(JSON["Pits"][i]["Sender"])), std::move(behaviourFactory->createReceiver(JSON["Pits"][i]["Receiver"])) ); levelBeingMade->addBoardObject(std::move(newObject)); } } void LevelFactory::createGoals(LevelBoard* levelBeingMade) { for (int i = 0; i < JSON["Goals"].size(); i++) { std::unique_ptr<BoardObject> newObject = std::make_unique<BoardObjectGoal>( Point(JSON["Goals"][i]["X"], JSON["Goals"][i]["Y"]), std::string(JSON["Goals"][i]["Key"]), std::move(behaviourFactory->createBehaviour(JSON["Goals"][i]["Behaviour"])), std::move(behaviourFactory->createSender(JSON["Goals"][i]["Sender"])), std::move(behaviourFactory->createReceiver(JSON["Goals"][i]["Receiver"])) ); levelBeingMade->addBoardObject(std::move(newObject)); } }
C#
UTF-8
1,889
3.671875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _443_string_compression { class Program { static void Main(string[] args) { var chars = "aabbccc".ToCharArray(); var result = Compress(chars); } /// <summary> /// compress the string /// </summary> /// <param name="chars"></param> /// <returns></returns> public static int Compress(char[] chars) { if (chars == null || chars.Length == 0) return 0; var length = chars.Length; int index = 0; int start = 0; char previous = chars[0]; for (int i = 0; i < length; i++) { var current = chars[i]; //if(i == 0 ||(current != chars[i - 1])) // bug: chars[i - 1] is overwritten if (i == 0 || (current != previous)) { start = i; } if (i == (length - 1) || current != chars[i + 1]) { chars[index] = current; var number = i - start + 1; if (number == 1) { index += 1; } else { var s = number.ToString(); var addLength = s.Length; for (int j = 0; j < addLength; j++) { chars[index + 1 + j] = s[j]; } index += 1 + addLength; } } previous = current; } return index; } } }
JavaScript
UTF-8
1,028
2.640625
3
[]
no_license
import React, {useState, useRef,useEffect} from 'react'; import useWebAnimations from "@wellyshen/use-web-animations"; import './App.css'; function App() { const {ref,playState,getAnimation} = useWebAnimations({ keyframes:[ {transform:"translateY(0px)" , backgroundColor:"blue"}, {transform:"translateY(500px)",backgroundColor:"green"} ], timing: { delay: 500, // Start with a 500ms delay duration: 500, // Run for 1000ms iterations: Infinity, // Repeat once direction: "alternate", // Run the animation forwards and then backwards easing: "ease-in-out", // Use a fancy timing function }, }) return ( <div><h1 ref={ref} style={{ backgroundColor:"red",width:"200px",height :"200px" }}>How ARE GOOD</h1> <h1>Animatino play state{playState}</h1> <button onClick={()=>{ getAnimation().play() }}>play</button> <button onClick={()=>{ getAnimation().pause() }}>pause</button> </div> ); } export default App;
Shell
UTF-8
369
2.984375
3
[]
no_license
#!/bin/bash for num in 8 4 2 1 do echo "$num Threads:" export OMP_NUM_THREADS=$num for i in $(ls ../public-instances/*.ini) do file_var=${i:20} echo "./lcs-omp $i > ../result/Threads$num/test-$file_var.out" ./lcs-omp $i > ../result/Threads$num/test-$file_var.out echo "DONE Exec" done echo "DONE THREAD" done echo "DONE TEST"
Java
UTF-8
817
2.203125
2
[ "Apache-2.0" ]
permissive
package org.robobinding; import org.robobinding.binder.InflatedViewWithRoot; import org.robobinding.binder.ViewBindingLifecycle; import org.robobinding.presentationmodel.AbstractPresentationModelObject; import android.view.View; /** * @since 1.0 * @author Cheng Wei * */ public class BindableView { private final ViewBindingLifecycle viewBindingLifecycle; private final InflatedViewWithRoot inflatedView; public BindableView(ViewBindingLifecycle viewBindingLifecycle, InflatedViewWithRoot inflatedView) { this.viewBindingLifecycle = viewBindingLifecycle; this.inflatedView = inflatedView; } public void bindTo(AbstractPresentationModelObject presentationModel) { viewBindingLifecycle.run(inflatedView, presentationModel); } public View getRootView() { return inflatedView.getRootView(); } }
Markdown
UTF-8
3,989
2.65625
3
[]
no_license
# [FixInsight](http://sourceoddity.com/fixinsight/): static code analysis catching so much more than the compiler does. [Nyborg, Denmark, 20151021](http://www.dapug.dk/2015/08/workshop-20.html) - Examples: <https://bitbucket.org/jeroenp/besharp.net> - Slides: <http://github.com/jpluimers/Conferences> - Blog: <http://wiert.me> FixInsight is a static code analysis tool which catches code issues the compiler doesn't. Using it you will be amazed how much the compiler forgets to notice and how many issues your code has. How often have you forgotten a parameter to a Format expression? This is only one of the things FixInsight catches. You will get a FixInsight license that lasts until early November so you can let it run on your own code at the end of the block and ask questions on the why of certain things it catches. ## Getting started - [Download](http://sourceoddity.com/fixinsight/download.html): the file http://sourceoddity.com/download/FixInsight_2015.10upd1_setup.exe (it got updated very recently). - Install: 1. Quit all your Delphi instances 2. Run the installer 3. Register the license - License: lasts until 20151102. Get it from Jens, then use either of these steps to apply the license: 1. Via the `FixInsight License Manager`: 1. Click on the Windows `Start` button 2. Click `Programs` -> `FixInsight -> `FixInsight License Manager`. 3. In the `FixInsight Registration` dialog: 1. In the menu, `Open License` and the license file. 2. Click the `Apply License` button. 2. Within Delphi 1. Choose the `Help` menu 2. Click on `About FixInsight` 3. In the `About FixInsight` dialog (that initially shows `trial version`), click `Register`. 4. In the `FixInsight Registration` dialog: 1. In the menu, `Open License` and the license file. 2. Click the `Apply License` button. 5. Confirm the dialog that asks you to restart Delphi. 6. Restart Delphi. - [Docs](http://sourceoddity.com/fixinsight/doc.html): we will see most of them in the session[.](http://sourceoddity.com/video/CodeRageX-FixInsight.mp4) The license until early November so you can play with it after the workshop. If you like it, use the coupon (ask Jens) to get a 20% discount when you [buy](http://sourceoddity.com/fixinsight/order.html) it. ## Why Often a Delphi program compiles without errors, warnings or hints and is still wrong. In addition to unit tests, static code analysis can also reveal many errors. Just over a year old, FixInsight catches a lot of those. This saves both time and improves your quality. ## How FixInsight is a smart wrapper around the [DelphiAST](https://github.com/RomanYankovsky/DelphiAST) parser. It parses about any Delphi language construct you can imagine. If it doesn't, report a bug (see below how). Then it reports them in the standard Delphi messages pane, similar to what the compiler does. ## Example https://bitbucket.org/jeroenp/besharp.net/src/tip/Native/Delphi/Apps/Console/FixInsightDemo/ ## Supported Delphi versions - Delphi 2006 - Delphi 2007 - Delphi 2009 - Delphi 2010 - Delphi XE - Delphi XE2 - Delphi XE3 - Delphi XE4 - Delphi XE5 - Delphi XE6 - Delphi XE7 - Delphi XE8 - Delphi 10 Seattle This means it supports both classic and modern ~~Delphi~~ Object Pascal language constructs in addition to non-Unicode and Unicode Delphi versions. ## Reporting issues Like any software, FixInsight can have bugs. To report bugs: 0. Within Delphi 1. Choose the `Help` menu 2. Click on `About FixInsight` 3. In the `About FixInsight` dialog enable the click `Debug Mode` checkbox. 4. Run your FixInsight as normal. 5. Copy the `*.filog` file in your project folder and post it as feed back to http://sourceoddity.com/ ## Time to play 1. Run it on your own source base. 2. Make a top-3 of the most surprising issues. 3. Volunteer to show them to the rest of the people.
SQL
UTF-8
472
3.609375
4
[]
no_license
CREATE TABLE USER ( ID BIGINT AUTO_INCREMENT PRIMARY KEY, USERNAME VARCHAR(128) NOT NULL UNIQUE, PASSWORD VARCHAR(256) NOT NULL, BLOCKED BOOLEAN NOT NULL ); CREATE TABLE AUTH_USER_GROUP ( ID BIGINT AUTO_INCREMENT PRIMARY KEY, USERNAME VARCHAR(128) NOT NULL, AUTH_GROUP VARCHAR(128) NOT NULL, CONSTRAINT USER_AUTH_USER_GROUP_FK FOREIGN KEY (USERNAME) REFERENCES USER (USERNAME), UNIQUE (USERNAME, AUTH_GROUP) )
JavaScript
UTF-8
1,136
2.796875
3
[]
no_license
function startGyro() { var tempa=0,tempb=0,tempc=0,count=0; var handleGyroData = function(alpha, beta, gamma){ count++; // running averages of gyroscope values tempa = ((tempa*(count-1)) + alpha)/count; tempb = ((tempb*(count-1)) + beta)/count; tempc = ((tempc*(count-1)) + gamma)/count; }; window.addEventListener('devicemotion', function(e){ handleGyroData( e.rotationRate.alpha, e.rotationRate.beta, e.rotationRate.gamma ); }); var rate = 1000; var store = localStorage.getItem(KEY_RATE_GYRO); if(store){ rate = parseInt(store); } var interval = window.setInterval(function(){ document.getElementById("gyro").innerHTML = (tempa+"").substring(0,4) + "," + (tempb+"").substring(0,4) + "," + (tempc+"").substring(0,4); saveGyro([tempa, tempb, tempc]); tempa = 0; tempb = 0; tempc = 0; count = 0; }, rate); sessionStorage.setItem(KEY_INTERVAL_GYRO, interval); } function stopGyro(){ clearInterval(parseInt(sessionStorage.getItem(KEY_INTERVAL_GYRO))); document.getElementById("gyro").innerHTML = "OFF"; sessionStorage.removeItem(KEY_INTERVAL_GYRO); }
SQL
UTF-8
3,189
2.75
3
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
-- Copyright 2020 The Nomulus Authors. All Rights Reserved. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. alter table if exists "RegistrarPoc" add constraint fk_registrar_poc_registrar_id foreign key (registrar_id) references "Registrar"; alter table if exists "Spec11ThreatMatch" add constraint fk_spec11_threat_match_domain_repo_id foreign key (domain_repo_id) references "Domain"; alter table if exists "Spec11ThreatMatch" add constraint fk_spec11_threat_match_registrar_id foreign key (registrar_id) references "Registrar"; alter table if exists "Spec11ThreatMatch" add constraint fk_spec11_threat_match_tld foreign key (tld) references "Tld"; alter table if exists "BillingEvent" add constraint fk_billing_event_domain_history foreign key (domain_repo_id, domain_history_revision_id) references "DomainHistory"; alter table "BillingEvent" rename allocation_token_id to allocation_token; alter table if exists "BillingEvent" add constraint fk_billing_event_allocation_token foreign key (allocation_token) references "AllocationToken"; alter table if exists "BillingRecurrence" add constraint fk_billing_recurrence_domain_history foreign key (domain_repo_id, domain_history_revision_id) references "DomainHistory"; alter table if exists "BillingCancellation" add constraint fk_billing_cancellation_domain_history foreign key (domain_repo_id, domain_history_revision_id) references "DomainHistory"; alter table if exists "Contact" add constraint fk_contact_transfer_gaining_poll_message_id foreign key (transfer_gaining_poll_message_id) references "PollMessage"; alter table if exists "Contact" add constraint fk_contact_transfer_losing_poll_message_id foreign key (transfer_losing_poll_message_id) references "PollMessage"; alter table if exists "Domain" add constraint fk_domain_tld foreign key (tld) references "Tld"; alter table if exists "DomainTransactionRecord" add constraint fk_domain_transaction_record_tld foreign key (tld) references "Tld"; alter table if exists "GracePeriod" add constraint fk_grace_period_registrar_id foreign key (registrar_id) references "Registrar"; alter table if exists "Host" add constraint fk_host_creation_registrar_id foreign key (creation_registrar_id) references "Registrar"; alter table if exists "Host" add constraint fk_host_current_sponsor_registrar_id foreign key (current_sponsor_registrar_id) references "Registrar"; alter table if exists "Host" add constraint fk_host_last_epp_update_registrar_id foreign key (last_epp_update_registrar_id) references "Registrar";
Java
UHC
475
2.953125
3
[]
no_license
import java.io.*; public class Exam_14 { public static void main(String[] args) throws IOException { File dir = new File("C:\\Users\\Administrator\\Desktop\\߾ӱ"); File file = new File(dir,"text01.txt"); FileInputStream fis = new FileInputStream(file); while(true) { int res = fis.read(); // Ͽ 1byte о´ . if(res < 0 ) break; // //EOF ==-1 ; System.out.print((char)res); } } }
C++
UTF-8
1,208
3.203125
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { double a, b, c; cout << "ax^2+bx+c=0 masodfoku egyenlet megoldasa.\n"; cout << "a: "; cin >> a; if(a==0.) cout << "Ez nem egy masodfoku egyenlet!(Nigger)" << endl; else { cout << "b: "; cin >> b; cout << "c: "; cin >> c; double x1, x2, dis; dis = pow(b, 2) - 4.*a*c; cout << "Diszkriminans: " << dis << '\n'; if(dis < 0.) cout << "Az egyenletnek nincsen valos megoldasa!"; else { x1 = (-b + sqrt(dis)) / (2.*a); x2 = (-b - sqrt(dis)) / (2.*a); cout << "Van valos gyoke:\n"; cout << "x1: " << x1 << '\n'; cout << "x2: " << x2 << endl; } } /*double a, b, c; cout << "Az ax^2+bx+c = 0 egyenlet megoldasa\n"; cout << "a erteke: "; cin >> a; if(a == 0.){ cout << "Az egyenlet nem masodfoku!\n"; } else { cout << "b erteke: "; cin >> b; cout << "c erteke: "; cin >> c; double d = b*b - 4.*a*c; if(d < 0.){ cout << "Nincs valos gyok!\n"; } else { cout << "x1 = " << (-b + sqrt(d)) / (2.*a) << "\nx2 = " << (-b - sqrt(d)) / (2.*a) << endl; } }*/ return 0; }
Markdown
UTF-8
4,343
2.578125
3
[ "MIT" ]
permissive
--- id: mail label: Mail title: Mail - Actions type: action description: "This add-on provides SMTP services so your rules and scripts can send e-mails." source: https://github.com/openhab/openhab1-addons/blob/master/bundles/action/org.openhab.action.mail/README.md since: 1x install: auto --- <!-- Attention authors: Do not edit directly. Please add your changes to the appropriate source repository --> <!-- {% include base.html %} --> # Mail Actions This add-on provides SMTP services so your rules and scripts can send e-mails. The `to` paremeter can contain a semicolon-separated list of email addresses. ## Actions - `sendMail(String to, String subject, String message)`: Sends an email via SMTP. - `sendMail(String to, String subject, String message, String attachmentUrl)`: Sends an email with attachment via SMTP. - `sendMail(String to, String subject, String message, List<String> attachmentUrlList)`: Sends an email with one or more attachments via SMTP. ## Configuration This action service can be configured via the `services/mail.cfg` file. | Property | Default | Required | Description | |---------------|----------------------------|:-----------------------------------------------------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------| | hostname | | Yes | SMTP server hostname, e.g. "smtp.gmail.com" | | port | 25 (resp. 587 for TLS/SSL) | No | SMTP port to use | | username | | if the SMTP server at `<hostname>` and `<port>` requires authentication | SMTP user name | | password | | if the SMTP server at `<hostname>` and `<port>` requires authentication | SMTP password | | from | | Yes | Email address to use for sending mails | | tls | false | No | `true` if STARTTLS is enabled (not required) for the connection | | ssl | false | No | `true` if SSL negotiation should occur on connection. Do not set both `tls` and `ssl` to `true`. | | popbeforesmtp | false | No | set to `true` if POP before SMTP (another authentication mechanism) should be enabled. Username and password are taken from the above configuration | | charset | platform default | No | Character set used to encode the message body | ## Examples ```javascript import java.util.List ... val List<String> attachmentUrlList = newArrayList( "http://some.web/site/snap.jpg&param=value", "http://192.168.1.100/data.txt", "file:///tmp/201601011031.jpg") sendMail("you@email.net", "Test", "This is the message.", attachmentUrlList) ```
Swift
UTF-8
4,498
2.53125
3
[]
no_license
// // ArrivalsCell.swift // CTA Train Tracker 2 // // Created by Thomas Bart on 8/9/19. // Copyright © 2019 Thomas Bart. All rights reserved. // import UIKit class ArrivalsCell: BaseCell { var route: Route? { didSet { if let station = route?.station { stationLabel.text = station } if let destination = route?.destination { routeLabel.text = "To: \(destination)" } if let etas = route?.etas { let length = etas.count - 1 for i in 0..<length { arrivalsTextView.text.append("\(etas[i].arrivalTime)\n") timeTextView.text.append("\(etas[i].timeRemaining)\n") } arrivalsTextView.text.append("\(etas[length].arrivalTime)") timeTextView.text.append("\(etas[length].timeRemaining)") } if let color = route?.color { trainImageView.setImageColor(color: color) routeLabel.textColor = color } } } let trainImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(named: "train_image") return imageView }() let stationLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.boldSystemFont(ofSize: 18) label.textColor = Theme.current.cellTextColor return label }() let routeLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.boldSystemFont(ofSize: 18) return label }() let arrivalsTextView: UITextView = { let textView = UITextView() textView.setupTrainTextView() return textView }() let timeTextView: UITextView = { let textView = UITextView() textView.setupTrainTextView() textView.textAlignment = NSTextAlignment.right return textView }() override func prepareForReuse() { super.prepareForReuse() arrivalsTextView.text = "" timeTextView.text = "" } override func setupViews() { super.setupViews() addSubview(trainImageView) addSubview(arrivalsTextView) addSubview(stationLabel) addSubview(routeLabel) addSubview(timeTextView) // Horizontal Constraints addConstraintsWithFormat(format: "H:|-16-[v0(44)]", views: trainImageView) addConstraintsWithFormat(format: "H:|-68-[v0(200)][v1]-16-|", views: arrivalsTextView, timeTextView) // Vertical Constraints addConstraintsWithFormat(format: "V:|-16-[v0(44)]-8-[v1]", views: trainImageView, arrivalsTextView) addConstraintsWithFormat(format: "V:|-16-[v0(44)]-8-[v1]", views: trainImageView, timeTextView) // Station Label Constraints addConstraint(NSLayoutConstraint(item: stationLabel, attribute: .bottom, relatedBy: .equal, toItem: routeLabel, attribute: .top, multiplier: 1, constant: -2)) addConstraint(NSLayoutConstraint(item: stationLabel, attribute: .left, relatedBy: .equal, toItem: trainImageView, attribute: .right, multiplier: 1, constant: 8)) addConstraint(NSLayoutConstraint(item: stationLabel, attribute: .right, relatedBy: .equal, toItem: arrivalsTextView, attribute: .right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: stationLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 22)) // Route Label Constraints addConstraint(NSLayoutConstraint(item: routeLabel, attribute: .bottom, relatedBy: .equal, toItem: arrivalsTextView, attribute: .top, multiplier: 1, constant: -6)) addConstraint(NSLayoutConstraint(item: routeLabel, attribute: .left, relatedBy: .equal, toItem: trainImageView, attribute: .right, multiplier: 1, constant: 8)) addConstraint(NSLayoutConstraint(item: routeLabel, attribute: .right, relatedBy: .equal, toItem: arrivalsTextView, attribute: .right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: routeLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 0, constant: 22)) } }
Markdown
UTF-8
540
2.96875
3
[ "MIT" ]
permissive
# auto-retryer extend the automatic retry function for the Promise function ## Build Setup ``` bash # install dependencies npm install auto-retryer --save # node test cd node_modules/auto-retryer npm run test ``` ## Usage ```js const AutoRetryer = require('auto-retryer') const _fetch = require('node-fetch') //max retry 3 time //sleep 300ms before retry var fetch = new AutoRetryer(_fetch,3,300) fetch('http://example.com',{method:'GET'}).then(ret=>{ console.log('succcess',ret) }).catch(err=>{ console.log('err',err) }) ```
Python
UTF-8
1,108
2.5625
3
[]
no_license
import requests import os import random import time import requests_cache from bs4 import BeautifulSoup requests_cache.install_cache('demo_cache') headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 ' 'Firefox/57.0'} response = requests.get("http://www.dy2018.com/html/gndy/dyzz/index.html") # , headers=headers html_doc = response.content.decode('gbk') # print(html_doc) with open('m.txt','w') as f: f.write(html_doc) soup = BeautifulSoup(html_doc, 'html.parser') # print(soup) links = [] for a in soup.select('.ulink'): # 类查找 # print(type(a)) href = 'http://www.dy2018.com' + a['href'] title = a.string links.append(href) # print(href, title) for link in links: response = requests.get(link, headers=headers) html_doc = response.content.decode('gbk') # print(html_doc) soup = BeautifulSoup(html_doc, 'html.parser') print(soup) ftp_element = soup.select('#Zoom table a') # id查找+标签 print(ftp_element) download_link = ftp_element[1]['href'] # print(download_link) time.sleep(random.randint(1, 2)) print()
Markdown
UTF-8
854
2.546875
3
[]
no_license
--- author: Jacob Tomlinson date: 2012-06-01T00:00:00+00:00 categories: - Events tags: - Download Festival - Google Docs thumbnail: download-festival title: Download Festival 2012 Timetable aliases: - /2012/06/01/download-2012-timetable/ --- Download have now released the times for Download Festival 2012 in the form of an app. The only problem with this is it&#8217;s not exactly clear and easy to see who is clashing or to make a plan. For my own benefit and anyone else who wants it I&#8217;ve put the timetable into a spreadsheet and put it in google docs. Feel free to download yourself a copy and sort out your plans! [https://docs.google.com/open?id=0BzChRg3SiZzDbDhhLUVpOGZrUXM][1] ![Download Festival Lineup 2012](https://i.imgur.com/z0AE46p.png) [1]: https://docs.google.com/open?id=0BzChRg3SiZzDbDhhLUVpOGZrUXM "Download 2012 Timetable"
Java
UTF-8
2,189
4.03125
4
[]
no_license
package DiningPhilosopherProblem; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class App { public static void main(String[] args) throws InterruptedException { ExecutorService executorService = null; Philosopher[] philosophers = null; try{ philosophers = new Philosopher[Constants.NUMBER_OF_PHILOSOPHERS]; ChopStick[] chopSticks = new ChopStick[Constants.NUMBER_OF_PHILOSOPHERS]; for(int i=0;i<Constants.NUMBER_OF_CHOPSTICKS;i++){ chopSticks[i] = new ChopStick(i); } /*Number of threads is going to be equal to the no of the PHILOSOPHER.*/ executorService = Executors.newFixedThreadPool(Constants.NUMBER_OF_PHILOSOPHERS); for(int i=0;i<Constants.NUMBER_OF_PHILOSOPHERS;i++){ /* Here, we assign left and right chopSticks to the each philosopher*/ philosophers[i] = new Philosopher(i, chopSticks[i], chopSticks[(i+1) % Constants.NUMBER_OF_PHILOSOPHERS]); executorService.execute(philosophers[i]); } Thread.sleep(Constants.SIMULATION_RUNNING_TIME); // We are to sleep as per SIMULATION_RUNNING_TIME //Then we have to stop the application once SIMULATION_RUNNING_TIME is over by setting 'setFull' for(Philosopher philosopher : philosophers){ philosopher.setFull(true); // once this is set to full, then our SIMULATION will stop execution. } }finally{ /**** * shutdown() -> Initiates an orderly shutdown in which previously submitted tasks are executed, * but no new tasks will be accepted. Invocation has no additional effect if already shut down. */ executorService.shutdown(); /*isTerminated() -> Returns true if all tasks have completed following shut down. * We should write this line of code to make sure that all executor task has been completed.*/ while(!executorService.isTerminated()){ Thread.sleep(1000); } /* Counting how many times a given Philosopher has eaten.*/ for(Philosopher philosopher : philosophers ){ System.out.println(philosopher+" has eaten #"+philosopher.getEatingCounter() + " times"); } } } }
Python
UTF-8
503
3.15625
3
[]
no_license
N = int(input()) LR = [list(map(int, input().split())) for _ in range(N)] def calc_expect_by_two(LR1, LR2): l1, r1 = LR1 l2, r2 = LR2 bunshi = 0 bunbo = 0 for i in range(1, 101): for j in range(1, 101): if l1 <= i <= r1 and l2 <= j <= r2: bunbo += 1 if i < j: bunshi += 1 return bunshi/bunbo ans = 0 for i in range(N): for j in range(i): ans += calc_expect_by_two(LR[i], LR[j]) print(ans)
Python
UTF-8
8,316
2.765625
3
[]
no_license
import csv import numpy import re import nltk import pandas import pymysql from parseSOAPI import extractAPI from bs4 import BeautifulSoup host = 'localhost' username = 'root' password = '123456' database='github_issues' #关键词 KWs=['fast','slow','efficient','scalable','expensive','intensive','quick','rapid','performant','faster','slower','better','worse','worst','fastest','slowest', 'performance','efficiency','speed ups','improve','slowdown','speedup', 'speed up','increase','accelerate','computationally'] def connectMySQL(): '''连接数据库''' print('Open the database connection......') # 打开数据库连接 db = pymysql.connect(host,username,password,database,charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() issues = executeSelect(cursor) parseBody(issues) db.close() # 关闭数据库连接 print('Close the database connection......') def executeSelect(cursor): ''' 执行Select操作,返回SELECT的结果(body) ''' print('Execute sql SELECT......') sql = "SELECT issues_number,repo,title,body,labels,link FROM issues" # SQL 查询语句 try: cursor.execute(sql) issues = cursor.fetchall() print('Sql SELECT execution is complete') except: print("Error: unable to fecth data") return issues def executeAlter(cursor): print('Execute sql Alter......') sql = 'alter table questions add question varchar(5000)' try: cursor.execute(sql) except: print("Error: unable to fecth data") def parseBody(columns): ''' 解析html代码(body,title) :param columns:title,body列 :return: 包含关键词和code的句子 ''' for column in columns: issues_number = column[0] # if issues_number!=276: # continue repo = column[1] title = column[2] body = column[3] label = column[4] link = column[5] # 如果含有代码片段,则删除 if body.find('<pre')!=-1: body = deleteCode(body) if title.find('<pre')!=-1: title = deleteCode(title) codes = get_all_code(body, title) apis = [] for code in codes: apis.extend(extractAPI.get_calls(code)) apis = list(set(apis)) # 去重 # print(codes) # print(apis) kw_and_code_descs = getKWDesc(body,title) savecsv(kw_and_code_descs,issues_number,repo,label,link,'G:\Performance\SO_Guid_Api\github_issues\desc\\issues3.csv',apis) for i in kw_and_code_descs: print(issues_number," : ",i) def deleteCode(body): ''' 删除代码片段(含有pre标志的代码) :param body: :return:返回删除代码片段的body ''' body_list = body.split('<pre') body = body_list[0] for i in range(len(body_list)): if body_list[i].find('</pre>') != -1: body_list[i] = body_list[i].split('</pre>') body = body + body_list[i][1] return body def get_all_code(body,title): codes = [] codes.extend(get_code_list(title)[1]) codes.extend(get_code_list(body)[1]) return codes def get_code_list(sentence): ''' 提取出sentence含有<code>标志的代码:例如<code>tf.py_func()</code> :param sentence:待处理字符串 :return:sen_codelist:[sen,code_list] code_list:sentence含有的所有代码,sen:sentence去除code_list之后的句子 ''' code_list = [] # 句子含有的代码 sen_codelist = [] # ['sen','codelist'] #提取出含有<code>的代码 sen='' if sentence.find('<code>') != -1: for i in range(len(sentence.split('<code>'))): if i == 0: sen = sen + sentence.split('<code>')[0] if sentence.split('<code>')[i].find('</code>') != -1: code_list.append(sentence.split('<code>')[i].split('</code>')[0]) sen = sen + sentence.split('<code>')[i].split('</code>')[1] else: sen = sentence # 去掉代码的标签(<code>) for i in range(len(code_list)): soup = BeautifulSoup(code_list[i],'html.parser') code_list[i] = '' for c in soup.find_all(text=True): code_list[i] = code_list[i] + c # 去掉句子的标签(<p>,</p>) soup = BeautifulSoup(sen, 'html.parser') sen = '' for q in soup.find_all(text=True): sen = sen + q # 去掉句子的链接(链接会影响正则表达式的匹配) pattern = re.compile(r'\S*http\S*|\S+\.com\S*|\S+\.htm\S*|\S+\.org\S*|\S+\.io\S*|\S+\.edu\S*|\S+\.shtml\S*|\S*/\w+/\w+/\w+\S*') linkList = pattern.findall(sen) for link in linkList: sen = sen.replace(link, '') # 用正则表达式匹配出code element pattern = re.compile( r'[a-zA-Z]\w*\(*\)*\[*\]*\.[a-zA-Z]\w*\(*\)*\[*\]*[a-zA-Z0-9,=\.\(\)\[\]]*|\s\.[a-zA-Z]\w*\(*\)*\[*\]*[a-zA-Z0-9,=\.\(\)\[\]]*|^\.[a-zA-Z]\w*\(*\)*\[*\]*[a-zA-Z0-9,=\.\(\)\[\]]*|[a-zA-Z]\w*\([a-zA-Z0-9,=\.\(\)\[\]]*\)|[a-zA-Z]\w*\[[a-zA-Z0-9,=\.\(\)\[\]]*\]') re_code_list = pattern.findall(sen) for code in re_code_list: sen = sen.replace(code,'') for i in range(len(re_code_list)): # 去点以",", "." 结尾的符号 if re_code_list[i][-1] == ',' or re_code_list[i][-1] == '.': re_code_list[i] = re_code_list[i][:-1] if re_code_list[i] == 'i.e' or re_code_list[i] == 'e.g' or re_code_list[i] == 'i.e.' or re_code_list[i] == 'e.g.': continue else: code_list.append(re_code_list[i]) code_list=list(set(code_list)) # 去重 sen_codelist.append(sen) sen_codelist.append(code_list) return sen_codelist def getKWDesc(body,title): ''' 提取含关键字和代码的句子 :param body:主体 :param title:标题 :return:kw_and_code_descs:['sen:含关键字和代码的句子','kw:sen包含的关键字','codelist:sen包含的代码'] ''' kw_and_code_descs = [] # 存放含有关键词也含有代码的句子 # 提取含关键字的body sentencesList = body.split('<p>') # 以<p>划分 for sentences in sentencesList: sentenceList = nltk.sent_tokenize(sentences) # 划分句子 for sentence in sentenceList: code_sen_list = get_code_list(sentence) code_list = code_sen_list[1] sen = code_sen_list[0] #code_list= get_code_list(sentence) if len(code_list)!=0: kwList = [] for kw in KWs: matchobj = re.search(r"(.*)" + r"\b" + kw + r"\b" + r"(.*)", sen, re.I) if matchobj is not None: kwList.append(kw) if len(kwList) != 0: soup = BeautifulSoup(sentence, 'html.parser') sen = '' for q in soup.find_all(text=True): sen = sen + q kw_and_code_descs.append([sen,kwList,code_list]) # 提取含关键字的title titles = nltk.sent_tokenize(title) for t in titles: code_sen_list = get_code_list(t) code_list = code_sen_list[1] sen = code_sen_list[0] if len(code_list)!=0: kwList = [] for kw in KWs: matchobj = re.search(r"(.*)" + r"\b" + kw + r"\b" + r"(.*)", str(sen), re.I) if matchobj is not None: kwList.append(kw) if len(kwList) != 0: kw_and_code_descs.append([t, kwList,code_list]) return kw_and_code_descs def savecsv(kw_and_code_descs,issues_number,repo,label,link,csv_Path,apis): ''' save desc data to csv file. :param descs: kw_and_code_descs:['sen:含关键字和代码的句子','kw:sen包含的关键字','codelist:sen包含的代码'] :param question_id: :param csv_Path: 保存csv的路径 ''' with open(csv_Path, 'a+', encoding='gb18030',newline="") as csvfilehandler: writer = csv.writer(csvfilehandler) for desc in kw_and_code_descs: writer.writerow([issues_number,repo,label,link,desc[0],desc[1],desc[2],apis]) # [question_id,desc,kw[],codelist] if __name__ == "__main__": connectMySQL()
SQL
UTF-8
2,436
3.71875
4
[ "MIT" ]
permissive
/* pco_powerplan_basic_attributes.sql ~~~~~~~~~~~~~~~~~~~ This query grabs any currently active powerplan and powerplan-level attributes (such as default view, or copy forward) in addition to reference text and powerplan commaents */ select powerplan = pwcat.description , plan_type = uar_get_code_display(pwcat.pathway_type_cd) , pwcat.cross_encntr_ind , reference_text = lb.long_blob , powerplan_comment = lt.long_text , allow_dx_propagation = pwcat.diagnosis_capture_ind , hide_flexd_cmp = pwcat.hide_flexed_comp_ind , default_view = evaluate2(if(pwcat.default_view_mean = "CHEMO*") "Chemotherapy Review" elseif(pwcat.default_view_mean is null) "None" endif) , prompt_ord_physician = pwcat.provider_prompt_ind , copy_fwd = pwcat.allow_copy_forward_ind , classification = uar_get_code_display(pwcat.pathway_class_cd) , dont_allow_proposal = pwcat.restricted_actions_bitmask , use_cycle_numbers = pwcat.cycle_ind , std_nbr_of_cycles = pwcat.standard_cycle_nbr , beg_cycle_nbr = pwcat.cycle_begin_nbr , end_cycle_nbr = pwcat.cycle_end_nbr , cycle_incrm_nbr = pwcat.cycle_increment_nbr , disp_std_nbr_or_end_val = pwcat.cycle_display_end_ind , restr_ability_to_mod_std_nbr_or_end_val = pwcat.cycle_lock_end_ind , cycle_disp_val = uar_get_code_display(pwcat.cycle_label_cd) from pathway_catalog pwcat , long_blob lb , ref_text_reltn rtr , ref_text rt , long_text lt plan pwcat where pwcat.active_ind = 1 and pwcat.type_mean in ("CAREPLAN", "PATHWAY") and (pwcat.description_key like 'ONC*' or pwcat.description_key like 'INF*') and pwcat.end_effective_dt_tm > cnvtdatetime(sysdate) and pwcat.beg_effective_dt_tm < cnvtdatetime(sysdate) /*Removes "Testing" and "Production, archived versions"*/ and pwcat.ref_owner_person_id = 0 /*Filter out pre-CPOE-built PowerPlans*/ join rtr where rtr.parent_entity_id = outerjoin(pwcat.pathway_catalog_id) and rtr.parent_entity_name = outerjoin("PATHWAY_CATALOG") and rtr.active_ind = outerjoin(1) join rt where rt.refr_text_id = outerjoin(rtr.refr_text_id) and rt.text_entity_name = outerjoin("LONG_BLOB") and rt.active_ind = outerjoin(1) join lb where lb.long_blob_id = outerjoin(rt.text_entity_id) and lb.active_ind = outerjoin(1) join lt where lt.long_text_id = outerjoin(pwcat.long_text_id) and lt.active_ind = outerjoin(1)
Markdown
UTF-8
2,053
2.515625
3
[]
no_license
--- title: L'équipe --- </div> </div> <div class="hero" style="background-image:url('/images/header7.jpg')"> <div class="title"> <h1>L'équipe</h1> <p>Autour de deux amis qui souhaitent partager leur passion pour les défis techniques et l'exploration:</p> </div> </div> <div class="container"> <div></div> ### Antoine Delafargue <div class="row"> <div class="col-sm-3"> <img src="images/AD.jpg" /> </div> <div class="col-sm-9"> <p> Il est à l'origine du projet et de la conception du sous-marin. Il embarquera dans le sous-marin comme co-pilote: </p> <ul> <li>34 ans, marié, 4 enfants, breton</li> <li>Ingénieur exerçant dans l'industrie</li> <li>Service militaire comme Commando dans la Marine Nationale</li> <li>A volé sous la terre en 2003</li> <li>Fan de sports de pleine nature (Course, escalade, plongée, spéléologie, vélo)</li> </ul> </div> </div> <hr/> ### Michael de Lagarde <div class="row"> <div class="col-sm-3"> <img src="images/MD.jpg" /> </div> <div class="col-sm-9"> <p>Associé au projet depuis la première heure, il embarquera comme co-pilote dans le sous-marin.</p> <ul> <li>35 ans</li> <li>Ingénieur et entrepreneur</li> <li>Préside et Fonde en 2011 une entreprise de drones aériens</li> <li>Service militaire comme Commando dans la Marine Nationale</li> <li>A volé sous la terre en 2003</li> <li>Fan de sports de pleine nature (course, escalade, parapente, spéléologie, vélo)</li> </ul> </div> </div> <hr/> ### Projet 'On a volé sous la Terre' <div class="row"> <div class="col-sm-5"> ![](images/Mongo.jpg) </div> <div class="col-sm-7"> <div></div> Salle de la Verna, massif de La Pierre Saint Martin dans les Pyrénées, mars 2003. Pour la première fois, cette immense cavité fut eclairée entièrement. Elle a depuis été l'objet d'un intérêt accru: elle abrite une installation hydroélectrique unique au monde et est ouverte au public. </div> </div>
Swift
UTF-8
7,207
2.78125
3
[]
no_license
// // PickPostTableViewCell.swift // abseil // // Created by Ann McDonough on 4/25/20. // import UIKit class PickPostTableViewCell: UITableViewCell { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var chosenTeamLineLabel: UILabel! var likedAlready = false var dislikedAlready = false @IBOutlet weak var profitLabl: UILabel! @IBOutlet weak var recordLabel: UILabel! var currentLikes = 0 var currentDislikes = 0 var pickPost = PickPost() func getTodayString() -> String{ let date = Date() let calender = Calendar.current let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date) let year = components.year let month = components.month let day = components.day let hour = components.hour let minute = components.minute let second = components.second let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) return today_string } func getTimeString() -> String{ let date = Date() let calender = Calendar.current let components = calender.dateComponents([.hour,.minute,.second], from: date) let hour = components.hour let minute = components.minute let second = components.second var ampm = "" if hour! < 12 { ampm = " AM" } else { ampm = " PM" } let time_string = String(hour!) + ":" + String(minute!) + ampm return time_string } @IBOutlet weak var profilePictureImageView: UIImageView! @IBOutlet weak var gameLabel: UILabel! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var sportLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timePostedLabel: UILabel! @IBOutlet weak var agreePickPostLabel: UILabel! @IBOutlet weak var riskingLabel: UILabel! @IBOutlet weak var toWinLabel: UILabel! @IBOutlet weak var disagreePickPostLabel: UILabel! @IBOutlet weak var disagreeButton: UIButton! @IBOutlet weak var agreeButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configureCell(pickPost: PickPost) { // let date = NSDate(timeIntervalSince1970: timeResult) let commenceDate = NSDate(timeIntervalSince1970: pickPost.commence_time) let dateFormatter = DateFormatter() dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style dateFormatter.timeZone = NSTimeZone() as TimeZone let commenceLocalDate = dateFormatter.string(from: commenceDate as Date) print("This is commenceDate: \(commenceDate)") print("This is commenceLocalDate: \(commenceLocalDate)") var time = getTimeString() var today = getTodayString() print(pickPost) usernameLabel.text = pickPost.username chosenTeamLineLabel.text = "\(pickPost.chosenTeam)" //" at \(pickPost.odds)" gameLabel.text = "\(pickPost.teams[0]) at \(pickPost.teams[1])" print("I haven't configured game Label yet") // gameLabel.text = "\(pickPost.teams[0]) @ \(pickPost.teams[1] ?? "")" //❤️❤️❤️❤️❤️❤️ HOw do i get game information??? startTimeLabel.text = "\(commenceLocalDate)" sportLabel.text = pickPost.sport // timePostedLabel.text = "\(pickPost.timePosted)" riskingLabel.text = "Risking: $\(Double(Int(pickPost.amountWagered*100.rounded())/100))0" toWinLabel.text = "To Win: $\(Double(Int(pickPost.amountToWin*100.rounded())/100))0" agreePickPostLabel.text = "\(pickPost.upVotes)" disagreePickPostLabel.text = "\(pickPost.downVotes)" dateLabel.text = today timePostedLabel.text = time } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func agreeButtonPressed(_ sender: UIButton) { print("Agree button pressed fill in code") if likedAlready != true { pickPost.upVotes = pickPost.upVotes + 1 currentLikes = currentLikes + 1 // likeLabelTextPost.text = "\(textPost.upVotes)" agreePickPostLabel.text = "\(currentLikes)" if dislikedAlready == true { print("We disliked it already") currentDislikes = currentLikes - 1 pickPost.downVotes = pickPost.downVotes - 1 // dislikeLabelTextPost.text = "\(textPost.downVotes)" disagreePickPostLabel.text = "\(currentDislikes)" dislikedAlready = false } likedAlready = true } } @IBAction func disagreeButtonPressed(_ sender: UIButton) { print("Disagree button pressed fill in code") if dislikedAlready == false { currentDislikes = currentDislikes + 1 pickPost.downVotes = pickPost.downVotes + 1 // dislikeLabelTextPost.text = "\(textPost.downVotes)" disagreePickPostLabel.text = "\(currentDislikes)" if likedAlready == true { print("We liked it already") pickPost.upVotes = pickPost.upVotes - 1 currentLikes = currentLikes - 1 // likeLabelTextPost.text = "\(textPost.upVotes)" agreePickPostLabel.text = "\(currentLikes)" likedAlready = false } dislikedAlready = true } } @IBAction func agreeButtonClicked(_ sender: UIButton) { print("I clicked like button") // today = getTodayString() // print("Today: \(today)") if likedAlready == false { currentLikes = currentLikes + 1 agreePickPostLabel.text = "\(currentLikes)" if dislikedAlready == true { print("We disliked it already") currentDislikes = currentLikes - 1 disagreePickPostLabel.text = "\(currentDislikes)" dislikedAlready = false } likedAlready = true } } @IBAction func dislikeButtonClicked(_ sender: UIButton) { print("I clicked dislike button") if dislikedAlready == false { currentDislikes = currentDislikes + 1 disagreePickPostLabel.text = "\(currentDislikes)" if likedAlready == true { print("We liked it already") currentLikes = currentLikes - 1 agreePickPostLabel.text = "\(currentLikes)" likedAlready = false } dislikedAlready = true } } }
C++
UTF-8
571
2.9375
3
[]
no_license
#pragma once #include <iostream> #define MAX_DEGREE 22 using namespace std; class Polynomial { private: int degree; double coeffecient[MAX_DEGREE]; public: Polynomial(); Polynomial operator*(const Polynomial& aRight) const; friend std::istream& operator>>(std::istream& aIStream, Polynomial& aPoly); friend std::ostream& operator<<(std::ostream& aOStream, const Polynomial& aPoly); double calculate(double aX) const; Polynomial buildIndefiniteIntegral() const; double buildDefiniteIntegral(double aLowX, double aHighX) const; };
Java
UTF-8
3,384
3.046875
3
[]
no_license
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Random; public class Population { float mutationRate; DNA[] population; ArrayList<DNA> matingPool; int generations; boolean finished; int perfectScore; int startingSize; float maxFitness; int fitnessSum; public Population(int numQ ,float mutationRate,int startingSize) { this.mutationRate = mutationRate; this.startingSize = startingSize; maxFitness = 0.0f; population = new DNA[startingSize]; for(int i = 0; i < population.length;i++) { population[i] = new DNA(numQ); } calcFitness(); matingPool = new ArrayList<DNA>(); finished = false; generations = 0; perfectScore = numQ * (numQ-1)/2; } public void print() { for(int i = 0; i < population.length;i++) { population[i].print(); } } //normalize fitness; public void calcFitness() { fitnessSum = 0; for(int i =0; i < population.length;i++) { population[i].calcFitness(); fitnessSum+=population[i].fitness; } } //Make the mating pool public void naturalSelection() { //empty pool matingPool.clear(); float maxFitness = 0; for(int i =0; i < population.length;i++) { if(population[i].fitness > maxFitness) { maxFitness = population[i].fitness; } } Comparator<DNA> comparator = new DnaComparator(); PriorityQueue<DNA> queue = new PriorityQueue<DNA>(comparator); for(int i = 0; i < population.length;i++) { queue.add(population[i]); } for(int i = 0; i < (int)(population.length/8);i++) { matingPool.add(queue.poll()); } // for(int i = 0; i < population.length;i++) { // float fitness = (float)(population[i].fitness/(float)fitnessSum); // int n = (int)(fitness *population.length*100); // for(int j =0; j<n;j++) { // matingPool.add(population[i]); // } // } } public void generate() { Random rand = new Random(); for(int i =0; i < population.length;i++) { int a = rand.nextInt(matingPool.size()); int b = rand.nextInt(matingPool.size()); DNA partnerA = matingPool.get(a); DNA partnerB = matingPool.get(b); DNA child = partnerA.crossOver(partnerB); child.mutate(mutationRate); population[i] = child; } generations++; } public int[] getBest() { float worldrecord = 0.0f; int index = 0; for(int i =0; i < population.length;i++) { if(population[i].fitness > worldrecord) { index = i; worldrecord = population[i].fitness; } } if(worldrecord == perfectScore) finished = true; return population[index].genes; } boolean finished() { return finished; } //average fitness for the population float getAverageFitness() { float total = 0; for(int i =0; i < population.length;i++) { total +=population[i].fitness; } return total / (population.length); } //Selection //Mutation //Crossover // private geneticAlgorithm(population,Fitness_fn) { // do { // //new_population <- empty set // //loop for i from 1 to SIZE(population) do // //x <- random selection population fitness // //y<- Random selection population, fitness function // }while(fit || elapsed time) // return best individual in population // } // private DNA reproduce(DNA x, DNA y) { // int n = x.length; // int c = Math.random(n)+1; // return DNA(Append(Substring(x,1,c),Substring(y,c+1,n))); // } }