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
JavaScript
UTF-8
1,546
2.96875
3
[]
no_license
// 예제 8.1 - Redux context 생성해보기 import React, {createContext, Component} from 'react' import {StyleSheet, Text, View} from 'react-native' const ThemeContext = React.createContext()     class Parent extends Component { state = {themeValue: 'light'}     toggleThemeValue = () => {     const value = this.state.themeValue === 'dark' ? 'light' : 'dark'     this.setState({themeValue: value})     }     render() { return ( <ThemeContext.Provider     value={{ themeValue: this.state.themeValue, toggleThemeValue: this.toggleThemeValue }} > <View style={styles.container}> <Text>Hello World</Text> </View> <Child1 /> </ThemeContext.Provider> ); } } const Child1 = () => <Child2 />     const Child2 = () => (     <ThemeContext.Consumer> {(val) => ( <View style={[styles.container, val.themeValue === 'dark' && {backgroundColor: 'black'}]}> <Text style={styles.text}>Hello from Component2</Text> <Text style={styles.text} onPress={val.toggleThemeValue}> Toggle Theme Value </Text> </View> )} </ThemeContext.Consumer> ) const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, text: { fontSize: 22, color: '#666' } }) export default Parent
C#
UTF-8
517
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace BL.DateParser { public class CsvParser : DataParser { public string FilePath { get; set; } protected override Stream GetStream() { return new FileStream(FilePath, FileMode.Open); } public CsvParser(string filePath, char[] delimiter) : base(delimiter) { this.FilePath = filePath; } } }
C
UTF-8
213
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> void write (void){ char word; printf("enter a word"); scanf("%c",&word); } int main() { char ch; ch = write; printf("%c",ch); return 0; }
Python
UTF-8
568
3.296875
3
[]
no_license
def menu(): import sys opcao = None print("=========================================="); print("| >>>>>>>>> Menu <<<<<<<<< |"); print("| 1 - Inserir valor |"); print("| 2 - Remover valor |"); print("| 3 - Carregar arvore de arquivo |"); print("| 0 - Sair |"); print("=========================================="); print("Sua opcao: "); opcao = sys.stdin.readline() # terminar, validat opcao para ser int return int(opcao);
Markdown
UTF-8
13,951
2.84375
3
[]
no_license
# Компонентный подход на примере styled-components и react-router Разберем компонентный подход на примере двух наиболее известных библиотек в Реакте Помните, в прошлых уроках мы говорили про то, что Реакт силён компонентным подходом? Мы ещё долго будем это [разбирать](https://reactjs.org/docs/composition-vs-inheritance.html), но начнём сейчас. ## Стайлед-компонентс Знаете, раньше был хайп по CSS-in-JS, люди изобретали всякие [JSS](https://github.com/cssinjs/jss) и прочие [Афродиты](https://github.com/Khan/aphrodite), но [все они](https://github.com/MicheleBertoli/css-in-js) были неудобными: да, прикольно иметь мощь Джс вместо настройки постцсс-плагинов, но за это приходилось расплачиваться удобством — посмотрите на этот синтаксис. ```jsx import React from "react"; import injectSheet from "react-jss"; const styles = { button: { background: props => props.color }, label: { fontWeight: "bold" } }; const Button = ({ classes, children }) => ( <button className={classes.button}> <span className={classes.label}>{children}</span> </button> ); export default injectSheet(styles)(Button); ``` Честно говоря, даже я долгое время не был впечатлён этим программированием объектами и обходился [ЦСС-модулями](https://github.com/css-modules/css-modules), но однажды летом 2017 случилось две вещи: я увидел [твитшторм](https://twitter.com/i/moments/861549552901468160) Джеймса Кайла и [стайлед-компонентс](https://www.styled-components.com/). Какая основная проблема ЦСС? В том, что во времена приложений мы зачем-то занимаемся AOP (Aspect Oriented Programming): описываем селекторы чтобы прицепить к компоненту (у нас же везде компонентный подход). ![](https://i.imgur.com/kXLb57n.png) [Эндрю Стальтц](https://twitter.com/andrestaltz) нарисовал диаграммы с этими тремя разными подходами: ![](https://i.imgur.com/TxYI86d.jpg) ![](https://i.imgur.com/y9Ear21.jpg) ![](https://i.imgur.com/OvNzNgR.jpg) Видите победителя? Да, стайлед-компонентс оказался самым живучим и удобным. Ведь зачем делать `.header--nav-____---_---button` когда можно сразу написать компонент и его стили? Сравните: ```jsx // подобие БЭМ-а import "./headerStyles.css"; // стайлед-компонентс import styled from "styled-components"; const LogOutButton = styled.button` color: #fff; border: 1px solid #e3e3e3; // etc `; function Header() { return ( <header> <button className="header--nav--button">Log In</button> <LogOutButton>Log Out</LogOutButton> </header> ); } ``` Ого-го, это что за магия? Это [стайлед-компонентс](https://www.styled-components.com/): наш первый босс, демонстрирующий компонентный подход. Как с этим работать? Да просто: используете функцию `styled(component)` чтобы застилизовать компонент. Как это работает? Автор, Макс Стойбер, рассказал в своём блоге: [The magic behind 💅 styled-components](https://mxstbr.blog/2016/11/styled-components-magic-explained/). За это отвечает [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) — фича из ES2015 (сам Экмаскрипт мы ещё в будущем разберём). Почему я написал `styled(component)`, а в примере выше `styled.button`? Потому что тут тот же принцип, что и в Реакте: ```jsx // Джсх <h1>Заголовок</h1>; // createElement React.createElement("h1", null, "Заголовок"); ``` Чтобы не грузить людей всякими `import { h1 } from 'React'` или `import { button } from 'styled-components'`, у Реакта и Стайлед-компонентс есть так называемые шорткаты (или альясы): эти библиотеки сами разбираются с дефолтными тегами ХТМЛ. ### Пропы в СК Окей, едем дальше. Одна из важных фич СК это работа с пропами: вы передаёте проп в СК, а в самом СК — читаете его. ```jsx import styled, { css } from styled-components; const Button = styled.button` display: inline-block; border-radius: 3px; padding: 0.5rem 0; margin: 0.5rem 1rem; width: 11rem; background: transparent; color: white; border: 2px solid white; ${props => props.kind === 'primary' && css` background: white; color: palevioletred; `} `; <Button>Обычная кнопка</Button> <Button kind="primary">Розовая кнопка</Button> ``` --- На этом моменте я вас должен отпустить читать [официальную документацию](https://www.styled-components.com/docs): ни один курс не объяснит лучше оригинала, а вам нужно учиться добывать информацию самому, если вы ещё не, а пока я отвечу на пару не заданных вопросов. #### Неужели можно хранить всё вместе? И стили, и отображение Можно, почему нет? У нас же **компонентный** подход, нам нет нужды разделять стили, логику и отображение, поэтому писать в одном файле и СК и их рендер — нормально. Но если вам кажется что слишком много компонентов, то выделите их в файл `styled.js` и положите в ту же директорию, что и компонент: например, ``` /src - /Header -- index.js -- Search.js -- styled.js ``` #### А как писать логику? Или стилизовать существующий компонент? В будущем мы будем проходить стейты и классы, но отвечу на вопрос уже сейчас: стилизовать существующие компоненты можно, СК передаёт в них проп `className` со стилями, поэтому у компонента он должен быть. ```jsx // допустим, из другой библиотеки function Header(props) { return ( <header className={props.className}> <nav>...</nav> <button>...</button> </header> ); } const StHeader = styled(Header)` background-color: #000; `; // если нет чилдрена, то можно тег сразу закрыть <StHeader />; ``` --- Вот и всё знакомство с СК! Оцените красоту: больше не нужно писать стили в отдельном файле и работать с селекторами, если можно сразу писать компоненты и использовать их. --- Кстати, Стайлед-компонентс, как и Реакт-роутер, ставятся через ярн: `yarn add styled-components`. ## Реакт-роутер [Реакт-роутер](https://reacttraining.com/react-router/) иногда не любят: ещё бы, к четвёртой версии (вы помните про [Семвер](http://semver.org/)?) ребята сломали АПИ раза три, причём последний был настолько жёстким, что впору было называть отдельным продуктом: не было даже Upgrade Guide, который принят при смене версий. Реакт-роутер сильно поменялся и стал **Реакт**-роутером. И дело вот в чём. Что такое роутер? Что такое роутинг? Базовая идея (если мы говорим про фронтэнд) проста: отобразить такой-то компонент (страницу, сборник компонентов) по такому адресу. Например, если мы находимся на странице `/courses/react`, то нужно отобразить страницу курса по Реакту, если на `/courses` — список курсов, а на `/` — главную. Давайте попробуем написать псевдокод для этого? Например, заведём компонент `<Route />`, который будет отображать компонент в зависимости от пропов. Для этого мы будем работать с [window.location](https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/) — глобальным объектом, который даёт браузер. В нём есть много разных свойств, нас интересует `pathname` — текущий путь без домена. В пропе `path` мы указываем этот путь, а в `component` — какой компонент нужно отрендерить. ```jsx function Route(props) { // есть ли в текущем `pathname` путь, указанный в `props.path` // .includes это метод у String, строки // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes if (window.location.pathname.includes(props.path)) { // мы не можем сделать <component />, // потому что Реакт подумает что это хтмл-тег, // поэтому мы воспользуемся React.createElement() React.createElement(props.component, null, null); } } function App() { return ( <section> {/* хедер будет рендериться на всех страницах */} <Header /> <Route path="/courses/react" component={Main} /> <Route path="/courses" component={Main} /> <Route path="/" component={Main} /> </section> ); } ``` Поздравляю! Мы написали Реакт-роутер. Я не шучу, его философия динамического роутинга именно в этом и заключается: отрендерь компонент (`component`) здесь, если путь (`path`) сходится. Правда, у него есть ещё [проп](https://reacttraining.com/react-router/web/api/Route) `exact={true}`, чтобы рендерить только если жёсткое соответствие: у нас в примере на странице `/courses/react` отрендерятся все три компонента. Зацените, какая простая и крутая идея: **использовать компонент, чтобы отрендерить другой, если путь сошёлся**. Реакт-роутер, на самом деле, чертовски мощный и вам нужно о нём знать три компонента: [`<BrowserRouter />`](https://reacttraining.com/react-router/web/api/BrowserRouter), [`<Route />`](https://reacttraining.com/react-router/web/api/Route) и [`<Link />`](https://reacttraining.com/react-router/web/api/Link). Ещё у него есть [`<Redirect />`](https://reacttraining.com/react-router/web/api/Redirect) и немного других — прочтите [документацию](https://reacttraining.com/react-router/web), а пока: корректно работающая демка. Кстати, эту демку я бесстыже скопировал из той же документации, раздел Examples. iframe: https://codesandbox.io/embed/01650wwoxv _(синяя кнопка — редактор кода, бежевая — превью)_ ## Итог Компонентный подход простой, но богатый, и сегодня мы начали его разбирать. Нам ещё предстоит много уроков чтобы научиться с ним хорошо работать, но фундамент заложен сегодня. Кстати, думаю у вас есть вопрос — а оправдывает ли себя такой подход на больших проектах? Ведь он такой простой, не сложно ли потом поддерживать, когда _нужно больше фич_? Нет, потому что легко сделать сложно и сложно сделать легко — командам Реакта, СК и Реакт-роутера приходится сильно стараться, чтобы выдавать такие простые продукты.
TypeScript
UTF-8
1,081
2.515625
3
[]
no_license
import { enableProdMode, ElementRef } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; import {Polity} from './app/polity/polity'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); /******************* * POLITY SIMULATION *******************/ // for(let i=0; i< tiles.length; i++){ // let tile = tiles[i]; // console.log(`yo`); // } // let tanky = new Band(10,10, "Tanky"); // let tile = new Tile(1); // //iterate over each polity in the tile // for (let i = 0; i < 100; i++){ // console.log(`THIS IS YEAR ${i}`); // console.log(`SETTLED STATUS = ${tile._settled}`) // if(tile._polity){ // tile._polity.details(); // tile._polity.act(tile); // tile._polity.populationGrowth(); // // console.log(`Tile-${tile.id} has ${tile.space} space left.`) // tile.resetSpace(); // } // }
Python
UTF-8
7,363
2.953125
3
[]
no_license
#----------------------------------------------------------------- # Toy Blockchain for DSBA 20598 FinTech and Blockchain course # (c) 2019 Silvio Petriconi <myfirstname.mylastname@unibocconi.it> # License: GNU General Public License 3.0 #----------------------------------------------------------------- import hashlib import datetime from collections import namedtuple import binascii import json from utils import merkle import struct GENESIS_ROOT_DATA = [binascii.unhexlify('0000DEADBEEFBADCAFFEBAADF00D')] GENESIS_ROOT_NONCE = 0 GENESIS_NONCE = 101 # FIXME GENESIS_DIFFICULTY = 1 # Every block header is a namedtuple, immutability is automatically enforced. Blockheader = namedtuple('Blockheader', \ 'height prev timestamp difficulty merkleroot nonce') # Data for the genesis block. It has no previous, so the prev hash is zero. _genesisblock = Blockheader( height = 0, prev = binascii.unhexlify('0000000000000000000000000000000000000000000000000000000000000000'), timestamp = 1572328964, difficulty = GENESIS_DIFFICULTY, merkleroot = merkle.MerkleTree(GENESIS_ROOT_DATA).digest(), nonce = GENESIS_NONCE ) class Blockchain: def __init__(self, genesis = _genesisblock, hashfunc = None): self._blockhdrs = [] # list of block headers self._blockindex = {} # dict that maps blockheader hash to index self._hashfunc = hashfunc if hashfunc else lambda x : hashlib.sha256(x).digest() self._difficulty = GENESIS_DIFFICULTY self._append_block(genesis) # append genesis block def create_blockheader(self, merkleroot, nonce): ''' Creates a block candidate for the blockchain. :merkleroot: the merkle root of the block's data :param nonce: the nonce that generates a valid block hash :returns: the new block (without appending it to the chain) ''' # compute hash of previous block if len(self._blockhdrs) > 0: prevhash = self._hashfunc(self._serialize_hdr(self._blockhdrs[-1])) else: # Genesis block has hash over empty set as previous field. prevhash = self._hashfunc(b'') thisBlock = Blockheader( height=len(self._blockhdrs), \ prev = prevhash, \ timestamp=int(datetime.datetime.now().timestamp()), \ difficulty=self._difficulty, \ merkleroot=binascii.hexlify(merkleroot), \ nonce=nonce) return thisBlock def _serialize_hdr(self, blockhdr): # serializes a block header to binary format (big endian): # struct Blockheader { # uint64 height; # char[32] prev; # uint64 timestamp; # uint64 difficulty; # char[32] merkleroot; # uint64 nonce; # } return struct.pack(">I32sII32sI", *blockhdr) def _deserialise_hdr(self, bindata): # returns a block header from serialized binary data, without # checking its validity in any way return Blockheader._make(struct.unpack(">I32sII32sI", bindata)) def _append_block(self, blockheader): # actually appends block header without checking it blockhash = self._hashfunc(self._serialize_hdr(blockheader)) if blockhash in self._blockindex: raise RuntimeError(f"Block {blockhash} already inserted.") print("Block hash: ", blockhash) # if all checkes go through, save block hash in a dict blockheight = len(self._blockhdrs) self._blockindex[blockhash] = blockheight self._blockhdrs.append(blockheader) return blockheight def can_append(self, block, diagnostics=False): ''' Checks whether a candidate block is valid and can be appended to the chain. :param block: candidate block to be verified :param diagnostics: if set True, returns diagnostics :returns: True if block is valid, False otherwise. If diagnostics is True, returns a tuple (valid, errorstring). ''' if block.height != len(self._blockhdrs) or \ block.prev != self._hashfunc(self._serialize_hdr(self._blockhdrs[-1])): return (False, "Bad block: block height or prev block invalid.") \ if diagnostics else False if block.prev not in self._blockindex: return(False, "Bad prev hash pointer: prev block not in chain.") \ if diagnostics else False if self._blockindex[block.prev] != len(self._blockhdrs)-1: return(False, "Can't append block: prev isn't at end of chain.") \ if diagnostics else False # then, check that difficulty is set appropriately if self._difficulty != block.difficulty: return(False, "Block difficulty is not at current level.") \ if diagnostics else False if not self._blockhash_matches_difficulty(block): raise ValueError("Block hash POW not commensurate to difficulty.") return (True,'') if diagnostics else True def append_block(self, block): ''' :param block: block to be appended :returns: the height of the new blockchain. Raises RuntimeError if the block was already inserted or ValueError if the block is not a valid continuation of the chain. ''' # first, validate that the block height is n+1 and # that prev hash points to the last block on chain append_ok, errormsg = self.can_append(block, diagnostics=True) if not append_ok: raise ValueError(errormsg) return self._append_block(block) def _blockhash_matches_difficulty(self, blockhdr): hexHashstring = str(binascii.hexlify(self._hashfunc(self._serialize_hdr(blockhdr)))) return hexHashstring.startswith('0'*self._difficulty) def get_block_by_hash(self, its_hash): ''' Finds a block by its hash value. :param its_hash: (binary) hash value of the block :returns: the block if it exists in the chain, otherwise None. ''' if its_hash in self._blockindex: return self._blockhdrs[self._blockindex[its_hash]] else: return None def is_valid(self): ''' Verifies the validity of the entire chain. ''' # FIXME pass def get_block(self, n): ''' Obtains a block. :param n: the index of the block to be obtained :returns: the n-th block in the chain (0=genesis), None if not existent ''' return self._blockhdrs[n] if n < len(self._blockhdrs) else None if __name__=='__main__': B = Blockchain() nonce = 0 while True: g = Blockheader(height=_genesisblock.height, prev=_genesisblock.prev, timestamp = _genesisblock.timestamp, difficulty=_genesisblock.difficulty, merkleroot=_genesisblock.merkleroot, nonce=nonce) print (f"Nonce: {nonce} Hash: ", binascii.hexlify(B._hashfunc(B._serialize_hdr(g)))) if B._blockhash_matches_difficulty(g): print ("======= FOUND GENESIS NONCE: =========", nonce) break nonce += 1
Java
UTF-8
453
2.21875
2
[]
no_license
package com.app.runners.model; /** * Created by Fede_CC on 22/09/2018. */ public class Resource { public String hash = ""; public String url = ""; public String type = ""; public Resource(){ this.hash = ""; this.url = ""; this.type = ""; } public Resource(String newHash, String newUrl, String newType){ this.hash = newHash; this.url = newUrl; this.type = newType; } }
C#
UTF-8
704
3.109375
3
[]
no_license
using System; using System.IO; namespace Extensibility { public class FileLogger : ILogger { private readonly string _path; public FileLogger(string path) { this._path = path; } public void LogError(string message) { Log(message, "ERROR"); } public void LogInfo(string message) { Log(message, "INFO"); } private void Log(string message, string messageType) { using (StreamWriter streamWriter = new StreamWriter(_path, true)) { streamWriter.WriteLine("{0}: {1}" , messageType, message); } } } }
Python
UTF-8
1,841
2.828125
3
[]
no_license
import pickle from pandas import read_csv from pandas.plotting import scatter_matrix from matplotlib import pyplot from sklearn.model_selection import train_test_split, KFold, cross_val_score from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC if __name__ == '__main__': # 导入数据集 filename = 'data/iris.data' names = ['separ-length', 'separ-width', 'petal-length', 'petal-width', 'class'] dataset = read_csv(filename, names=names) # 概述数据 print('数据维度:行 %s, 列 %s' % dataset.shape) print(dataset.head(10)) print(dataset.describe()) print(dataset.groupby('class').size()) # 数据可视化 dataset.plot(kind='box', subplots=True, layout=(2, 2), sharex=False, sharey=False) # 评估模型:80%数据训练,20%数据评估 array = dataset.values X = array[:, 0:4] Y = array[:, 4] validation_size = 0.2 seed = 7 # X_train, Y_train: 训练 # X_validation, Y_validation: 评估验证 X_train, X_validation, Y_train, Y_validation = \ train_test_split(X, Y, test_size=validation_size, random_state=seed) svm_model = SVC() svm_model.fit(X=X_train, y=Y_train) predictions = svm_model.predict(X_validation) # print(accuracy_score(Y_validation, predictions)) # print(confusion_matrix(Y_validation, predictions)) # print(classification_report(Y_validation, predictions)) with open('/Users/langshiquan/workspace/ml/iris/models/iris.model', 'wb') as f: pickle.dump(svm_model, f)
Java
UTF-8
1,385
2.75
3
[]
no_license
package kotakpasir; import java.util.Vector; import java.awt.Color; public abstract class Element{ private int absis; private int ordinat; private int temperatur; private static double densitas; private static String nama; private static Color warna; public int getAbsis(){ return absis; } public int getOrdinat(){ return ordinat; } public int getTemperatur(){ return temperatur; } public void setAbsis(int _absis){ absis = _absis; } public void setOrdinat(int _ordinat){ ordinat = _ordinat; } public void setTemperatur(int _temperatur){ temperatur = _temperatur; } public void mendingin(){ temperatur--; } public void memanas(){ temperatur++; } public void moveUp(){ ordinat--; } public void moveDown(){ ordinat++; } public void moveLeft(){ absis--; } public void moveRight(){ absis++; } public void moveUpRight(){ moveUp(); moveRight(); } public void moveUpLeft(){ moveUp(); moveLeft(); } public void moveDownRight(){ moveDown(); moveRight(); } public void moveDownLeft(){ moveDown(); moveLeft(); } abstract void life(String[][] a, Vector<Element> DE, int EnvTemp); public boolean isSameElement(Element OtherElement){ return nama == OtherElement.getNama(); } public abstract String getNama(); public abstract Color getWarna(); public abstract double getDensitas(); }
JavaScript
UTF-8
1,741
2.828125
3
[ "MIT" ]
permissive
// Dependencies const express = require('express'); const path = require('path'); const fs = require('fs'); const { v4: uuidv4 } = require('uuid'); var dbNotes = require('./db/db.json'); const app = express(); const PORT = process.env.PORT || 3000; app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(express.static('public')); // ROUTES GET METHOD // //Route to index.html file app.get('/', (req, res) => { res.sendFile(path.join(__dirname, './public/index.html')); }); //Route to notes.html file app.get('/notes', (req, res) => { // console.log(req); // console.log(res); res.sendFile(path.join(__dirname, './public/notes.html')); }); //Route to db file to create a new note app.get('/api/notes', (req, res) => { res.json(dbNotes); }); //Route to Html file app.get('*', (req, res) => { res.sendFile(path.join(__dirname, './public/index.html')); }); //POST METHOD app.post('/api/notes', (req, res) => { console.log("DATABASE ARRAY WE PUSHIN TO", dbNotes); const newEntry = req.body; req.body.id = uuidv4(); console.log(newEntry); console.log(newEntry.id); // PUSH newEntry to dbNotes dbNotes.push(newEntry); console.log(dbNotes); res.json(dbNotes); }); // DELETE NOTES WITH DELETE METHOD app.delete('/api/notes/:id', (req, res) => { console.log("ARRAY TO DELETE FROM", dbNotes) console.log("params.id", req.params.id) const deletedNotes = dbNotes.find(dbNotes => dbNotes.id === req.params.id) console.log("DELETED notes", deletedNotes) dbNotes = dbNotes.filter(dbNotes => dbNotes.id !== req.params.id) res.json(deletedNotes); }); app.listen(PORT, () => console.log(`App listening on PORT ${PORT}`));
C++
UTF-8
412
2.875
3
[]
no_license
#ifndef _BOOK_ #define _BOOK_ #include <iostream> #include <ostream> #include <string> #include <vector> using namespace std; class Book { private: string title; string author; int numberPages; public: Book(); ~Book(); Book(string name, string author, int numberPages); friend ostream& operator<< (ostream &o, Book const &book); string getTitle(); void setTitle(string title); }; #endif
Java
UTF-8
675
2.171875
2
[]
no_license
package com.tommy.rider.adapter; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; /** * Created by navneet on 4/6/16. */ public interface RetrofitArrayAPI { /* * Retrofit get annotation with our URL * And our method that will return us details of student. */ @GET("getRequest/request_id/{requestid}") Call<List<RequestInfo>> repoContributors( @Path("requestid") String requestid); @GET("home/getpercentage") Call<List<Contributor>> repoContributors( @Query("start_time") String starttime, @Query("end_time") String endtime); }
Go
UTF-8
2,041
2.8125
3
[]
no_license
package middleware import ( "ginblog/utils" "ginblog/utils/errmsg" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "net/http" "strings" "time" ) var JwtKey = []byte(utils.JwtKey) type MyClaims struct { Username string `json:"username"` jwt.StandardClaims } var code int //生成token func SetToken(username string)(string,int){ expireTime :=time.Now().Add(10*time.Hour) SetClaims :=MyClaims{ username, jwt.StandardClaims{ ExpiresAt: expireTime.Unix(), Issuer:"ginblog", }, } reqClaim := jwt.NewWithClaims(jwt.SigningMethodHS256,SetClaims) token,err :=reqClaim.SignedString(JwtKey) if err!=nil{ return "",errmsg.ERROR } return token,errmsg.SUCCSE } //验证token func CheckToken(token string)(*MyClaims,int){ setToken,_ := jwt.ParseWithClaims(token,&MyClaims{}, func(token *jwt.Token) (interface{}, error) { return JwtKey,nil }) if key, _:= setToken.Claims.(*MyClaims);setToken.Valid{ return key,errmsg.SUCCSE } else{ return nil,errmsg.ERROR } } //jwt中间件 func JwtToken()gin.HandlerFunc{ return func(c *gin.Context) { tokenHeader := c.Request.Header.Get("Authorization") if tokenHeader ==""{ code = errmsg.ERROR_TOKEN_EXIT c.JSON(http.StatusOK,gin.H{ "code":code, "message":errmsg.GetErrMsg(code), }) c.Abort() return } checkToken := strings.SplitN(tokenHeader," ",2) if (len(checkToken)!=2&&checkToken[0] !="Bearer"){ code = errmsg.ERROR_TOKEN_TYPE_WRONG c.JSON(http.StatusOK,gin.H{ "code":code, "message":errmsg.GetErrMsg(code), }) c.Abort() return } key,tCode := CheckToken(checkToken[1]) if tCode == errmsg.ERROR{ code = errmsg.ERROR_TOKEN_WRONG c.JSON(http.StatusOK,gin.H{ "code":code, "message":errmsg.GetErrMsg(code), }) c.Abort() return } if time.Now().Unix()>key.ExpiresAt{ code = errmsg.ERROR_TOKEN_RUNTIME c.JSON(http.StatusOK,gin.H{ "code":code, "message":errmsg.GetErrMsg(code), }) c.Abort() return } c.Set("username",key.Username) c.Next() } }
Java
UTF-8
2,038
4.1875
4
[ "MIT" ]
permissive
/** * A Simple Algorithm to Execute Floyd Warshall. * * This checks whether edges can be connected from one to another vertex. * Note that the graph is impelmented using an Adjacency Matrix. * * @author seanlowjk */ public class FloydGraph { /** * The number of Vertices in the Graph. */ private int numOfVertex; /** * The Data Structure used for the graph. */ private boolean[][] adjMatrix; /** * Create a Graph with an empty adjacency matrix. * @param numOfVertex the number of vertices in the graph. */ public FloydGraph(int numOfVertex) { this.numOfVertex = numOfVertex; adjMatrix = new boolean[numOfVertex][numOfVertex]; for (int i = 0; i < numOfVertex; i ++) { for (int j = 0; j < numOfVertex; j ++) { adjMatrix[i][j] = false; } } } /** * Adds an edge to the graph. * * Note that this Edge is uni-directional. * @param i the start vertex. * @param j the end vertex. */ public void addEdge(int i, int j) { adjMatrix[i][j] = true; } /** * An SSSP Algorithm. * * Except that this is to check connectivity between vertices. * Time Complexity: O(V * V * V) */ public void floydWarshall() { for (int k = 0; k < numOfVertex; k ++) { for (int i = 0; i < numOfVertex; i ++) { for (int j = 0; j < numOfVertex; j ++) { adjMatrix[i][j] = adjMatrix[i][j] || (adjMatrix[i][k] && adjMatrix[k][j]); } } } } /** * Checks if two vertices can be connected from one vertex to another. * @param source the source vertex. * @param dest the destination vertex. * @return true if they can be accessed by a certain network. False if otherwise. */ public boolean areEdgesConnected(int source, int dest) { return adjMatrix[source][dest]; } }
Rust
UTF-8
8,858
2.984375
3
[]
no_license
use counter::Counter; use smorse::{smalpha, smalpha_all, smorse}; use std::collections::HashSet; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf}; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "smorse", about = "convert strings to squashed morse code")] struct Opts { /// convert a lowercase string to squashed morse input: Option<String>, /// path to wordlist #[structopt(short, long = "word-list", parse(from_os_str))] word_list: Option<PathBuf>, /// find the only sequence that's the code for 13 different words #[structopt(long = "bonus-1-1")] bonus_1_1: bool, /// find the only word that has 15 dashes in a row #[structopt(long = "bonus-1-2")] bonus_1_2: bool, /// find all 21-letter words with the same number of dots and dashes #[structopt(long = "bonus-1-3")] bonus_1_3: bool, /// find the only 13-letter word that encodes to a palindrome #[structopt(long = "bonus-1-4")] bonus_1_4: bool, /// find all 13-char sequences which do not appear in the encoding of any word #[structopt(long = "bonus-1-5")] bonus_1_5: bool, /// search for permutations of an alphabet which produce this squashed morse value #[structopt(long)] smalpha: Option<String>, /// search for permutations of an alphabet which produce this sm value for each line in this input file #[structopt(long = "smorse-file", parse(from_os_str))] smorse_file: Option<PathBuf>, /// find lexicographically minimal input which produces exactly one alphabet #[structopt(long = "bonus-2-2")] bonus_2_2: Option<Option<i128>>, } type Rv = Result<(), Box<dyn Error>>; fn main() -> Rv { let opts = Opts::from_args(); if let Some(s) = opts.input { println!("{}", smorse(&s)); } if let Some(wl_path) = opts.word_list { if opts.bonus_1_1 { bonus_1_1(&wl_path)?; } if opts.bonus_1_2 { bonus_1_2(&wl_path)?; } if opts.bonus_1_3 { bonus_1_3(&wl_path)?; } if opts.bonus_1_4 { bonus_1_4(&wl_path)?; } if opts.bonus_1_5 { bonus_1_5(&wl_path)?; } if !(opts.bonus_1_1 || opts.bonus_1_2 || opts.bonus_1_3 || opts.bonus_1_4 || opts.bonus_1_5) { let mut counts: Counter<u8> = Counter::new(); for word in get_words(&wl_path)? { counts += smorse(&word).as_bytes().iter().cloned(); } println!("Total counts:"); for (b, c) in counts.iter() { println!(" {}: {}", *b as char, c); } } } else { if opts.bonus_1_1 || opts.bonus_1_2 || opts.bonus_1_3 || opts.bonus_1_4 || opts.bonus_1_5 { eprintln!("bonus challenges require wordlist"); } } if let Some(s) = opts.smalpha { let expect = smorse(&(b'a'..=b'z').map(char::from).collect::<String>()) .chars() .collect::<Counter<_>>(); let got = s.trim().chars().collect::<Counter<_>>(); if expect != got { eprintln!("Bad input for smalpha: require:\n{:#?}", expect); } match smalpha(&s) { None => println!("no permutation found for this alphabet"), Some(s) => println!("{}", s), } } if let Some(path) = opts.smorse_file { for input in get_words(&path)? { println!("{} -> {:?}", input, smalpha(&input)); } } if let Some(start) = opts.bonus_2_2 { bonus_2_2(start); } Ok(()) } fn get_words(wl_path: &Path) -> Result<Box<impl Iterator<Item = String>>, Box<dyn Error>> { let wordlist = File::open(wl_path)?; let reader = BufReader::new(wordlist); Ok(Box::new(reader.lines().filter_map(|r| r.ok()))) } /// find the only sequence that's the code for 13 different words fn bonus_1_1(wl_path: &Path) -> Rv { let counts = get_words(wl_path)? .map(|word| smorse(&word)) .collect::<Counter<_>>(); for (seq, count) in counts.iter() { if *count == 13 { println!("Sequence encoding 13 words: {}", seq); break; } } Ok(()) } /// find the only word that has 15 dashes in a row fn bonus_1_2(wl_path: &Path) -> Result<(), Box<dyn Error>> { let needle = b"---------------"; 'outer: for word in get_words(wl_path)? { let seq = smorse(&word); let hay = seq.as_bytes(); for w in hay.windows(15) { if w == needle { println!("{} encodes as {} which has 15 dashes in a row", word, seq); break 'outer; } } } Ok(()) } /// find all 21-letter words with the same number of dots and dashes fn bonus_1_3(wl_path: &Path) -> Rv { for word in get_words(wl_path)?.filter(|word| word.len() == 21) { let seq = smorse(&word); let counts = seq.as_bytes().iter().collect::<Counter<_>>(); if counts.get(&b'-').is_some() && counts.get(&b'-') == counts.get(&b'.') { println!( "{} encodes as {} which has {} each dots and dashes", word, seq, counts.get(&b'-').unwrap() ); } } Ok(()) } /// find the only 13-letter word that encodes to a palindrome fn bonus_1_4(wl_path: &Path) -> Rv { for word in get_words(wl_path)?.filter(|word| word.len() == 13) { let seq = smorse(&word); let seqb = seq.as_bytes(); if seqb.iter().zip(seqb.iter().rev()).all(|(a, b)| a == b) { println!("{} encodes as {} which is a palindrome", word, seq); } } Ok(()) } fn n2s(n: u16) -> String { let mut out = String::with_capacity(16); for i in (0_u16..16).rev() { if n & (1 << i) > 0 { out.push('-') } else { out.push('.') } } out } /// find all 13-char sequences which do not appear in the encoding of any word fn bonus_1_5(wl_path: &Path) -> Rv { let word_sequences = get_words(wl_path)? .map(|word| smorse(&word).into_bytes()) .collect::<HashSet<_>>(); println!("13-char sequences which appear in no words:"); for seq in (0_u16..(1 << 13)).map(n2s) { let needle = &seq.as_bytes()[3..]; // final 13 if !word_sequences .iter() .any(|ws| ws.windows(13).any(|hay| needle == hay)) { println!(" {}", &seq[3..]); } } Ok(()) } /// Find lexicographically minimal input which produces exactly one alphabet. /// /// Every input which produces an alphabet contains 82 dots and dashes, and /// no other symbols. Of those, 44 are dots, and 38 are dashes. /// /// Lexicographically, dashes are lower than dots. We can therefore restate /// the problem as: Representing dashes as 0 and dots as 1, find the lowest /// number containing 44 `1` bits and 38 `0` bits, which when suitably transformed /// produces exactly one alphabet. /// /// Because of this restatement, we can sharply reduce the number of permutations /// we must consider, because there are efficient algorithms for generating /// integers containing exactly N `1` bits. fn bonus_2_2(start: Option<i128>) { // this is expected to be a long-running process, so we use rayon::iter::ParallelBridge; use rayon::prelude::ParallelIterator; use smorse::input_generator::InputGenerator; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; let halt = Arc::new(AtomicBool::new(false)); let hhalt = halt.clone(); // gets moved into the handler ctrlc::set_handler(move || hhalt.store(true, Ordering::SeqCst)) .expect("Error setting Ctrl-C handler"); if let Some((_, input)) = InputGenerator::maybe_start_at(start) .enumerate() .par_bridge() .inspect(|(idx, input)| { // emit some output every once in a while just to demonstrate activity if idx & 0xff_ffff == 0 { println!("{}", input); } }) .map_with(halt, |halt, (idx, input)| { // check the interrupt every 256 iterations if idx & 0xfff == 0 && halt.load(Ordering::SeqCst) { println!(); println!("Checked {} inputs; continue with", idx); println!(" smorse --bonus-2-2 {}", InputGenerator::i2n(&input)); None } else { Some((idx, input)) } }) .while_some() .find_first(|(_, input)| smalpha_all(&input).take(2).count() == 1) { println!("{} => {}", input, smalpha(&input).unwrap()); } else { println!("no valid input was found"); } }
Python
UTF-8
1,485
3.078125
3
[]
no_license
import os, time import sys import signal # Импорт модуля для установки и ловли сигнала import time # Модуль для тестов, ставит на паузу скрипт # Функция для показа пользователю информации о номере сигнале и выход из программы def sig_handler(sig_num, frame): print("SIGNAL: " + str(sig_num)) exit(0) # Устанавливаем сигналы signal.signal(signal.SIGINT, sig_handler) # Cttl + C. Сигнал 2 signal.signal(signal.SIGTERM, sig_handler) # Сигнал 15, прекращающий выполнение программы signal.signal(signal.SIGHUP, sig_handler) # Если пользователь выходит из терминала. Сигнал 1 print('Hello! I am an example') pid = os.fork() print('pid of my child is %s' % pid) if pid == 0: print('I am a child. Im going to sleep') for i in range(1,40): print('mrrrrr') a = 2**i print(a) pid = os.fork() if pid == 0: print('my name is %s' % a) sys.exit(0) else: print("my child pid is %s" % pid) time.sleep(1) print('Bye') sys.exit(0) else: for i in range(1,200): print('HHHrrrrr') time.sleep(1) print(3**i) print('I am the parent') #pid, status = os.waitpid(pid, 0) #print "wait returned, pid = %d, status = %d" % (pid, status)
JavaScript
UTF-8
1,016
2.5625
3
[]
no_license
const UPDATE_PERCENT = "UPDATE_PERCENT" const UPDATE_URL = "UPDATE_URL"; const FILE_UPLOADED = "FILE_UPLOADED" export const reducer = (state = {}, action) => { switch(action.type){ case FILE_UPLOADED: return { ...state, fileUploadedStatus : action.fileUploadedStatus } case UPDATE_PERCENT: return { ...state, percent : action.percent } case UPDATE_URL: return { ...state, url :action.url } default: return state; } } export const updatePercent = (percent)=>{ return { type : UPDATE_PERCENT, percent : percent } } export const updateUrl = (url)=>{ return { type : UPDATE_URL, url : url } } export const fileUploaded = (fileUploadedStatus)=>{ return { type : FILE_UPLOADED, fileUploadedStatus : fileUploadedStatus } }
Markdown
UTF-8
744
2.578125
3
[]
no_license
# About This robot is used to take orders from different tables in a restaurant. The taken on the basis of different colour flags shown by the customer. Once the robot takes the order from all the tables, it goes to the kitchen area to place the order in respective cooking zone, which are marked by similar colour flags. # Hardware Used Firebird V kit is used to make this robot. # Environment The code is written in Arduino IDE and Embedded C. <br> For Embedded C code, the C source file <br> Pin number of Arduino Mega is matched with pins on firebird V using the datasheet.<br> <br><br> For more information visit http://www.nex-robotics.com/resources/using-arduino-to-program-firebird-v-2560-platform.html # Co-Authors Harish Kumar S Guragol<br>
C#
UTF-8
2,810
2.703125
3
[]
no_license
using SamuraiDbModel; using System.Collections.Generic; using System.Linq; namespace SamuraiLogic { public class NumberingOfMatches { public List<CompetitionGridNode> SetMatchesGridNumber(List<CompetitionGridNode> nodes) { foreach (var group in nodes.GroupBy(x => x.CompetitionGridId).Select(x => new { gridId = x.Key, nodes = x.Select(m => m) }).ToList()) { int i = 1; foreach (var gridNode in group.nodes.OrderByDescending(x => x.NodeLevel).ThenBy(x => x.ParentNodeId).ThenBy(x => x.CompetitorRest)) { gridNode.GridMatchNumber = gridNode.Match.GridMatchNumber = i++; } } return nodes; } public List<CompetitionGridNode> SetMatchesGlobalNumber(List<CompetitionGridNode> nodes) { int i = 1; foreach (var group in nodes.GroupBy(x => x.Match.Tatami).Select(x => new { tatami = x.Key, nodes = x.Select(m => m) }).ToList()) { foreach (var gridNode in group.nodes.OrderByDescending(x => x.NodeLevel) .ThenBy(x=> x.CompetitionGrid.CompetitionCategory.Name) .ThenBy(x=> x.GridMatchNumber)) { gridNode.GlobalMatchNumber = gridNode.Match.GlobalMatchNumber = i;//$"{group.tatami.MatchPrefix}{i}"; i++; } } return nodes; } public List<Match> InitTatamiMatchNumber(List<CompetitionGridNode> gridNodes, List<Match> matches, List<Tatami> tatamis) { List<int> tatamiIds = tatamis.Select(x => x.Id).ToList(); foreach (var id in tatamiIds) { int tatamiMatchNumber = 1; List<int> gridIds = matches.Where(x => x.TatamiId == id).Select(x => x.CompetitionGridId).Distinct().ToList(); var tempGridNodes = gridNodes .Where(x => gridIds.Contains(x.CompetitionGridId) && !x.CompetitorId.HasValue) .OrderBy(x => x.CompetitionGrid.TatamiOrder) .ToList(); int maxNodeLevel = tempGridNodes.Select(x => x.NodeLevel).Max(); for (int i = maxNodeLevel; i >= 0; i--) { var nodes = tempGridNodes.Where(x => x.NodeLevel == i).OrderBy(x => x.CompetitionGridId).ToList(); foreach (var n in nodes) { var match = matches.SingleOrDefault(m => m.Id == n.MatchId); match.TatamiMatchNumber = tatamiMatchNumber++; } } } return matches; } } }
Markdown
UTF-8
1,168
2.640625
3
[ "MIT" ]
permissive
# Routes Folder Routes define endpoints within your application. Fastify provides an easy path to a microservice architecture, in the future you might want to independently deploy some of those. In this folder you should define all the routes that define the endpoints of your web application. Each service is a [Fastify plugin](https://www.fastify.io/docs/latest/Reference/Plugins/), it is encapsulated (it can have its own independent plugins) and it is typically stored in a file; be careful to group your routes logically, e.g. all `/users` routes in a `users.js` file. We have added a `root.js` file for you with a '/' root added. If a single file become too large, create a folder and add a `index.js` file there: this file must be a Fastify plugin, and it will be loaded automatically by the application. You can now add as many files as you want inside that folder. In this way you can create complex routes within a single monolith, and eventually extract them. If you need to share functionality between routes, place that functionality into the `plugins` folder, and share it via [decorators](https://www.fastify.io/docs/latest/Reference/Decorators/).
Shell
UTF-8
151
2.890625
3
[]
no_license
#!/bin/bash -x isAvailable= env | awk -F= '{print $1}' if [[ $isAvailable == 0 ]] then export usersecret="dH34xjaa23" else echo "Already value set " fi
C++
UTF-8
122
2.515625
3
[]
no_license
#include<iostream> using namespace std; int main(){ int n=3,temp; temp = n /2/2; cout << temp <<endl; return 0; }
Rust
UTF-8
1,789
2.78125
3
[]
no_license
mod aabb; mod aarect; mod block; mod bvhnode; mod constantmedium; mod hitrecord; mod rotate; mod sphere; mod translate; use crate::{Ray, Vec3}; use aabb::Aabb; pub use aarect::{XyRect, XzRect, YzRect}; pub use block::Block; pub use bvhnode::BvhNode; pub use constantmedium::ConstantMedium; pub use hitrecord::HitRecord; pub use rotate::{RotateX, RotateY, RotateZ}; pub use sphere::{MovingSphere, Sphere}; use std::{fmt::Debug, ops::Range, sync::Arc}; pub use translate::Translate; /** * Trait for hittable objects. */ pub trait Hittable: Debug + Send + Sync { #[must_use] fn hit(&self, r: &Ray, tr: Range<f64>) -> Option<HitRecord>; #[must_use] fn bounding_box(&self, tr: Range<f64>) -> Aabb; } impl Hittable for [Arc<dyn Hittable>] { fn hit(&self, r: &Ray, t: Range<f64>) -> Option<HitRecord> { let mut rec = None; let mut closest_so_far = t.end; for object in self { if let Some(temp_rec) = object.hit(r, t.start..closest_so_far) { closest_so_far = temp_rec.t(); rec = Some(temp_rec); } } rec } fn bounding_box(&self, tr: Range<f64>) -> Aabb { match self.len() { 0 => Aabb::new(Vec3(0.0, 0.0, 0.0), Vec3(0.0, 0.0, 0.0)), 1 => self.first().unwrap().bounding_box(tr), _ => self .iter() .map(|object| object.bounding_box(tr.clone())) .reduce(Aabb::surrounding_box) .unwrap(), } } } impl Hittable for Vec<Arc<dyn Hittable>> { fn hit(&self, r: &Ray, tr: Range<f64>) -> Option<HitRecord> { self.as_slice().hit(r, tr) } fn bounding_box(&self, tr: Range<f64>) -> Aabb { self.as_slice().bounding_box(tr) } }
PHP
UTF-8
768
2.640625
3
[]
no_license
<?php class modifyForm { private $username; private $price; private $id; public function __construct($username = null, $email = null, $id = null) { $this->username = $username; $this->email = $email; $this->id = $id; } public function html() { ?> <form action="/finals/?page=modify" method="POST"> <input name="username" value="<?= $this->username ?>"> <input name="password" value="<?= $this->password ?>"> <input type="hidden" name="id" value="<?= $this->id ?>"> <button type="submit">Save</button> </form> <?php } } ?>
Java
UTF-8
896
3.703125
4
[]
no_license
package com.sda.SzukamDrugiejPolowki; public class Main { public static void main(String[] args) { int[] tab = {1, 2, 4, 6, 7}; int p = tab.length; int x = 1; // szukany element int l = 1; // boolean ending = false; while (!ending) { if (l > p) { System.out.println("nie odnaleziono elementu o wartosci " + x); ending = true; } else { int s = (l + p - 1) / 2; // ustawiamy srodkowy index tab if (tab[s] == x) { System.out.println("Odnaleziono " + x + " pod indeksem " + s); ending = true; } else if (tab[s] > x) { p = s - 1; } else { l = s + 1; } } } } }
C++
UTF-8
2,211
3.609375
4
[]
no_license
#include <iostream> #include <string> #include "BankAccount.h" using namespace std; BankAccount::BankAccount() { Balance = 0; Interest = 0; Time = 0; } int main() { double Amount; double rate; double timee; int loop = 1; int option = 1; BankAccount call; call.setBalance(0.0); while (loop != 0) { cout<<"Here are your options: "<<endl<<endl; cout<<"1: Depost \t"<<"2: Withdraw"<<endl; cout<<"3: Balance \t"<<"4: Interest"<<endl; cout<<"The exit press 0:"<<endl; cout<<":"; cin >> option; if (option==1) { cout << "Enter deposit amount: " << endl; cin >> Amount; call.Deposit(Amount); } if (option==2) { cout << "Enter withdraw amount: " << endl; cin >> Amount; call.Withdraw(Amount); } if (option==3) { double balance = call.getBalance(); cout << balance << endl; } if (option==4) { cout << "Enter your Interest Rate: " << endl <<endl; cin >> rate; call.setInterestRate(rate); cout << "Enter your time period in years: " << endl <<endl; cin >> timee; call.setTime(timee); double adjustedRate = call.InterestRate(); cout << "Your Interest for " << timee << " years " << "at a rate of " << rate << " is " << adjustedRate << endl << endl; } } return 0; } //------------------------------------------------------------------ void BankAccount::Deposit(double amount) { Balance = Balance + amount; } void BankAccount::Withdraw(double amount) { Balance = Balance - amount; } double BankAccount::getBalance() const { return Balance; } void BankAccount::setBalance(double newBalance) { Balance = newBalance; } void BankAccount::setTime(double newTime) { Time = newTime; } void BankAccount::setInterestRate(double newRate) { Interest = newRate; } double BankAccount::InterestRate() const { double AdjustedRate = Balance * (1+ Time * Interest); }
Python
UTF-8
3,755
2.84375
3
[]
no_license
import tensorflow as tf import pandas as pd from sklearn.model_selection import train_test_split import numpy as np import os from dataProcessing_NYC import dataProcessing_NYC os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' rng = np.random learning_rate = 0.01 epochs = 50 display_step = 1 # Network Parameters n_hidden_1 = 10 # 1st layer number of neurons n_hidden_2 = 10 # 2nd layer number of neurons #n_input = 263 # number of features #n_classes = 1 # one target sess = tf.Session() #Import the data data = pd.read_csv('New York City Taxi Trip Duration.csv') x_data=dataProcessing_NYC(data) #dataprocessing #set the dependent variable which is saleprice y_data=x_data['trip_duration'] x_data=x_data.drop(['dropoff_datetime','pickup_longitude','pickup_latitude','dropoff_longitude','dropoff_latitude','trip_duration'],axis = 1) #Splitting the data int train and test as 70/30 x_train, x_test, y_train, y_test = train_test_split(x_data, y_data,test_size=.30) x_train_array = np.asmatrix(x_train.values.tolist()) #print(x_train_array) y_train_array = np.asmatrix(y_train.values.tolist()) x_test_array = np.asmatrix(x_test.values.tolist()) y_test_array = np.asmatrix(y_test.values.tolist()) y_train_array = y_train_array[:,None] y_test_array = y_train_array[:,None] x_train_array=np.float32(x_train_array) y_train_array=np.float32(y_train_array) x_test_array=np.float32(x_test_array) y_test_array=np.float32(y_test_array) n_samples = x_train_array.shape[0] n_input = x_train_array.shape[1] # number of features print("no of clumns : ", x_train_array.shape[0]) n_classes = 1 # one target #print("rows: ",n_samples) #print("colums : ", x_train_array.shape[1]) # tf Graph Input X = tf.placeholder("float") Y = tf.placeholder("float") # Create neural network model def multilayer_perceptron(x, weights, biases): # Hidden layer with RELU activation layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Hidden layer with RELU activation layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) # Output layer with linear activation out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] out = tf.sigmoid(out_layer) return out # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Construct model pred = multilayer_perceptron(X, weights, biases) error = tf.subtract(y_test_array, pred) total_error = tf.reduce_sum(tf.square(tf.subtract(y_test_array, tf.reduce_mean(y_test_array)))) unexplained_error = tf.reduce_sum(tf.square(tf.subtract(y_test_array, pred))) # Define loss and optimizer cost = tf.reduce_mean(tf.square(Y-pred)) #cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y)) #optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) #end new #points = [[], []] init = tf.global_variables_initializer() sess.run(init) for i in list(range(epochs)): for x, y in zip(x_train_array, y_train_array): sess.run(optimizer, feed_dict={X: x, Y: y}) rmse = sess.run(tf.sqrt(tf.reduce_mean(tf.square(error))), feed_dict={X: x_test_array, Y: y_test_array}) print("RMSE: ", rmse) R2 = sess.run(tf.subtract(1.0, tf.divide(unexplained_error, total_error)), feed_dict={X: x_test_array, Y: y_test_array}) print("\nR2 : ",R2)
Java
UTF-8
416
2.078125
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.core.bll.scheduling.external; import java.util.LinkedList; import java.util.List; import org.ovirt.engine.core.compat.Guid; public class FilteringResult extends SchedulerResult { private List<Guid> possibleHosts = new LinkedList<>(); public void addHost(Guid host) { possibleHosts.add(host); } public List<Guid> getHosts(){ return possibleHosts; } }
C
UTF-8
2,544
2.96875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nkamolba <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/15 10:14:17 by nkamolba #+# #+# */ /* Updated: 2017/12/07 16:53:56 by nkamolba ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" static int get_data(t_fd_list *current, char **line) { size_t l_len; size_t a_len; char *temp; l_len = ft_wordlen(current->content, '\n'); if (!(*line = ft_strsub(current->content, 0, l_len))) return (-1); a_len = ft_strlen(current->content); if (!(temp = ft_strsub(current->content, l_len + 1, a_len - l_len - 1))) return (-1); free(current->content); current->content = temp; return (1); } static int join_buff(t_fd_list *current, char *buff) { char *temp; if (!(temp = ft_strjoin(current->content, buff))) return (0); free(current->content); current->content = temp; return (1); } static int read_more(int fd, t_fd_list *current, char **line) { int read_result; char buff[BUFF_SIZE + 1]; while ((read_result = read(fd, buff, BUFF_SIZE)) > 0) { buff[read_result] = '\0'; if (!(join_buff(current, buff))) return (-1); if (ft_strchr(current->content, '\n')) return (get_data(current, line)); } if (read_result == 0 && current->content[0]) { if (!(join_buff(current, "\n"))) return (-1); return (get_data(current, line)); } return (read_result); } int get_next_line(const int fd, char **line) { static t_fd_list *fd_list; t_fd_list *current; current = fd_list; while (current && current->fd != fd) current = current->next; if (!current) { if (!(current = (t_fd_list *)malloc(sizeof(t_fd_list)))) return (-1); current->fd = fd; current->content = ft_strnew(0); current->next = fd_list; fd_list = current; } else if (ft_strchr(current->content, '\n')) return (get_data(current, line)); return (read_more(fd, current, line)); }
PHP
UTF-8
690
2.640625
3
[]
no_license
<?php declare(strict_types=1); namespace App\Controllers; use App\Libraries\Request; class AuthController extends DefaultController { public function loginAction() { $login = strtolower(Request::getString('login')); $password = strtolower(Request::getString('password')); if ($login === 'admin' && $password === '123') { $this->app->setAdmin(true); $this->redirect('?'); } else { $this->redirect('?error='.urlencode('Login or password incorrect')); } } public function logoutAction() { $this->app->setAdmin(false); $this->redirect('?'); } }
C#
UTF-8
1,570
2.625
3
[]
no_license
using System; using System.Diagnostics; using System.Numerics; using Strilanc.Value; namespace Circuit.Phys { [DebuggerDisplay("{ToString()}")] public struct Photon { public readonly Position Pos; public readonly Velocity Vel; public readonly Polarization Pol; public Photon(Position pos, Velocity vel, Polarization pol) { this.Pos = pos; this.Vel = vel; this.Pol = pol; } public Superposition<Photon> SwapVelocity() { return new Photon(this.Pos, new Velocity(this.Vel.Y, this.Vel.X), this.Pol).Super() * Complex.ImaginaryOne; } public Superposition<Photon> SwapNegateVelocity() { return new Photon(this.Pos, new Velocity(-this.Vel.Y, -this.Vel.X), this.Pol).Super() * Complex.ImaginaryOne; } public Superposition<Photon> HalfSwapVelocity() { return this.Super() | SwapVelocity(); } public Superposition<Photon> HalfNegateSwapVelocity() { return this.Super() | SwapNegateVelocity(); } public Superposition<May<Photon>> Polarize(Polarization polarizer) { var turn = polarizer.Dir - Pol.Dir; return new Photon(Pos, Vel, polarizer).Maybe().Super()*Math.Cos(turn.NaturalAngle) + May<Photon>.NoValue.Super()*Math.Sin(turn.NaturalAngle); } public override string ToString() { return string.Format("{0}, {1}, {2}", this.Pos, this.Vel, this.Pol); } } }
Java
UTF-8
109
2.078125
2
[]
no_license
public class Class9982{ public void callMe(){ System.out.println("called"); } }
C
IBM852
2,184
3.3125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <string.h> int main() { FILE *input, *output; input = fopen("input.txt", "r"); //input file output = fopen("output.txt", "a"); //output file int number_r, number_c, count; //read rule fscanf (input, "%d", &number_r); char rule[number_r][3]; for (count = 0; count < number_r; count++) fscanf (input, " %c %c %c", &rule[count][0], &rule[count][1], &rule[count][2]); //read IP fscanf (input, "%d", &number_c); char check_IP[number_c][2], check_port[number_c][5]; for (count = 0; count < number_c; count++) fscanf (input, " %c %c", &check_IP[count][0], &check_IP[count][1]); //compare IP & rule, then fill in port int count_2; for (count = 0; count < number_c; count++) { for (count_2 = 0; count_2 < number_c; count_2++) { //IP1 & IP2 both same if (check_IP[count][0] == rule[count_2][0] && check_IP[count][1] == rule[count_2][1]) { check_port[count][0] = rule[count_2][2]; check_port[count][1] = '\0'; break; } //IP1:same IP2:dont care else if (check_IP[count][0] == rule[count_2][0] && rule[count_2][1] == '*') { check_port[count][0] = rule[count_2][2]; check_port[count][1] = '\0'; break; } //IP1:dont care IP2:same else if (check_IP[count][1] == rule[count_2][1] && rule[count_2][0] == '*') { check_port[count][0] = rule[count_2][2]; check_port[count][1] = '\0'; break; } } //both different if (check_port[count][0] != rule[count_2][2]) strcpy (check_port[count], "drop"); } fprintf (output, "%d\n", number_c); for (count = 0; count < number_c; count++) fprintf (output, "%c %c %s\n", check_IP[count][0], check_IP[count][1], check_port[count]); fclose(input); fclose(output); return (0); }
Ruby
UTF-8
580
4.375
4
[]
no_license
# Ask for a Name, subname and last name # Show the full name in upercase #Check if values are empty, in that case, ask again #Initialize vars name = '' second_name = '' last_name = '' while name.nil? || name.empty? print "Write your name: " name = gets.chomp.upcase end while second_name.nil? || second_name.empty? print "Write your second name: " second_name = gets.chomp.upcase end while last_name.nil? || last_name.empty? print "Write your last name: " last_name = gets.chomp.upcase end print "Hello " + name + " " + second_name + " " + last_name
Python
UTF-8
6,656
3.890625
4
[]
no_license
""" Программа для переноса на определенное количество дней, месяцев и годов с учетом високосности и (или) изменения текущего дня, месяца, года. """ class Date: DAY_OF_MONTH = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), # Month_of_Year (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)) # Month_of_Leap_Year def __init__(self, year, month, day): self.is_valid_date(year, month, day) self._year = year self._month = month self._day = day def __str__(self): return f"Год: {self._year}, Месяц: {self._month}, День: {self._day}" @staticmethod def is_leap_year(year): if year % 4 == 0 and year % 100 != 0: return True elif year % 400 == 0: return True return False @classmethod def max_day_in_month(cls, year, month): return cls.DAY_OF_MONTH[cls.is_leap_year(year)][month-1] def is_valid_date(self, year, month, day): if not isinstance(year, int): raise TypeError('year must be int') if not isinstance(month, int): raise TypeError('Month must be int') if not isinstance(day, int): raise TypeError('Day must be int') if not 12 >= month > 0: raise ValueError("Month must be in range 1 - 12") if not year > 0: raise ValueError("Year must be > 0") if not self.max_day_in_month(year, month) >= day > 0: raise ValueError(f"Day must be in range 1 - {self.max_day_in_month(year, month)}") def add_year(self, adding_year): if not isinstance(adding_year, int): raise TypeError('Year must be int') if self._day <= self.max_day_in_month(self._year + adding_year, self._month): self._year += adding_year else: self._day -= self.max_day_in_month(self._year + adding_year, self._month) self._month += 1 self._year += adding_year def add_month(self, adding_month): if not isinstance(adding_month, int): raise TypeError('Month must be int') future_month = (self._month + adding_month - 1) % 12 + 1 future_year = self._year + (self._month + adding_month - 1) // 12 max_day_in_future_month = self.max_day_in_month(future_year, future_month) if adding_month <= 12 - self._month and self._day <= max_day_in_future_month: self._month += adding_month elif adding_month < 12 - self._month and self._day > max_day_in_future_month: self._month += adding_month + 1 self._day = max_day_in_future_month elif adding_month > 12 - self._month and self._day <= max_day_in_future_month: self._year += future_year self._month = future_month elif adding_month > 12 - self._month and self._day > max_day_in_future_month: self._year += future_year self._month = future_month self._day = max_day_in_future_month def add_day(self, adding_day): if not isinstance(adding_day, int): raise TypeError('Day must be int') while adding_day > 0: if adding_day + self._day <= self.max_day_in_month(self._year, self._month): self._day += adding_day adding_day = 0 else: adding_day -= (self.max_day_in_month(self._year, self._month) - self._day + 1) self._day = 1 if self._month == 12: self._month = 1 self._year += 1 else: self._month += 1 return self.add_day(adding_day) @property def year(self): return self._year @year.setter def year(self, year): if not isinstance(year, int): raise TypeError('Year must be int') if not year >= 0: raise TypeError('Year must be >= 0') if self._day < self.max_day_in_month(year, self._month): print(f"Setting year to {year}") self._day = self.max_day_in_month(year, self._month) self._year = year else: print(f"Setting year to {year}") self._year = year @property def month(self): return self._month @month.setter def month(self, month): if not isinstance(month, int): raise TypeError('Month must be int') if not 12 >= month > 0: raise TypeError('Month must be in [1, 12] interval') # if next_month == february and current_day > max_day_in_february => 29.02 if self._day <= self.max_day_in_month(self._year, month): print(f"Setting month to {month}") self._month = month else: print(f"Setting month to {month}") self._day = self.max_day_in_month(self._year, month) self._month = month @property def day(self): return self._day @day.setter def day(self, day): if not isinstance(day, int): raise TypeError('Day must be int') if not self.max_day_in_month(self._year, self._month) >= day > 0: raise TypeError(f"Day must be in [1, {self.max_day_in_month(self._year, self._month)}] interval") print(f"Setting day to {day}") self._day = day date = Date(884, 2, 29) print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") print(f"------------------------------------------------------------------------ ") date.add_day(5) print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") date.add_day(366) print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") date.add_month(29) print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") # date.add_year(1) # date.year = 2502 # date.month = 2 # print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") # date.day = 29 # print(f"{date} // ({date._year} год високосный?: {date.is_leap_year(date._year)})") # date1 = Date(2018, 11, "Thirty two") # print(date1) # print(f"Год: {date1.year}, Месяц: {date1.month}, День: {date1.day}") # date2 = Date(2018, 11, 34) # print(date2) # print(f"Год: {date2.year}, Месяц: {date2.month}, День: {date2.day}") # date1 = Date(2030, 2, 28) # print(date1) # print(date1.NEW_DATES)
JavaScript
UTF-8
432
2.828125
3
[]
no_license
/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar ps= previous scroll position cs= current scroll position */ var ps = window.pageYOffset; window.onscroll = function() { var cs = window.pageYOffset; if (ps > cs) { document.getElementByClassName("top-container").style.top = "0"; } else { document.getElementByClassName("top-container").style.top = "-50px"; } ps = cs; }
Java
UTF-8
980
2.109375
2
[]
no_license
package com.carparkingsystem.dao.repository; import com.carparkingsystem.dao.entity.VehicleTrackingTime; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; import java.util.Map; @Repository public interface VehicleTrackingTimeRepository extends JpaRepository<VehicleTrackingTime, Long> { @Query(value = "SELECT count(time_in) FROM vehicle_tracking_time WHERE (time_in BETWEEN ?1 AND ?2) GROUP BY time_in ORDER BY time_in", nativeQuery = true) List<Integer> getVehicleTrackingTimeIn(Date timeIn, Date timeOut); @Query(value = "SELECT count(time_out) FROM vehicle_tracking_time WHERE (time_out BETWEEN ?1 AND ?2) GROUP BY time_out ORDER BY time_out", nativeQuery = true) List<Integer> getVehicleTrackingTimeOut(Date timeIn, Date timeOut); }
Java
UTF-8
3,630
2.15625
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 csg.workspace; import csg.CSGApp; import djf.AppTemplate; import djf.components.AppDataComponent; import djf.components.AppWorkspaceComponent; import javafx.scene.control.TabPane; import static csg.controllers.ReciController.reciJ; import static csg.controllers.TAController.TaJ; import static csg.controllers.ScheController.scheJ; import static csg.controllers.ProjectController.proJ; import djf.ui.AppGUI; /** * * @author Hengqi Zhu */ public class Workspace extends AppWorkspaceComponent { CSGApp app; CourseTab courseTab; TaTab taTab; RecitationTab recitationTab; ScheduleTab scheduleTab; ProjectTab projectTab; public Workspace(AppTemplate initApp){ app=(CSGApp)initApp; workspace = new TabPane(); courseTab = new CourseTab((CSGApp)initApp); taTab = new TaTab((CSGApp)initApp); recitationTab = new RecitationTab((CSGApp)initApp); scheduleTab = new ScheduleTab((CSGApp)initApp); projectTab = new ProjectTab((CSGApp)initApp); workspace.getTabs().add(courseTab); workspace.getTabs().add(taTab); workspace.getTabs().add(recitationTab); workspace.getTabs().add(scheduleTab); workspace.getTabs().add(projectTab); app.getGUI().getUndoButton().setOnAction(e->{ if(workspace.getSelectionModel().getSelectedIndex()==1) TaJ.undoTransaction(); else if (workspace.getSelectionModel().getSelectedIndex()==2) reciJ.undoTransaction(); else if (workspace.getSelectionModel().getSelectedIndex()==3) scheJ.undoTransaction(); else if(workspace.getSelectionModel().getSelectedIndex()==4) proJ.undoTransaction(); AppGUI gui = app.getGUI(); gui.getFileController().markAsEdited(gui); }); app.getGUI().getRedoButton().setOnAction(e->{ if (workspace.getSelectionModel().getSelectedIndex()==1) TaJ.doTransaction(); else if (workspace.getSelectionModel().getSelectedIndex()==2) reciJ.doTransaction(); else if (workspace.getSelectionModel().getSelectedIndex()==3) scheJ.doTransaction(); else if(workspace.getSelectionModel().getSelectedIndex()==4) proJ.doTransaction(); AppGUI gui = app.getGUI(); gui.getFileController().markAsEdited(gui); }); } public TaTab getTaTab(){ return taTab; } public CourseTab getCourseTab(){ return courseTab; } public RecitationTab getRecitationTab() { return recitationTab; } public ScheduleTab getScheduleTab() { return scheduleTab; } public ProjectTab getProjectTab() { return projectTab; } @Override public void resetWorkspace() { taTab.resetWorkspace(); //recitationTab.resetWorkspace(); //scheduleTab.resetWorkspace(); // projectTab.resetWorkspace(); } @Override public void reloadWorkspace(AppDataComponent dataComponent) { taTab.reloadWorkspace(dataComponent); } }
Java
UTF-8
6,343
2.09375
2
[ "Apache-2.0" ]
permissive
package com.itheima.mobilesafe.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.text.TextUtils; import com.itheima.mobilesafe.R; import com.itheima.mobilesafe.services.GPSService; import com.itheima.mobilesafe.utils.BroadcastActions; import com.itheima.mobilesafe.utils.CLog; import com.itheima.mobilesafe.utils.MyAdminManager; import com.itheima.mobilesafe.utils.SpNames; import tw.com.softworld.messagescenter.Client; import tw.com.softworld.messagescenter.CustomReceiver; import tw.com.softworld.messagescenter.Result; /** * Created by Catherine on 2016/8/19. * Soft-World Inc. * catherine919@soft-world.com.tw */ public class SMSReceiver extends BroadcastReceiver { public static final String TAG = "SmsReceiver"; public static String address; public static String content; private String safePhone; /** * ANR异常: * 如果主线程阻塞超过10秒,很容易ANR异常。 * 因为广播接收者的生命周期短,容易被系统回收,连同子线程被销毁。 * <p/> * 广播接收者两种注册方式: * 1.Manifest里面注册,只需要继承BroadcastReceiver的class,一旦应用被部署到手机,广播就会生效,ex:SMSReceiver.class。 * 2.代码里注册:不用在Manifest里注册receiver,在activities里注册,一旦代码所在的进程被杀死,广播也会跟着失效,ex:SMSReceiverActivity.class。 * <p/> * 广播接收者分成两种类型: * 1.有序广播:在Manifest设置广播的优先级(-1000~1000),高到低的顺序,abortBroadcast()可拦截。 * 2.无序广播:任何注册广播的应用都能用,没有优先级。 * * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { CLog.d(TAG, "SMS received!"); SharedPreferences sp = context.getSharedPreferences(SpNames.FILE_CONFIG, Context.MODE_PRIVATE); safePhone = sp.getString(SpNames.safe_phone, ""); /* //测试ANR,阻塞主线程 try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } */ Object[] pdus = (Object[]) intent.getExtras().get("pdus"); if (pdus != null) { for (Object pdu : pdus) { SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu); final SmsManager manager = SmsManager.getDefault(); //获取短信的正文内容 content = message.getMessageBody(); //获取短信的发送者 address = message.getOriginatingAddress(); CLog.d(TAG, address + "\n" + content); if (address.equals(safePhone)) { MyAdminManager myAdminManager = new MyAdminManager(context); if (content.contains("#*location*#")) { CLog.d(TAG, "#*location*#"); //截获短信,根据AndroidManifest的优先级判断,其他优先级低的应用就不会收到推播 abortBroadcast(); //启动服务 Intent i = new Intent(context, GPSService.class); context.getApplicationContext().startService(i); CustomReceiver cr = new CustomReceiver() { @Override public void onBroadcastReceive(Result result) { Bundle b = result.getBundle(); String longitude = b.getString(SpNames.longitude); String latitude = b.getString(SpNames.latitude); String accutacy = b.getString(SpNames.accutacy); CLog.d(TAG, "Longitude:" + longitude + "\nLatitude:" + latitude + "\nAccutacy:" + accutacy); if (TextUtils.isEmpty(longitude)) manager.sendTextMessage(safePhone, null, "Getting location...", null, null); else manager.sendTextMessage(safePhone, null, "Longitude:" + longitude + "\nLatitude:" + latitude + "\nAccutacy:" + accutacy, null, null); } }; Client client = new Client(context, cr); client.gotMessages(BroadcastActions.LOCATION_INFO); } if (content.contains("#*alarm*#")) { CLog.d(TAG, "#*alarm*#"); //截获短信,根据AndroidManifest的优先级判断,其他优先级低的应用就不会收到推播 abortBroadcast(); MediaPlayer mp = MediaPlayer.create(context, R.raw.ylzs); mp.setLooping(true); mp.setVolume(1.0f, 1.0f); mp.start(); } if (content.contains("#*wipedata*#")) { CLog.d(TAG, "#*wipedata*#"); //截获短信,根据AndroidManifest的优先级判断,其他优先级低的应用就不会收到推播 abortBroadcast(); myAdminManager.wipeData(); } if (content.contains("#*lockscreen*#")) { CLog.d(TAG, "#*lockscreen*#"); //截获短信,根据AndroidManifest的优先级判断,其他优先级低的应用就不会收到推播 abortBroadcast(); myAdminManager.lockScreen(); } } //回传讯息 // SmsManager manager = SmsManager.getDefault(); // manager.sendTextMessage(address, null, "Go to hel.", null, null); } } else CLog.e(TAG, "null pdus"); } }
Markdown
UTF-8
6,547
2.75
3
[]
no_license
sermonis ======== Sermonis started as an experimentation using mongoDB, atmosphere and Spring-Data and finished with a working web chat application using these technologies. The Sermonis application was born. Its goal is to provide users an easy way to deploy a simple web application that let users talk with each other without the need to install an application like Skype. Sermonis supports Markdown and password protected rooms. It‘s not aimed to grow bigger than that for the moment. ### First run In order to test Sermonis on your local machine all you need is Java, Maven and mongoDB. If you want to test rapidly just type the following command: Install a mongoDB on your machine, by downloading it here, then open a shell and type the following to run it: $ cd mongodb/bin $ mkdir data $ mongod --dbpath data Download Sermonis and run it like this: $ cd sermonis $ mvn compile exec:java -Dexec.mainClass=me.grison.sermonis.SermonisInit jetty:run During the execution of the command you will be asked for an administrator password. This very password will be stored in a file called `sermonis.properties` in an encrypted way (md5 hash of an AES password encrypted with a secret token generated previously). Here is a sample of `sermonis.properties` file # _ # ________ _________ ___ ____ ____ (_)____ # / ___/ _ \/ ___/ __ `__ \/ __ \/ __ \/ / ___/ # (__ ) __/ / / / / / / / /_/ / / / / (__ ) # /____/\___/_/ /_/ /_/ /_/\____/_/ /_/_/____/ # # Sermonis property file generated on Mon May 13 10:11:44 CEST 2013 # Sermonis secret token used to encrypt password and browser request information into cookies # to secure access to password protected room and admin interface secretKey=0b388F1ab18EA5-7426E2-2e2C-8f1781683f-68Da1b1eA2C8-b5BD161Fb2f4140D06 # MD5 hash of the admin password AES encrypted with the above secret token adminPassword=E591B207FA96239F368382E45BC55816 and a sample of the execution of the previous mvn command. $ mvn compile exec:java -Dexec.mainClass=me.grison.sermonis.SermonisInit jetty:run [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building sermonis Maven Webapp 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ _ ________ _________ ___ ____ ____ (_)____ / ___/ _ \/ ___/ __ `__ \/ __ \/ __ \/ / ___/ (__ ) __/ / / / / / / / /_/ / / / / (__ ) /____/\___/_/ /_/ /_/ /_/\____/_/ /_/_/____/ You're about to generate a secret key and admin password for sermonis. Generating the secret key... Please provide an admin password: foobar Updating sermonis.properties... All done! [INFO] [INFO] >>> jetty-maven-plugin:8.1.0.v20120127:run (default-cli) @ sermonis >>> [INFO] Configuring Jetty for project: sermonis Maven Webapp ... [INFO] Started Jetty Server [INFO] Starting scanner at interval of 1 seconds. ### Play with it Just hit http://localhost:9001 and you will be redirected to a newly created room asking you for your username. Just share that same URL to someone else so that he can join you, and finally have some chat with your friend. ### About the name sermonis means (sort-of) discussion in Latin, since a corpus of chat messages is seen as a discussion, that name make sense :-). ## Technical ### Technical Stack Sermonis was started as an experimentation around multiple technologies, which are listed below: * Atmosphere * Spring with Spring-Data, Spring-Data-Mongo and Spring-Atmosphere * MongoDB * AngularJS * Websockets I‘m using Websockets to provide realtime-like chat within browser, using a library called Atmosphere. The RT stuff is bound to `.../async/...` URLs and is supported by recent web-browsers. You will note that not every Java application container supports them. If you‘re using Tomcat you will need Tomcat7. Jetty and Glassfish supports them too. ### MongoDB In Sermonis MongoDB is used only to save chat rooms configuration (password, administrator) and chat messages within them. Used with Spring-Data and it‘s binding specific to MongoDB it is really super-easy to use. ### AngularJS & Bootstrap I‘ve used AngularJS to render the messages in the chat rooms, with some jQuery touch where I‘m not enough skilled with Angular. The skin is using the well-known-already-seen-everywhere Bootstrap CSS framework. ### Cookies Sermonis use cookies to save user preferences (name, color, markdown, password (encrypted)). Cookies are related to one and only one room. This means that a user can have different name, color and password for every room he has access. ### Use cases Let‘s say the url of your deployed version of Sermonis is http://localhost/sermonis/. #### Creating a room Just hit the index page of the application at http://localhost/sermonis/, you will be redirected to a newly created room. #### Creating a password protected room Just hit the index page of the application with a query parameter withPassword at http://localhost/sermonis/?withPassword, you will be redirected to a page asking you the password with which the room should be protected, along with an administrator password. When you click on Create the room will be created and you will be redirected on it directly. #### Joining a room Just hit the URL someone shared you. #### Joining a password protected room Just hit the URL someone shared you. You will be asked for a password, providing it and clicking Join will redirect you to the chat room. Depending on the room configuration, you may be able to see the chat messages history. #### Choosing your user color Click on your username, and pick a color from the color picker. The color is stored in a cookie. #### Messages To send a message in the room just type it in the input at the bottom of the page and press Enter. Sermonis supports Markdown by relying on the PageDown Markdown JS Library. The IRC `/me` command is supported, and a shortcut for posting images is available with `img:url` instead of the longer markdown syntax `![alt](url)`.
Markdown
UTF-8
1,496
2.734375
3
[]
no_license
# poc-netcore-rest .Net Core Rest in a Docker Container This project is a quick POC (control) project to test exposing .Net services via Docker on AWS Fargate. On Windows this is really straight forward using the AWS Toolkit. On Mac there are few more steps because everything is done via the AWS CLI. ## Fargate Deployment - Assumptions - You have a .Net Core Project Running Locally - You have added Docker Support in the prject (Right-click the project in Solution Explorer and select Add > Docker Support) - You have Docker Desktop running locally - You have AWS credentials setup for the target account ## Fargate - Publish Docker Image to ECR - CLI Steps (Mac Only, PC has Publish to AWS option) - Create your AWS Repo:<br /> `aws ecr create-repository --repository-name oscillo-rest-test --region us-east-1` - Docker Build your Relase Image:<br /> `docker build -t oscillo-rest-test-2 -f oscillo_rest_test/Dockerfile .` - Docker Tag your Image<br /> `docker tag oscillo-rest-test-2 {ACCOUNTID}.dkr.ecr.us-east-1.amazonaws.com/oscillo-rest-test` - Login to the AWS ECR with Docker<br /> `aws ecr get-login-password | docker login --username AWS --password-stdin {ACCOUNTID}.dkr.ecr.us-east-1.amazonaws.com` - Docker Push your Tagged Image<br /> `docker push {ACCOUNTID}.dkr.ecr.us-east-1.amazonaws.com/oscillo-rest-test` ## Fargate - Configure Cluster - AWS Console OR CLI - Create your task definition - Create your cluster - Create your service ## Fargate - CI/CD Pipeline
Python
UTF-8
3,877
2.734375
3
[]
no_license
#!/usr/bin/env python3 import math import sys import xml.etree.ElementTree as etree from gmplot import gmplot import subprocess import os # thanks to Pasa on stackoverflow # https://stackoverflow.com/questions/53873673/plot-data-on-satellite-maps/54164812 class CustomGoogleMapPlotter(gmplot.GoogleMapPlotter): def __init__(self, center_lat, center_lng, zoom, apikey='', map_type='satellite'): super().__init__(center_lat, center_lng, zoom, apikey) self.map_type = map_type assert(self.map_type in ['roadmap', 'satellite', 'hybrid', 'terrain']) def write_map(self, f): f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' % (self.center[0], self.center[1])) f.write('\t\tvar myOptions = {\n') f.write('\t\t\tzoom: %d,\n' % (self.zoom)) f.write('\t\t\tcenter: centerlatlng,\n') # This is the only line we change f.write('\t\t\tmapTypeId: \'{}\'\n'.format(self.map_type)) f.write('\t\t};\n') f.write( '\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n') f.write('\n') def parse_gps_xml(path): gps_dict = {} print('trying to parse xml') tree = etree.parse(path) root = tree.getroot() print('entering xml parse') for child in root: try: mac = child.attrib['bssid'] lat = child.attrib['lat'] lon = child.attrib['lon'] rssi = child.attrib['signal_dbm'] if mac != '00:00:00:00:00:00' and 'GP' not in mac: if mac not in gps_dict: gps_dict[mac] = [(float(lat), float(lon), int(rssi))] elif mac in gps_dict: gps_dict[mac].append((float(lat), float(lon), int(rssi))) except Exception as e: pass print('leaving parse_gps_xml') return gps_dict def find_map_center(loc_list): temp_lat_list = [] temp_lon_list = [] for x in loc_list: temp_lat_list.append(x[0]) temp_lon_list.append(x[1]) # avg_lat = [gps_dict[key] for key in gps_dict for gps_dict[key] in key] # failed list comp return((sum(temp_lat_list)/len(temp_lat_list), min(temp_lat_list), max(temp_lat_list)), (sum(temp_lon_list)/len(temp_lon_list), min(temp_lon_list), max(temp_lon_list))) def make_map(mac, lat_list, lon_list, rssi_list): locs = zip(lat_list, lon_list, rssi_list) locs = list(locs) # cluge code to sidestep the zip iterable issue middle = find_map_center(locs) # gmap = gmplot.GoogleMapPlotter(middle[0][0], middle[1][0], 15, apikey=os.environ["GOOGLE_API_KEY"]) gmap = CustomGoogleMapPlotter(middle[0][0], middle[1][0], 15, apikey=os.environ["GOOGLE_API_KEY"]) for loc in locs: rad = get_distance_rssi(loc[2]) # gmap.circle(loc[0], loc[1], rad/2, c='red', edge_color='black',face_alpha=0.01, face_color='black') gmap.circle(loc[0], loc[1], rad/2, edge_color='black', face_alpha=0.01, face_color='red') gmap.draw(''.join([x for x in mac.split(':')]) + '.html') def draw_points(gps_dict): for key in gps_dict: lat_list = [] lon_list = [] rssi_list = [] for x in gps_dict[key]: lat_list.append(x[0]) lon_list.append(x[1]) rssi_list.append(x[2]) make_map(key, lat_list, lon_list, rssi_list) def get_distance_rssi(rssi, tx_pow=-20): ''' RSSI = TxPower - 10 * n * lg(d) d = 10 ^ ((TxPower - RSSI) / (10 * n)) n = 2 (in free space) - adjust based on GIS lookup ''' # distance = math.pow(10, (tx_pow - rssi) / (10 * 2)) distance = math.pow(10, -((rssi - tx_pow) / (10 * 2.7))) return distance if __name__ == '__main__': xml_path = sys.argv[1] gps_dict = parse_gps_xml(xml_path) draw_points(gps_dict)
C++
UTF-8
966
2.859375
3
[]
no_license
#ifndef SPACESHIPBLUEPRINTS_H #define SPACESHIPBLUEPRINTS_H #include "SpaceShips/Battleship.h" #include "SpaceShips/Exploration_vessel.h" #include "SpaceShips/Fighter.h" #include "SpaceShips/Frigate.h" #include "SpaceShips/Transporter.h" #include <iostream> #include <string> using namespace std; /**This class is the abstract factory class and is used to define an abstract blueprint. *It gives access to all the different blueprints used to create different spaceships. *It also has all the virtual create methods which are inherited by the concrete blueprints. */ class SpaceshipBlueprints { private: public: ///SpaceshipBlueprints constructor. SpaceshipBlueprints(/* args */); ///SpaceshipBlueprints destructor. ~SpaceshipBlueprints(); /**pure virtual function to be implemented in the concrete blueprints which will allow *the space station to create space ships. */ virtual Spaceships* createSpaceship() = 0; }; #endif
Java
UTF-8
1,129
2.15625
2
[]
no_license
package org.self.learn.springmvc.config; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * Extending WebMvcConfigurerAdapter is not a * mandate, is definitely a good practice though. */ @Configuration @ComponentScan(basePackages="org.self.learn") @EnableWebMvc @Scope(scopeName=ConfigurableBeanFactory.SCOPE_SINGLETON) public class SpringmvcConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/springmvc/jsp/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
Python
UTF-8
4,046
2.515625
3
[]
no_license
# import sys import requests import random from util.user_agents import ua_list from util.util_function import get_html_soup, extract_ip from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as ec # available since 2.26.0 from bs4 import BeautifulSoup # for debug to disable insecureWarning requests.packages.urllib3.disable_warnings() # 应该不需要,在主模块执行一次就好 # sys.path.append('..') class GetFreeProxy(object): """ proxy getter """ @staticmethod def get_wuyou(proxy_ip): """ 无忧代理 http://www.data5u.com/ 几乎没有能用的 """ url_list = [ 'http://www.data5u.com/', # 'http://www.data5u.com/free/gngn/index.shtml', # 'http://www.data5u.com/free/gnpt/index.shtml' ] for url in url_list: soup = get_html_soup(url, proxy_ip) ip_list = soup.find_all('ul', {"class": "l2"}) for info in ip_list: yield extract_ip(str(info)) @staticmethod def get_66ip(proxy_ip): base_url = "http://www.66ip.cn/" try: # 设置参数选项 chrome_options = Options() chrome_options.add_argument("--headless") # proxy_ip = "186.24.11.165:8080" # ip, port = proxy_ip.split(':') # proxy_ip = '{}:{}'.format(ip, port) user_agent = random.choice(ua_list) # chrome_options.add_argument('--proxy-server=' + proxy_ip) chrome_options.add_argument("--user-agent=" + user_agent) driver = webdriver.Chrome(options=chrome_options) end_page = 200 # 每次只爬取前200页(根据代理质量调整) page_num = 1 while page_num <= end_page: driver.get(base_url + str(page_num) + '.html') WebDriverWait(driver, 30).until(ec.title_contains("66免费代理ip")) page_source = driver.page_source soup = BeautifulSoup(page_source, features='lxml') ip_list = soup.find_all('tr') for info in ip_list: yield extract_ip(str(info)) page_num += 1 except Exception as e: print(e) finally: driver.close() @staticmethod def get_xici(proxy_ip): """ 西刺代理 http://www.xicidaili.com :return: """ url_list = [ 'http://www.xicidaili.com/nn/', # 高匿 'http://www.xicidaili.com/nt/', # 透明 ] last_page = 200 page_num = 1 for url in url_list: while page_num <= last_page: url = url + str(page_num) soup = get_html_soup(url, proxy_ip) ip_list = soup.find_all('tr') for info in ip_list: yield extract_ip(str(info)) else: # last_page = 729 page_num = 1 if __name__ == '__main__': from util.check_proxy import CheckProxy CheckProxy.checkGetProxyFunc(GetFreeProxy.get_wuyou) CheckProxy.checkGetProxyFunc(GetFreeProxy.get_66ip) CheckProxy.checkGetProxyFunc(GetFreeProxy.get_xici) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyFourth) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyFifth) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxySixth) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxySeventh) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyEight) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyNinth) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyTen) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyEleven) # CheckProxy.checkGetProxyFunc(GetFreeProxy.freeProxyTwelve) # CheckProxy.checkAllGetProxyFunc()
Markdown
UTF-8
4,676
2.796875
3
[]
no_license
<div id="hypercomments_widget" class="js-hypercomments-widget invisible"></div> # Тема 2. Хімічні реакції <table> <tr> <td width="10%" align="center"><b>К-ть годин</b></td> <td width="45%" align="center"><b>Зміст навчального матеріалу</b></td> <td width="45%" align="center"><b>Державні вимоги до рівня загальноосвітньої підготовки учнів</b></td> </tr> <tbody> <tr> <td width="10%" style="vertical-align:top !important;">12</td> <td width="45%" style="vertical-align:top !important;"> Класифікація хімічних реакцій за кількістю і складом реагентів та продуктів реакцій: реакції сполучення, розкладу, заміщення, обміну.<br> Окисно-відновні реакції. Процеси окиснення, відновлення, окисники, відновники.<br> Складання рівнянь окисно-відновних реакцій.<br> Значення окисно-відновних процесів у житті людини, природі й техніці.<br> Екзотермічні та ендотермічні реакції. Термохімічне рівняння.<br> Оборотні й необоротні реакції.<br> Швидкість хімічної реакції, залежність швидкості реакції від різних чинників </td> <td width="45%" style="vertical-align:top !important;"> <i><b>Учень/учениця:</b></i><br> <b>наводить приклади:</b> основних типів хімічних реакцій; відновників і окисників;<br> <b>класифікує: </b> реакції за різними ознаками;<br> <b>розрізняє:</b> реакції сполучення, заміщення, обміну, розкладу; окисно-відновні та реакції без зміни ступеня окиснення; екзо- та ендотермічні, оборотні й необоротні реакції; окисники і відновники;<br> <b>характеризує:</b> процеси окиснення, відновлення, сполучення, розкладу, заміщення, обміну; вплив різних чинників на швидкість хімічних реакцій; роль окисно-відновних процесів у довкіллі;<br> <b>обґрунтовує:</b> процеси окиснення та відновлення з погляду електронної будови атомів; <br> <b>складає: </b> рівняння найпростіших окисно-відновних реакцій на основі електронного балансу, термохімічні рівняння; рівняння оборотних і необоротних реакцій;<br> <b>застосовує:</b> закон збереження маси речовин для складання рівнянь хімічних реакцій;<br> <b>висловлює судження:</b> про значення хімічних реакцій та знань про них у природі, промисловості, побуті </td> </tr> <tr> <td width="45%" style="vertical-align:top !important;" colspan="3"> <b><i>Демонстрації</i></b><br> 4. Реакції розкладу, сполучення, заміщення, обміну, екзо- та ендотермічні реакції.<br> 5. Залежність швидкості реакцій металів (цинк, магній, залізо) з хлоридною кислотою від активності металу та концентрації кислоти.<br> <b><i>Лабораторні досліди</i></b><br> 11. Вплив площі поверхні контакту реагентів, концентрації і температури на швидкість реакції цинку з хлоридною кислотою<br> <b><i>Навчальні проекти</i></b><br> 7. Ендотермічні реакції на службі людині.<br> 8. Екзотермічні реакції в життєдіяльності живих органі. </td> </tr> </tbody> </table> <div class="js-hypercomments-container"> <a href="http://hypercomments.com" class="hc-link" title="comments widget">comments powered by HyperComments</a> </div>
TypeScript
UTF-8
67,292
2.71875
3
[ "MIT" ]
permissive
import paper = require("paper"); import { BubbleSpec, TailSpec, BubbleSpecPattern } from "bubbleSpec"; import { Comical } from "./comical"; import { Tail } from "./tail"; import { ArcTail } from "./arcTail"; import { ThoughtTail } from "./thoughtTail"; import { LineTail } from "./lineTail"; import { makeSpeechBubble, makeSpeechBubbleParts } from "./speechBubble"; import { makeThoughtBubble } from "./thoughtBubble"; import { makeCaptionBox } from "./captionBubble"; import { activateLayer } from "./utilities"; import { SimpleRandom } from "./random"; import { makeCircleBubble } from "./circleBubble"; // This class represents a bubble (including the tails, if any) wrapped around an HTML element // and handles: // - storing and retrieving the BubbleSpec that represents the persistent state of // the Bubble from the element's data-bubble attribute; // - creating paper.js shapes (technically Items) representing the shapes of the bubble and tails // - positioning and sizing those shapes based on the position and size of the wrapped element // - automatically repositioning them when the wrapped element changes // - creating handles on the tails to allow the user to drag them, and updating // the data-bubble as well as the shapes when this happens // - allowing the Bubble to be dragged, and updating the wrapped element's position (ToDo) export class Bubble { // The element to wrap with a bubble public content: HTMLElement; public static defaultBorderWidth = 3; // Represents the state which is persisted into // It is private because we want to try to ensure that callers go through the saveBubbleSpec() setter method, // because it's important that changes here get persisted not just in this instance's memory but additionally to the HTML as well. private spec: BubbleSpec; // the main shape of the bubble, including its border. Although we think of this as a shape, // and it determines the shape of the bubble, it may not actually be a paper.js Shape. // When it's simply obtained from an svg, it's usually some kind of group. // When we extract a single outline from the svg (or eventually make one algorithmically), // it will most likely be a Path. public outline: paper.Item; // The original stroke color of the outline. In some modes, the actual outline color is changed. private oulineStrokeColor: paper.Color | null = null; // When possible, the shapes of all bubbles and their tails at the same level are combined // into this one shape, allowing a partly transparent background color without // extra strokes showing through. The combinedShape is stored on the parent of the // bubble family. public combinedShapes: paper.Item | undefined = undefined; // If the item has a shadow, this makes it. // We would prefer to do this with the paper.js shadow properties applied to shape, // but experiment indicates that such shadows do not convert to SVG. private shadowShape: paper.Item; // a clone of this.outline with no border and an appropriate fill; drawn on top of all outlines // to fill them in and erase any overlapping borders. // When possible, this is left undefined and combinedShapes is set up instead. public fillArea: paper.Item | undefined; // contentHolder is a shape which is a required part of an SVG object used as // a bubble. It should be a rectangle in the SVG; it currently comes out as a Shape // when the SVG is converted to a paper.js object. // (We can also cause it to come out as a Path, by setting expandShapes: true // in the getItem options). // It has property size, with height, width as numbers matching the // height and width specified in the SVG for the rectangle.) // Also position, which surprisingly is about 50,50...probably a center. // It is identified by having id="contentHolder". The bubble shape gets stretched // and positioned so this rectangle corresponds to the element that the // bubble is wrapping. private contentHolder: paper.Item | undefined; // The tail objects (which include things like its PaperJs underlying objects and how to draw them). // Contains more details than the "tips" array in the spec object // The elements in each array should correspond, though. private tails: Tail[] = []; private observer: MutationObserver | undefined; private hScale: number = 1; // Horizontal scaling private vScale: number = 1; // Vertical scaling // The PaperJS layers in which to draw various pieces of the bubble into. private lowerLayer: paper.Layer; private upperLayer: paper.Layer; private handleLayer: paper.Layer; // true if we computed a shape for the bubble (in such a way that more than just // its size depends on the shape and size of the content element). private shapeIsComputed: boolean; // Remember the size of the content element when we last computed the bubble shape. oldContentWidth: number = 0; oldContentHeight: number = 0; public constructor(element: HTMLElement) { this.content = element; this.spec = Bubble.getBubbleSpec(this.content); } // True if this bubble uses the old approach, hiding outline strokes behind a fillArea. // False if the outline shape is one we can combine using uniteShapes into a combinedShapes. public usingOverlay(): boolean { return !!this.fillArea; } // Retrieves the bubble associated with the element public static getBubbleSpec(element: HTMLElement): BubbleSpec { const escapedJson = element.getAttribute("data-bubble"); if (!escapedJson) { return Bubble.getDefaultBubbleSpec(element, "none"); } const json = escapedJson.replace(/`/g, '"'); return JSON.parse(json); // enhance: can we usefully validate it? } public static getDefaultBubbleSpec(element: HTMLElement, style?: string): BubbleSpec { if (!style || style === "none") { return { version: Comical.bubbleVersion, style: "none", tails: [], level: Comical.getMaxLevel(element) + 1, backgroundColors: ["transparent"], shadowOffset: 0, outerBorderColor: undefined }; } const tailSpec = Bubble.makeDefaultTail(element); const result: BubbleSpec = { version: Comical.bubbleVersion, style: style, tails: [tailSpec], level: Comical.getMaxLevel(element) + 1 }; if (style === "caption") { result.backgroundColors = ["#FFFFFF", "#DFB28B"]; result.tails = []; result.shadowOffset = 5; } else if (style === "pointedArcs" || style === "circle" || style === "rectangle") { result.tails = []; } return result; } // // Getter methods for various things saved in the spec field. They are Getters() so that consumers of this class will be encouraged to save them using getters/setters // because we probably need persistBubbleSpec() to be called afterward // // Gets the level (z-index) of this object public getSpecLevel(): number | undefined { return this.spec.level; } public getFullSpec(): BubbleSpec { const parents = Comical.findAncestors(this); if (parents.length == 0) { return this.spec; } const parent: Bubble = parents[0]; // We probably don't need to be this careful, since functions that want // this bubble's tails or order go to its own spec. But these are // things that should NOT be inherited from parent, so let's get them right. const result: BubbleSpec = { ...parent.spec, tails: this.spec.tails }; if (this.spec.hasOwnProperty("order")) { result.order = this.spec.order; } else { delete result.order; } return result; } // ENHANCE: Add more getters and setters, as they are needed // Returns the spec object. If you modify this object, make sure to use the setter to set the value again or use persistBubbleSpec() in order to get the changes to persist! public getBubbleSpec() { return this.spec; } // Setter for the spec field. Also persists the data into the HTML of the content element. public setBubbleSpec(spec: BubbleSpec): void { console.assert(!!(spec.version && spec.level && spec.tails && spec.style), "Bubble lacks minimum fields"); this.spec = spec; this.persistBubbleSpec(); } public persistBubbleSpecWithoutMonitoring() { this.callWithMonitoringDisabled(() => { this.persistBubbleSpec(); }); } // Persists the data into the content element's HTML. Should be called after making changes to the underlying spec object. public persistBubbleSpec(): void { const json = JSON.stringify(this.spec); const escapedJson = json.replace(/"/g, "`"); this.content.setAttribute("data-bubble", escapedJson); } // Return true if the two arrays are equal (one level deep...items are ===) // Also if both are undefined. // This ought to be generic...arrays of any type...but I can't persuade Typescript // to allow it. For now I only need arrays of strings. private comparePossibleArrays(first: string[] | undefined, second: string[] | undefined): boolean { if (!first && !second) { return true; } if (!first || !second) { return false; } if (first.length != second.length) { return false; } for (let i = 0; i < first.length; i++) { if (first[i] !== second[i]) { return false; } } return true; } public mergeWithNewBubbleProps(newBubbleProps: BubbleSpecPattern): void { // Figure out a default that will supply any necessary properties not // specified in data, including a tail in a default position. // In certain cases some of these properties may override values in // oldData (but never newBubbleProps). const newDefaultData = Bubble.getDefaultBubbleSpec(this.content, newBubbleProps.style || this.spec.style); const oldData: BubbleSpec = this.spec; const oldDataOverrides: BubbleSpecPattern = {}; // If newBubbleProps doesn't have a style defined, that means we want to keep the existing // style. Therefore, "extra work" for "the new style" (below) doesn't apply. if (newBubbleProps.style && oldData.style !== newBubbleProps.style) { // We will do some extra work to possibly switch other props // to their default values for the new style. // This gives the default properties associated with the OLD style const oldDefaultData = Bubble.getDefaultBubbleSpec(this.content, oldData.style); // For various properties, if oldData has the same value as oldDefaultData // (that is, the property in the current bubble is unchanged from // the default for the old style), we will update that property to the // default for the new style. // When bubble styles that normally have tails have the tail turned off, at least oldData.tails // could be undefined here. if (oldData.tails && oldDefaultData.tails && oldData.tails.length === oldDefaultData.tails.length) { // nothing has changed the number of tails, so we want the new spec to // have the default number for its style. First, we keep as many tails // as are wanted and present (currently always zero or one) oldDataOverrides.tails = oldData.tails.slice(0, newDefaultData.tails.length); if (oldDataOverrides.tails.length < newDefaultData.tails.length) { // if we don't already have enough, add another one from defaultData // May need to do something fancier here one day if we might need to add more than // one. I don't think that's likely. oldDataOverrides.tails.push(newDefaultData.tails[0]); } // Enhance: If different bubble styles have different default tail styles, // we may want to consider forcing the style of the tail. } if (this.comparePossibleArrays(oldData.backgroundColors, oldDefaultData.backgroundColors)) { oldDataOverrides.backgroundColors = newDefaultData.backgroundColors; } if (oldData.borderStyle === oldDefaultData.borderStyle) { oldDataOverrides.borderStyle = newDefaultData.borderStyle; } if (oldData.shadowOffset === oldDefaultData.shadowOffset) { oldDataOverrides.shadowOffset = newDefaultData.shadowOffset; } if (oldData.outerBorderColor === oldDefaultData.outerBorderColor) { oldDataOverrides.outerBorderColor = newDefaultData.outerBorderColor; } } // We get the default bubble for this style and parent to provide // any properties that have never before occurred for this bubble, // particularly a default tail placement if it was previously "none". // Any values already in oldData override these; for example, if // this bubble has ever had a tail, we'll keep its last known position. // If we put any values in oldDataOverrides (typically cases where we // prefer the defaultData value), they win next. // Finally, any values present in newBubbleProps override anything else. const mergedBubble = { ...newDefaultData, ...oldData, ...oldDataOverrides, ...(newBubbleProps as BubbleSpec) }; this.setBubbleSpec(mergedBubble); } public getStyle(): string { return this.getFullSpec().style; } public setStyle(style: string): void { // TODO: Consider validating this.spec.style = style; this.persistBubbleSpec(); } public setLayers(newLowerLayer: paper.Layer, newUpperLayer: paper.Layer, newHandleLayer: paper.Layer): void { this.setLowerLayer(newLowerLayer); this.setUpperLayer(newUpperLayer); this.setHandleLayer(newHandleLayer); } public getLowerLayer(): paper.Layer { return this.lowerLayer; } // Sets the value of lowerLayer. The "outline" shapes are drawn in the lower layer. public setLowerLayer(layer: paper.Layer): void { this.lowerLayer = layer; } public getUpperLayer(): paper.Layer { return this.upperLayer; } // Sets the value of upperLayer. The "fill" shapes are drawn in the upper layer. public setUpperLayer(layer: paper.Layer): void { this.upperLayer = layer; } // The layer containing the tip and midpoint curve handles public setHandleLayer(layer: paper.Layer): void { this.handleLayer = layer; } // Ensures that this bubble has all the required layers and creates them, if necessary private initializeLayers(): void { if (!this.lowerLayer) { this.lowerLayer = new paper.Layer(); // Note that the constructor automatically adds the newly-created layer to the project } if (!this.upperLayer) { this.upperLayer = new paper.Layer(); } if (!this.handleLayer) { this.handleLayer = new paper.Layer(); } } // The root method to call to cause this object to make its shapes, // adjust their sizes to match the content, // and sets up monitoring so the shapes continue to adjust as the content // element size and position change. public initialize() { this.initializeLayers(); // To keep things clean we discard old tails before we start. for (let i = 0; i < this.tails.length; ++i) { // Erase it off the current canvas this.tails[i].remove(); } this.tails = []; // Make the bubble part of the bubble+tail this.loadShapeAsync((newlyLoadedShape: paper.Item) => { this.makeShapes(newlyLoadedShape); if (this.isTransparent()) { this.outline.strokeWidth = 0; if (this.shadowShape) { this.shadowShape.strokeWidth = 0; this.shadowShape.fillColor = new paper.Color(0, 0, 0, 0); } } // If we're making the main shape first (especially, thoughtBubble), // we need to adjust its size and position before making the tail, // since we depend on that to decide where to stop making mini-bubbles. // If we're making the shape asynchronously, it's possible the call // that adjusted the tails already happened. But it won't hurt do do it // one more time once we have everything. this.adjustSizeAndPosition(); }); // Make any tails the bubble should have. // For some tail types (e.g., currently, thoughtTail), it's important // to make the main shape first, since making the tail shapes depends // on having it. Currently this can only be guaranteed with computational // shapes (that don't depend on loading an svg). if (this.spec.tails) { // mostly paranoia, but I ran into a problem here in one version of the code this.spec.tails.forEach(tail => { this.makeTail(tail); }); } // Need to do this again, mainly to adjust the tail positions. // Note that in some cases, this might possibly happen before // the main bubble shape is created. this.adjustSizeAndPosition(); this.monitorContent(); } // Returns true if nothing in the bubble spec makes the bubble visible. public isTransparent() { if (this.spec.style !== "caption" && this.spec.style !== "none") { return false; } if (this.spec.tails.length > 0) { return false; } const outerBorderColor = this.spec.outerBorderColor; if (outerBorderColor && outerBorderColor !== "none") { return false; } if (this.spec.shadowOffset) { return false; } const backColors = this.spec.backgroundColors; if (backColors && backColors.length === 1 && backColors[0] === "transparent") { return true; } return false; } // Returns the SVG contents string corresponding to the specified input bubble style public static getShapeSvgString(bubbleStyle: string): string { let svg: string = ""; switch (bubbleStyle) { case "ellipse": svg = Bubble.ellipseBubble(); break; case "shout": svg = Bubble.shoutBubble(); break; // "none" is now a "computed" shape. default: console.log("unknown bubble type; using default"); svg = Bubble.ellipseBubble(); } return svg; } // Get the main shape immediately if computed. // return undefined if the current bubble style is not a computed shape. private getComputedShape(): paper.Item | undefined { if (this.content) { // remember the shape of the content from the most recent call. this.oldContentHeight = this.content.offsetHeight; this.oldContentWidth = this.content.offsetWidth; } const bubbleStyle = this.getStyle(); activateLayer(this.lowerLayer); // at least for now, the main shape always goes in this layer. switch (bubbleStyle) { case "pointedArcs": return this.makePointedArcBubble(); case "thought": return makeThoughtBubble(this); case "speech": return makeSpeechBubble(this.content.offsetWidth, this.content.offsetHeight, 0.6, 0.8); case "circle": return makeCircleBubble(this.content.offsetWidth, this.content.offsetHeight); case "caption": // purposeful fall-through; these four types should have the same shape case "caption-withTail": case "rectangle": case "none": const spec = this.getFullSpec(); const rounderCornerRadii = spec.cornerRadiusX && spec.cornerRadiusY ? new paper.Size(spec.cornerRadiusX, spec.cornerRadiusY) : undefined; // The padding thing is kind of backwards compatibility. In an earlier version, // the border set up by makeCaptionBox was always 3px, but we reduced the thickness // to zero for 'none' later. That actually left the box 3px larger, which acted as padding. // It's probably a good thing, might even be desirable to have some for other bubbles, // but we don't want to change things and break existing books. So, put the 3px padding // back in for 'none' (BL-11715). return makeCaptionBox(this, rounderCornerRadii, this.getBorderWidth(), bubbleStyle == "none" ? 3 : 0); default: return undefined; // not a computed shape, may be svg...caller has real default } } // Loads the shape (technically Item) corresponding to the specified bubbleStyle, // and calls the onShapeLoadeed() callback once the shape is finished loading // (passing it in as the shape parameter) private loadShapeAsync(onShapeLoaded: (shape: paper.Item) => void) { const bubbleStyle = this.getStyle(); this.shapeIsComputed = false; var shape = this.getComputedShape(); if (shape) { this.shapeIsComputed = true; onShapeLoaded(shape); return; } const svg = Bubble.getShapeSvgString(bubbleStyle); activateLayer(this.lowerLayer); // Sets this bubble's lowerLayer as the active layer, so that the SVG will be imported into the correct layer. // ImportSVG may return asynchronously if the input string is a URL. // Even though the string we pass contains the svg contents directly (not a URL), when I ran it in Bloom I still got a null shape out as the return value, so best to treat it as async. this.lowerLayer.project.importSVG(svg, { onLoad: (item: paper.Item) => { onShapeLoaded(item); } }); } private hasOuterBorder(): boolean { return !!this.getFullSpec().outerBorderColor && this.spec.outerBorderColor !== "none"; } // Attaches the specified shape to this object's content element private makeShapes(shape: paper.Item) { var oldOutline = this.outline; var oldFillArea = this.fillArea; activateLayer(this.lowerLayer); this.setOutline(shape); // if the SVG contains a single shape (marked with an ID) that is all // we need to draw, we can replace the whole-svg item with a path derived // from that one shape. Some benefits: // - paths painted with gradient colors convert correctly to SVG; // complex groups do not. // - simpler shape may help performance // - (future) it's possible to subtract one path from another, offering an // alternative way to hide overlapping line segments that is // compatible with bubbles having partly transparent fill colors. // Enhance: we could also look for a child, like the one in the shout // bubble, that is already a path, possibly by giving such elements // an outlinePath id. The only difference would be that the result from // getItem is already a path, so we don't need to cast it to shape and // call toPath(). // If we add that, all our current bubbles can be converted to a single // path each. We may, however, not want to have the code assume that will // always be the case. For example, a bubble with a shadow or double outline // might not be doable with a single path. const outlineShape = shape.getItem({ recursive: true, match: (x: any) => x.name === "outlineShape" }); if (outlineShape) { shape.remove(); this.setOutline((outlineShape as paper.Shape).toPath()); this.lowerLayer.addChild(this.outline); } if (oldOutline) { this.outline.insertBelow(oldOutline); oldOutline.remove(); } this.outline.strokeWidth = this.getBorderWidth(); this.hScale = this.vScale = 1; // haven't scaled it at all yet. // recursive: true is required to see any but the root "g" element // (apparently contrary to documentation). // The 'name' of a paper item corresponds to the 'id' of an element in the SVG this.contentHolder = shape.getItem({ recursive: true, match: (x: any) => { return x.name === "content-holder"; } }); if (this.spec.shadowOffset) { if (this.shadowShape) { this.shadowShape.remove(); } this.shadowShape = this.outline.clone({ deep: true }); this.shadowShape.insertBelow(this.outline); this.shadowShape.fillColor = this.shadowShape.strokeColor; } // If we don't do this it somehow shows up in the fill area clone, // on top of the outline if it dips inside the rectangle this.contentHolder.remove(); if (outlineShape && !this.hasOuterBorder()) { // We can use the new strategy that supports partly transparent background colors this.outline.fillColor = this.getBackgroundColor(); Comical.setItemOnClick(this.outline, () => { Comical.activateBubble(this); }); } else { this.fillArea = this.outline.clone({ insert: false }); Comical.setItemOnClick(this.fillArea, () => { Comical.activateBubble(this); }); // If we get rid of the stroke of the fill area, then it hides the outline // completely. Then we have to try to guess how much to shrink it so it // doesn't hide the outline. And if the outline border is thicker, we // have to shrink it more. Better to leave the border properties, // but make that part of the fill area transparent. this.fillArea.strokeColor = new paper.Color("white"); this.fillArea.strokeColor.alpha = 0; this.fillArea.fillColor = this.getBackgroundColor(); if (oldFillArea) { this.fillArea.insertBelow(oldFillArea); oldFillArea.remove(); } else { this.upperLayer.addChild(this.fillArea); } } if (this.hasOuterBorder()) { var outerBorder = this.outline.clone(); // We want two more borders, a thick one in the outerBorderColor, // and a thin black one (or perhaps eventually the color of the main // border, if we allow that to be controlled). However, doing the main outer border as a // stroke color is problematic: there doesn't seem to be a way to put // more than one stroke on a single shape, and if we try to wrap another // shape around it and use stroke, we'll tend to get white space in between, // especially since I also can't find a way to grow a shape by an exact // distance in all directions. So instead, we make a clone shape and set // its FILL color to the outerBorderColor...and then put it behind the // main shape so only the part outside it shows. And we can use its stroke for // the second outer border. outerBorder.fillColor = new paper.Color(this.getFullSpec().outerBorderColor!); outerBorder.insertBelow(this.outline); // Now we have to get it the right size, which is also tricky. // We want about 8 px of red. The overall shape will eventually be scaled // by this.content.offsetWidth/(contentHolder width), so first we // apply the inverse of that to 16 to get the absolute increase in width // that we want (there's a factor of two for border on each side). // Scaling is a fraction, so to make the outerBorder 16/scale wider, we scale by // (width + 16/scale)/width, which when multiplied by width is 16/scale bigger. // And similarly for the vertical scale, which is very likely different. const chWidth = (this.contentHolder as any).size.width; const hScale = this.content.offsetWidth / chWidth; const chHeight = (this.contentHolder as any).size.height; const vScale = this.content.offsetHeight / chHeight; const obWidth = outerBorder.bounds.width; const obHeight = outerBorder.bounds.height; outerBorder.scale((obWidth + 16 / hScale) / obWidth, (obHeight + 16 / vScale) / obHeight); // Visually this seems to give the right effect. I have not yet // figured out why the main border is not coming out as thick as I think // it should (and does, in the absense of the overlaying fill shape). outerBorder.strokeWidth = 1; // We don't have to insert this group, just make it and set it as this.outline, // so that when we adjustShapes() both shapes get adjusted. const newOutline = new paper.Group([outerBorder, this.outline]); this.outline = newOutline; } } public getDefaultContentHolder(): paper.Shape { const contentTopLeft = new paper.Point(this.content.offsetLeft, this.content.offsetTop); const contentSize = new paper.Size(this.content.offsetWidth, this.content.offsetHeight); const contentHolder = new paper.Shape.Rectangle(contentTopLeft, contentSize); contentHolder.name = "content-holder"; // the contentHolder is normally removed, but this might be useful in debugging. contentHolder.strokeColor = new paper.Color("red"); contentHolder.fillColor = new paper.Color("transparent"); return contentHolder; } public getBorderWidth() { const style = this.getStyle(); if (style === "rectangle") { return 1; // BL-11618, we want rectangle thickness to match the tail line } return style === "none" ? 0 : Bubble.defaultBorderWidth; } public getBackgroundColor(): paper.Color { const spec = this.getFullSpec(); // enhance: we want to do gradients if the spec calls for it by having more than one color. // Issue: sharing the gradation process with any tails (and maybe // other bubbles in family??) if (!spec.backgroundColors && spec.style === "none") { // default background Color for style 'none' is now transparent spec.backgroundColors = ["transparent"]; this.setBubbleSpec(spec); } if (spec.backgroundColors && spec.backgroundColors.length) { if (spec.backgroundColors.length === 1) { return new paper.Color(spec.backgroundColors[0]); } const gradient = new paper.Gradient(); const stops: paper.GradientStop[] = []; // We want the gradient offsets evenly spaced from 0 to 1. spec.backgroundColors!.forEach((x, index) => stops.push( new paper.GradientStop(new paper.Color(x), (1 / (spec.backgroundColors!.length - 1)) * index) ) ); gradient.stops = stops; const xCenter = this.content.offsetWidth / 2; // enhance: we'd like the gradient to extend over the whole fillArea, // but we can't depend on that existing when we need this, especially when // called by one of the tails. So just make one from the top of the content // to the bottom. // After introducing new algorithmic captions, it seems to work in all cases to use // the Y coordinate of the top of the box to the Y coordinate of the bottom. // Previously, captions seemed to need using 0 to height instead. // // enhance 2: If the tail is above the bubble, might make more sense to do gradient bottom -> top instead of top -> bottom const gradientOrigin = new paper.Point(xCenter, this.outline.bounds.top); const gradientDestination = new paper.Point(xCenter, this.outline.bounds.top + this.outline.bounds.height); // Old code which used 0 to height (seemed necessary for SVG captions) // const gradientOrigin = new paper.Point(xCenter, 0); // const gradientDestination = new paper.Point(xCenter, this.outline ? this.outline.bounds.height : 50); const result: paper.Color = new paper.Color(gradient, gradientOrigin, gradientDestination); return result; } return Comical.backColor; } // Adjusts the size and position of the shapes/tails to match the content element adjustSizeAndPosition() { var contentWidth = -1; var contentHeight = -1; if (this.content) { contentWidth = this.content.offsetWidth; contentHeight = this.content.offsetHeight; } if (contentWidth < 1 || contentHeight < 1) { // Horrible kludge until I can find an event that fires when the object is ready. window.setTimeout(() => { this.adjustSizeAndPosition(); }, 100); return; } if ( this.shapeIsComputed && Math.abs(contentWidth - this.oldContentWidth) + Math.abs(contentHeight - this.oldContentHeight) > 0.001 ) { const shape = this.getComputedShape()!; this.makeShapes(shape); } if (this.contentHolder) { const [desiredHScale, desiredVScale] = this.getScaleFactors(); const scaleXBy = desiredHScale / this.hScale; const scaleYBy = desiredVScale / this.vScale; this.outline.scale(scaleXBy, scaleYBy); if (this.shadowShape) { this.shadowShape.scale(scaleXBy, scaleYBy); } if (this.fillArea) { this.fillArea.scale(scaleXBy, scaleYBy); } this.hScale = desiredHScale; this.vScale = desiredVScale; } const contentLeft = this.content.offsetLeft; const contentTop = this.content.offsetTop; const contentCenter = new paper.Point(contentLeft + contentWidth / 2, contentTop + contentHeight / 2); if (this.outline) { // it's just possible if shape is created asynchronously from // an SVG that this method is called to adjust tails before the main shape // exists. If so, it will be called again when it does. this.outline.position = contentCenter; if (this.fillArea) { this.fillArea.position = contentCenter; } if (this.shadowShape) { // We shouldn't have a shadowShape at all unless we have a shadowOffset. // In case somehow we do, hide the shadow completely when that offset is // falsy by putting it entirely behind the main shapes. this.shadowShape.position = this.outline.position.add(this.spec.shadowOffset || 0); } } // Enhance: I think we could extract from this a method updateTailSpec // which loops over all the tails and if any tail's spec doesn't match the tail, // it turns off the mutation observer while updating the spec to match. // Such a method would be useful for updating the spec when the tail is dragged, // and perhaps for other things. this.tails.forEach(tail => { tail.adjustRoot(contentCenter); }); // Now, look for a child whose joiner should be our center, and adjust that. const child = Comical.findChild(this); if (child) { console.assert(child.tails.length <= 1, "A child may only have at most 1 tail."); // Note: I think it's better to adjust the joiners even if they would subsequently be hidden. // This keeps the internal state looking more up-to-date and reasonable, even if it's invisible. // However, it is also possible to only adjust the joiners if they are not overlapping child.adjustJoiners(contentCenter); const shouldTailsBeVisible = !this.isOverlapping(child); child.tails.forEach(tail => { tail.setTailAndHandleVisibility(shouldTailsBeVisible); }); } const parent = Comical.findParent(this); if (parent) { // Need to check both child and parent, because even if we loaded the bubbles in a certain order, // due to async nature, we can't be sure which one will be loaded first. // (This should only applicable to determining whether the tail is visible or not. // Don't think we need to adjust the joiners, they should all be loaded at that time.) const shouldTailsBeVisible = !this.isOverlapping(parent); console.assert(this.tails.length <= 1, "A child bubble may have at most 1 tail."); this.tails.forEach(tail => { tail.setTailAndHandleVisibility(shouldTailsBeVisible); }); } this.uniteShapes(); } private setOutline(outline: paper.Item): void { this.outline = outline; this.oulineStrokeColor = outline.strokeColor; } public uniteShapes() { // Since we have set the includeSelf flag, we are guaranteed that selfAndRelatives will contain // at least this (self) bubble. const selfAndRelatives = Comical.findRelatives(this, true); // Get rid of any old combinedShapes. This is especially important to do first when // switching to 'none' as no new one will be created. selfAndRelatives.forEach(r => { if (r.combinedShapes) { r.combinedShapes.remove(); r.combinedShapes = undefined; } }); const parent = selfAndRelatives[0]; if (selfAndRelatives.some(r => !r.outline || !(r.outline as paper.PathItem).unite)) { // We can't do this before the outlines have been created, or if the // outline is some complex object, like a Group or an SVG import, // that doesn't implement the unite() function. return; } // Accumulates tails that can't be "united" with their bubbles. // Currently these are LineTails. const tailsToClip: Tail[] = []; let combinedPath: paper.PathItem = parent.outline.clone({ insert: false }) as paper.PathItem; combinedPath = parent.uniteTails(combinedPath, tailsToClip); // Now merge any remaining family members (note the first one, the parent, is skipped). for (var i = 1; i < selfAndRelatives.length; i++) { if (!selfAndRelatives[i].isOverlapping(selfAndRelatives[i - 1])) { // Child tails should overlap the shape we already have. // Joining the tail first may help to keep the shape simple, or at least contiguous. // Not sure this is necessary, unite() seems to handle discontiguous shapes. combinedPath = selfAndRelatives[i].uniteTails(combinedPath, tailsToClip); } else { // If the bubbles overlap we don't need the joining tail; just hide it. selfAndRelatives[i].tails.forEach(t => t.pathstroke && this.hideShape(t.pathstroke)); } // We can be confident the outline is a PathItem because we checked // above that it has the unite() function. combinedPath = combinedPath.unite(selfAndRelatives[i].outline as paper.PathItem); this.hideShape(selfAndRelatives[i].outline); } combinedPath.strokeWidth = this.getBorderWidth(); combinedPath.strokeColor = this.oulineStrokeColor; combinedPath.fillColor = this.getBackgroundColor(); parent.combinedShapes = combinedPath; if (tailsToClip.length) { const groupItems: paper.PathItem[] = [combinedPath]; tailsToClip.forEach(t => { if (!t.pathstroke) return; let clippedTail = t.pathstroke.clone({ insert: false }) as paper.PathItem; this.hideShape(t.pathstroke); selfAndRelatives.forEach(r => { // The following didn't work, not sure why not. // clippedTail = clippedTail.subtract(r.outline as PathItem, { insert: false }); // For now the only tails we need to clip are lines. // This simple algorithm is enough. If the line crosses other // boxes besides the one it belongs to, it will simply be drawn. if (r.tails.includes(t)) { const outlinePath = r.outline as paper.PathItem; const intersections = outlinePath.getIntersections(clippedTail); if (intersections.length > 0) { clippedTail = (t as LineTail).makeShape(intersections[0].point); clippedTail.remove(); } } }); groupItems.push(clippedTail); }); parent.combinedShapes = new paper.Group(groupItems); } parent.combinedShapes.insertBelow(parent.outline); parent.combinedShapes.sendToBack(); // maybe redundant? this.hideShape(parent.outline); selfAndRelatives.forEach(r => { if (r.shadowShape) { // Shadow needs to be behind the combinedShape. r.shadowShape.sendToBack(); } }); } uniteTails(combinedPath: paper.PathItem, tailsToClip: Tail[]): paper.PathItem { let result = combinedPath; this.tails.forEach(t => { if (t.canUnite() && t.pathstroke) { result = result.unite(t.pathstroke, { insert: false }); this.hideShape(t.pathstroke); } else { tailsToClip.push(t); } }); return result; } public static almostInvisibleColor = new paper.Color(1, 1, 1, 0.001); // The original shapes that we merge into the combinedShapes path still have click // actions and so forth attached, and are the things we move and reshape and then // use again to make new combinedShapes. So they need to stay around. But we don't // want to actually see them...that would defeat the purpose of combining them // into a single shape that omits interior lines. OTOH, they can't be completely // transparent, or paper.js wouldn't recognize clicks on them. So make them very, // very nearly transparent. hideShape(shape: paper.Item): void { shape.strokeColor = Bubble.almostInvisibleColor; shape.fillColor = Bubble.almostInvisibleColor; } getScaleFactors(): [number, number] { const contentWidth = this.content.offsetWidth; const contentHeight = this.content.offsetHeight; var holderWidth = (this.contentHolder as any).size.width; var holderHeight = (this.contentHolder as any).size.height; const desiredHScale = contentWidth / holderWidth; const desiredVScale = contentHeight / holderHeight; return [desiredHScale, desiredVScale]; } // Returns true if the bubbles overlap. Otherwise, returns false public isOverlapping(otherBubble: Bubble): boolean { if (!this.outline || !otherBubble.outline) { // If at least one of the bubbles doesn't have its shape (yet), we define this as being not overlapping return false; } const isIntersecting = this.outline.intersects(otherBubble.outline); if (isIntersecting) { // This is the standard case (at least if an overlap does exist) where this bubble's outline intersects the other's outline return true; } else { // TODO: Check pathological case where one bubble is entirely contained within the other return false; } } // Returns true if the point is contained within the bubble itself (not including the tail). public isHitByPoint(point: paper.Point): boolean { if (!this.fillArea) { if (this.outline?.fillColor && this.outline.fillColor.alpha > 0) { return !!this.outline.hitTest(point); } // If style = none, then fillArea and outline can both be undefined // Do a hit test against the underlying content element directly (rather than the bubble fillArea, which doesn't exist) return this.isContentHitByPoint(point); } const hitResult: paper.HitResult | null = this.fillArea.hitTest(point); return !!hitResult; } // Returns true if the point is contained within the content element's borders. public isContentHitByPoint(point: paper.Point): boolean { // The point is relative to the canvas... so you need to make sure to get the position of the content relative to the canvas too. // OffsetLeft/Top works perfectly. It is relative to the offsetParent (which is the imageContainer). // It goes from the inside edge of the parent's border (which coincides with where the canvas element is placed) // to the outside edge of the content's border. // That is perfect, because that means 0, 0 for content's offsetLeft/Top will be 0, 0 in the coordinate system our Comical canvas uses. // Both systems are also independent of the zoom scaling // So that works perfectly! const left = this.content.offsetLeft; const right = left + this.content.offsetWidth; // FYI, includes content's borders, which I think is good. const top = this.content.offsetTop; const bottom = top + this.content.offsetHeight; return left <= point.x && point.x <= right && top <= point.y && point.y <= bottom; } private adjustJoiners(newTip: paper.Point): void { this.tails.forEach((tail: Tail) => { if (tail.spec.joiner && tail.adjustTip(newTip)) { this.persistBubbleSpecWithoutMonitoring(); } }); } // Disables monitoring, executes the callback, then returns monitoring back to its previous state private callWithMonitoringDisabled(callback: () => void) { const wasMonitoring = !!this.observer; this.stopMonitoring(); callback(); if (wasMonitoring) { this.monitorContent(); } } public stopMonitoring() { if (this.observer) { this.observer.disconnect(); this.observer = undefined; } } // Monitors for changes to the content element, and update this object if the content element is updated monitorContent() { this.observer = new MutationObserver(() => this.adjustSizeAndPosition()); this.observer.observe(this.content, { attributes: true, characterData: true, childList: true, subtree: true }); } // A callback for after the shape is loaded/place. // Figures out the information for the tail, then draws the shape and tail private makeTail(desiredTail: TailSpec) { const currentBubbleStyle = this.spec.style; if (this.spec.tails.length === 0) { return; } const tipPoint = new paper.Point(desiredTail.tipX, desiredTail.tipY); const midPoint = new paper.Point(desiredTail.midpointX, desiredTail.midpointY); let startPoint = this.calculateTailStartPoint(); activateLayer(this.upperLayer); // This code was initially written to have a system of different tails based on // a tail style parameter, but actually the type of tail used turns out to be more // based on which style of bubble is used. let tail: Tail; switch (currentBubbleStyle) { // Currently thought tails are specific to thought bubbles. // So these tails don't have their own style; instead, // failing to match a known tail style, we fall through here // and make one based on the bubble style. case "thought": tail = new ThoughtTail( startPoint, tipPoint, midPoint, this.lowerLayer, this.upperLayer, this.handleLayer, desiredTail, this ); break; // Currently captions have optional tails. If they have a tail, // it will be a straight line. The 'none' style may soon be able to have tails too. case "caption": case "rectangle": case "none": // Purposeful fall-through. tail = new LineTail( startPoint, tipPoint, this.lowerLayer, this.upperLayer, this.handleLayer, desiredTail, this ); break; // Currently every other bubble type uses an arc tail. default: tail = new ArcTail( startPoint, tipPoint, midPoint, this.lowerLayer, this.upperLayer, this.handleLayer, desiredTail, this ); } tail.makeShapes(); tail.onClick(() => { Comical.activateBubble(this); }); // keep track of the Tail shapes; eventually adjustSize will adjust its start position. this.tails.push(tail); } public showHandles() { this.tails.forEach((tail: Tail) => { tail.showHandles(); }); } public calculateTailStartPoint(): paper.Point { return new paper.Point( this.content.offsetLeft + this.content.offsetWidth / 2, this.content.offsetTop + this.content.offsetHeight / 2 ); } public static makeDefaultTail(targetDiv: HTMLElement): TailSpec { // careful here to use dimensions like offset that don't get inflated // by transform:scale. getBoundingContextRect() would need to be unscaled. const parent: HTMLElement = targetDiv.parentElement as HTMLElement; const targetLeft = targetDiv.offsetLeft; const targetWidth = targetDiv.offsetWidth; const targetRight = targetLeft + targetWidth; const targetTop = targetDiv.offsetTop; const targetHeight = targetDiv.offsetHeight; const targetBottom = targetTop + targetHeight; const parentLeft = 0; // offset of target is already relative to parent. const parentWidth = parent.offsetWidth; const parentRight = parentLeft + parentWidth; const parentTop = 0; const parentHeight = parent.offsetHeight; // center of targetbox relative to parent. const rootCenter = new paper.Point( targetLeft - parentLeft + targetWidth / 2, targetTop - parentTop + targetHeight / 2 ); let targetX = targetLeft - parentLeft - targetWidth / 2; if (targetLeft - parentLeft < parentRight - targetRight) { // box is closer to left than right...make the tail point right targetX = targetRight - parentLeft + targetWidth / 2; } let targetY = targetBottom - parentTop + 20; if (targetY > parentHeight - 5) { targetY = parentHeight - 5; } if (targetY < targetBottom - parentTop) { // try pointing up targetY = targetTop - parentTop - 20; if (targetY < 5) { targetY = 5; } } // Final checks: make sure the target is at least in the picture. if (targetX < 0) { targetX = 0; } if (targetX > parentWidth) { targetX = parentWidth; } if (targetY < 0) { targetY = 0; } if (targetY > parentHeight) { targetY = parentHeight; } const target = new paper.Point(targetX, targetY); const mid: paper.Point = Bubble.defaultMid( rootCenter, target, new paper.Size(targetDiv.offsetWidth, targetDiv.offsetHeight) ); const result: TailSpec = { tipX: targetX, tipY: targetY, midpointX: mid.x, midpointY: mid.y, autoCurve: true }; return result; } static adjustTowards(origin: paper.Point, target: paper.Point, originSize: paper.Size): paper.Point { // Return the origin point adjusted along a line towards target far enough to fall on // the border of a retangle of size originSize centered at origin. let delta = target.subtract(origin); const xRatio = delta.x == 0 ? Number.MAX_VALUE : originSize.width / 2 / Math.abs(delta.x); const yRatio = delta.y == 0 ? Number.MAX_VALUE : originSize.height / 2 / Math.abs(delta.y); const borderRatio = Math.min(xRatio, yRatio); // use whichever is closer return origin.add(delta.multiply(borderRatio)); } // Find the default midpoint for a tail from start to target, given the sizes of the // bubbles at start and possibly (if start is a child) at target. // First, we compute a point half way between where the line from start to target // crosses the rectangle(s) of the specified size(s) centered at the points...an // approximation of half way between the bubbles, or between the bubble and the tip. // Then we bump it a little to one side so that the curve bends slightly towards // the y axis, by an amount that decreases to zero as the line approaches // horizontal or vertical. static defaultMid( start: paper.Point, target: paper.Point, startSize: paper.Size, targetSize?: paper.Size ): paper.Point { const startBorderPoint = Bubble.adjustTowards(start, target, startSize); const targetBorderPoint = targetSize ? Bubble.adjustTowards(target, start, targetSize) : target; let delta = targetBorderPoint.subtract(startBorderPoint); const mid = startBorderPoint.add(delta.divide(2)); delta = delta.divide(5); delta.angle -= 90; // At this point, delta is 10% of the distance from start to target, // at right angles to that line, and on the side of it toward // the y axis. We prefer the line to curve in that direction, // both above and below the x axis. // Now, we want to reduce the curvature if the line is close to // horizontal or vertical. This is in line with comic expectations; // it also has the benefit that as the tip is dragged from one // quadrant to another, the transition is smooth, as the curve // reduces to a line and then starts to bend the other way rather // than suddenly jumping from one quadrant's rule to the other. if (Math.abs(delta.x) > Math.abs(delta.y)) { delta.length *= delta.y / delta.x; } else { delta.length *= delta.x / delta.y; } return mid.add(delta); } // This is a helper method which is useful for making a variety of computed bubble types. // It returns a Group containing a path and a content-holder rectangle // as makeShapes requires, given a function that makes a path from // an array of points and a center. // The content-holder rectangle is made a bit smaller than the actual height and width // of the bubble's content; makeShapes will scale it back up. // The array of points is created by first making our standard speech bubble shape // for a text box this shape (plus the requested padding, if any), // then breaking it up into segments about 30px long. // A little randomness (but predictable for a box of a given size) is // introduced to make things look more natural. // Enhance: could provide some parameter to control the ratio between // the border length and the number of points. makeBubbleItem( padWidth: number, pathMaker: (points: paper.Point[], center: paper.Point) => paper.Path ): paper.Item { const width = this.content.clientWidth; const height = this.content.clientHeight; const [outlineShape, contentHolder] = makeSpeechBubbleParts( width + padWidth * 2, height + padWidth * 2, 0.6, 0.8 ); outlineShape.remove(); // don't want it on the canvas, just use it to make points. // contentHolder isn't actually width+padWidth*2 wide and height + padWidth * 2 high. // It's a rectangle fitting inside an oval that size. // We want contentHolder to end up a size such that, when it is scaled to (width, height), // the oval is padWidth outside it. // This is difficult to visualize. The "playing with beziers" story may help. We've // asked for a speech bubble width + padWidth*2 wide...that's the width of the blue // oval. Along with it we get a contentHolder, like the red rectangle, that touches // the oval. We now want to make contentHolder smaller, so the red rectangle doesn't // touch the oval, but is 'padWidth' clear of it in both directions. However, we don't // just want it to be smaller by padWidth...we want that much clearance AFTER other // code makes the transformation that maps contentHolder onto our bubble's content // (which is 'width' wide). // // We want to solve for xRatio, which is the scaling factor we need to apply to // the eventual content holder (with the new width we are about to set) to grow // it (and the final bubble shape) to fit our content (width wide). // To do so, we can set up a system of 3 equations, 3 unknowns, and then use algebra // The equations we know: // 1) xRatio = shrunkPadWidth / padWidth // 2) xRatio = newContentHolderWidth / width // 3) newContentHolderWidth + 2 * shrunkPadWidth = contentHolderWidth // where xRatio is the ratio between what we're going to make the contentHolder width // and the actual width of the content, and shrunkPadWidth is the pad width // we need in the shape we're making (that will be scaled up by xRatio to padWidth). // // Of these, xRatio, shrunkPadWidth, and newContentHolderWidth are variables. // (padWidth, width, and contentHolderWidth are already known) // From here, you can do algebra to get this: const xRatio = contentHolder.size.width / (width + padWidth * 2); const yRatio = contentHolder.size.height / (height + padWidth * 2); contentHolder.set({ center: contentHolder.position, size: new paper.Size(width * xRatio, height * yRatio) }); // aiming for arcs ~30px long, but fewer than 5 would look weird. const computedArcCount = Math.round(((width + height) * 2) / 30); const arcCount = Math.max(computedArcCount, 5); const points: paper.Point[] = []; // We need a 'random' number generator that is predictable so // the points don't move every time we open the page. const rng = new SimpleRandom(width + height); let remainingLength = outlineShape.length; const delta = remainingLength / arcCount; const maxJitter = delta / 2; for (let i = 0; i < arcCount; i++) { const expectedPlace = i * delta; // This introduces a bit of randomness to make it look more natural. // (Since we're working around an oval, it doesn't matter whether // all the jitters are positive or whether they go both ways, // except that we have to be careful not to produce a negative // actualPlace or one beyond the length of the curve, since that // will throw an exception.) const jitter = maxJitter * rng.nextDouble(); const actualPlace = expectedPlace + jitter; const point = outlineShape.getLocationAt(actualPlace).point; points.push(point); } const outline = pathMaker(points, contentHolder.position!); return new paper.Group([outline, contentHolder]); } // Make a computed bubble shape by drawing an inward arc between each pair of points // in the array produced by makeBubbleItem. makePointedArcBubble(): paper.Item { const arcDepth = 7; return this.makeBubbleItem(arcDepth, (points, center) => { const outline = new paper.Path(); for (let i = 0; i < points.length; i++) { const start = points[i]; const end = i < points.length - 1 ? points[i + 1] : points[0]; const mid = new paper.Point((start.x + end.x) / 2, (start.y + end.y) / 2); const deltaCenter = mid.subtract(center); deltaCenter.length = arcDepth; const arcPoint = mid.subtract(deltaCenter); const arc = new paper.Path.Arc(start, arcPoint, end); arc.remove(); outline.addSegments(arc.segments); } outline.strokeWidth = 1; outline.strokeColor = new paper.Color("black"); outline.closed = true; // It should already be, but may help paper.js to treat it so. return outline; }); } // The SVG contents of a round (elliptical) bubble // // Note: An algorithmic (getComputedShapes) version of an ellipse exists here: https://github.com/BloomBooks/comical-js/blob/algorithimicEllipses/src/ellipseBubble.ts // The scaled ellipse bubble there is mathematically better proportioned and positioned, simpler, and probably faster than the SVG one here // However, as a result of the improvement, it is only very similar but not 100% identical to this existing SVG one public static ellipseBubble() { return `<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" id="svg8" version="1.1" viewBox="0 0 100 100" height="100mm" width="100mm"> <defs id="defs2" /> <metadata id="metadata5"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <g transform="translate(0,-197)" id="layer1"> <ellipse ry="49.702854" rx="49.608364" cy="247.10715" cx="50.36533" id="outlineShape" style="fill:#ffffff;stroke:#000000;stroke-width:0.26660731;stroke-opacity:1" /> <rect id="content-holder" class="content-holder" y="214.03423" x="13.229166" height="65.956848" width="74.461304" style="fill:none;stroke:#000000;stroke-width:0.26458332;stroke-opacity:1" /> </g> </svg>`; } // The SVG contents of a shout bubble (jagged / exploding segments coming out) public static shoutBubble() { return `<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" id="svg8" version="1.1" viewBox="0 0 100 100" height="100mm" width="100mm"> <defs id="defs2" /> <metadata id="metadata5"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <g transform="translate(0,-197)" id="layer1"> <path id="path4528" d="m 34.773809,223.10566 14.174107,-25.89137 12.662202,25.51339 21.92262,-25.13542 -6.199227,26.04296 19.050415,-5.82123 -18.898809,23.62351 22.489583,8.50447 -22.678569,13.60714 20.78869,31.56101 -39.498513,-24.94643 2.834823,21.73363 -17.386906,-21.73363 -17.575892,27.0253 0.566965,-27.0253 L 4.346726,290.00744 22.489583,258.44643 0.37797618,247.67411 22.867559,235.76786 1.7008928,199.29316 Z" style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" /> <rect id="content-holder" y="223.63522" x="22.830175" height="46.376858" width="54.503334" style="fill:none;stroke:#000000;stroke-width:0.18981449;stroke-opacity:1;fill-opacity:0" /> </g> </svg>`; } }
Java
UTF-8
18,486
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: https://www.jooq.org/legal/licensing * * * * * * * * * * * * * * * * */ package org.jooq; // ... // ... // ... // ... import static org.jooq.SQLDialect.CUBRID; // ... import static org.jooq.SQLDialect.DERBY; // ... import static org.jooq.SQLDialect.H2; // ... import static org.jooq.SQLDialect.HSQLDB; import static org.jooq.SQLDialect.IGNITE; // ... // ... import static org.jooq.SQLDialect.MARIADB; // ... // ... import static org.jooq.SQLDialect.MYSQL; // ... // ... import static org.jooq.SQLDialect.POSTGRES; // ... // ... import static org.jooq.SQLDialect.SQLITE; // ... // ... // ... import static org.jooq.SQLDialect.TRINO; // ... import static org.jooq.SQLDialect.YUGABYTEDB; import java.util.Collection; import java.util.List; import org.jooq.impl.DSL; import org.jooq.impl.QOM; import org.jooq.impl.QOM.UnmodifiableList; import org.jooq.impl.QOM.With; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.ApiStatus.Experimental; /** * A <code>SELECT</code> statement. * <p> * <strong>Example:</strong> * <p> * <pre><code> * // Assuming import static org.jooq.impl.DSL.*; * * using(configuration) * .select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME) * .from(ACTOR) * .fetch(); * </code></pre> * <p> * Instances can be created using {@link DSL#select(SelectFieldOrAsterisk...)}, * or {@link DSLContext#selectQuery()} and overloads. * * @param <R> The record type being returned by this query * @author Lukas Eder */ public non-sealed interface Select<R extends Record> extends ResultQuery<R>, TableLike<R>, FieldLike, FieldOrRowOrSelect { /** * Apply the <code>UNION</code> set operation. * <p> * In SQL, a <code>UNION</code> is <code>DISTINCT</code> by default, * meaning, duplicates are removed from the result set. So, this is the same * as {@link #unionDistinct(Select)}. If duplicate removal isn't required, * or already guaranteed by the data model, it is recommended to use * {@link #unionAll(Select)}, instead. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support Select<R> union(Select<? extends R> select); /** * Apply the <code>UNION DISTINCT</code> set operation. * <p> * In SQL, a <code>UNION</code> is <code>DISTINCT</code> by default. * However, it is often useful to make this explicit to express intent when * distinct removal is really desired. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support Select<R> unionDistinct(Select<? extends R> select); /** * Apply the <code>UNION ALL</code> set operation. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support Select<R> unionAll(Select<? extends R> select); /** * Apply the <code>EXCEPT</code> (or <code>MINUS</code>) set operation. * <p> * In SQL, an <code>EXCEPT</code> is <code>DISTINCT</code> by default, * meaning, duplicates are removed from the result set. So, this is the same * as {@link #exceptDistinct(Select)}. If duplicate removal isn't required, * or already guaranteed by the data model, it is recommended to use * {@link #exceptAll(Select)}, instead, if the underlying RDBMS supports it. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, H2, HSQLDB, IGNITE, MARIADB, MYSQL, POSTGRES, SQLITE, TRINO, YUGABYTEDB }) Select<R> except(Select<? extends R> select); /** * Apply the <code>EXCEPT</code> (or <code>MINUS</code>) set operation. * <p> * In SQL, an <code>EXCEPT</code> is <code>DISTINCT</code> by default. * However, it is often useful to make this explicit to express intent when * distinct removal is really desired. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, H2, HSQLDB, IGNITE, MARIADB, MYSQL, POSTGRES, SQLITE, TRINO, YUGABYTEDB }) Select<R> exceptDistinct(Select<? extends R> select); /** * Apply the <code>EXCEPT ALL</code> set operation. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, HSQLDB, MARIADB, MYSQL, POSTGRES, TRINO, YUGABYTEDB }) Select<R> exceptAll(Select<? extends R> select); /** * Apply the <code>INTERSECT</code> set operation. * <p> * In SQL, an <code>INTERSECT</code> is <code>DISTINCT</code> by default, * meaning, duplicates are removed from the result set. So, this is the same * as {@link #intersectDistinct(Select)}. If duplicate removal isn't * required, or already guaranteed by the data model, it is recommended to * use {@link #intersectAll(Select)}, instead, if the underlying RDBMS * supports it. Apply the <code>INTERSECT</code> set operation. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, H2, HSQLDB, IGNITE, MARIADB, MYSQL, POSTGRES, SQLITE, TRINO, YUGABYTEDB }) Select<R> intersect(Select<? extends R> select); /** * Apply the <code>INTERSECT</code> set operation. * <p> * In SQL, a <code>INTERSECT</code> is <code>DISTINCT</code> by default. * However, it is often useful to make this explicit to express intent when * distinct removal is really desired. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, H2, HSQLDB, IGNITE, MARIADB, MYSQL, POSTGRES, SQLITE, TRINO, YUGABYTEDB }) Select<R> intersectDistinct(Select<? extends R> select); /** * Apply the <code>INTERSECT ALL</code> set operation. * * @throws IllegalArgumentException If the argument select has the same * identity as this select. The jOOQ 3.x API is mutable, which * means that calls to the DSL API mutate this instance. Adding * this instance as an set operation argument would lead to a * {@link StackOverflowError} when generating the SQL. */ @NotNull @CheckReturnValue @Support({ CUBRID, DERBY, HSQLDB, MARIADB, MYSQL, POSTGRES, TRINO, YUGABYTEDB }) Select<R> intersectAll(Select<? extends R> select); /** * All fields selected in this query */ @NotNull @CheckReturnValue List<Field<?>> getSelect(); // ------------------------------------------------------------------------- // XXX: Query Object Model // ------------------------------------------------------------------------- /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable With $with(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<?> $with(With newWith); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends SelectFieldOrAsterisk> $select(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<?> $select(Collection<? extends SelectFieldOrAsterisk> newSelect); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental boolean $distinct(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $distinct(boolean newDistinct); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends SelectFieldOrAsterisk> $distinctOn(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $distinctOn(Collection<? extends SelectFieldOrAsterisk> newDistinctOn); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends Table<?>> $from(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $from(Collection<? extends Table<?>> newFrom); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable Condition $where(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $where(Condition newWhere); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends GroupField> $groupBy(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $groupBy(Collection<? extends GroupField> newGroupBy); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental boolean $groupByDistinct(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $groupByDistinct(boolean newGroupByDistinct); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable Condition $having(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $having(Condition newHaving); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends WindowDefinition> $window(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $window(Collection<? extends WindowDefinition> newWindow); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable Condition $qualify(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $qualify(Condition newQualify); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @NotNull UnmodifiableList<? extends SortField<?>> $orderBy(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $orderBy(Collection<? extends SortField<?>> newOrderBy); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable Field<? extends Number> $limit(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $limit(Field<? extends Number> newLimit); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental boolean $limitPercent(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $limitPercent(boolean newLimitPercent); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental boolean $limitWithTies(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $limitWithTies(boolean newLimitWithTies); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @Nullable Field<? extends Number> $offset(); /** * Experimental query object model accessor method, see also {@link QOM}. * Subject to change in future jOOQ versions, use at your own risk. */ @Experimental @CheckReturnValue @NotNull Select<R> $offset(Field<? extends Number> newOffset); }
C++
UTF-8
438
2.890625
3
[]
no_license
#include <iostream> #include <sstream> using namespace std; int *inputArray; int *countingArray; int *sortedArray; void createArrays() { } void getInputArray() { string inputString; /* getline(cin,inputString); istringstream iss(inputString);*/ int j = 0; while(iss >> i) { int i = 0; } } int main() { getInputArray(); createDynamicArrays(); countingSort(); printSortedArray(); destroyArrays(); return 0; }
Java
UTF-8
1,720
2.421875
2
[]
no_license
package org.sdrc.scsl.web.controller; import org.sdrc.scsl.model.mobile.LoginDataModel; import org.sdrc.scsl.model.mobile.MasterDataModel; import org.sdrc.scsl.model.mobile.SyncModel; import org.sdrc.scsl.model.mobile.SyncResult; import org.sdrc.scsl.service.MobileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * The following controller class will deal with all the request (login and sync) that comes from mobile device * @since 1.0.0 * @author Ratikanta Pradhan (ratikanta@sdrc.co.in) on 24-Apr-2017 3:51:47 pm */ @RestController public class MobileController { @Autowired private MobileService mobileService; /** * When user try to login, the following method will deal with that functionality * @param LoginDataModel user information that have come from mobile * @since 1.0.0 * @author Ratikanta Pradhan (ratikanta@sdrc.co.in) on 24-Apr-2017 4:46:01 pm */ @RequestMapping( value = "login", method = RequestMethod.POST) public MasterDataModel login(@RequestBody LoginDataModel loginDataModel){ return mobileService.getMasterData(loginDataModel); } /** * When mobile device will send transaction data to server, following method is going to deal with it * @param SyncModel data that have come from mobile. * @since 1.0.0 * @author Ratikanta Pradhan (ratikanta@sdrc.co.in) on 24-Apr-2017 4:36:14 pm */ @RequestMapping( value = "sync", method = RequestMethod.POST) public SyncResult sync(@RequestBody SyncModel syncModel){ return mobileService.sync(syncModel); } }
Java
UTF-8
783
2.484375
2
[]
no_license
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.Background; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * Created by XZL on 2017/5/24. */ public class False extends Stage{ public void start(Stage primaryStage) throws Exception { Label label=new Label("该单词不在词表中!"); Button button=new Button("确定"); button.setOnAction(event -> { primaryStage.close(); }); VBox vBox=new VBox(label,button); vBox.setAlignment(Pos.CENTER); Scene scene=new Scene(vBox); primaryStage.setScene(scene); primaryStage.show(); } }
Python
UTF-8
2,511
3.984375
4
[]
no_license
''' Level: Medium Tag: [Math] You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr: Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer n, return the last number that remains in arr. Example 1: Input: n = 9 Output: 6 Explanation: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr = [2, 4, 6, 8] arr = [2, 6] arr = [6] Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 10^9 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] [2, 6, 10, 14, 18] [6, 14] [6] 我們首先分析能夠得到的信息。一個很容易觀察到的變化規律就是步長信息,那我們就首先得到步長的規律。 觀察第一列的步長爲2,第二列的步長爲4(相隔元素), 第三列元素爲8(假設存在10 11 12 第二列元素就變成 2 4 6 8 10 12 第三列就變成 2 6 10), 也就是說步數在每輪循環中是上一輪的兩倍。我們再來觀察元素個數遞減規律,發現元素個數是按1/2的速度遞減的。 當遞減元素個數減少到1時,就得到了最終的剩餘元素。 最難的部分就是追蹤每次的頭部元素,很容易觀察到的一個結論是,從左側開始的頭部元素都是上一次的頭部元素加上步長。 對於從右側開始的迭代過程,則分爲兩種情況,一種情況是左側頭部元素不變, 一種情況是左側頭部元素爲上次迭代的頭部元素加步長, 對於後一種情況,我們容易觀察到的一點是,在剩餘元素是奇數個時,頭部元素會發生改變,否則不變 ''' class Solution(object): def lastRemaining(self, n): """ :type n: int :rtype: int """ is_left = True head = 1 step = 1 remain = n while remain > 1: if is_left or remain % 2 == 1: head += step print(head) step *= 2 remain /= 2 is_left = not is_left # print(head) return head n = 9 Solution().lastRemaining(n) n = 20 Solution().lastRemaining(n)
Python
UTF-8
564
3.5625
4
[]
no_license
inventory = {'arrow': 12, 'goldcoin': 42, 'rope': 1, 'torch': 6, 'dagger': 1} addeditems = ['arrow', 'goldcoin', 'rope', 'goldcoin', 'dagger', 'goldcoin'] def addtoinventory(iventory, addeditems): for items in addeditems: inventory[items] += 1 def displayinventory(items): print("Inventory:") count = 0 for keys in items.keys(): print(inventory[keys], keys) count += inventory[keys] print("Total number of items: ", str(count)) addtoinventory(inventory, addeditems) displayinventory(inventory)
Java
UTF-8
2,092
1.710938
2
[]
no_license
package com.tencent.mm.plugin.webview.fts.b.a.a; import android.text.TextUtils; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.sdk.platformtools.ab; import com.tencent.mm.sdk.platformtools.bo; import org.json.JSONException; import org.json.JSONObject; public final class a { public String csB; public String ugA; public String ugB; private String ugC; private String ugD; private String ugE; private boolean ugF; public String ugz; public a(String str) { boolean z = true; AppMethodBeat.i(5776); String str2 = new String(bo.readFromFile(str)); if (TextUtils.isEmpty(str2)) { IllegalArgumentException illegalArgumentException = new IllegalArgumentException("there is no test data"); AppMethodBeat.o(5776); throw illegalArgumentException; } try { JSONObject jSONObject = new JSONObject(str2); this.csB = jSONObject.optString("appid"); this.ugz = jSONObject.optString("versionType"); try { this.ugA = jSONObject.optJSONObject("queryIntent").toString(); } catch (Exception e) { ab.printErrStackTrace("WidgetUiTestInfo", e, "", new Object[0]); } this.ugB = jSONObject.optString("realQuery"); try { this.ugC = jSONObject.optJSONObject("testData").toString(); } catch (Exception e2) { ab.printErrStackTrace("WidgetUiTestInfo", e2, "", new Object[0]); } this.ugD = jSONObject.optString("domResultPath"); this.ugE = jSONObject.optString("widgetPicDir"); if (jSONObject.optInt("onlyPic") != 1) { z = false; } this.ugF = z; AppMethodBeat.o(5776); } catch (JSONException e3) { IllegalArgumentException illegalArgumentException2 = new IllegalArgumentException(e3); AppMethodBeat.o(5776); throw illegalArgumentException2; } } }
JavaScript
UTF-8
5,628
2.890625
3
[]
no_license
var quiztitle = " Leviticus ಅಧ್ಯಾಯ 2"; var quiz = [ { "question" : " 1. This should be poured on meat offerings of fine flour. ", "image" : "", "choices" : [ " a. Blood ", " b. Water ", " c. Oil ", " d. Wine " ], "correct" : " c. Oil ", "explanation" : " And when any will offer a meat offering unto the LORD, his offering shall be of fine flour; and he shall pour oil upon it, and put frankincense thereon: Lev 2:1 ", }, { "question" : " 2. This should also be put on it. ", "image" : "", "choices" : [ " a. Ashes ", " b. Sand ", " c. Frankincense ", " d. A linen cover " ], "correct" : " c. Frankincense ", "explanation" : " And when any will offer a meat offering unto the LORD, his offering shall be of fine flour; and he shall pour oil upon it, and put frankincense thereon: Lev 2:1 ", }, { "question" : " 3. What will the priests do with a handful of the mixture? ", "image" : "", "choices" : [ " a. Eat it ", " b. Sprinkle it over the sea ", " c. Burn it ", " d. Sell it " ], "correct" : " c. Burn it ", "explanation" : " And he shall bring it to Aaron's sons the priests: and he shall take thereout his handful of the flour thereof, and of the oil thereof, with all the frankincense thereof; and the priest shall burn the memorial of it upon the altar, to be an offering made by fire, of a sweet savour unto the LORD: Lev 2:2 ", }, { "question" : " 4. Whose sons were the priests? ", "image" : "", "choices" : [ " a. Aaron ", " b. Levi ", " c. Moses ", " d. Joshua " ], "correct" : " a. Aaron ", "explanation" : " And he shall bring it to Aaron's sons the priests: and he shall take thereout his handful of the flour thereof, and of the oil thereof, with all the frankincense thereof; and the priest shall burn the memorial of it upon the altar, to be an offering made by fire, of a sweet savour unto the LORD: Lev 2:2 ", }, { "question" : " 5. Baked cakes or wafers given as an offering were to be ", "image" : "", "choices" : [ " a. Baked before dawn. ", " b. Baked in Jerusalem. ", " c. Unleavened. ", " d. Made with leaven. " ], "correct" : " c. Unleavened. ", "explanation" : " And if thou bring an oblation of a meat offering baken in the oven, it shall be unleavened cakes of fine flour mingled with oil, or unleavened wafers anointed with oil. Lev 2:4 ", }, { "question" : " 6. The priests were to take a memorial from the meat offering and do this. ", "image" : "", "choices" : [ " a. Test it ", " b. Burn it on the altar ", " c. Give it to the poor ", " d. Bury it " ], "correct" : " b. Burn it on the altar ", "explanation" : " And the priest shall take from the meat offering a memorial thereof, and shall burn it upon the altar: it is an offering made by fire, of a sweet savour unto the LORD. Lev 2:9 ", }, { "question" : " 7. That which was left was to be ", "image" : "", "choices" : [ " a. Destroyed. ", " b. Sold. ", " c. Aaron's and his sons. ", " d. Fed to the livestock. " ], "correct" : " c. Aaron's and his sons. ", "explanation" : " And that which is left of the meat offering shall be Aaron's and his sons': it is a thing most holy of the offerings of the LORD made by fire. Lev 2:10 ", }, { "question" : " 8. None of the offerings were to be made with this. ", "image" : "", "choices" : [ " a. Oil ", " b. Flour ", " c. Incense ", " d. Honey " ], "correct" : " d. Honey ", "explanation" : " No meat offering, which ye shall bring unto the LORD, shall be made with leaven: for ye shall burn no leaven, nor any honey, in any offering of the LORD made by fire. Lev 2:11 ", }, { "question" : " 9. Every meat offering was to be seasoned with this. ", "image" : "", "choices" : [ " a. Salt ", " b. Pepper ", " c. Mint ", " d. Sage " ], "correct" : " a. Salt ", "explanation" : " And every oblation of thy meat offering shalt thou season with salt; neither shalt thou suffer the salt of the covenant of thy God to be lacking from thy meat offering: with all thine offerings thou shalt offer salt. Lev 2:13 ", }, { "question" : " 10. What was to be put on the corn to be offered? ", "image" : "", "choices" : [ " a. Blood ", " b. Water ", " c. Ashes ", " d. Oil " ], "correct" : " d. Oil ", "explanation" : " And if thou offer a meat offering of thy firstfruits unto the LORD, thou shalt offer for the meat offering of thy firstfruits green ears of corn dried by the fire, even corn beaten out of full ears.And thou shalt put oil upon it, and lay frankincense thereon: it is a meat offering. Lev 2:14-15 ", }, ]
Python
UTF-8
9,823
2.828125
3
[]
no_license
import os from flask import Flask from flask import render_template from flask import request from flask import redirect from flask import url_for from flask import session from flask import flash # import flask functions from data import db_manager, db_builder # import database functions app = Flask(__name__) # Must be replaced by a static long random string. How to: http://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables app.secret_key = os.urandom(32) # set up sessions with random secret key @app.route("/") def root(): if "username" in session: #if user is logged in, return redirect(url_for("home")) # redirect to homepage return redirect(url_for("login")) # else, redirect to login page @app.route("/login") def login(): if "username" in session: # if user is logged in, return redirect(url_for("home")) # redirect to homepage if len(request.args) == 2: # if users clicked the log in button, if request.args["username"] == "" or request.args["password"] == "": # if either username or password is blank flash("Please do not leave any fields blank") # flash error else: response = db_manager.verify_login(request.args["username"], request.args["password"]) # verify entered username and password with database if response == "": # if username and password combo is in database session["username"] = request.args["username"] # add username to session (log user in) return redirect(url_for("home")) # redirect to homepage else: # else is username/password is incorrect flash(response) # flash error return render_template("login/login.html") # render login template @app.route("/create-account") def create_account(): if "username" in session: # if user is logged in, return redirect(url_for("home")) # redirect to homepage if len(request.args) == 3: # if users clicked the submit button on create account page if request.args["username"] == "" or request.args["passwordNew"] == "" or request.args["passwordRepeat"] == "": # if any one of the three fields are blank, flash("Please do not leave any fields blank") # flash an error else: if request.args["passwordNew"] != request.args["passwordRepeat"]: # if the two passwords do not match, flash("Passwords don't match, try again") # flash an error else: # else if the passwords match response = db_manager.add_login(request.args["username"], request.args["passwordNew"]) # check with database to see if the username is valid/unique if response == "": # if username is valid, session["username"] = request.args["username"] # add username to session (log user in) return redirect(url_for("home")) # redirect to homepage else: # else if the username is already taken flash(response) # flash error return render_template("login/create-account.html") # render create-account.html template @app.route("/home") def home(): if "username" not in session: # if user is not logged in, return redirect(url_for("login")) # redirect to login page if "user" in request.args: # if user clicked on a button to view other users' blogs return redirect(url_for("blogs", user=request.args["user"])) # redirect logged in user to blogs page with the username they clicked on as a GET request blog_users = db_manager.get_usernames_with_blogs() # get the list of usernames with blogs from database user = session["username"] # user is set to the username of person logged in if user in blog_users: # if the user logged in has blogs blog_users.remove(user) # remove their username from the list of usernames return render_template("home.html", username=user, usernames=blog_users) # render home.html template with the username and list of other users with blogs @app.route("/blogs", methods=['GET']) def blogs(): if "username" not in session: # if user is not logged in, return redirect(url_for("login")) # redirect to login page user = session["username"] # user is set to username of logged in user blog_owner = user # blog_owner is set to user by default if "user" in request.args: # if user is not blog_owner blog_owner = request.args["user"][:len(request.args["user"]) - 8] #set blog_owner to the username of the actual owner of the blog if "blog_creation" in request.args: # if the blog_owner clicked on create blog button, title = request.args["blog_name"] # set title to the blog title that user entered if title == "": flash("Please do not have an empty blog title") else: response = db_manager.create_blog_for_username(user, title) # verify blog title with database if response == "": # if blog title is unique return redirect(url_for("entries", blog_id=db_manager.get_blog_id_from_title( user, title), blog_name=title)) # redirect to the entries page of the new blog with # the blog title and blog id as GET requests flash(response) # else flash error if blog with the same title already exists return render_template("blogs.html", username=user, name=("Your" if blog_owner == user else blog_owner), isOwner=(blog_owner == user), blogs=db_manager.get_blogs_for_username(blog_owner)) # render blogs.html template with the username of user logged in, # the blog owner, whether the user logged in is the owner, and # the list of blogs owned by logged in user @app.route("/blogs/entries", methods=['GET']) def entries(): if "username" not in session: # if user is not logged in, return redirect(url_for("login")) # redirect to login page blog_title = request.args["blog_name"] # set blog_title to blog name acquired from GET request user = session["username"] # set user to username of person logged in blog_owner = user # blog_owner is set to user by default if "user" in request.args and request.args["user"] != "Your": blog_owner = request.args["user"] if "blog_id" in request.args: # if blog_id is in GET request (which happens when blog is just created), blog_id = request.args["blog_id"] # set blog_id to that GET request else: # else if blog_id is not in GET request blog_id = db_manager.get_blog_id_from_title(blog_owner, blog_title) # get blog_id from database based on the username and blog_title # if user is not the owner of the blog, None is returned if len(request.args) == 4: # if the length of GET requests is 4, meaning user is updating, deleting, # or creating entries, entry_title = request.args["entry_title"] entry_content = request.args["entry_content"] # set entry_title and entry_content based on the GET requests if "update" in request.args: # if user is updating an entry db_manager.remove_entry(db_manager.get_entry_id(entry_title, blog_id)) # tell database to remove the entry db_manager.add_entry(entry_title, entry_content, blog_id) # create a new entry in database with the same blog_id and entry_title, # but with the updated content if "delete" in request.args: # if user is deleting an entry db_manager.remove_entry(db_manager.get_entry_id(entry_title, blog_id)) # tell database to remove the entry after getting its entry_id given # entry_title and blog_id if "create" in request.args: # if user is creating entry if entry_title == "": # if entry_title is blank, flash("Please do not have a blank entry title") # flash an error else: response = db_manager.add_entry(entry_title, entry_content, blog_id) # tell database to add entry given the entry_title, entry_content, # and blog_id if response != "": # if entry was not added successfully (because of duplicate title), flash(response) # flash an error return render_template("entries.html", blog_name=blog_title, entries=db_manager.get_entries_for_blog(blog_id), isOwner=db_manager.is_owner( user, blog_id)) # render entries.html template given blog_name, list of entries, and isOwner @app.route("/logout") def logout(): if "username" in session: # if user is logged in session.pop("username") # pop "username" from session (logging the user out) return redirect(url_for("login")) # redirect user back to login page if __name__ == "__main__": app.debug = True app.run()
Python
UTF-8
113
2.609375
3
[]
no_license
def hello(x): print('Hi ' + str(x)) print('my name') print('Hello there') hello(3) #hello() #hello()
Markdown
UTF-8
3,782
2.84375
3
[]
no_license
# CI/CD > A integração contínua (CI) é uma prática de desenvolvimento de software de DevOps em que os desenvolvedores, com frequência, juntam suas alterações de código em um repositório central. Deploy Contínuo (CD) é o ato implantar o produto produzido no servidor de aplicação, ou seja, entregar o produto ao cliente, seja ele em ambiente de desenvolvimento, stagging ou produção. ## Continuous Integration > _[...] integrating code is one of a common class of problems in software, where time moves linearly but pain moves exponentially: the longer you delay, the worse > the problem becomes”_ > > _Neal Ford - Director at ThoughtWork_ ![](images/continuousIntegration.png) * Uma prática de desenvolvimento de software onde os membros do time de desenvolvimento integram seu trabalha constantemente; * Cada integração é feita automaticamente por um processo para detectar falhas rapidamente; * Reduz drasticamente problemas de integração e possibilita o desenvolvimento de um software seguro e coeso; * Escreva testes automatizados para desenvolvedores; * Execute compilações privadas; * Confirme código com frequência; * Não confirme código com defeito; * Evite obter código com defeito; * Corrija construções com defeito imediatamente; * Todos os testes e inspeções devem passar; ## Continuous Delivery >Quão frequentes você entrega software em produção para os seus usuários? * Mais de uma vez por dia? * Mais de uma vez por semana? * Mais de uma vez por mês? * Mais de uma vez por ano? * Uma vez por ano ou menos? * Releases entregue em produção de forma frequente: * Medida real de progresso * Feedback do usuário * Reduz consideravelmente o risco de release ![](images/continuousDelivery.png) * Princípios * Cada commit gera um release candidate * Automatize tudo que pode ser automatizado * If it hurts, do it more often and bring the pain forward "_Se doer, faça-o com mais frequência e traga a dor para frente_" * A qualidade interna é obrigatória * Testes automatizados são essenciais * Todo mundo é responsável pela release * Pronto significa released _DOD e DOR - Definitions of Ready/Definitions of Done_ * Melhoria Contínua(Continuous Improvement) > _“Continuous Delivery deixou de ser um diferencial tecnológico para ser uma necessidade dentro das organizações”_ > > _Jezz Humble - 2011_ ![](images/continuousDelivery1.png) ## Ferramentas ![](images/ferramentas.png) ## Build Pipeline ![](images/buildPipeline.png) * Commit Stage: * Poll SCM; * Compilação; * Cobertura dos testes; * Unitários e integração; * Qualidade do código fonte; * Conformidades com padrões empresariais; * Possíveis bugs; * Boas práticas; * Empacotamento e publicação; * Acceptance Stage: * Testes automatizados; * Testes funcionais; * Testes de aceitação; * Testes de performance; * Testes de segurança; * Production Stage: * Etapa final do pipeline; * Requer permissão para executar; * Going live; * Deve ser apenas mais um deployment; * Tenha em mente as alternativas de “remediação”; * Conheça as alterações do seu software; ## Considerações * Automatização + testes = sucesso; * Reduza os riscos com releases incrementais; * Existem inúmeras formas de se construir um build pipeline. Descubra a sua; * Cultura de DevOps é necessária; * Prepare-se: quanto tempo você demora para reconstruir o seu ambiente a partir do zero? * Dificuldades: * Exige mudança cultural; * Maior dificuldade encontrada nas implantações de Continuous Delivery; * Exige Ciclos Curtos; * Empresas organizadas em silos/áreas; * Requer envolvimento de todos; ![](images/consideracoes.png)
PHP
UTF-8
1,457
2.5625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Aggrego\TerminalSymfonyExample\Model\TransformationStatus; use Aggrego\Component\BoardComponent\Contract\Application\UseCases\TransformBoard\TransformBoardCommand; use Aggrego\Component\BoardComponent\Contract\Application\UseCases\TransformBoard\Messages\BoardCreated; use Aggrego\Component\BoardComponent\Contract\Application\UseCases\TransformBoard\Messages\BoardNotTransformed; class TransformationStatusProjection { public function __construct( private TransformationStatusRepository $transformationStatusRepository ) { } public function handleTransformBoardCommand(TransformBoardCommand $command): void { $this->transformationStatusRepository->set( TransformationStatus::fromTransformBoardCommand($command) ); } public function handleBoardCreated(BoardCreated $boardCreated): void { $status = $this->transformationStatusRepository->get($boardCreated->getCorrelatedCommand()); $status->applyBoardCreated($boardCreated); $this->transformationStatusRepository->set($status); } public function handleBoardNotTransformed(BoardNotTransformed $boardNotCreated): void { $status = $this->transformationStatusRepository->get($boardNotCreated->getCorrelatedCommand()); $status->applyBoardNotTransformed($boardNotCreated); $this->transformationStatusRepository->set($status); } }
Markdown
UTF-8
2,610
3.265625
3
[]
no_license
# icg-assignment-1 assignment 1 for icg due 26/05/2021 Description: What we have is a website with a customer and staff side. On the customer side it is going to be a website where users can create accounts or log in and then using special code on the product they will certify that they have bought this item. After which they will review it and then when they submit the review they will get reward points that they can use to get discounts or free items from the company's range of products a the selected distributors. They can also browse the website like a catalog to read more information about the items. There will also be a special section where people who are logged in can do a survey about the products for some points. All the info from the customers goes into the customer relations database On the staff side there will be an option to login as an employee or as an admin(only the boss and it people). Here the employees have a tool to schedule  other employees. In the scheduler they can set events like for example a meeting or team building event. Employees can also set deadline reminders in the scheduler . People who have access to admin accounts are able to set deadline for other employees they are also able to add or remove employees /their information. They can also add or remove products from the customer side of the site and mark somethibg in or out of stock. Note this *not* an online selling website they continue to sell through their distributors modules: staff,customers,scheduling,products - staff:This module groups togethere all the functions which are actions employees can take on the website. - customer:This module groups togethere all the functions which are actions customers can take on the website. - scheduling: This is all the functions that effect the scheduler. - products: This is all the functions that effect product like updating product description. funtions: - employees login - administrative login - add employee account to system(admin) - update employee details. - remove employee account(admin) - admin log out - delete review(admin) - Broadcast announcements (to both employees and customers) - customer log in - customer log out - customer create account - customer delete account - submit review - submit survey - update stock codes. - delete the stock codes. - add product description. - update product description - add product - remove product - certify unique item code - mark in stock - mark out of stock - decrease rewards points - add event (eg. meeting) - remove event - move event - add deadline - remove deadline - assign task
PHP
UTF-8
300
2.640625
3
[]
no_license
<?php $m = rand(1,12); echo $m.'<br>' switch ($m){ case 1 :case 3 :case 5 :case 7 :case 8 :case 1 : echo'31' break; case 2 echo'28' break; case 4 :case 6 :case 9 :case 11: echo '30' break; } echo '<>'; $a='1';
PHP
UTF-8
1,250
3.015625
3
[ "MIT" ]
permissive
<?php namespace src\models; use HCTorres02\QueryBuilder\Database; class Category { /** @var int */ public $id; /** @var string */ public $title; /** @var bool */ public $active; /** * @return Category[]|null */ public static function all($onlyActives = false): ?array { $qb = self::queryBuilder(); if ($onlyActives == true) { $qb->addColumns('SUM(p.active = 1) AS posts') ->where('c.active', true); } return $qb->fetchAll(); } /** * @param sting $column * @param string $value * @param bool $fetchAll * @return Category[]|Category|null */ public static function findBy($column, $value, $fetchAll = true) { $qb = self::queryBuilder()->where($column, $value); if ($fetchAll) { return $qb->fetchAll(); } return $qb->fetchObject(self::class); } /** * @return HCTores02\QueryBuilder\Database */ private static function queryBuilder() { return Database::table('categories', 'c') ->join('posts p', 'p.category_id = c.id') ->addColumns('COUNT(*) AS posts') ->groupBy('c.id'); } }
Java
UTF-8
1,117
2.46875
2
[ "Apache-2.0" ]
permissive
package org.sirenia.func.core; import lombok.Cleanup; import lombok.SneakyThrows; import org.sirenia.func.anno.SideEffect; import org.springframework.util.FileCopyUtils; import javax.annotation.Nonnull; import java.io.InputStream; import java.io.OutputStream; import java.util.function.BiConsumer; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public abstract class ZipFunc { @SneakyThrows @SideEffect public static void zip(@Nonnull InputStream input, @Nonnull OutputStream output, @Nonnull String entryName) { @Cleanup ZipOutputStream zos = new ZipOutputStream(output); zos.putNextEntry(new ZipEntry(entryName)); FileCopyUtils.copy(input, zos); zos.closeEntry(); } @SneakyThrows @SideEffect public static void unZip(@Nonnull InputStream input, @Nonnull BiConsumer<String, ZipInputStream> consumer) { @Cleanup ZipInputStream zis = new ZipInputStream(input); ZipEntry entry = zis.getNextEntry(); consumer.accept(entry.getName(), zis); zis.closeEntry(); } }
C++
UTF-8
658
3.65625
4
[]
no_license
// Main’s only responsibilityis to call a function called doAllThework. // doAllTheWork should ask the user for the 2 ints and the char, do the // calculations and write all info to the screen. // Mekhi 2.24.20 #include <iostream> using namespace std; void doAllTheWork() { int int1, int2, intSum; char charPlus; intSum = 0; cout << "Please enter two integers\n"; cin >> int1 >> int2; cout << "Please enter a '+'\n"; cin >> charPlus; while (intSum == 0) { if (charPlus == '+') { intSum = int1 + int2; cout << int1 << " + " << int2 << " = " << intSum; } else { cout << "Please enter a '+'\n"; cin >> charPlus; } } } int main() { doAllTheWork(); return 0; }
Markdown
UTF-8
2,204
3.015625
3
[]
no_license
Frameworks ========== Frameworks are collections of code that can be thought of and loaded as a single unit. They can depend on each other (though not circularly). SproutCore has several frameworks. For instance: - Runtime - Foundation - Desktop Desktop requires Foundation, which requires Runtime. Frameworks are basically just folders inside a "frameworks" folder. The frameworks folder can be inside an app's folder, or inside another framework's folder. They are just like apps in many ways; for instance, they can have a resources folder (or english.lproj, if that's your thing). They will recursively include every JavaScript file inside of them, and every CSS or image file inside their resource directories. Using Frameworks ================ SC's build tools cannot magically tell when you want to use a framework. Putting a framework in your "frameworks" directory is not enough. That just puts the framework in a place available to SproutCore's build tools. To actually reference them, you have to edit your Buildfile(s). Buildfiles (which need high-level documentation themselves) give build configuration to a project or app. For instance, they can tell SproutCore which frameworks are required by which applications. Here's an example entry that "requires" a couple SproutCore frameworks: #ruby config :all, :required => [:sproutcore, :"sproutcore/animation"] This code is actually Ruby code. The command "config" takes multiple arguments: the first is what to configure— in this case, everything—and following that is a set of key+value arguments for the individual settings. Now, your app probably will require SproutCore's runtime, foundation, and desktop frameworks. As you might have noticed, you do **not** have to specify these in your Buildfile. Why? Because somewhere, buried in SproutCore's own master Buildfile, is something which equates to the following: #ruby config :all, :required => [:runtime, :foundation, :desktop] Since you are requiring the "sproutcore" framework, which already requires these, you have no need to require them yourself. Only "sproutcore/animation" must be required manually, because it is an optional framework.
Java
UTF-8
2,799
3.125
3
[ "MIT" ]
permissive
package diya.model.automata.components; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; import diya.model.automata.events.TapeUpdatedEvent; import diya.model.language.Symbol; import diya.model.language.Word; public class Tape extends Component implements Iterable<Symbol>{ Stack<Symbol> successors; Stack<Symbol> predecessors; Symbol blank; public Tape(int x, int y){ super(x, y); successors = new Stack<Symbol>(); predecessors = new Stack<Symbol>(); blank = new Symbol(""); } public void setContent(Word word){ predecessors.clear(); successors.clear(); ArrayList<Symbol> symbols = word.getSymbols(); //Words must be added backwards onto the stack - current symbol is the top most. for(int i = symbols.size()-1; i >= 0; i--){ successors.push(symbols.get(i)); } } public void setBlank(Symbol blank){ this.blank = blank; } public Symbol readCurrentSymbol(){ if(successors.isEmpty()){ return null; } Symbol readSymbol = successors.peek(); if(readSymbol != null) { return readSymbol; } else{ return null; } } public void moveHeadRight(){ predecessors.push(successors.pop()); if(successors.isEmpty()){ successors.push(blank); } } public void moveHeadLeft(){ if(predecessors.isEmpty()){ predecessors.push(blank); } successors.push(predecessors.pop()); } public int getCurrentHeadPosition(){ return predecessors.size(); } public void writeSymbol(Symbol symbol){ successors.pop(); successors.push(symbol); } public void resetTape(){ while(predecessors.isEmpty() == false){ moveHeadLeft(); } } @Override public String toString(){ String content = ""; for(Symbol aSymbol : this){ if(content.equals("")){ content += aSymbol.toString(); } else{ content += " "+aSymbol.toString(); } } return content; } @Override public Iterator<Symbol> iterator() { return new TapeIterator(); } private final class TapeIterator implements Iterator<Symbol>{ private int cursor; private final int boundary; private final int end; public TapeIterator(){ this.cursor = 0; this.boundary = predecessors.size(); this.end = boundary+successors.size(); } @Override public boolean hasNext() { return this.cursor < end; } @Override public Symbol next() { if(!this.hasNext()){ throw new NoSuchElementException(); } Symbol symbol; if(cursor < boundary){ symbol = predecessors.get(cursor); } else{ symbol = successors.get((successors.size()-1)-(cursor-boundary)); } cursor++; return symbol; } @Override public void remove(){ throw new UnsupportedOperationException(); } } }
C
WINDOWS-1252
614
3.96875
4
[]
no_license
/* Write a function to change the account number from 11060 to 12050 From the array. 11060, 2003, 2106, 52003, 11060, 87645 */ #include <stdio.h> void change(int* acc , int size , int a , int b){ int i; for(i=0; i < size ; i++) if(acc[i] == a) { printf("1 "); acc[i] = b; } } int main(void){ int accNum[6] = {11060, 2003, 2106, 52003, 11060, 87645}; int i; printf("original array : "); for(i=0 ; i<6 ; i++) printf("%d ",accNum[i]); printf("\n"); change(accNum,6,11066,12050); printf("changed array : "); for(i=0 ; i<6 ; i++) printf("%d ",accNum[i]); printf("\n"); return 0; }
C
UTF-8
3,274
2.625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* str_char_handlers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vdelsie <vdelsie@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/13 17:43:38 by vdelsie #+# #+# */ /* Updated: 2019/12/14 17:39:34 by vdelsie ### ########.fr */ /* */ /* ************************************************************************** */ #include <libft.h> #include <ft_printf.h> #include <wchar.h> void handle_wchar(t_vfpf *p) { int pf; wint_t wc; pf = p->flags; wc = (wchar_t)va_arg(p->args, wint_t); if (pf & WIDTH_OB_FLAG && !(pf & DASH_FLAG)) pad_width(p, 1); pf_putwchar(p, wc); if (pf & WIDTH_OB_FLAG && (pf & DASH_FLAG)) pad_width(p, 1); } void handle_char(t_vfpf *p) { int pf; char c; pf = p->flags; if (pf & L_FLAG || p->specifier == 'C') handle_wchar(p); else { c = (char)va_arg(p->args, int); if (pf & WIDTH_OB_FLAG && !(pf & DASH_FLAG)) pad_width(p, 1); buff(p, &c, 1); if (pf & WIDTH_OB_FLAG && (pf & DASH_FLAG)) pad_width(p, 1); } } size_t calc_precision(wchar_t *str, int precision, size_t new_prec) { if (*str == '\0' || precision == 0) return (new_prec); else if (*str <= 0x007F) return (calc_precision(str + 1, precision - 1, new_prec + 1)); else if (*str <= 0x07FF && precision >= 2) return (calc_precision(str + 1, precision - 2, new_prec + 2)); else if (*str <= 0xFFFF && precision >= 3) return (calc_precision(str + 1, precision - 3, new_prec + 3)); else if (*str <= 0x10FFFF && precision >= 4) return (calc_precision(str + 1, precision - 4, new_prec + 4)); else return (new_prec); } void handle_wstr(t_vfpf *p) { int pf; wchar_t *wstr; int wslen; pf = p->flags; if ((wstr = va_arg(p->args, wchar_t *)) == NULL) wstr = L"(null)"; wslen = (int)pf_wstrlen(wstr); p->precision = (int)calc_precision(wstr, p->precision, 0); if (p->precision < 0) p->precision = wslen; p->precision = (p->precision > wslen) ? wslen : p->precision; wslen = (pf & PRECI_OB_FLAG) ? p->precision : wslen; if (pf & WIDTH_OB_FLAG && !(pf & DASH_FLAG)) pad_width(p, wslen); pf_putwstr(p, wstr, wslen); if (pf & WIDTH_OB_FLAG && (pf & DASH_FLAG)) pad_width(p, wslen); } void handle_str(t_vfpf *p) { int pf; char *str; int slen; pf = p->flags; if (pf & L_FLAG || p->specifier == 'S') handle_wstr(p); else { if ((str = va_arg(p->args, char *)) == NULL) str = "(null)"; slen = (int)ft_strlen(str); if (p->precision < 0) p->precision = slen; p->precision = (p->precision > slen) ? slen : p->precision; slen = (pf & PRECI_OB_FLAG) ? p->precision : slen; if (pf & WIDTH_OB_FLAG && !(pf & DASH_FLAG)) pad_width(p, slen); buff(p, str, slen); if (pf & WIDTH_OB_FLAG && (pf & DASH_FLAG)) pad_width(p, slen); } }
Markdown
UTF-8
14,890
2.8125
3
[]
no_license
# TLS Transport Layer Security. As well known as SSL (SSL is the old standard). ## Content <!-- toc --> - [Introduction](#introduction) * [TLS handshake](#tls-handshake) * [Pre master secret vs master secret](#pre-master-secret-vs-master-secret) * [Certificate Authorities](#certificate-authorities) * [SNI and domain fronting](#sni-and-domain-fronting) * [Certificates](#certificates) + [X.509](#x509) + [PKCS 12](#pkcs-12) + [Certificate bundle](#certificate-bundle) * [Mutual authentication](#mutual-authentication) - [Creating and signing certificates](#creating-and-signing-certificates) * [Commands](#commands) <!-- tocstop --> ## Introduction The goal of TLS is transport bytes securerly over internet or other networks. It's an hybrid cryptosytem, it uses both symmetric and asymmetric encrytption algorithms. Using different encrytptions schemas for different purposes. On a TLS handshake, client and server need to agree in which [algorithms to use (cipherSuite)](https://wiki.mozilla.org/Security/Server_Side_TLS). ``` 0xC0,0x2C - ECDHE-ECDSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(256) Mac=AEAD 0xC0,0x30 - ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD 0xCC,0xA9 - ECDHE-ECDSA-CHACHA20-POLY1305 TLSv1.2 Kx=ECDH Au=ECDSA Enc=ChaCha20(256) Mac=AEAD 0xCC,0xA8 - ECDHE-RSA-CHACHA20-POLY1305 TLSv1.2 Kx=ECDH Au=RSA Enc=ChaCha20(256) Mac=AEAD 0xC0,0x2B - ECDHE-ECDSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AESGCM(128) Mac=AEAD 0xC0,0x2F - ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(128) Mac=AEAD 0xC0,0x24 - ECDHE-ECDSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(256) Mac=SHA384 0xC0,0x28 - ECDHE-RSA-AES256-SHA384 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(256) Mac=SHA384 0xC0,0x23 - ECDHE-ECDSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256 0xC0,0x27 - ECDHE-RSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AES(128) Mac=SHA256 ``` This list is for moderns TLS servers (and secure). All the CipherSuites use [ECDHE](https://www.peerlyst.com/posts/a-technical-rant-about-the-different-e-s-in-ssl-tls) for exchange of key. The problem with using RSA, is that doesn't follow *forward secrecy* , this is the property that an attacker that recorded your encrypted communication and then later obtained your private key, they shouldn't be able to decrypt the previously recorded communication. However, RSA can be used for signing and authentication. If we choose ECDHE-RSA-AES128-SHA256. This means that the client and the server will use the TLS with Eliptic Curve Diffie-HellmanEphemeral (ECDHE). The authentication method will use RSA. This will be used in conjunction with AES symmetric encryption algorithm with a 128-bit key and a SHA-256 hashing algorithm to maintain data integrity during the transfer of information. Remember that key exchange can suffer from man in the middle, so you need a "signature", this can be achieve with RSA or DSA. ### TLS handshake The TLS Handshake Protocol involves the following steps: 1. The client sends a *Client hello* message to the server, along with the client's random value and supported cipher suites. 2. The server responds by sending a *Server hello* message to the client, along with the server's random value, TLS version and cipher suites selected. 3. The server sends its certificate to the client for authentication and may request a certificate from the client. The server sends the *Server hello done* message. 4. If the server has requested a certificate from the client, the client sends it. 5. The client creates a random Pre-Master Secret and encrypts it with the public key from the server's certificate, sending the encrypted Pre-Master Secret to the server. 6. The server receives the Pre-Master Secret. The server and client each generate the Master Secret and session keys based on the Pre-Master Secret. 7. The client sends *Change cipher spec* notification to server to indicate that the client will start using the new session keys for hashing and encrypting messages. Client also sends *Client finished* message. 8. Server receives *Change cipher spec* and switches its record layer security state to symmetric encryption using the session keys. Server sends *Server finished* message to the client. 9. Client and server can now exchange application data over the secured channel they have established. All messages sent from client to server and from server to client are encrypted using session key. Notice than in this case, in the step 5, we share the pre master secret using RSA (only using the public key of the server). In Diffie-Hellman, the client can't compute a premaster secret on its own; both sides contribute to computing it, so the client needs to get a Diffie-Hellman public key from the server. In ephemeral Diffie-Hellman, that public key isn't in the certificate (that's what ephemeral Diffie-Hellman means). So the server has to send the client its ephemeral DH public key in a separate message so that the client can compute the premaster secret (remember, both parties need to know the premaster secret, because that's how they derive the master secret). If we want to use DHE, we should replace some steps. 1. The server sends its *ServerKeyExchange* message, sending his DH Keys (generated) signed with is public key. This message is sent for all DHE and DH_anon ciphersuites. (Before step 3) 2. The server sends a *ServerHelloDone* message, indicating it is done with handshake negotiation. (like step 3) 3. The client responds with a ClientKeyExchange message, with a PreMasterSecret. This PreMasterSecret is encrypted using the public key of the server certificate. (Step 6). The DH-anon and ECDH-anon key agreement methods do not authenticate the server or the user and hence are rarely used because those are vulnerable to man-in-the-middle attack. Only DHE and ECDHE provide forward secrecy. Resuming a secure sesion on TLS: 1. The client sends a *Client hello* message using the Session ID of the session to be resumed. 2. The server checks its session cache for a matching Session ID. If a match is found, and the server is able to resume the session, it sends a *Server hello* message with the Session ID. 3. Client and server must exchange *Change cipher spec* messages and send *Client finished* and *Server finished* messages. 4. Client and server can now resume application data exchange over the secure channel. If a session ID match is not found, the server generates a new session ID and the TLS client and server perform a full handshake. ### Pre master secret vs master secret [The point of a premaster secret is to provide greater consistency between TLS cipher suites](https://crypto.stackexchange.com/questions/24780/what-is-the-purpose-of-pre-master-secret-in-ssl-tls). Once Server and Client has the *pre master secret*, they will derive the *master secret* from the random numbers exchanged in the steps 1 and 2, and the *pre master secret* ### Certificate Authorities As we saw in the step 3 of the handshake, the server sends its certificate to the client for authentication. But how do we know that the certificate is actually from the server and not from a man in the middle? Through Certificated Authorities (CA). TLS clients has a list of certifications of CA, from the OS and from the browser. For example to see the CA of the OS, we can check: ``` cat /etc/ssl/certs/ca-bundle.crt ``` This are trusted certificates. For a fee, this CA will sign other certificates as long as they can prove who they are. When a TLS client connects to a server, that server provides a certificate chain. Typically, their own certificate is signed by an intermediary CA certificate, which is signed by another, and another, and one that is signed by a trusted root certificate authority. Since the client already has a copy of that root certificate, they can verify the *signature chain* starting with the root. You can generate your own CA. Depending of the protocol may be rejected. - HTTPS -> Some browsers won't allow visit the webpage. - OpenVPN -> We can create our own CA, for example [when we set the router to suppport OpenVPN](https://www.forshee.me/2016/03/16/ubiquiti-edgerouter-lite-setup-part-5-openvpn-setup.html). ### SNI and domain fronting [Server Name Indication](https://en.wikipedia.org/wiki/Server_Name_Indication) is an extension of TLS, on which the client can indicate the hostname he is trying to connect at the start of the handshaking TLS. The reason to include the hostname is when we want one IP to provide different certificates. In order to know which certificate need to be selected for the handshake we use the host provided in the SNI. Because is at the start of the Handshake this information won't be encrypted. This provide one advantage (one IP can host different services), but in the other hand some countries have been use this for [censoring] (https://signal.org/blog/looking-back-on-the-front/) One way to avoid censoring this some companies like [Signal](https://signal.org/blog/looking-back-on-the-front/) have been using [domain fronting](https://www.bamsoftware.com/papers/fronting/). Some server provides have the peculiarity that if you provide as a SNI hostname a webpage from their domain, thy will end up redirecting to the actual server described in the HTTP data. (After decrypt). So lets say that if you are usig GCP service, you can set your SNI hostname as ```google.com```, and the encrypt HTTP will have the info to which host to redirect. Unfortunately this is considered a breach in the Terms and Conditions of GCP and AWS, and asked Signal to cease using it. ### Certificates #### X.509 [X.509](https://en.wikipedia.org/wiki/X.509) is the most common format for certificates. Is used in HTTPS. [RFC](https://tools.ietf.org/html/rfc5280) Common extensions of this cert are: - CRT -> use for certificates, it may be DER or PEM - CER -> Microsoft version of CRT - KEY -> Used for both public and private PKCS#8 keys. Common ways of encondig the cert (also use as extensions): - PEM -> Is an armored base64 of the binary cert. (the one that starts with -----BEGIN CERTIFICATE----) - DER -> Is the cert in binary. To verify the content of a cerfiticate: ``` openssl x509 -text -inform PEM -in client-auth-ca/staging/root/certs/ca.cert.pem openssl x509 -text -inform DER -in client-auth-ca/staging/root/certs/ca.cert.pem ``` For `openssl x509` PEM is the default, so no need to inform the `-inform PEM` Some common fields of this certicate are: - Issuer. Is the issuer (for example GoDadaddy). - O (Organization) - OU (Organization unit) - L, ST, C (locality, state, country) - Validity - Not Before - Not After - Subject: - CN (Common Name) - Subject Public Key Info -> carry the public key and identify the algorith. - Signature Algorithm -> contains the algorithm identifier for the algorithm used by the CA to sign the certificate. - X509v3 extensions. - X509v3 Authority key Identifier -> Identifier of who signed this cert - X509v3 Subject Key Identifier -> Identifier of this cert #### PKCS 12 A format to store several chrptography objects in a single file. Is commonly use to bundle private key + X.509 certificate. As well can be used to bundle a chain of trust. To verify the content of a pkcs12 file: ``` openssl pkcs12 -in file.pkcs12 ``` #### Certificate bundle This is just some certs written in the same file one after another.It identify the certificate chain, from your cert, to the root certificate. Example: ``` ---BEGIN CERTIFICATE---- base64 code leaf cert ---END CERTIFICATE---- ---BEGIN CERTIFICATE---- base64 code intermediate cert ---END CERTIFICATE---- ---BEGIN CERTIFICATE---- base64 code root cert ---END CERTIFICATE---- ``` Two ways to verify which one is the root cert: - Verify that the Issuer and Subject has the same information. - Verify that the `X509v3 Authority key Identifier` and `X509v3 Subject Key Identifier` has the same identifier. To verify which one is the leaf cert: - Verify which one has the CN of your webpage. To verify the order is correct: - You can check `X509v3 Authority key Identifier` and `X509v3 Subject Key Identifier`. Each intermediate has the `Authority key` set as the previous `Subject key`. ### Mutual authentication Very nice article about TLS handshake and mutual authentication [mutual authentication](https://medium.com/sitewards/the-magic-of-tls-x509-and-mutual-authentication-explained-b2162dec4401) The idea is the server wants to make sure that the Client is who is he claiming to be. So the client will have its own certificate. There will be some new steps in the TLS handshake so the client can send its certificate. ![mutual authenitcation image](https://miro.medium.com/max/952/1*P1ujapQhTYNgd2hWl_8Njg.png) ## Creating and signing certificates When you have a key and you want the CA to sign, you need to create a CSR (Certificate Signing Request). Then you will need to send this CSR to the CA, and ask for the signature. Every time a CA signs a key, it needs to add a `serial`, this serial is unique by CA + Cert, and if they are not unique it may missbehave. The first time you sign a cert with a CA, you need to add `-CAcreateserial`, this will create a file with the seria. The next time you sign a cert, you will have to inform `-CAserial file_name`, adding the file with the seria. ### Commands **Generate CA key and cert** Generate private key for CA: ``` openssl genrsa -out ca.key 2048 # output ca.key ``` Generate a Certificate Signing Requests: ``` openssl req -new -key ca.key -subj "/CN=jesus-ca" -out ca.csr # output ca.csr ``` Sign the CA certificate (Self sign with the CA): ``` openssl x509 -req -days 3650 -in ca.csr -signkey ca.key -out ca.crt # output ca.crt ``` **Generate server key and cert** Generate private key for Server: ``` openssl genrsa -out jesus.key 2048 # output jesus.key ``` Generate a Certificate Signing Requests: ``` openssl req -new -key jesus.key -subj "/CN=www.jesus-webpage.com" -out jesus.csr # output jesus.csr ``` Sign the certificate with the CA (first time signing with this CA) ``` openssl x509 -req -days 365 -in jesus.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out jesus.crt # output jesus.crt # output ca.srl --> This has the counter for the serials, you will need next time you sign with the same CA ``` Sign the certificate with the CA (not first time signing with this CA) ``` openssl genrsa -out sharon.key 2048 openssl req -new -key sharon.key -subj "/CN=www.sharon-webpage.com" -out sharon.csr openssl x509 -req -days 365 -in sharon.csr -CA ca.crt -CAkey ca.key -CAserial ca.srl -out sharon.crt # output sharon.key # output sharon.csr # output sharon.crt ```
Java
UTF-8
614
4
4
[]
no_license
// 문자를 입력받고 단 수 만큼 출력하기 package java_example; import java.util.Scanner; public class Exam7_7 { static void putChar(int n,char x) { for (int i = 0; i < n; i++) { System.out.print(x); } } static void putStart(int n, char x) { putChar(n,x); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("어떤 문자를 출력할까요? : "); char x = sc.next().charAt(0); System.out.print("몇 단 ? "); int n = sc.nextInt(); for (int i = 1; i <= n; i++) { putStart(i,x); System.out.println(); } } }
Python
UTF-8
703
3.140625
3
[]
no_license
class lipstick: brands=3 def __init__(self,col1,col2,col3,col4): self.col1=col2 self.col2=col2 self.col3=col3 self.col4=col4 @staticmethod def longlipstick(): print("lipstick lenght is more") def avg(self): print((self.col1+self.col2+self.col3+self.col4)/4) @classmethod def chinnu(cls): print(cls.brands) def get_col3(self): return(self.col3) def set_col3(self,value): self.col3=value lip1= lipstick(23,56,45,67) lip2 = lipstick(45,23,98,50) print(lipstick.brands) print(lipstick.chinnu()) lip2.longlipstick() print(lipstick.get_col3())
JavaScript
UTF-8
1,243
3.484375
3
[]
no_license
var numbers=[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]; var container=document.getElementById("container"); var cards; var inner; var r; for(var i=0; i<16; i++){ r=Math.floor(Math.random()*numbers.length); cards=document.createElement("div"); inner=document.createElement("div"); cards.className="cards"; inner.className="inner"; inner.className+=" hidden"; container.appendChild(cards); cards.appendChild(inner); inner.innerHTML= numbers[r]; numbers.splice(r,1); } var count=1; var check; var previous; var checkInner=document.getElementsByClassName("cards"); //console.log(checkInner); function reveal(){ for(var i = 0; i<checkInner.length; i++){ checkInner[i].onclick=function(){ check=this.firstChild.innerHTML; console.log(check); if(count==1){ //console.log(this.childNodes.classList); this.firstChild.classList.toggle("hidden"); previous=check; count++; } else{ count=1; if(check == previous){ alert("ok"); } else { alert("ko"); } } } } } reveal();
C
UTF-8
590
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> int no_subset_sum_ge(int set[],int set_size,int value) { int count=0,x,sum,k; for(x=0;x<(pow(2,set_size));x++) { sum=0; for(k=0;k<set_size;k++) { if(x&(1<<k)) { sum=sum+set[k]; } } if(sum>=value) { count++; } } return count; } int main() { int set[5]={3,5,2},n; int set_size=3; int value=4; n=no_subset_sum_ge(set,set_size,value); printf("%d",n); return 0; }
JavaScript
UTF-8
1,763
3.53125
4
[]
no_license
/** Variables **/ const form = document.querySelector('form'); const tabla = document.querySelector('table'); const btnEnviar = document.querySelector('#btnEnviar'); /** Objetos **/ class Interfaz { }; /** Event's Listeners's **/ // Cuando envía el formulario... btnEnviar.addEventListener('click', function (event){ event.preventDefault(); /* Variables */ let coordX = document.querySelector('#coordX').value; let coordY = document.querySelector('#coordY').value; // Minuscula a Mayuscula coordY = coordY.toUpperCase(); console.log(coordX); if(valInput(coordY, coordX)){ /* Enviar por consola las coordenadas */ console.log(coordX, coordY); /* Acceder al elemento enviado */ let casilla = document.getElementById(`${coordY}`); // Mueve hasta coordX veces... for (var i = 0; i < coordX; i++) { casilla = casilla.nextElementSibling; } pushPoint(casilla); } else { console.log('entrada ivalida'); } }); // Cuando da click a una de las casillas tabla.addEventListener('click', function(evt){ if(evt.target.nodeName === 'TD' && evt.target.id === ''){ pushPoint(evt.target); } }); /** Funciones **/ // Coloca los puntos en las casillas... function pushPoint (casilla) { let points = casilla.getAttribute('points'); if(points < 2) { points++; casilla.innerHTML += ` <i class="tiny material-icons">lens</i> `; } else { points = 0; casilla.innerHTML = null; } casilla.setAttribute('points', points); } function valInput (letra, numero) { let boolNum = false, boolLet = false; if(numero != '') if(numero > 0 || numero <= 5) boolNum = true; if(letra === 'A' || letra === 'B' || letra === 'C' || letra === 'D' || letra === 'E') boolLet = true; return boolNum && boolLet; }
Markdown
UTF-8
5,651
2.875
3
[]
no_license
# Windows Forensics ## Partie 1: RDP Cache Voici une machine virtuelle Windows. Plusieurs flags ont été manipulés dans cette machine, mais ils ont tous été supprimés. Pourtant, des traces des flags restent sur ces machines. Dans les quatre prochains exercices, vous serez introduit au monde complexe du *Windows Forensics* et découvrirez divers artifacts utilisés par Windows qui permettent de tirer de l'information sur des actions passées. Tous les outils nécessaires à la récupération des flags sont inclus dans la machine virtuelle, sur le bureau. Défi: **L'utilisateur de la machine s'est connecté en RDP vers une machine externe et a consulté un flag. Récupérez ce flag.** **Nom d'utilisateur: user** **Mot de passe: toor** [Lien vers le OVA](https://drive.google.com/file/d/1bCkf312TXr7DgTvZLq9C-tMEtRDBIPFm/view?usp=sharing). Note 2: Cette track de défis est inspirée de la playlist [Introduction to Windows Forensics par 13Cubed sur Youtube](https://www.youtube.com/playlist?list=PLlv3b9B16ZadqDQH0lTRO4kqn2P1g9Mve). La playlist comprend plein d'autres éléments de forensics Windows si vous voulez approfondir vos connaissances. Note 3: Puisqu'il s'agit d'une machine Windows d'essai, la machine virtuelle va s'éteindre chaque heure, automatiquement. Rien n'est perdu, c'est simplement désagréable. Avant de commencer les défis, il serait préférable de créer une "snapshot" de la machine virtuelle pour y revenir au besoin. ## Partie 2: Shellbags Le même utilisateur a supprimé un répertoire qui contenait un flag. Quel était le nom de ce répertoire? ## Partie 3: LNK Files Dans le répertoire supprimé dans la partie 2, il y avait un fichier. Trouvez le nom de ce fichier. # Partie 4: NTFS Journal Trouvez la date de suppression du fichier trouvé dans l’exercice précédent. Flag format: `FLAG-YYYY-MM-DD_HH:mm:ss` Exemple: `FLAG-2021-20-08_20:37:06` Note: Les artifacts nécessaires à la résolution du défi ont déjà été extraits dans la machine virtuelle. ## Solution ### Part 1 Le défi s'appelle "Windows Forensics - RDP Cache". En cherchant précisément ça, ou en visionnant le vidéo de 13Cubed sur le RDP Cache (de la playlist mentionnée dans la description), on comprend que des bouts d'images de sessions RDP sont persistées sur le disque après avoir terminé la session RDP. C'est situé dans `C:\users\<user qui a fait la connexion RDP>\appdata\local\Microsoft\Terminal Server Client\Cache`. L'outil "bmc-tools" permet de transformer ce cache en images qu'on peut visionner facilement. C'est disponible sur le bureau. C'est un script python. 1. Ouvrir cmd ou powershell et se déplacer dans le bon répertoire: `cd C:\Users\user\Desktop\bmc-tools-master\bmc-tools-master` 2. `python .\bmc-tools.py --help` pour voir comment utiliser l'outil. 3. Exécuter la commande pour extraire le RDP cache: `python .\bmc-tools.py -d . -s "C:\users\user\appdata\local\Microsoft\Terminal Server Client\Cache"` 4. Les images ont été écrites dans le répertoire courant. Clic droit dans le répertoire --> view --> large icons pour voir les aperçus. 5. En se promenant dans les images, on peut apercevoir des bouts de flags. Avec un peu de patience, on peut recréer le flag: `FLAG-06c078dd3ebf7801575feaa109f73ddc` ### Part 2 Semblable à la partie 1, en googlant "Windows Forensics Shellbags", on trouve de l'information. On remarque qu'on peut utiliser l'outil "ShellBags Explorer" pour trouver notre flag. Les Shellbags sont des informations sur les répertoires accédés par un utilisateur avec l'explorateur Windows, qui contient quelques métadonnées intéressantes sur les répertoires. Même après la suppression d'un répertoire, les shellbags persistent. 1. Ouvrir `C:\Users\user\Desktop\ShellBagsExplorer\ShellBagsExplorer.exe` 2. File --> Load Active Registry 3. Fouiller un peu les entrées. Il y a une entrée appelée "monflag" qui contient un répertoire "deeper" qui contient le flag: `flag-folderContenantFlag2`. ### Part 3 Les LNK files sont créés lorsqu'on ouvre un fichier ou programme dans Windows. Ils contiennent des métadonnées intéressantes comme le nom du fichier, le dernier temps d'exécution, la taille du fichier et d'autres. Même après la suppression d'un fichier, sa référence .LNK persiste. Un peu de googling nous apprend que les .LNK se situent dans %appdata\Microsoft\Windows\Recent. 1. Ouvrir un cmd. 2. On lance la commande: `C:\Users\user\Desktop\LECmd\LECmd.exe -d "C:\users\user\appdata\roaming\Microsoft\Windows\Recent" --csv .` 3. Ouvrir le fichier .csv avec un éditeur texte. On fouille un peu, et on trouve le flag: `flag-leDeuxiemeFlag.txt` ### Part 4 Le système de fichier NTFS garde un journal des opérations faites afin d'assurer l'intégrité des données. Les trois fichiers utiles, $MFT, $J et $LogFile, peuvent être extraits du système avec FTK Imager. Pour *parse* ces données, on peut utiliser ANJP pour trouver le flag. Pour ce défi, nous cherchons à lire le USNJournal, qui traque les changements faits aux fichiers et répertoires. 1. (déjà fait) Utiliser FTK Imager pour extraire $MFT, $J et $LogFile. 2. Lancer ANJP, mettre les trois fichiers dans leur case respective et faire "Parse". C'est un long processus (30mins-1h) 3. Aller dans reports -> usn -> usn events -> transaction events -> Deletions 4. Filter -> Column = USN Rcd File Name, Condition = LIKE, Value = %flag% --> Add --> Filter 4. On regarde l'entrée qui concerne flag-leDeuxiemeFlag.txt (et non pas le .txt.lnk), on voit dans la colonne USN Rcd Time: 2019-11-17 01:18:36 `FLAG-2019-11-17_01:18:36`
Java
UTF-8
2,153
2.484375
2
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
/** * ============LICENSE_START==================================================== * org.onap.aaf * =========================================================================== * Copyright (c) 2018 AT&T Intellectual Property. 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. * ============LICENSE_END==================================================== * */ package org.onap.aaf.auth.dao.cass; /** * Defines the Type Codes in the NS Table. * @author Jonathan * */ public enum NsType { UNKNOWN (-1), DOT (0), ROOT (1), COMPANY (2), APP (3), STACKED_APP (10), STACK (11); public final int type; private NsType(int t) { type = t; } /** * This is not the Ordinal, but the Type that is stored in NS Tables * * @param t * @return */ public static NsType fromType(int t) { for (NsType nst : values()) { if (t==nst.type) { return nst; } } return UNKNOWN; } /** * Use this one rather than "valueOf" to avoid Exception * @param s * @return */ public static NsType fromString(String s) { if (s!=null) { for (NsType nst : values()) { if (nst.name().equals(s)) { return nst; } } } return UNKNOWN; } }
Rust
UTF-8
1,274
3.109375
3
[ "MIT", "Apache-2.0" ]
permissive
//! A simple demonstration how iron's helper macros make e.g. IO-intensive code easier to write. #[macro_use] extern crate iron; use std::fs; use std::io; use std::io::Cursor; use iron::prelude::*; use iron::Method; use iron::StatusCode; fn main() { Iron::new(|req: &mut Request| { Ok(match req.method { Method::GET => { // It's not a server error if the file doesn't exist yet. Therefore we use // `iexpect`, to return Ok(...) instead of Err(...) if the file doesn't exist. let f = iexpect!(fs::File::open("foo.txt").ok(), (StatusCode::OK, "")); Response::with((StatusCode::OK, f)) } Method::PUT => { // If creating the file fails, something is messed up on our side. We probably want // to log the error, so we use `itry` instead of `iexpect`. let mut f = itry!(fs::File::create("foo.txt")); itry!(io::copy( &mut Cursor::new(itry!(req.get_body_contents())), &mut f )); Response::with(StatusCode::CREATED) } _ => Response::with(StatusCode::BAD_REQUEST), }) }).http("localhost:3000"); }
Java
UTF-8
3,073
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package eu.geoknow.generator.publish; import java.util.HashMap; import com.hp.hpl.jena.rdf.model.Model; import eu.geoknow.generator.exceptions.InformationMissingException; import eu.geoknow.generator.utils.Utils; /** * Class for holding all required information to do a data publishing. * * @author mvoigt * */ public class PublishingConfiguration { private String endpointUri; private HashMap<String, Boolean> inputGraphs; private String targetGraphUri; private boolean backupExistingData; private Model metaData; private String user; /** * Constructor to create a config with initial data. * * @param ep SPARQL endpoint * @param in map with the input graphs and a flag if the service should try to drop them * afterwards * @param target target named graph * @param backup should the existing data be backed and versioned * @param meta a Jena model with triples of meta data to add to the graph * @param user the logged in framework user, not the RDF store user * @throws InformationMissingException */ public PublishingConfiguration(String ep, HashMap<String, Boolean> in, String target, boolean backup, Model meta, String user) throws InformationMissingException { if (!Utils.isNullOrEmpty(ep)) { this.endpointUri = ep; } else { throw new InformationMissingException("No endpoint given"); } if (in != null) { this.inputGraphs = in; } else { throw new InformationMissingException("No input graphs given"); } if (!Utils.isNullOrEmpty(target)) { this.targetGraphUri = target; } else { throw new InformationMissingException("No target graph given"); } this.backupExistingData = backup; if (meta != null) { this.metaData = meta; } else { throw new InformationMissingException( "Metadata model is NULL. If no metadata available, pass an empty model"); } if (!Utils.isNullOrEmpty(user)) { this.user = user; } else { throw new InformationMissingException("No framework user given"); } } public String getEndpointUri() { return endpointUri; } public void setEndpointUri(String endpointUri) { this.endpointUri = endpointUri; } public HashMap<String, Boolean> getInputGraphs() { return inputGraphs; } public void addInputGraphs(HashMap<String, Boolean> inputGraphs) { this.inputGraphs.putAll(inputGraphs); } public String getTargetGraphUri() { return targetGraphUri; } public void setTargetGraphUri(String targetGraphUri) { this.targetGraphUri = targetGraphUri; } public boolean backupExistingData() { return backupExistingData; } public void setBackupExistingData(boolean backupExistingData) { this.backupExistingData = backupExistingData; } public Model getMetaData() { return metaData; } public void setMetaData(Model metaData) { this.metaData = metaData; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } }
C
UTF-8
549
2.640625
3
[]
no_license
// // List.h // DataStructure // // Created by Daniel on 15/9/23. // Copyright (c) 2015年 Daniel. All rights reserved. // #ifndef __DataStructure__List__ #define __DataStructure__List__ #include <stdio.h> struct node { struct node *pre; struct node *next; int key; }; struct node * list_search(struct node *head,int k); struct node * list_insert(struct node *head,struct node *x); struct node * list_delete(struct node *head,struct node *x); void list_print(struct node *head); #endif /* defined(__DataStructure__List__) */
SQL
UTF-8
2,121
3.578125
4
[]
no_license
SELECT PROG.ID, PROG.NAME, PROG.DESCRIPTION, PROG_PROF.ID, PROG_PROF.EFFECTIVE, PROG_PROF.EXPIRATION, PROG_PROF.DISPLAY_ORDER,PROG_PROF.DEFAULT_OPT_IN, PROG_PROF.VISIBLE_IN_UI, PROG_PROF.CHAN_EMAIL,PROG_PROF.CHAN_IVR, PROG_PROF.CHAN_SMS, PROG_PROF.CHAN_SECURE, PROG_CONF.ID, PROG_CONF.EFFECTIVE, PROG_CONF.EXPIRATION, PROG_CONF.CHAN_EMAIL_PRIORITY, PROG_CONF.CHAN_IVR_PRIORITY, PROG_CONF.CHAN_SMS_PRIORITY, PROG_CONF.CHAN_SECURE_PRIORITY, PROG_CONF.CHAN_DEFAULT, PROG_CONF.REQUIRED, PROG_CONF.MANDATORY, PROG_PROF_CLT.ID, PROG_PROF_CLT.EFFECTIVE, PROG_PROF_CLT.EXPIRATION, PROG_PROF_CLT.DISPLAY_ORDER, PROG_PROF_CLT.DEFAULT_OPT_IN, PROG_PROF_CLT.VISIBLE_IN_UI, PROG_PROF_CLT.CHAN_EMAIL, PROG_PROF_CLT.CHAN_IVR, PROG_PROF_CLT.CHAN_SMS, PROG_PROF_CLT.CHAN_SECURE, CLT_CONF.ID, CLT_CONF.EFFECTIVE, CLT_CONF.EXPIRATION, CLT_CONF.CHAN_EMAIL_PRIORITY, CLT_CONF.CHAN_IVR_PRIORITY, CLT_CONF.CHAN_SMS_PRIORITY, CLT_CONF.CHAN_SECURE_PRIORITY, CLT_CONF.CHAN_CLIENT_SECURE_PRIORITY, CLT_CONF.CHAN_DEFAULT, CLT_CONF.REQUIRED, CLT_CONF.MANDATORY FROM PROGRAM AS PROG JOIN PROGRAM_PROFILE AS PROG_PROF ON PROG.ID = PROG_PROF.PROGRAM_ID JOIN PROGRAM_CONFIGURATION AS PROG_CONF ON PROG.ID = PROG_CONF.PROGRAM_ID AND PROG_CONF.COMMUNICATION_ID = :COMM_ID LEFT OUTER JOIN PROGRAM_PROFILE_CLIENT_EXCEPTION AS PROG_PROF_CLT ON PROG.ID = PROG_PROF_CLT.PROGRAM_ID AND PROG_PROF_CLT.CLIENT_ID = :CLIENT_ID LEFT OUTER JOIN CLIENT_CONFIGURATION AS CLT_CONF ON PROG_CONF.COMMUNICATION_ID = CLT_CONF.COMMUNICATION_ID AND CLT_CONF.CLIENT_ID = :CLIENT_ID WHERE (PROG_PROF.EFFECTIVE <= CURRENT_TIMESTAMP AND PROG_PROF.EXPIRATION > CURRENT_TIMESTAMP) AND (PROG_CONF.EFFECTIVE <= CURRENT_TIMESTAMP AND PROG_CONF.EXPIRATION > CURRENT_TIMESTAMP) AND (PROG_PROF_CLT.ID IS NULL OR (PROG_PROF_CLT.EFFECTIVE <= CURRENT_TIMESTAMP AND PROG_PROF_CLT.EXPIRATION > CURRENT_TIMESTAMP)) AND (CLT_CONF.ID IS NULL OR (CLT_CONF.EFFECTIVE <= CURRENT_TIMESTAMP AND CLT_CONF.EXPIRATION > CURRENT_TIMESTAMP));
PHP
UTF-8
1,556
2.515625
3
[]
no_license
<?php /** * @author Tim Rupp * @see http://www.enrise.com/2011/01/rest-style-context-switching-part-2/ */ class ErrorController extends Zend_Controller_Action { const IDENT = __CLASS__; public function init() { $this->_helper->viewRenderer->setNoRender(); } public function errorAction() { try { $log = App_Log::getInstance(self::IDENT); } catch (App_Exception $error) { $this->view->status = 'error'; $this->view->message = $error->getMessage(); return; } $errors = $this->_getParam('error_handler'); $exception = $errors->exception; $log->err($exception->getMessage()); $this->view->status = 'error'; $this->view->message = $exception->getMessage(); } public function expiredXmlHttpAction() { $this->view->assign(array( 'status' => 'expired', 'message' => 'The token you provided has expired' )); } public function noAccountAction() { $this->view->assign(array( 'status' => 'denied', 'message' => 'No account could be mapped to the token' )); } public function permissionDeniedAction() { $this->view->assign(array( 'status' => 'denied', 'message' => 'You do not have permission to access this resource' )); } public function permissionDeniedMethodAction() { $this->view->assign(array( 'status' => 'denied', 'message' => 'You do not have permission to call this method' )); } public function noTokenAction() { $this->view->assign(array( 'status' => 'denied', 'message' => 'You must provide an authentication token to access this resource' )); } } ?>
C#
UTF-8
2,015
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.Threading.Tasks; using Verbarium.DAL.Interfaces; namespace Verbarium.DAL.Realisations { public class GenericRepository<T> : IGenericRepository<T> where T : class, IEntity { protected readonly DbContext _context; private IDbSet<T> _entities; public GenericRepository(DbContext context) { _context = context; } public IDbSet<T> Entities => _entities ?? (_entities = _context.Set<T>()); public async Task<IEnumerable<T>> GetAllAsync() { return await Entities.ToListAsync(); } public IEnumerable<T> GetAll() { return Entities.ToList(); } public Task<T> GetByIdAsync(int id) { return Entities.SingleOrDefaultAsync(i => i.Id == id); } public virtual T Create(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } return Entities.Add(item); } public void Update(T item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } Entities.AddOrUpdate(item); } public void Delete(int id) { var entity = GetByIdAsync(id); if (entity == null) { throw new ArgumentNullException(nameof(id)); } Entities.Remove(entity.Result); } public async Task DeleteAsync(int id) { var entity = await GetByIdAsync(id); if (entity == null) { throw new ArgumentNullException(nameof(id)); } Entities.Remove(entity); } public IQueryable<T> Query => Entities; } }
Java
UTF-8
3,753
2.140625
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * ============LICENSE_START======================================================= * ONAP : ccsdk features * ================================================================================ * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. * 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. * ============LICENSE_END========================================================= * */ package org.onap.ccsdk.features.sdnr.wt.common.database.data; import java.util.Arrays; import java.util.List; import org.onap.ccsdk.features.sdnr.wt.common.database.queries.RangeQueryBuilder; public class DbFilter { private static final List<String> timestampValueNames = Arrays.asList("timestamp", "start", "end", "date"); public static String createDatabaseRegex(String restFilterValue) { return restFilterValue == null ? null : restFilterValue.replace("?", ".{1,1}").replace("*", ".*"); } public static boolean hasSearchParams(String restFilterValue) { return restFilterValue == null ? false : restFilterValue.contains("*") || restFilterValue.contains("?"); } public static boolean hasSearchParams(List<String> restFilterValues) { for (String restFilterValue : restFilterValues) { if (!hasSearchParams(restFilterValue)) { return false; } } return true; } public static boolean isComparisonValid(String restFilterValue) { return restFilterValue == null ? false : restFilterValue.contains(">") || restFilterValue.contains("<"); } public static boolean isComparisonValid(List<String> restFilterValues) { for (String restFilterValue : restFilterValues) { if (!isComparisonValid(restFilterValue)) { return false; } } return true; } public static boolean isDatetimeKeyValue(String key, String value) { return timestampValueNames.contains(key.toLowerCase()); } public static RangeQueryBuilder getRangeQuery(String key, String restFilterValue) { RangeQueryBuilder query = new RangeQueryBuilder(key); restFilterValue = restFilterValue.trim(); if (restFilterValue.startsWith(">=")) { query.gte(getObjectFromString(key,restFilterValue.substring(2).trim())); } else if (restFilterValue.startsWith(">")) { query.gt(getObjectFromString(key,restFilterValue.substring(1).trim())); } else if (restFilterValue.startsWith("<=")) { query.lte(getObjectFromString(key,restFilterValue.substring(2).trim())); } else if (restFilterValue.startsWith("<")) { query.lt(getObjectFromString(key,restFilterValue.substring(1).trim())); } else { return null; } return query; } private static Object getObjectFromString(String key, String str) { if(isDatetimeKeyValue(key, str)) { return str; } try { return Double.parseDouble(str); } catch (NumberFormatException | NullPointerException nfe) { return str; } } }
C#
UTF-8
5,923
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using OXML.DL; using OXML.Library; namespace OXML.UI { public partial class MainForm : Form { private readonly string PPT_Location = @"E:\003_P\openxml_tutorial\Test_PowerPoinT.pptx"; //private readonly string Excel_Location = @"E:\003_P\openxml_tutorial\Test_Excel.xlsx"; private readonly string Word_Location = @"E:\003_P\openxml_tutorial\Test_Word.docx"; public MainForm() { InitializeComponent(); } private void Btn_GetSlidesNumber_Click(object sender, EventArgs e) { Helper_PPT helper_PPT = new Helper_PPT(); AppendTo_ExcelLog(helper_PPT.PPTGetSlideCount(PPT_Location).ToString()); AppendTo_ExcelLog(helper_PPT.PPTGetSlideCount(PPT_Location, false).ToString()); } private void Btn_GetExcelSheetsNames_Click(object sender, EventArgs e) { string excelLocation = tbo_CurrentExcelFile.Text; AppendTo_ExcelLog(Helper_Excel.GetAllExcelSheetsName(excelLocation)); } private void Btn_GetWordCreationDateTime_Click(object sender, EventArgs e) { DateTime? created = Helper_Word.WDGetCreationDate(Word_Location); AppendTo_ExcelLog(created.ToString()); } private void Btn_GetExcelCellValue_Click(object sender, EventArgs e) { string excelLocation = tbo_CurrentExcelFile.Text; AppendTo_ExcelLog(Helper_Excel.XLGetCellValue(excelLocation, "Sheet1", "A1")); AppendTo_ExcelLog(Helper_Excel.XLGetCellValue(excelLocation, "Sheet1", "C4")); } private void Btn_WriteInExcelCell_Click(object sender, EventArgs e) { if(string.IsNullOrWhiteSpace(tbo_CurrentExcelFile.Text) == false) { string excelLocation = tbo_CurrentExcelFile.Text; AppendTo_ExcelLog(Helper_Excel.XLInsertTextIntoCell(excelLocation, "Sheet1", "A1", "Hello There")); AppendTo_ExcelLog(Helper_Excel.XLInsertNumberIntoCell(excelLocation, "Sheet1", "C4", 420)); } else { Tbo_ExcelLog.Text += "Pick an Excel File!"; } } private void Btn_InsertTableInWorldDocument_Click(object sender, EventArgs e) { string[,] data = { { "Row 1, Col 1", "Row 1, Col 2" }, { "Row 2, Col 1", "Row 2, Col 2" }, { "Row 3, Col 1", "Row 3, Col 2" }, }; Helper_Word.WDAddTable(Word_Location, data); } private void Btn_RetrievePlainText_Click(object sender, EventArgs e) { Tbo_ExcelLog.Text += Helper_Word.WDRetrieveText(Word_Location) + Environment.NewLine; } private void Btn_CreateEmptyExcelFile_Click(object sender, EventArgs e) { using(FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) { //navigate to a folder. If the user input is "OK" ..Continue operation if(folderBrowserDialog.ShowDialog() == DialogResult.OK) { string ExcelName_01 = "ExcelExemple_01.xlsx"; string ExcelName_02 = "ExcelExemple_02.xlsx"; string folderPath = folderBrowserDialog.SelectedPath; Helper_Excel.XLCreateEmptyFile(ExcelName_01, folderPath); Helper_Excel.XLCreateEmptyFile_version2(ExcelName_02, folderPath); //keep the location of one of the Excel files for future testing tbo_CurrentExcelFile.Text = folderPath + ExcelName_01; } } } private void Btn_AddExcelSheets_Click(object sender, EventArgs e) { string excelLocation = tbo_CurrentExcelFile.Text; for (int i = 0; i < 3; i++) { Helper_Excel.InsertWorksheet(excelLocation); } } private void AppendTo_ExcelLog(object message) { string final = $"{Environment.NewLine} {message}"; Tbo_ExcelLog.AppendText(final); } private void Btn_CreateExcelFileTableFormattedCells_Click(object sender, EventArgs e) { #region Creating some objects to write in Excel List<Employee> employees_List = new List<Employee>(); Employee employee1 = new Employee() { FirstName = "Arakida", LastName = "Moritake", Age = 30, HireDate = DateTime.Now }; Employee employee2 = new Employee() { FirstName = "Petrescu", LastName = "Camil", Age = 30, HireDate = DateTime.Now.AddDays(-100D) }; employees_List.Add(employee1); employees_List.Add(employee2); #endregion #region Create path of in User\MyDocuments\OXMLTesting string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string foldername = "OXMLTesting"; string fullPath = System.IO.Path.Combine(path, foldername); #endregion #region Create the Excel File with the objects Helper_Excel helper_Excel = new Helper_Excel(); helper_Excel.CreateExcelFile(employees_List, fullPath); AppendTo_ExcelLog($"Excel Created in {fullPath}"); #endregion } } } /*Testing Repository Namespace transfer. --==Ignore this==-- speaking of migration.. here is a penguin family (o_ (o_ (o_ //\ (/)_ (/)_ V_/_ */
Python
UTF-8
166
3.5625
4
[]
no_license
n = int(input()) sum1 = 0 sum2 = 0 for i in range(1,n+1): if (i%2 == 0): sum1 += i else: sum2 += i func = sum1 - sum2 print(func)
PHP
UTF-8
7,622
2.859375
3
[]
no_license
<?php require_once "utils/functions.php"; if( isLogged() && isNew($_SESSION['uid']) ) { if(isset($_POST['submit'])) { $q1 = $_POST['q1']; $q2 = $_POST['q2']; $q3 = $_POST['q3']; $q4 = $_POST['q4']; $q5 = $_POST['q5']; if( !isset($q1) || !isset($q2) || !isset($q3) || !isset($q4) || !isset($q5) ) { header('Location: quiz.php?error'); exit(); } $q1 = cleanPOST($_POST['q1']); $q2 = cleanPOST($_POST['q2']); $q3 = cleanPOST($_POST['q3']); $q4 = cleanPOST($_POST['q4']); $q5 = cleanPOST($_POST['q5']); $score = $q1 + $q2 + $q3 + $q4 + $q5; $classtype = classQuiz($score); if ($classtype == "warrior") header('Location: quiz.php?warrior'); elseif ($classtype == "enchanter") header('Location: quiz.php?enchanter'); elseif ($classtype == "ranger") header('Location: quiz.php?ranger'); elseif ($classtype == "templar") header('Location: quiz.php?templar'); elseif ($classtype == "mystic") header('Location: quiz.php?mystic'); elseif ($classtype == "rogue") header('Location: quiz.php?rogue'); exit(); } else { // set $url to page.php?QUERY if (isset($_SERVER['QUERY_STRING'])) { $url = $_SERVER['QUERY_STRING']; parse_str($url, $vars); } else { $url = $_GET; } include_once "header.php"; ?> <div class="container-fluid"> <h1>Character Class Quiz</h1> <?php if ($url == "warrior") { ?> <div class="jumbotron"><h2>You got Warrior! <a href="selectclass.php">Select your class?</a></h2></div> <?php } elseif ($url == "enchanter") { ?> <div class="jumbotron"><h2>You got Enchanter! <a href="selectclass.php">Select your class?</a></h2></div> <?php } elseif ($url == "ranger") { ?> <div class="jumbotron"><h2>You got Ranger! <a href="selectclass.php">Select your class?</a></h2></div> <?php } elseif ($url == "templar") { ?> <div class="jumbotron"><h2>You got Templar! <a href="selectclass.php">Select your class?</a></h2></div> <?php } elseif ($url == "mystic") { ?> <div class="jumbotron"><h2>You got Mystic! <a href="selectclass.php">Select your class?</a></h2></div> <?php } elseif ($url == "rogue") { ?> <div class="jumbotron"><h2>You got Rogue! <a href="selectclass.php">Select your class?</a></h2></div> <?php } else { ?> <form action="quiz.php" method="post"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">1) When you run into a problem, how do you go about solving it?</h3> </div> <div class="panel-body"> <div class="radio"> <label> <input type="radio" name="q1" id="optionsRadios1" value="2" required> Use your physical powers to defeat it. </label> </div> <div class="radio"> <label> <input type="radio" name="q1" id="optionsRadios2" value="4"> Cast an appropriate spell to make it go away. </label> </div> <div class="radio"> <label> <input type="radio" name="q1" id="optionsRadios3" value="6"> Secretly sabotage whatever it is that's causing your problems. </label> </div> </div> </div> <!-- question separator --> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">2) In a perfect world, where you can do whatever you like, you'd spend your life doing what?</h3> </div> <div class="panel-body"> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios1" value="5" required> Stealing and breaking into restricted places for fun. </label> </div> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios2" value="6"> Explore the wilderness and live off your own hunting abilities. </label> </div> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios3" value="3"> Locking yourself up in the library reading up on all the knowledge. </label> </div> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios4" value="4"> Volunteer your time helping the sick and wounded. </label> </div> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios5" value="3"> Travel the world as a missonary. </label> </div> <div class="radio"> <label> <input type="radio" name="q2" id="optionsRadios6" value="1"> Become a professional sports player. </label> </div> </div> </div> <!-- question separator --> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">3) A stray dog follows you on your way home, what do you do?</h3> </div> <div class="panel-body"> <div class="radio"> <label> <input type="radio" name="q3" id="optionsRadios1" value="2" required> Try to find its owner, and if that fails, adopt it. </label> </div> <div class="radio"> <label> <input type="radio" name="q3" id="optionsRadios2" value="4"> Drop it off at a safe shelter. </label> </div> <div class="radio"> <label> <input type="radio" name="q3" id="optionsRadios3" value="6"> Find a good buyer and sell the dog. </label> </div> </div> </div> <!-- question separator --> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">4) What character traits do you consider to be virtuous?</h3> </div> <div class="panel-body"> <div class="radio"> <label> <input type="radio" name="q4" id="optionsRadios1" value="4" required> Compassion and intelligence. </label> </div> <div class="radio"> <label> <input type="radio" name="q4" id="optionsRadios2" value="6"> Cunning and a sharp wit. </label> </div> <div class="radio"> <label> <input type="radio" name="q4" id="optionsRadios3" value="2"> Honor and duty. </label> </div> </div> </div> <!-- question separator --> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">5) Which class do you think you're most suited to play?</h3> </div> <div class="panel-body"> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios1" value="1" required> Warrior. </label> </div> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios2" value="2"> Templar. </label> </div> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios3" value="3"> Enchanter. </label> </div> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios4" value="4"> Mystic. </label> </div> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios5" value="5"> Rogue. </label> </div> <div class="radio"> <label> <input type="radio" name="q5" id="optionsRadios6" value="6"> Ranger. </label> </div> </div> </div> <button type="submit" name="submit" class="btn btn-success btn-lg center-block">Submit answers</button> </form> <?php } /* end else for url query string */ ?> </div> <!-- end .container-fluid --> <?php } } // end isLogged() && isNew() else { header('Location: index.php'); exit(); } include_once("footer.php"); ?>
JavaScript
UTF-8
274
2.640625
3
[ "MIT" ]
permissive
client.on('guildMemberAdd', async member => { let cfxtag2 = await db.fetch(`cfxtag${member.guild.id}`) var cfxtag = []; if(cfxtag2 == null) cfxtag = `${member.user.username}` else cfxtag = `${cfxtag2} ${member.user.username}` member.setNickname(`${cfxtag}`) });
JavaScript
UTF-8
1,992
3.734375
4
[]
no_license
'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.replace(/\s*$/, '') .split('\n') .map(str => str.replace(/\s*$/, '')); main(); }); function readLine() { return inputString[currentLine++]; } /* Task: Complete the timeInWords function in the editor below. It should return a time string as described. timeInWords has the following parameter(s): h: an integer representing hour of the day m: an integer representing minutes after the hour */ function timeInWords(h, m) { let minutes = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'quarter', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty one', 'twenty two', 'twenty three', 'twenty four', 'twenty five', 'twenty six', 'twenty seven', 'twenty eight', 'twenty nine', 'half'] let hour = minutes[h]; if (m == 0) { return `${hour} o' clock` } else if (m == 1) { return `${minutes[m]} minute past ${hour}` } else if (m > 1 && m <= 29 && m != 15) { return `${minutes[m]} minutes past ${hour}` } else if (m == 15) { return `quarter past ${hour}` } else if (m === 30) { return `half past ${hour}` } else if (m > 30 && m <= 58 && m != 45) { return `${minutes[60 - m]} minutes to ${minutes[h + 1]}` } else if (m == 45) { return `quarter to ${minutes[h + 1]}` } else { return `${minutes[60 - m]} minute to ${minutes[h + 1]}` } } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const h = parseInt(readLine(), 10); const m = parseInt(readLine(), 10); let result = timeInWords(h, m); ws.write(result + "\n"); ws.end(); }
C#
UTF-8
1,517
2.921875
3
[]
no_license
using System.Collections.Generic; using System.Linq; namespace Holiday { public class DAL { private readonly IStorage storage; public DAL(IStorage storage) { this.storage = storage; } public IEnumerable<HolidayRequest> GetAllRequest(Employee employee) { return storage.GetStorageFor<HolidayRequest>().Where(r=>r.employee.ID == employee.ID); } public IEnumerable<HolidayRequest> GetRequestsWaitingApproval(Employee manager) { return storage.GetStorageFor<HolidayRequest>().Where(r => (r.status == Status.Pending) && (r.manager.ID == manager.ID)); } public void AddEmployee(Employee employee) { storage.Add(employee); } public Employee GetEmployeeByID(int id) { return storage.GetStorageFor<Employee>().SingleOrDefault(e => e.ID == id); } public void AddRequest(HolidayRequest request) { storage.Add(request); } public HolidayRequest GetRequestByID(int id) { return storage.GetStorageFor<HolidayRequest>().SingleOrDefault(r => r.ID == id); } public void ApproveRequest(HolidayRequest request) { request.Approve(); storage.Update(request); } public void RejectRequest(HolidayRequest request) { request.Reject(); storage.Update(request); } } }
Java
UTF-8
173
1.851563
2
[]
no_license
package task.dao; import java.util.List; import task.model.Item; public interface TaskDAO { List<Item> queryItemList(); void del(String name, int count); }
JavaScript
UTF-8
767
4.6875
5
[]
no_license
// Faça um programa que defina três variáveis com os valores dos três ângulos internos de um triângulo. Retorne true se os ângulos representarem os ângulos de um triângulo e false , caso contrário. Se algum ângulo for inválido o programa deve retornar uma mensagem de erro. // Para os ângulos serem de um triângulo válido, a soma dos três deve ser 180 graus. // Um ângulo será considerado inválido se não tiver um valor positivo. let angle1 = 35; let angle2 = 110; let angle3 = 35; let sumAngles = angle1 + angle2 + angle3; let positive = angle1 > 0 && angle2 > 0 && angle3 > 0; if(positive){ if (sumAngles === 180) { console.log(true); } else { console.log(false); } } else { console.log('Erro: ângulo inválido'); }
C++
UTF-8
2,779
3.21875
3
[]
no_license
#include <iostream> #include <string> #include <fstream> using namespace std; void bfs(string **, int, int); int main(int argc, char * args[]) { ifstream inputFile; int verticiesSize = 0; int edgeSize = 0; string ** verticies; string user; inputFile.open(args[1]); // handle verticies inputFile >> verticiesSize; verticies = new string*[verticiesSize + 1]; for (int i = 0; i < verticiesSize + 1; i++) { verticies[i] = new string[verticiesSize + 1]; } for (int i = 0; i < verticiesSize; i++) { inputFile >> verticies[0][i]; } // handle edges inputFile >> edgeSize; string verticie; string edge; int checkBreakout = 0; int countAddedEdge = 0; // iterate until check all edges while (checkBreakout != edgeSize) { inputFile >> verticie; inputFile >> edge; for (int i = 0; i < verticiesSize; i++) { // find columns if (verticie == verticies[0][i]) { for (int j = 0; j < verticiesSize; j++) { if (edge == verticies[0][j]) { verticies[j+1][i] = edge; verticies[i+1][j] = verticie; countAddedEdge = 1; checkBreakout++; break; } } // if edge is already checked, reset the value, and break the loop if (countAddedEdge == 1) { countAddedEdge--; break; } } } } bfs(verticies, verticiesSize, edgeSize); inputFile.close(); return 0; } // by using bfs, fill out babyfaces and heels array according to the rivarity status. void bfs(string **verticies, int verticiesSize, int edgeSize) { bool viableSplit = true; // set babyfaces array string * babyface; babyface = new string[verticiesSize]; // set heels array string * heels; heels = new string[verticiesSize]; int countBabyfaces = 0; int countHeels = 0; if (edgeSize != (verticiesSize * 2)) { int i = 0; // check first two matches while (i != 2) { for (int j = 0; j < verticiesSize; j++) { // if verticies is empty, add according member if (verticies[j + 1][i] != "") { if (i == 0) { heels[j] = verticies[j + 1][i]; countHeels++; } else { babyface[j] = verticies[j + 1][i]; countBabyfaces++; } } } i++; } int z = 0; while (z != verticiesSize) { if (babyface[z] == heels[z]) { viableSplit = false; } z++; } } else { // otherwise, set viable to false viableSplit = false; } // print out if (viableSplit) { cout << "Yes" << endl << "Babyface: "; for (int i = 0; i < verticiesSize; i++) { cout << babyface[i] << " "; } cout << endl << "Heels:"; for (int i = verticiesSize - 1; i > -1; i--) { cout << heels[i] << " "; } cout << endl; } else { cout << "No, if impossible" << endl; } // //Array Cleanup // delete[] babyface; // babyface = 0; // delete[] heels; heels = 0; }
Python
UTF-8
5,461
2.546875
3
[]
no_license
# coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt get_ipython().magic(u'matplotlib inline') import pickle as pkl from sklearn.metrics import roc_auc_score from sklearn.metrics import accuracy_score from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from sklearn.model_selection import train_test_split def load_data(filename): with open(filename, 'r') as f: data = f.readlines() #txt中所有字符串读入data y = np.zeros(len(data)) X = np.zeros([len(data),123]) for i,line in enumerate(data): line_list = line.strip().split(' ') #将单个数据分隔开存好 y[i] = line_list[0] for fea in line_list[1:]: #第一列是label feature_id,feature = fea.split(':') X[i][int(feature_id)-1] = feature return X,y X_train, y_train = load_data('a9a') X_test, y_test = load_data('a9a.t') print len(y_train),X_train.shape print len(y_test),X_test.shape # In[5]: y_train[y_train < 0] = 0 y_test[y_test < 0] = 0 # In[7]: # 从train中分出15%给dev集 X_train, X_dev, y_train, y_dev = train_test_split(X_train, y_train, test_size=0.15, random_state=42) X_train.shape, X_dev.shape, y_train.shape, y_dev.shape # In[8]: def gradient_L(X,y,w): mu = sigmoid(X.dot(w)) grad_L = (y-mu).dot(X) return grad_L # In[9]: def calc_H(X,w): u = sigmoid(X.dot(w)) m, n = X.shape R = np.eye(m) * u * (1 - u) H = -X.T.dot(R).dot(X) return H # In[10]: def sigmoid(value): return 1.0 / (1.0 + np.exp(-value)) # In[11]: def get_proba(X, w): prob_y = sigmoid(X.dot(w)) # prob_y[prob_y > 0.5] = 1 # prob_y[prob_y < 0.5] = 0 return prob_y # In[13]: def get_accuracy(y, prob_y, threshold = 0.5): temp = np.ones(len(y)) prob_y[prob_y > threshold] = 1 prob_y[prob_y < threshold] = 0 correct_cnt = np.sum(temp[y==prob_y]) return 1.0*correct_cnt/len(y) # In[14]: def L(X, y, w): return y.dot(X.dot(w)) - np.sum(np.log(1+np.exp(X.dot(w)))) # In[15]: def l2_L(X, y, w, lbd): return -0.5*lbd*np.linalg.norm(w)+L(X, y, w) # In[80]: def l2_norm_IRLS(X, y, lbd, max_iter=50, loss=1e-3): m,n = X.shape wt = np.array([1e-13]*n) accuracy_list = list() l2_norm_wt_list = list() loss_list = list() delta = 1 print "="*10, " lambda ", lbd, "="*10 f=open('log.txt','w') f.write("="*10+str(lbd)+"="*10+"\n") for i in range(max_iter): prob_y = sigmoid(X.dot(wt)) prob_y[prob_y > 0.5] = 1 prob_y[prob_y < 0.5] = 0 # auc_score = roc_auc_score(y, prob_y) accuracy = accuracy_score(y, prob_y) accuracy_list.append(accuracy) l2_norm_wt_list.append(np.linalg.norm(wt)) u = sigmoid(X.dot(wt)) R = np.eye(m) * u * (1 - u) H = -X.T.dot(R).dot(X)-lbd*np.eye(n) grad_L = X.T.dot(y-u)-lbd*wt wt_ = wt-np.linalg.pinv(H).dot(grad_L) delta = np.linalg.norm(l2_L(X, y, wt_, lbd)-l2_L(X, y, wt, lbd)) loss_list.append(delta) print "iter_num:", i+1, "L:", l2_L(X, y, wt_, lbd),"accuracy:", accuracy, "loss:", delta if delta < loss: break f.write("iter_num:"+ str(i+1)+"L:"+str(l2_L(X, y, wt_, lbd))+"accuracy:"+str(accuracy)+"loss:"+str(delta)+"\n") wt = wt_ f.close() # plot_prec_recall_curve(y_test=y, y_prob=prob_y) return wt, accuracy_list, l2_norm_wt_list,loss_list # In[69]: def test(X,y,w): prob_y = sigmoid(X.dot(w)) prob_y[prob_y > 0.5] = 1 prob_y[prob_y < 0.5] = 0 return accuracy_score(y, prob_y) # In[93]: # lambda=0 没有加正则项 # lambda>0 加了正则项 plot_train = [] lbd_list = [0,0.01,0.1,1,10,100] # for lbd in [0,0.01,0.1,1,10,100]: for lbd in lbd_list: result = l2_norm_IRLS(X_train, y_train, lbd, max_iter=50, loss=1e-4) plot_train.append(result) print "Complete train!" # In[95]: accuracy_score_list = list() for wt, accuracy_list, l2_norm_wt_list, loss_list in plot_train: accuracy_score_dev = test(X_dev, y_dev, wt) accuracy_score_list.append(accuracy_score_dev) max_index = accuracy_score_list.index(max(accuracy_score_list)) best_wt = plot_train[max_index][0] accuracy_score_test = test(X_test, y_test, best_wt) # In[103]: accuracy_score_test # In[97]: for i, (wt, accuracy_list, l2_norm_wt_list, loss_list) in enumerate(plot_train): plt.plot(accuracy_list,label="$\lambda = $"+str(lbd_list[i])) plt.legend(loc=0,prop={'size': 6}) plt.xlabel('iteration') plt.ylabel('Accuracy') plt.title('Accuracy curve in training set') plt.savefig("Accuracy_train.jpg") # In[101]: for i, (wt, accuracy_list, l2_norm_wt_list, loss_list) in enumerate(plot_train): plt.plot(l2_norm_wt_list,label="$\lambda = $"+str(lbd_list[i])) plt.legend(loc=0,prop={'size': 6}) plt.xlabel('iteration') plt.ylabel('l2-norm of $\|w\|_2$') plt.title('l2-norm of $\|w\|_2$ curve in training set') plt.savefig("l2_norm_w_train.jpg") # In[100]: for i, (wt, accuracy_list, l2_norm_wt_list, loss_list) in enumerate(plot_train): plt.plot(loss_list,label="$\lambda = $"+str(lbd_list[i])) plt.legend(loc=0,prop={'size': 6}) plt.xlabel('iteration') plt.ylabel('loss$') plt.title('loss curve in training set') plt.savefig("loss_curve_train.jpg")
Python
UTF-8
324
2.8125
3
[]
no_license
from anytree import Node, RenderTree node=Node("a") b=Node("b" , node) c=Node("c", node) d=Node("d", b) for pre, fill, node in RenderTree(node): print("%s%s" % (pre, node.name)) # print(d.parent) # print(d.name) # print(d.root) d=None for pre, fill, node in RenderTree(node): print("%s%s" % (pre, node.name))
C++
UTF-8
2,448
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define pb push_back typedef long long int ll; typedef pair < int,int > PII; typedef pair < ll,ll > PLL; #define F first #define S second ostream& operator<<(ostream & os, PLL h) { return os << "( " << h.F << ", " << h.S << " )" << endl; } PLL operator+ (PLL a, ll x) {return {a.F + x, a.S + x} ;} PLL operator- (PLL a, ll x) {return {a.F - x, a.S - x} ;} PLL operator* (PLL a, ll x) {return {a.F * x, a.S * x} ;} PLL operator+(PLL x, PLL y) { return {x.F + y.F,x.S + y.S} ;} PLL operator-(PLL x,PLL y) { return {x.F - y.F, x.S - y.S} ;} PLL operator*(PLL x,PLL y) { return {x.F * y.F , x.S * y.S} ;} PLL operator%(PLL x,PLL y) { return {x.F % y.F, x.S % y.S} ;} PLL base = {37,41}; PLL M = {1000000021, 1e9 + 9 }; string s; int mem[5005][5005] ; PLL H[5005] ; PLL power[5005]; PLL subHash(int l,int r) { int len = r - l + 1; return ( (H[r+1] - H[l]*power[len]) % M + M) % M ; } int dp2[5005][5005]; bool isPalin(int l, int r) { if(l > r ) return 1; if(l == r) return 1; int &ret = dp2[l][r] ; if(ret != -1) return ret; if(s[l] == s[r]){ return ret = isPalin(l+1,r-1); } return ret = 0; } int DP(int l,int r) { if(l == r) return 1; if(r - l == 1) { if(s[r] == s[l]) return 2; return 0; } if(r - l == 2) { if(s[r] == s[l]) return 2; return 0; } int &ret = mem[l][r] ; if(ret != -1) return ret; ret = 0; int len = r - l; int c1 = DP(l,l+(len - 1)/ 2 ) ; int c2 = DP(r-(len -1) / 2,r) ; PLL h1 = subHash(l,l+(len - 1)/ 2) ; PLL h2 = subHash(r-(len - 1) / 2 , r); //cout << h1 << " " << h2 << endl; if(h1 == h2 and c1 and c1 == c2 ) return ret = c1 + 1; if(isPalin(l,r)) return ret = 1; return ret; } ll val(char ch) { return ch - 'a' + 1; } int main() { ios::sync_with_stdio(false); cin.tie(0); memset(mem,-1,sizeof mem); memset(dp2,-1,sizeof dp2); cin >> s; power[0] = {1,1}; for(int i = 1; i < 5005; i++) power[i] = (power[i-1] * base) % M ; H[0] = {0,0}; for(int i = 0; i < s.size(); i++) { H[i+1] = (H[i] * base + val(s[i])) % M ; } vector < ll > dp(s.size() + 2, 0 ); for(int i = 0; i < s.size(); i++) { for(int j = i ; j < s.size(); j++) { int val = DP(i,j); //cout << i << " " << j << " "<< val << endl; dp[val]++; } } for(int i = s.size() - 1; i > 0; i--) dp[i] += dp[i+1] ; for(int i = 1; i <= s.size(); i++) { cout << dp[i] << "\n"; } return 0; }
PHP
UTF-8
1,853
2.609375
3
[]
no_license
<?php require_once('includes/db.php'); include('includes/functions.php'); if(isset($_POST['Submit'])){ if($_POST['email']!='' && valid_email($_POST['email'])==TRUE){ $sql = "SELECT id, username, temp_pass, email FROM users WHERE email = '".mysqli_real_escape_string($cn,$_POST['email'])."'"; $getUser = mysqli_query($cn, $sql); if(mysqli_num_rows($getUser)==1){ $temp_pass = random_string('alnum', 12); $row = mysqli_fetch_assoc($getUser); $sql = "UPDATE users SET temp_pass='".$temp_pass."', temp_pass_active=1 WHERE `email`='".$row['email']."'"; $query = mysqli_query($cn, $sql); $headers = "From: ".$smail."" . "\r\n" . "Reply-To: ".$smail."" . "\r\n" . "X-Mailer: PHP/" . phpversion(); $subject = "Recuperação da password"; $message = "Caro ".$row['username'].", Pediste a reposição da tua password, colocou-se esta: $temp_pass . Para confirmar este pedido visita o link: ".$surl."/confirm_password.php?ID=".$row['id']."&new=".$temp_pass."."; if(mail($row['email'], $subject, $message, $headers)){ $msg = 'Password enviada, verifica o e-mail para mais informações'; } else { $error = 'Não enviei o e-mail'; } } else { $error = 'Não existe nenhum membro com esse e-mail.'; } } else { $error = 'E-mail inválido !'; } } include("includes/top.php"); if(isset($error)){ echo $error; } if(isset($msg)){ echo $msg; } else { ?> <table> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <tr><td>E-mail:</td><td><input type="text" id="email" name="email" size="32" value="" /></td></tr> <tr><td><input type="reset" name="Reset" value="Repor" /></td><td><input type="submit" name="Submit" value="Submeter" /></td></tr> </form> </table> <?php } include("includes/bottom.php"); ?>
JavaScript
UTF-8
4,538
2.78125
3
[]
no_license
/* globals React */ 'use strict'; var PlaneValues = React.createClass({ getInitialState: function() { return({ idSelected: this.props.idSelected }); }, componentWillReceiveProps: function(nextProps) { this.setState({ idSelected: nextProps.idSelected }); }, componentDidUpdate: function() { var planes = this.props.planes; var drawDottedLine = this.props.drawDottedLine; var drawArrow = this.props.drawArrow; var plane = planes[this.state.idSelected]; var dV = plane.dV; var dS = plane.dS; var dVMag = dV.mag; var aMagActual = plane.a.actual.mag; var aMagDesired = plane.a.desired.mag; var rho = dS.mag; var dAlpha = dV.angle; var theta = dS.angle; var phiActual = plane.a.actual.angle; var phiDesired = plane.a.desired.angle; var targetsCollected = plane.targetsCollected; var canvasInput = document.getElementById('plane-values-input'); var canvasOutput = document.getElementById('plane-values-output'); var ctxInput = canvasInput.getContext('2d'); var ctxOutput = canvasOutput.getContext('2d'); var width = canvasInput.width; var height = canvasInput.height; var xo1 = height / 10; var yo = height / 4; var dX = (width - 3 * xo1) / 2; var angle = Math.PI / 12; var r = dX / Math.cos(angle); var xo2 = width - dX - xo1; var heightText = 3 * xo1 / 2; var formatScalar = function(scalar, units) { return Math.round(scalar) + ' ' + units; }; var formatAngle = function(angle) { return Math.round(angle * 180 / Math.PI) + '°'; }; var drawInput = function() { ctxInput.clearRect(0, 0, width, height); // drawDottedLine(ctxInput, xo1, yo, xo1 + dX, yo); // drawArrow(ctxInput, xo1, yo, r, 2 * r / 5, angle, '#C1FA1C'); ctxInput.font = '18px monaco, Consolas, "Lucida Console", monospace'; ctxInput.fillStyle = '#C1FA1C'; // ctxInput.fillText('rel velocity', xo1, heightText); ctxInput.fillText('v: ' + formatScalar(dVMag, 'm/s'), xo1, height - 2 * heightText - 4); ctxInput.fillText('⍺: ' + formatAngle(dAlpha), xo1, height - heightText); // drawDottedLine(ctxInput, xo2, yo, xo2 + dX, yo); // drawArrow(ctxInput, xo2, yo, r, 2 * r / 5, angle, '#1DFD84'); ctxInput.fillStyle = '#1DFD84'; // ctxInput.fillText('rel position', xo2, heightText); ctxInput.fillText('ρ: ' + formatScalar(rho, 'm'), xo2, height - 2 * heightText - 4); ctxInput.fillText('θ: ' + formatAngle(theta), xo2, height - heightText); }; var drawOutput = function() { ctxOutput.clearRect(0, 0, width, height); // drawDottedLine(ctxOutput, xo1, yo, xo1 + dX, yo); // drawArrow(ctxOutput, xo1, yo, r, 2 * r / 5, angle, 'fuchsia'); ctxOutput.font = '18px monaco, Consolas, "Lucida Console", monospace'; ctxOutput.fillStyle = 'fuchsia'; // ctxOutput.fillText('actual', xo1, heightText); ctxOutput.fillText('Tₓ: ' + formatScalar(aMagActual, 'kN'), xo1, height - 2 * heightText - 4); ctxOutput.fillText('φₓ: ' + formatAngle(phiActual), xo1, height - heightText); // drawDottedLine(ctxOutput, xo2, yo, xo2 + dX, yo); // drawArrow(ctxOutput, xo2, yo, r, 2 * r / 5, angle, 'lime'); ctxOutput.fillStyle = 'lime'; // ctxOutput.fillText('desired', xo2, heightText); ctxOutput.fillText('Tₒ: ' + formatScalar(aMagDesired, 'kN'), xo2, height - 2 * heightText - 4); ctxOutput.fillText('φₒ: ' + formatAngle(phiDesired), xo2, height - heightText); }; var draw = function() { drawInput(); drawOutput(); }; window.requestAnimationFrame(draw); }, selectPlane: function(event) { this.props.updateIndex(event.target.value); }, render: function() { var planes = this.props.planes; var idSelected = this.state.idSelected; var plane = planes[idSelected]; var options = planes.map(function(plane, i) { return <option key={ i } value={ i } >{ window.classifier.classify(plane.color) }</option>; }); return( <div> <div className='nav'> <select value={ this.state.idSelected } onChange={ this.selectPlane }> { options } </select> <code> { '   targets collected: ' + plane.targetsCollected } </code> </div> <canvas id='plane-values-input' width='300' height='150' /> <canvas id='plane-values-output' width='300' height='150' /> </div> ); } });
JavaScript
UTF-8
9,835
2.78125
3
[]
no_license
/** * define the common JS sdk */ var JSDK = (function() { "use strict"; /** make setTimeout() a promise, usage: * later(1000, 'any data').then(function(data) { * // do anything * return later(2000, data); // if you want to chain * }).then(function(data) { * // do anything... * }); */ function later(delay, data) { return new Promise(function(resolve, reject) { if (delay === undefined) { delay = 0; } window.setTimeout(function() { resolve(data); }, delay); }); } var debug = (function() { var list = null; function log(str, prtTrace) { try { if (log.caller != null) { str = log.caller.name + ': ' + str; } } catch(e) {} if (list == null) { list = document.getElementById('debug'); if (list == null) { list = document.createElement('ul'); list.id = 'debug'; document.getElementsByTagName('body')[0].appendChild(list); } } var li = document.createElement('li'); li.innerHTML = str; later().then(function() { list.insertBefore(li, list.firstChild); }); if (prtTrace) { trace(); } } function trace() { try { window['3.1415926535'].x = 2.7182818284; } catch (e) { if (e.stack) { log('call stack: ' + e.stack); } } } return { log: log, trace: trace } })(); // event manager var em = (function() { var CHECKDUP = false; // TODO: use ref counter instead var map = {}; function checkParams(events, subscriber) { var evts = null; if (typeof subscriber === 'function') { if ('string' === typeof events) { evts = [events]; } else if (Array.isArray(events)){ evts = events; } } return evts; } function subscribe(events, subscriber) { var evts = checkParams(events, subscriber); if (evts === null) { return this; } for (var i = 0; i < evts.length; ++ i) { var k = evts[i]; if (map[k] === undefined) { map[k] = []; } if (!Array.isArray(map[k])) { // TODO: add log here map[k] = []; } if (!CHECKDUP || map[k].indexOf(subscriber) === -1) { map[k].push(subscriber); } } return this; } function unsubscribe(events, subscriber) { var evts = checkParams(events, subscriber); if (evts === null) { return this; } for (var i = 0; i < evts.length; ++ i) { var k = evts[i]; var m = map[k]; if (m === undefined) { continue; } if (!Array.isArray(m)) { // TODO: log this error map[k] = undefined; continue; } if (CHECKDUP) { // TODO: use ref counter here } var idx = m.indexOf(subscriber); if (idx === -1) { // not found continue; } map[k] = m.slice(0, idx).concat(m.slice(idx + 1, m.length)); if (map[k].length === 0) { map[k] = undefined; } } return this; } function fire(evt, param) { if (typeof evt !== 'string') { return false; } var m = map[evt]; if (m === undefined || !Array.isArray(m)) { return false; } for (var i = 0; i < m.length; ++ i) { if (typeof m[i] === 'function') { m[i](evt, param); } } return true; } function shutdown() { map = {}; } return { subscribe: subscribe, unsubscribe: unsubscribe, fire: fire, shutdown: shutdown }; })(); // error handle var errcode = { ERR_OK: 0, ERR_ERROR: 1, // general error ERR_INIT_FAILED: 2, ERR_JSON: 3, ERR_BRIDGE: 10, ERR_NETWORK_TIMEOUT: 1000, ERR_INVALID_PARAM: 2000, }; // For promise try { if (window && window.Promise === undefined) { window.Promise = Q.promise; } } catch (e) { try { require(['Q'], function(Q) { window.Promise = Q.promise; }); } catch (e) { } } // Create a promise for function func(callback) or func(onSucceed, onFailed); function newPromise(fn) { return new Promise(function(resolve, reject) { fn(function(data) { resolve(data); }, function(e) { reject(e); }); }); } function waitForDeviceID(evt, data) { if (data.changed && data.changed['deviceID']) { readonly.deviceID = data.changed.deviceID.value; window.setTimeout(function() { em.unsubscribe('evtDeviceInfoChanged', waitForDeviceID); fireReady(); }, 0); } } function fireReady() { ready = true; em.subscribe('evtDeviceInfoChanged', onDeviceInfoChanged); em.fire('evtReady', {}); if (readyCallback) { readyCallback(); readyCallback = undefined; } } function onKickoff(evt, data) { em.unsubscribe('evtKickoff', onKickoff); if (readonly.deviceID === undefined) { em.subscribe('evtDeviceInfoChanged', waitForDeviceID); } else { fireReady(); } } function onDeviceInfoChanged(evt, data) { if (data.changed && data.changed['deviceID']) { readonly.deviceID = data.changed.deviceID.value; } } function checkProfile() { if (!window.PROFILE) { alert("Profile doesn't exist"); return false; } if (PROFILE.srvs === undefined || !Array.isArray(PROFILE.srvs) || PROFILE.srvs.length == 0) { alert("profile.srvs is invalid"); return false; } return true; } // Device related var ready = false; var READY_TIMEOUT = 5000; function isReady() { return ready; } if (!checkProfile()) { return null; } var readonly = { profile: PROFILE, deviceID: undefined }; function init() { ADPT.init(this); em.subscribe('evtKickoff', onKickoff); window.setTimeout(function() { if (!isReady()) { em.fire('evtSDKFailed', {}); } }, READY_TIMEOUT); } function setDeviceStatus(deviceID, subDeviceID, cmd) { if (!isReady()) { debug.log('not ready'); return null; } if (!cmdFactory.checkCmd(cmd)) { debug.log('cmd is invalid: ' + JSON.stringify(cmd)); return null; } if (cmd.params.length === 0) { debug.log('nothing to control'); return null; // nothing to control } return ADPT.setDeviceStatus(deviceID, subDeviceID, cmd); } function getDeviceStatus(deviceID, subDeviceID, status) { if (!isReady()) { return null; } if (status !== undefined && !Array.isArray(status)) { debug.log('status should be an array'); return null; } return ADPT.getDeviceStatus(deviceID, subDeviceID, status === undefined ? [] : status); } function getIntf(k) { return PROFILE.suids[0].intfs[k]; } function getAllParams() { return Object.keys(PROFILE.suids[0].intfs); } var cmdFactory = (function() { function checkCommand(cmd) { if (cmd == null) { return false; } var props = ['did', 'srv', 'act', 'params', 'vals']; for (var i = 0; i < props.length; ++ i) { if (!cmd.hasOwnProperty(props[i])) { return false; } } if (['get', 'set'].indexOf(cmd.act) === -1) { return false; } if (!Array.isArray(cmd.params) || !Array.isArray(cmd.vals)) { return false; } if (cmd.act !== 'get') { if (cmd.params.length != cmd.vals.length) { return false; } } else { if (cmd.vals.length != 0) { return false; } } return true; } function getValueString(value) { return '[{"val":' + JSON.stringify(value) + ',"idx":1}]'; } // @return null if failed (invalid action) function newCommand(deviceID, srv, action, params, values) { if (action !== 'get' && action !== 'set') { debug.log('action must be "get" or "set"'); return null; } var isget = action === 'get'; if ((params == null) != (values == null)) { debug.log('params and values must both be null or not'); return null; } if (params && !Array.isArray(params)) { debug.log('params must be an array'); return null; } if (values && !Array.isArray(values)) { debug.log('values must be an array'); return null; } if (params != null && values != null && (params.length != values.length)) { if (!isget) { debug.log('params and values must have the same items if not "get".'); return null; } } var cmd = { did: deviceID, srv: srv, act: action, params: [], vals: [] }; if (params != null) { for (var i = 0; i < params.length; ++ i) { cmd.params.push(params[i]); if (!isget) { cmd.vals.push(JSON.parse(getValueString(values[i]))); } } } return cmd; } function addParam(cmd, param, value) { if (!checkCommand(cmd)) { return false; } var p = param; var v = getvstring(value); var idx = -1; for (var i = 0; i < cmd.params.length; ++ i) { if (cmd.params[i] === p) { cmd.vals[i] = v; return true; } } cmd.params.push(p); cmd.vals.push(v); return true; } return { checkCmd: checkCommand, newCommand: newCommand, addParam: addParam } })(); var readyCallback = null; function setReadyCallback(fn) { if (readyCallback === null) { if (isReady()) { fn(); } else { readyCallback = fn; } } } var sdk = { // error code errcode: errcode, // methods 'init': init, // device 'isReady': isReady, 'ready': setReadyCallback, 'newCommand': cmdFactory.newCommand, 'addParam': cmdFactory.addParam, 'setDeviceStatus': setDeviceStatus, 'getDeviceStatus': getDeviceStatus, 'getIntf': getIntf, 'getAllParams': getAllParams, // event em: em, // promise 'newPromise': newPromise, // debug 'debug': debug, // utils 'utils': { later: later } }; // readonly properties ['profile', 'deviceID'].forEach(function(name) { Object.defineProperty(sdk, name, { get: function() { return readonly[name]; } }); }); return sdk; })(); JSDK.init();